[project @ 2001-08-03 20:40:43 by sof]
[ghc-hetmet.git] / ghc / compiler / ghci / ByteCodeGen.lhs
index b9e0002..59170d5 100644 (file)
@@ -6,28 +6,33 @@
 \begin{code}
 module ByteCodeGen ( UnlinkedBCO, UnlinkedBCOExpr, ItblEnv, ClosureEnv, HValue,
                     filterNameMap,
-                     byteCodeGen, coreExprToBCOs, 
-                    linkIModules, linkIExpr
+                     byteCodeGen, coreExprToBCOs
                   ) where
 
 #include "HsVersions.h"
 
 import Outputable
-import Name            ( Name, getName, mkSysLocalName )
-import Id              ( Id, idType, isDataConId_maybe, mkVanillaId )
+import Name            ( Name, getName )
+import Id              ( Id, idType, isDataConId_maybe, isPrimOpId_maybe, isFCallId,
+                         idPrimRep, mkSysLocal, idName, isFCallId_maybe )
+import ForeignCall     ( ForeignCall(..), CCallTarget(..), CCallSpec(..) )
 import OrdList         ( OrdList, consOL, snocOL, appOL, unitOL, 
                          nilOL, toOL, concatOL, fromOL )
 import FiniteMap       ( FiniteMap, addListToFM, listToFM,
-                         addToFM, lookupFM, fmToList, plusFM )
+                         addToFM, lookupFM, fmToList )
 import CoreSyn
 import PprCore         ( pprCoreExpr )
 import Literal         ( Literal(..), literalPrimRep )
 import PrimRep         ( PrimRep(..) )
+import PrimOp          ( PrimOp(..)  )
 import CoreFVs         ( freeVars )
-import Type            ( typePrimRep )
-import DataCon         ( dataConTag, fIRST_TAG, dataConTyCon, dataConWrapId )
-import TyCon           ( TyCon, tyConFamilySize )
+import Type            ( typePrimRep, splitTyConApp_maybe, isTyVarTy, splitForAllTys )
+import DataCon         ( dataConTag, fIRST_TAG, dataConTyCon, 
+                          dataConWrapId, isUnboxedTupleCon )
+import TyCon           ( TyCon(..), tyConFamilySize, isDataTyCon, tyConDataCons,
+                         isFunTyCon, isUnboxedTupleTyCon )
 import Class           ( Class, classTyCon )
+import Type            ( Type, repType, splitRepFunTys )
 import Util            ( zipEqual, zipWith4Equal, naturalMergeSortLe, nOfThem )
 import Var             ( isTyVar )
 import VarSet          ( VarSet, varSetElems )
@@ -36,19 +41,23 @@ import CmdLineOpts  ( DynFlags, DynFlag(..) )
 import ErrUtils                ( showPass, dumpIfSet_dyn )
 import Unique          ( mkPseudoUnique3 )
 import FastString      ( FastString(..) )
+import Panic           ( GhcException(..) )
 import PprType         ( pprType )
-import ByteCodeInstr   ( BCInstr(..), ProtoBCO(..), nameOfProtoBCO )
+import ByteCodeInstr   ( BCInstr(..), ProtoBCO(..), nameOfProtoBCO, bciStackUse )
 import ByteCodeItbls   ( ItblEnv, mkITbls )
 import ByteCodeLink    ( UnlinkedBCO, UnlinkedBCOExpr, assembleBCO,
-                         ClosureEnv, HValue, linkSomeBCOs, filterNameMap )
+                         ClosureEnv, HValue, filterNameMap,
+                         iNTERP_STACK_CHECK_THRESH )
+import ByteCodeFFI     ( taggedSizeW, untaggedSizeW, mkMarshalCode )
+import Linker          ( lookupSymbol )
 
-import List            ( intersperse, sortBy )
+import List            ( intersperse, sortBy, zip4 )
 import Foreign         ( Ptr(..), mallocBytes )
-import Addr            ( addrToInt, writeCharOffAddr )
+import Addr            ( Addr(..), nullAddr, addrToInt, writeCharOffAddr )
 import CTypes          ( CInt )
+import Exception       ( throwDyn )
 
 import PrelBase                ( Int(..) )
-import PrelAddr                ( Addr(..) )
 import PrelGHC         ( ByteArray# )
 import IOExts          ( unsafePerformIO )
 import PrelIOBase      ( IO(..) )
@@ -98,8 +107,9 @@ coreExprToBCOs dflags expr
 
       -- create a totally bogus name for the top-level BCO; this
       -- should be harmless, since it's never used for anything
-      let invented_name = mkSysLocalName (mkPseudoUnique3 0) SLIT("Expr-Top-Level")
-      let invented_id   = mkVanillaId invented_name (panic "invented_id's type")
+      let invented_id   = mkSysLocal SLIT("Expr-Top-Level") (mkPseudoUnique3 0) 
+                                    (panic "invented_id's type")
+      let invented_name = idName invented_id
 
       let (BcM_State all_proto_bcos final_ctr) 
              = runBc (BcM_State [] 0) 
@@ -117,27 +127,6 @@ coreExprToBCOs dflags expr
       root_bco <- assembleBCO root_proto_bco
 
       return (root_bco, auxiliary_bcos)
-
-
--- Linking stuff
-linkIModules :: ItblEnv    -- incoming global itbl env; returned updated
-            -> ClosureEnv -- incoming global closure env; returned updated
-            -> [([UnlinkedBCO], ItblEnv)]
-            -> IO ([HValue], ItblEnv, ClosureEnv)
-linkIModules gie gce mods 
-   = do let (bcoss, ies) = unzip mods
-            bcos = concat bcoss
-            final_gie = foldr plusFM gie ies
-        (final_gce, linked_bcos) <- linkSomeBCOs final_gie gce bcos
-        return (linked_bcos, final_gie, final_gce)
-
-
-linkIExpr :: ItblEnv -> ClosureEnv -> UnlinkedBCOExpr
-          -> IO HValue           -- IO BCO# really
-linkIExpr ie ce (root_ul_bco, aux_ul_bcos)
-   = do (aux_ce, _) <- linkSomeBCOs ie ce aux_ul_bcos
-        (_, [root_bco]) <- linkSomeBCOs ie aux_ce [root_ul_bco]
-        return root_bco
 \end{code}
 
 %************************************************************************
@@ -168,12 +157,35 @@ ppBCEnv p
 -- Create a BCO and do a spot of peephole optimisation on the insns
 -- at the same time.
 mkProtoBCO nm instrs_ordlist origin
-   = ProtoBCO nm (id {-peep-} (fromOL instrs_ordlist)) origin
+   = ProtoBCO nm maybe_with_stack_check origin
      where
+        -- Overestimate the stack usage (in words) of this BCO,
+        -- and if >= iNTERP_STACK_CHECK_THRESH, add an explicit
+        -- stack check.  (The interpreter always does a stack check
+        -- for iNTERP_STACK_CHECK_THRESH words at the start of each
+        -- BCO anyway, so we only need to add an explicit on in the
+        -- (hopefully rare) cases when the (overestimated) stack use
+        -- exceeds iNTERP_STACK_CHECK_THRESH.
+        maybe_with_stack_check
+           | stack_overest >= 65535
+           = pprPanic "mkProtoBCO: stack use won't fit in 16 bits" 
+                      (int stack_overest)
+           | stack_overest >= iNTERP_STACK_CHECK_THRESH
+           = (STKCHECK stack_overest) : peep_d
+           | otherwise
+           = peep_d    -- the supposedly common case
+             
+        stack_overest = sum (map bciStackUse peep_d)
+                        + 10 {- just to be really really sure -}
+
+
+        -- Merge local pushes
+        peep_d = peep (fromOL instrs_ordlist)
+
         peep (PUSH_L off1 : PUSH_L off2 : PUSH_L off3 : rest)
            = PUSH_LLL off1 (off2-1) (off3-2) : peep rest
         peep (PUSH_L off1 : PUSH_L off2 : rest)
-           = PUSH_LL off1 off2 : peep rest
+           = PUSH_LL off1 (off2-1) : peep rest
         peep (i:rest)
            = i : peep rest
         peep []
@@ -209,10 +221,10 @@ collect xs not_lambda
 
 schemeR_wrk is_top original_body nm (args, body)
    | Just dcon <- maybe_toplevel_null_con_rhs
-   = trace ("nullary constructor! " ++ showSDocDebug (ppr nm)) (
+   = --trace ("nullary constructor! " ++ showSDocDebug (ppr nm)) (
      emitBc (mkProtoBCO (getName nm) (toOL [PACK dcon 0, ENTER])
                                      (Right original_body))
-     )
+     --)
 
    | otherwise
    = let fvs       = filter (not.isTyVar) (varSetElems (fst original_body))
@@ -254,10 +266,12 @@ schemeE :: Int -> Sequel -> BCEnv -> AnnExpr Id VarSet -> BcM BCInstrList
 
 -- Delegate tail-calls to schemeT.
 schemeE d s p e@(fvs, AnnApp f a) 
-   = returnBc (schemeT d s p (fvs, AnnApp f a))
+   = schemeT d s p (fvs, AnnApp f a)
+
 schemeE d s p e@(fvs, AnnVar v)
    | isFollowableRep v_rep
-   = returnBc (schemeT d s p (fvs, AnnVar v))
+   =  -- Ptr-ish thing; push it in the normal way
+     schemeT d s p (fvs, AnnVar v)
 
    | otherwise
    = -- returning an unboxed value.  Heave it on the stack, SLIDE, and RETURN.
@@ -297,7 +311,7 @@ schemeE d s p (fvs, AnnLet binds b)
 
          -- ToDo: don't build thunks for things with no free variables
          buildThunk dd ([], size, id, off)
-            = PUSH_G (getName id) 
+            = PUSH_G (Left (getName id))
               `consOL` unitOL (MKAP (off+size-1) size)
          buildThunk dd ((fv:fvs), size, id, off)
             = case pushAtom True dd p' (AnnVar fv) of
@@ -313,6 +327,51 @@ schemeE d s p (fvs, AnnLet binds b)
      returnBc (allocCode `appOL` thunkCode `appOL` bodyCode)
 
 
+
+
+
+schemeE d s p (fvs_case, AnnCase (fvs_scrut, scrut) bndr 
+                                 [(DEFAULT, [], (fvs_rhs, rhs))])
+
+   | let isFunType var_type 
+            = case splitTyConApp_maybe var_type of
+                 Just (tycon,_) | isFunTyCon tycon -> True
+                 _ -> False
+         ty_bndr = repType (idType bndr)
+     in isFunType ty_bndr || isTyVarTy ty_bndr
+
+   -- Nasty hack; treat
+   --     case scrut::suspect of bndr { DEFAULT -> rhs }
+   --     as 
+   --     let bndr = scrut in rhs
+   --     when suspect is polymorphic or arrowtyped
+   -- So the required strictness properties are not observed.
+   -- At some point, must fix this properly.
+   = let new_expr
+            = (fvs_case, 
+               AnnLet 
+                  (AnnNonRec bndr (fvs_scrut, scrut)) (fvs_rhs, rhs)
+              )
+
+     in  trace ("WARNING: ignoring polymorphic case in interpreted mode.\n" ++
+                "   Possibly due to strict polymorphic/functional constructor args.\n" ++
+                "   Your program may leak space unexpectedly.\n")
+                -- ++ showSDoc (char ' ' $$ pprCoreExpr (deAnnotate new_expr) $$ char ' '))
+         (schemeE d s p new_expr)
+
+
+
+{- Convert case .... of (# VoidRep'd-thing, a #) -> ...
+      as
+   case .... of a -> ...
+   Use  a  as the name of the binder too.
+-}
+schemeE d s p (fvs, AnnCase scrut bndr [(DataAlt dc, [bind1, bind2], rhs)])
+   | isUnboxedTupleCon dc && VoidRep == typePrimRep (idType bind1)
+   = trace "automagic mashing of case alts (# VoidRep, a #)" (
+     schemeE d s p (fvs, AnnCase scrut bind2 [(DEFAULT, [bind2], rhs)])
+     )
+
 schemeE d s p (fvs, AnnCase scrut bndr alts)
    = let
         -- Top of stack is the return itbl, as usual.
@@ -328,17 +387,21 @@ schemeE d s p (fvs, AnnCase scrut bndr alts)
 
         scrut_primrep = typePrimRep (idType bndr)
         isAlgCase
-           = case scrut_primrep of
-                CharRep -> False ; AddrRep -> False
-                IntRep -> False ; FloatRep -> False ; DoubleRep -> False
-                PtrRep -> True
-                other  -> pprPanic "ByteCodeGen.schemeE" (ppr other)
+           | scrut_primrep == PtrRep
+           = True
+           | scrut_primrep `elem`
+             [CharRep, AddrRep, WordRep, IntRep, FloatRep, DoubleRep,
+              VoidRep, Int8Rep, Int16Rep, Int32Rep, Int64Rep,
+              Word8Rep, Word16Rep, Word32Rep, Word64Rep]
+           = False
+           | otherwise
+           =  pprPanic "ByteCodeGen.schemeE" (ppr scrut_primrep)
 
         -- given an alt, return a discr and code for it.
         codeAlt alt@(discr, binds_f, rhs)
            | isAlgCase 
            = let (unpack_code, d_after_unpack, p_after_unpack)
-                    = mkUnpackCode binds_f d' p'
+                    = mkUnpackCode (filter (not.isTyVar) binds_f) d' p'
              in  schemeE d_after_unpack s p_after_unpack rhs
                                        `thenBc` \ rhs_code -> 
                  returnBc (my_discr alt, unpack_code `appOL` rhs_code)
@@ -347,12 +410,18 @@ schemeE d s p (fvs, AnnCase scrut bndr alts)
              schemeE d' s p' rhs       `thenBc` \ rhs_code ->
              returnBc (my_discr alt, rhs_code)
 
-        my_discr (DEFAULT, binds, rhs)  = NoDiscr
-        my_discr (DataAlt dc, binds, rhs) = DiscrP (dataConTag dc - fIRST_TAG)
+        my_discr (DEFAULT, binds, rhs) = NoDiscr
+        my_discr (DataAlt dc, binds, rhs) 
+           | isUnboxedTupleCon dc
+           = unboxedTupleException
+           | otherwise
+           = DiscrP (dataConTag dc - fIRST_TAG)
         my_discr (LitAlt l, binds, rhs)
            = case l of MachInt i     -> DiscrI (fromInteger i)
                        MachFloat r   -> DiscrF (fromRational r)
                        MachDouble r  -> DiscrD (fromRational r)
+                       MachChar i    -> DiscrI i
+                       _ -> pprPanic "schemeE(AnnCase).my_discr" (ppr l)
 
         maybe_ncons 
            | not isAlgCase = Nothing
@@ -384,95 +453,303 @@ schemeE d s p other
                (pprCoreExpr (deAnnotate other))
 
 
--- Compile code to do a tail call.  Three cases:
+-- Compile code to do a tail call.  Specifically, push the fn,
+-- slide the on-stack app back down to the sequel depth,
+-- and enter.  Four cases:
+--
+-- 0.  (Nasty hack).
+--     An application "PrelGHC.tagToEnum# <type> unboxed-int".
+--     The int will be on the stack.  Generate a code sequence
+--     to convert it to the relevant constructor, SLIDE and ENTER.
 --
 -- 1.  A nullary constructor.  Push its closure on the stack 
 --     and SLIDE and RETURN.
 --
--- 2.  Application of a non-nullary constructor, by defn saturated.
+-- 2.  (Another nasty hack).  Spot (# a::VoidRep, b #) and treat
+--     it simply as  b  -- since the representations are identical
+--     (the VoidRep takes up zero stack space).
+--
+-- 3.  Application of a non-nullary constructor, by defn saturated.
 --     Split the args into ptrs and non-ptrs, and push the nonptrs, 
 --     then the ptrs, and then do PACK and RETURN.
 --
--- 3.  Otherwise, it must be a function call.  Push the args
+-- 4.  Otherwise, it must be a function call.  Push the args
 --     right to left, SLIDE and ENTER.
 
 schemeT :: Int                 -- Stack depth
         -> Sequel      -- Sequel depth
         -> BCEnv       -- stack env
         -> AnnExpr Id VarSet 
-        -> BCInstrList
+        -> BcM BCInstrList
 
 schemeT d s p app
 --   | trace ("schemeT: env in = \n" ++ showSDocDebug (ppBCEnv p)) False
 --   = panic "schemeT ?!?!"
 
+--   | trace ("\nschemeT\n" ++ showSDoc (pprCoreExpr (deAnnotate app)) ++ "\n") False
+--   = error "?!?!" 
+
+   -- Handle case 0
+   | Just (arg, constr_names) <- maybe_is_tagToEnum_call
+   = pushAtom True d p arg             `bind` \ (push, arg_words) ->
+     implement_tagToId constr_names    `thenBc` \ tagToId_sequence ->
+     returnBc (push `appOL`  tagToId_sequence            
+                    `appOL`  mkSLIDE 1 (d+arg_words-s)
+                    `snocOL` ENTER)
+
    -- Handle case 1
    | is_con_call && null args_r_to_l
-   = (PUSH_G (getName con) `consOL` mkSLIDE 1 (d-s))
-     `snocOL` ENTER
+   = returnBc (
+        (PUSH_G (Left (getName con)) `consOL` mkSLIDE 1 (d-s))
+        `snocOL` ENTER
+     )
+
+   -- Handle case 2
+   | let isVoidRepAtom (_, AnnVar v)    = VoidRep == typePrimRep (idType v)
+         isVoidRepAtom (_, AnnNote n e) = isVoidRepAtom e
+     in  is_con_call && isUnboxedTupleCon con 
+         && length args_r_to_l == 2 
+         && isVoidRepAtom (last (args_r_to_l))
+   = trace ("schemeT: unboxed pair with Void first component") (
+     schemeT d s p (head args_r_to_l)
+     )
 
-   -- Cases 2 and 3
+   -- Cases 3 and 4
    | otherwise
-   = code
+   = if   is_con_call && isUnboxedTupleCon con
+     then returnBc unboxedTupleException
+     else code `seq` returnBc code
 
-     where
-         -- Extract the args (R->L) and fn
-         (args_r_to_l_raw, fn) = chomp app
-         chomp expr
-            = case snd expr of
-                 AnnVar v   -> ([], v)
-                 AnnApp f a -> case chomp f of (az, f) -> (snd a:az, f)
-                 other      -> pprPanic "schemeT" 
-                                  (ppr (deAnnotate (panic "schemeT.chomp", other)))
+   where
+      -- Detect and extract relevant info for the tagToEnum kludge.
+      maybe_is_tagToEnum_call
+         = let extract_constr_Names ty
+                  = case splitTyConApp_maybe (repType ty) of
+                       (Just (tyc, [])) |  isDataTyCon tyc
+                                        -> map getName (tyConDataCons tyc)
+                       other            -> panic "maybe_is_tagToEnum_call.extract_constr_Ids"
+           in 
+           case app of
+              (_, AnnApp (_, AnnApp (_, AnnVar v) (_, AnnType t)) arg)
+                 -> case isPrimOpId_maybe v of
+                       Just TagToEnumOp -> Just (snd arg, extract_constr_Names t)
+                      other            -> Nothing
+              other -> Nothing
+
+      -- Extract the args (R->L) and fn
+      (args_r_to_l_raw, fn) = chomp app
+      chomp expr
+         = case snd expr of
+              AnnVar v    -> ([], v)
+              AnnApp f a  -> case chomp f of (az, f) -> (a:az, f)
+              AnnNote n e -> chomp e
+              other       -> pprPanic "schemeT" 
+                                (ppr (deAnnotate (panic "schemeT.chomp", other)))
          
-         args_r_to_l = filter (not.isTypeAtom) args_r_to_l_raw
-         isTypeAtom (AnnType _) = True
-         isTypeAtom _           = False
-
-         -- decide if this is a constructor call, and rearrange
-         -- args appropriately.
-         maybe_dcon  = isDataConId_maybe fn
-         is_con_call = case maybe_dcon of Nothing -> False; Just _ -> True
-         (Just con)  = maybe_dcon
-
-         args_final_r_to_l
-            | not is_con_call
-            = args_r_to_l
-            | otherwise
-            = filter (not.isPtr) args_r_to_l ++ filter isPtr args_r_to_l
-              where isPtr = isFollowableRep . atomRep
-
-         -- make code to push the args and then do the SLIDE-ENTER thing
-         code = do_pushery d args_final_r_to_l
-
-         tag_when_push = not is_con_call
-         narg_words    = sum (map (get_arg_szw . atomRep) args_r_to_l)
-         get_arg_szw   = if tag_when_push then taggedSizeW else untaggedSizeW
-
-         do_pushery d (arg:args)
-            = let (push, arg_words) = pushAtom tag_when_push d p arg
-              in  push `appOL` do_pushery (d+arg_words) args
-         do_pushery d []
-            = case maybe_dcon of
-                 Just con -> PACK con narg_words `consOL` (
-                             mkSLIDE 1 (d - narg_words - s) `snocOL` ENTER)
-                 Nothing
-                    -> let (push, arg_words) = pushAtom True d p (AnnVar fn)
-                       in  push 
-                           `appOL` mkSLIDE (narg_words+arg_words) 
-                                           (d - s - narg_words)
-                           `snocOL` ENTER
+      args_r_to_l = filter (not.isTypeAtom.snd) args_r_to_l_raw
+      isTypeAtom (AnnType _) = True
+      isTypeAtom _           = False
+
+      -- decide if this is a constructor call, and rearrange
+      -- args appropriately.
+      maybe_dcon  = isDataConId_maybe fn
+      is_con_call = case maybe_dcon of Nothing -> False; Just _ -> True
+      (Just con)  = maybe_dcon
+
+      args_final_r_to_l
+         | not is_con_call
+         = args_r_to_l
+         | otherwise
+         = filter (not.isPtr.snd) args_r_to_l ++ filter (isPtr.snd) args_r_to_l
+           where isPtr = isFollowableRep . atomRep
+
+      -- make code to push the args and then do the SLIDE-ENTER thing
+      code          = do_pushery d (map snd args_final_r_to_l)
+      tag_when_push = not is_con_call
+      narg_words    = sum (map (get_arg_szw . atomRep . snd) args_r_to_l)
+      get_arg_szw   = if tag_when_push then taggedSizeW else untaggedSizeW
+
+      do_pushery d (arg:args)
+         = let (push, arg_words) = pushAtom tag_when_push d p arg
+           in  push `appOL` do_pushery (d+arg_words) args
+      do_pushery d []
+
+         -- CCALL !
+         | Just (CCall (CCallSpec (StaticTarget target) 
+                                  cconv safety)) <- isFCallId_maybe fn
+         = let -- Get the arg and result reps.
+               (a_reps, r_rep) = getCCallPrimReps (idType fn)               
+               tys_str = showSDoc (ppr (a_reps, r_rep))
+               {-
+               Because the Haskell stack grows down, the a_reps refer to 
+               lowest to highest addresses in that order.  The args for the call
+               are on the stack.  Now push an unboxed, tagged Addr# indicating
+               the C function to call.  Then push a dummy placeholder for the 
+               result.  Finally, emit a CCALL insn with an offset pointing to the 
+               Addr# just pushed, and a literal field holding the mallocville
+               address of the piece of marshalling code we generate.
+               So, just prior to the CCALL insn, the stack looks like this 
+               (growing down, as usual):
+                 
+                  <arg_n>
+                  ...
+                  <arg_1>
+                  Addr# address_of_C_fn
+                  <placeholder-for-result#> (must be an unboxed type)
+
+               The interpreter then calls the marshall code mentioned
+               in the CCALL insn, passing it (& <placeholder-for-result#>), 
+               that is, the addr of the topmost word in the stack.
+               When this returns, the placeholder will have been
+               filled in.  The placeholder is slid down to the sequel
+               depth, and we RETURN.
+
+               This arrangement makes it simple to do f-i-dynamic since the Addr#
+               value is the first arg anyway.  It also has the virtue that the
+               stack is GC-understandable at all times.
+
+               The marshalling code is generated specifically for this
+               call site, and so knows exactly the (Haskell) stack
+               offsets of the args, fn address and placeholder.  It
+               copies the args to the C stack, calls the stacked addr,
+               and parks the result back in the placeholder.  The interpreter
+               calls it as a normal C call, assuming it has a signature
+                  void marshall_code ( StgWord* ptr_to_top_of_stack )
+               -}
+
+               -- resolve static address
+               target_addr 
+                  = let unpacked = _UNPK_ target
+                    in  case unsafePerformIO (lookupSymbol unpacked) of
+                           Just aa -> case aa of Ptr a# -> A# a#
+                           Nothing -> panic ("interpreted ccall: can't resolve: " 
+                                             ++ unpacked)
+
+               -- push the Addr#
+               addr_usizeW  = untaggedSizeW AddrRep
+               addr_tsizeW  = taggedSizeW AddrRep
+               push_Addr    = toOL [PUSH_UBX (Right target_addr) addr_usizeW,
+                                    PUSH_TAG addr_usizeW]
+               d_after_Addr = d + addr_tsizeW
+               -- push the return placeholder
+               r_lit        = mkDummyLiteral r_rep
+               r_usizeW     = untaggedSizeW r_rep
+               r_tsizeW     = 1{-tag-} + r_usizeW
+               push_r       = toOL [PUSH_UBX (Left r_lit) r_usizeW,
+                                    PUSH_TAG r_usizeW]
+               d_after_r    = d_after_Addr + r_tsizeW
+               -- do the call
+               do_call      = unitOL (CCALL addr_of_marshaller)
+               -- slide and return
+               wrapup       = mkSLIDE r_tsizeW
+                                      (d_after_r - r_tsizeW - s)
+                              `snocOL` RETURN r_rep
+
+               -- generate the marshalling code we're going to call
+               r_offW       = 0 
+               addr_offW    = r_tsizeW
+               arg1_offW    = r_tsizeW + addr_tsizeW
+               args_offW    = map (arg1_offW +) 
+                                  (init (scanl (+) 0 (map taggedSizeW a_reps)))
+               addr_of_marshaller
+                            = mkMarshalCode (r_offW, r_rep) addr_offW
+                                            (zip args_offW a_reps)               
+           in
+               --trace (show (arg1_offW, args_offW  ,  (map taggedSizeW a_reps) )) (
+               target_addr 
+               `seq`
+               (push_Addr `appOL` push_r `appOL` do_call `appOL` wrapup)
+               --)
+
+         | otherwise
+         = case maybe_dcon of
+              Just con -> PACK con narg_words `consOL` (
+                          mkSLIDE 1 (d - narg_words - s) `snocOL` ENTER)
+              Nothing
+                 -> let (push, arg_words) = pushAtom True d p (AnnVar fn)
+                    in  push 
+                        `appOL` mkSLIDE (narg_words+arg_words) 
+                                        (d - s - narg_words)
+                        `snocOL` ENTER
 
 mkSLIDE n d 
    = if d == 0 then nilOL else unitOL (SLIDE n d)
+bind x f 
+   = f x
+
+
+mkDummyLiteral :: PrimRep -> Literal
+mkDummyLiteral pr
+   = case pr of
+        IntRep    -> MachInt 0
+        DoubleRep -> MachDouble 0
+        FloatRep  -> MachFloat 0
+        AddrRep   | taggedSizeW AddrRep == taggedSizeW WordRep -> MachWord 0
+        _         -> pprPanic "mkDummyLiteral" (ppr pr)
+
+
+-- Convert (eg) 
+--       PrelGHC.Int# -> PrelGHC.State# PrelGHC.RealWorld
+--                    -> (# PrelGHC.State# PrelGHC.RealWorld, PrelGHC.Int# #)
+--
+-- to [IntRep] -> IntRep
+-- and check that the last arg is VoidRep'd and that an unboxed pair is
+-- returned wherein the first arg is VoidRep'd.
+
+getCCallPrimReps :: Type -> ([PrimRep], PrimRep)
+getCCallPrimReps fn_ty
+   = let (a_tys, r_ty) = splitRepFunTys fn_ty
+         a_reps        = map typePrimRep a_tys
+         (r_tycon, r_reps) 
+            = case splitTyConApp_maybe (repType r_ty) of
+                      (Just (tyc, tys)) -> (tyc, map typePrimRep tys)
+                      Nothing -> blargh
+         ok = length a_reps >= 1 && VoidRep == last a_reps
+               && length r_reps == 2 && VoidRep == head r_reps
+               && isUnboxedTupleTyCon r_tycon
+               && PtrRep /= r_rep_to_go        -- if it was, it would be impossible 
+                                        -- to create a valid return value 
+                                        -- placeholder on the stack
+         a_reps_to_go = init a_reps
+         r_rep_to_go  = r_reps !! 1
+         blargh       = pprPanic "getCCallPrimReps: can't handle:" 
+                                 (pprType fn_ty)
+     in 
+     --trace (showSDoc (ppr (a_reps, r_reps))) (
+     if ok then (a_reps_to_go, r_rep_to_go) else blargh
+     --)
 
 atomRep (AnnVar v)    = typePrimRep (idType v)
 atomRep (AnnLit l)    = literalPrimRep l
 atomRep (AnnNote n b) = atomRep (snd b)
 atomRep (AnnApp f (_, AnnType _)) = atomRep (snd f)
+atomRep (AnnLam x e) | isTyVar x = atomRep (snd e)
 atomRep other = pprPanic "atomRep" (ppr (deAnnotate (undefined,other)))
 
 
+-- Compile code which expects an unboxed Int on the top of stack,
+-- (call it i), and pushes the i'th closure in the supplied list 
+-- as a consequence.
+implement_tagToId :: [Name] -> BcM BCInstrList
+implement_tagToId names
+   = ASSERT(not (null names))
+     getLabelsBc (length names)                        `thenBc` \ labels ->
+     getLabelBc                                        `thenBc` \ label_fail ->
+     getLabelBc                                `thenBc` \ label_exit ->
+     zip4 labels (tail labels ++ [label_fail])
+                 [0 ..] names                  `bind`   \ infos ->
+     map (mkStep label_exit) infos             `bind`   \ steps ->
+     returnBc (concatOL steps
+               `appOL` 
+               toOL [LABEL label_fail, CASEFAIL, LABEL label_exit])
+     where
+        mkStep l_exit (my_label, next_label, n, name_for_n)
+           = toOL [LABEL my_label, 
+                   TESTEQ_I n next_label, 
+                   PUSH_G (Left name_for_n), 
+                   JMP l_exit]
+
+
 -- Make code to unpack the top-of-stack constructor onto the stack, 
 -- adding tags for the unboxed bits.  Takes the PrimReps of the 
 -- constructor's arguments.  off_h and off_s are travelling offsets
@@ -534,10 +811,10 @@ mkUnpackCode vars d p
         code_np = do_nptrs vreps_env_uszw ptrs_szw (reverse (map snd vreps_np))
         do_nptrs off_h off_s [] = nilOL
         do_nptrs off_h off_s (npr:nprs)
-           = case npr of
-                IntRep -> approved ; FloatRep -> approved
-                DoubleRep -> approved ; AddrRep -> approved
-                _ -> pprPanic "ByteCodeGen.mkUnpackCode" (ppr npr)
+           | npr `elem` [IntRep, FloatRep, DoubleRep, CharRep, AddrRep]
+           = approved
+           | otherwise
+           = pprPanic "ByteCodeGen.mkUnpackCode" (ppr npr)
              where
                 approved = UPK_TAG usizeW (off_h-usizeW) off_s   `consOL` theRest
                 theRest  = do_nptrs (off_h-usizeW) (off_s + tsizeW) nprs
@@ -570,8 +847,21 @@ mkUnpackCode vars d p
 -- 6 stack has valid words 0 .. 5.
 
 pushAtom :: Bool -> Int -> BCEnv -> AnnExpr' Id VarSet -> (BCInstrList, Int)
-pushAtom tagged d p (AnnVar v) 
-   = let str = "\npushAtom " ++ showSDocDebug (ppr v) 
+pushAtom tagged d p (AnnVar v)
+
+   | idPrimRep v == VoidRep
+   = ASSERT(tagged)
+     (unitOL (PUSH_TAG 0), 1)
+
+   | isFCallId v
+   = pprPanic "pushAtom: shouldn't get an FCallId here" (ppr v)
+
+   | Just primop <- isPrimOpId_maybe v
+   = (unitOL (PUSH_G (Right primop)), 1)
+
+   | otherwise
+   = let  {-
+         str = "\npushAtom " ++ showSDocDebug (ppr v) 
                ++ " :: " ++ showSDocDebug (pprType (idType v))
                ++ ", depth = " ++ show d
                ++ ", tagged = " ++ show tagged ++ ", env =\n" ++ 
@@ -579,14 +869,12 @@ pushAtom tagged d p (AnnVar v)
                ++ " --> words: " ++ show (snd result) ++ "\n" ++
                showSDoc (nest 4 (vcat (map ppr (fromOL (fst result)))))
                ++ "\nendPushAtom " ++ showSDocDebug (ppr v)
-                  where
-                     cmp_snd x y = compare (snd x) (snd y)
-         str' = if str == str then str else str
+        -}
 
          result
             = case lookupBCEnv_maybe p v of
                  Just d_v -> (toOL (nOfThem nwords (PUSH_L (d-d_v+sz_t-2))), nwords)
-                 Nothing  -> ASSERT(sz_t == 1) (unitOL (PUSH_G nm), nwords)
+                 Nothing  -> ASSERT(sz_t == 1) (unitOL (PUSH_G (Left nm)), nwords)
 
          nm = case isDataConId_maybe v of
                  Just c  -> getName c
@@ -596,7 +884,6 @@ pushAtom tagged d p (AnnVar v)
          sz_u   = untaggedIdSizeW v
          nwords = if tagged then sz_t else sz_u
      in
-         --trace str'
          result
 
 pushAtom True d p (AnnLit lit)
@@ -605,6 +892,7 @@ pushAtom True d p (AnnLit lit)
 
 pushAtom False d p (AnnLit lit)
    = case lit of
+        MachWord w   -> code WordRep
         MachInt i    -> code IntRep
         MachFloat r  -> code FloatRep
         MachDouble r -> code DoubleRep
@@ -613,7 +901,7 @@ pushAtom False d p (AnnLit lit)
      where
         code rep
            = let size_host_words = untaggedSizeW rep
-             in (unitOL (PUSH_UBX lit size_host_words), size_host_words)
+             in (unitOL (PUSH_UBX (Left lit) size_host_words), size_host_words)
 
         pushStr s 
            = let mallocvilleAddr
@@ -629,18 +917,15 @@ pushAtom False d p (AnnLit lit)
                             let n = I# l
                             -- CAREFUL!  Chars are 32 bits in ghc 4.09+
                             in  unsafePerformIO (
-                                   do a@(Ptr addr) <- mallocBytes (n+1)
-                                      strncpy a ba (fromIntegral n)
-                                      writeCharOffAddr addr n '\0'
-                                      return addr
+                                   do (Ptr a#) <- mallocBytes (n+1)
+                                      strncpy (Ptr a#) ba (fromIntegral n)
+                                      writeCharOffAddr (A# a#) n '\0'
+                                      return (A# a#)
                                    )
                          _ -> panic "StgInterp.lit2expr: unhandled string constant type"
-
-                 addrLit 
-                    = MachInt (toInteger (addrToInt mallocvilleAddr))
              in
                 -- Get the addr on the stack, untaggedly
-                (unitOL (PUSH_UBX addrLit 1), 1)
+                (unitOL (PUSH_UBX (Right mallocvilleAddr) 1), 1)
 
 
 
@@ -652,6 +937,10 @@ pushAtom tagged d p (AnnApp f (_, AnnType _))
 pushAtom tagged d p (AnnNote note e)
    = pushAtom tagged d p (snd e)
 
+pushAtom tagged d p (AnnLam x e) 
+   | isTyVar x 
+   = pushAtom tagged d p (snd e)
+
 pushAtom tagged d p other
    = pprPanic "ByteCodeGen.pushAtom" 
               (pprCoreExpr (deAnnotate (undefined, other)))
@@ -804,24 +1093,18 @@ lookupBCEnv_maybe :: BCEnv -> Id -> Maybe Int
 lookupBCEnv_maybe = lookupFM
 
 
--- When I push one of these on the stack, how much does Sp move by?
-taggedSizeW :: PrimRep -> Int
-taggedSizeW pr
-   | isFollowableRep pr = 1
-   | otherwise          = 1{-the tag-} + getPrimRepSize pr
-
-
--- The plain size of something, without tag.
-untaggedSizeW :: PrimRep -> Int
-untaggedSizeW pr
-   | isFollowableRep pr = 1
-   | otherwise          = getPrimRepSize pr
-
-
 taggedIdSizeW, untaggedIdSizeW :: Id -> Int
 taggedIdSizeW   = taggedSizeW   . typePrimRep . idType
 untaggedIdSizeW = untaggedSizeW . typePrimRep . idType
 
+unboxedTupleException :: a
+unboxedTupleException 
+   = throwDyn 
+        (Panic 
+           ("Bytecode generator can't handle unboxed tuples.  Possibly due\n" ++
+            "\tto foreign import/export decls in source.  Workaround:\n" ++
+            "\tcompile this module to a .o file, then restart session."))
+
 \end{code}
 
 %************************************************************************
@@ -866,4 +1149,9 @@ getLabelBc :: BcM Int
 getLabelBc st
    = (nextlabel st, st{nextlabel = 1 + nextlabel st})
 
+getLabelsBc :: Int -> BcM [Int]
+getLabelsBc n st
+   = let ctr = nextlabel st 
+     in  ([ctr .. ctr+n-1], st{nextlabel = ctr+n})
+
 \end{code}