[project @ 2005-07-19 16:44:50 by simonpj]
[ghc-hetmet.git] / ghc / compiler / deSugar / DsForeign.lhs
1 %
2 % (c) The AQUA Project, Glasgow University, 1998
3 %
4 \section[DsCCall]{Desugaring \tr{foreign} declarations}
5
6 Expanding out @foreign import@ and @foreign export@ declarations.
7
8 \begin{code}
9 module DsForeign ( dsForeigns ) where
10
11 #include "HsVersions.h"
12 import TcRnMonad        -- temp
13
14 import CoreSyn
15
16 import DsCCall          ( dsCCall, mkFCall, boxResult, unboxArg, resultWrapper )
17 import DsMonad
18
19 import HsSyn            ( ForeignDecl(..), ForeignExport(..), LForeignDecl,
20                           ForeignImport(..), CImportSpec(..) )
21 import DataCon          ( splitProductType_maybe )
22 #ifdef DEBUG
23 import DataCon          ( dataConSourceArity )
24 import Type             ( isUnLiftedType )
25 #endif
26 import MachOp           ( machRepByteWidth, MachRep(..) )
27 import SMRep            ( argMachRep, typeCgRep )
28 import CoreUtils        ( exprType, mkInlineMe )
29 import Id               ( Id, idType, idName, mkSysLocal, setInlinePragma )
30 import Literal          ( Literal(..), mkStringLit )
31 import Module           ( moduleString )
32 import Name             ( getOccString, NamedThing(..) )
33 import OccName          ( encodeFS )
34 import Type             ( repType, coreEqType )
35 import TcType           ( Type, mkFunTys, mkForAllTys, mkTyConApp,
36                           mkFunTy, tcSplitTyConApp_maybe, 
37                           tcSplitForAllTys, tcSplitFunTys, tcTyConAppArgs,
38                         )
39
40 import BasicTypes       ( Boxity(..) )
41 import HscTypes         ( ForeignStubs(..) )
42 import ForeignCall      ( ForeignCall(..), CCallSpec(..), 
43                           Safety(..), playSafe,
44                           CExportSpec(..), CLabelString,
45                           CCallConv(..), ccallConvToInt,
46                           ccallConvAttribute
47                         )
48 import TysWiredIn       ( unitTy, tupleTyCon )
49 import TysPrim          ( addrPrimTy, mkStablePtrPrimTy, alphaTy )
50 import PrelNames        ( hasKey, ioTyConKey, stablePtrTyConName, newStablePtrName, bindIOName,
51                           checkDotnetResName )
52 import BasicTypes       ( Activation( NeverActive ) )
53 import SrcLoc           ( Located(..), unLoc )
54 import Outputable
55 import Maybe            ( fromJust, isNothing )
56 import FastString
57 \end{code}
58
59 Desugaring of @foreign@ declarations is naturally split up into
60 parts, an @import@ and an @export@  part. A @foreign import@ 
61 declaration
62 \begin{verbatim}
63   foreign import cc nm f :: prim_args -> IO prim_res
64 \end{verbatim}
65 is the same as
66 \begin{verbatim}
67   f :: prim_args -> IO prim_res
68   f a1 ... an = _ccall_ nm cc a1 ... an
69 \end{verbatim}
70 so we reuse the desugaring code in @DsCCall@ to deal with these.
71
72 \begin{code}
73 type Binding = (Id, CoreExpr)   -- No rec/nonrec structure;
74                                 -- the occurrence analyser will sort it all out
75
76 dsForeigns :: [LForeignDecl Id] 
77            -> DsM (ForeignStubs, [Binding])
78 dsForeigns [] 
79   = returnDs (NoStubs, [])
80 dsForeigns fos
81   = foldlDs combine (ForeignStubs empty empty [] [], []) fos
82  where
83   combine stubs (L loc decl) = putSrcSpanDs loc (combine1 stubs decl)
84
85   combine1 (ForeignStubs acc_h acc_c acc_hdrs acc_feb, acc_f) 
86            (ForeignImport id _ spec depr)
87     = traceIf (text "fi start" <+> ppr id)      `thenDs` \ _ ->
88       dsFImport (unLoc id) spec                 `thenDs` \ (bs, h, c, mbhd) -> 
89       warnDepr depr                             `thenDs` \ _                ->
90       traceIf (text "fi end" <+> ppr id)        `thenDs` \ _ ->
91       returnDs (ForeignStubs (h $$ acc_h)
92                              (c $$ acc_c)
93                              (addH mbhd acc_hdrs)
94                              acc_feb, 
95                 bs ++ acc_f)
96
97   combine1 (ForeignStubs acc_h acc_c acc_hdrs acc_feb, acc_f) 
98            (ForeignExport (L _ id) _ (CExport (CExportStatic ext_nm cconv)) depr)
99     = dsFExport id (idType id) 
100                 ext_nm cconv False                 `thenDs` \(h, c, _, _) ->
101       warnDepr depr                                `thenDs` \_              ->
102       returnDs (ForeignStubs (h $$ acc_h) (c $$ acc_c) acc_hdrs (id:acc_feb), 
103                 acc_f)
104
105   addH Nothing  ls = ls
106   addH (Just e) ls
107    | e `elem` ls = ls
108    | otherwise   = e:ls
109
110   warnDepr False = returnDs ()
111   warnDepr True  = dsWarn msg
112      where
113        msg = ptext SLIT("foreign declaration uses deprecated non-standard syntax")
114 \end{code}
115
116
117 %************************************************************************
118 %*                                                                      *
119 \subsection{Foreign import}
120 %*                                                                      *
121 %************************************************************************
122
123 Desugaring foreign imports is just the matter of creating a binding
124 that on its RHS unboxes its arguments, performs the external call
125 (using the @CCallOp@ primop), before boxing the result up and returning it.
126
127 However, we create a worker/wrapper pair, thus:
128
129         foreign import f :: Int -> IO Int
130 ==>
131         f x = IO ( \s -> case x of { I# x# ->
132                          case fw s x# of { (# s1, y# #) ->
133                          (# s1, I# y# #)}})
134
135         fw s x# = ccall f s x#
136
137 The strictness/CPR analyser won't do this automatically because it doesn't look
138 inside returned tuples; but inlining this wrapper is a Really Good Idea 
139 because it exposes the boxing to the call site.
140
141 \begin{code}
142 dsFImport :: Id
143           -> ForeignImport
144           -> DsM ([Binding], SDoc, SDoc, Maybe FastString)
145 dsFImport id (CImport cconv safety header lib spec)
146   = dsCImport id spec cconv safety no_hdrs        `thenDs` \(ids, h, c) ->
147     returnDs (ids, h, c, if no_hdrs then Nothing else Just header)
148   where
149     no_hdrs = nullFastString header
150
151   -- FIXME: the `lib' field is needed for .NET ILX generation when invoking
152   --        routines that are external to the .NET runtime, but GHC doesn't
153   --        support such calls yet; if `nullFastString lib', the value was not given
154 dsFImport id (DNImport spec)
155   = dsFCall id (DNCall spec) True {- No headers -} `thenDs` \(ids, h, c) ->
156     returnDs (ids, h, c, Nothing)
157
158 dsCImport :: Id
159           -> CImportSpec
160           -> CCallConv
161           -> Safety
162           -> Bool       -- True <=> no headers in the f.i decl
163           -> DsM ([Binding], SDoc, SDoc)
164 dsCImport id (CLabel cid) _ _ no_hdrs
165  = resultWrapper (idType id) `thenDs` \ (resTy, foRhs) ->
166    ASSERT(fromJust resTy `coreEqType` addrPrimTy)    -- typechecker ensures this
167     let rhs = foRhs (mkLit (MachLabel cid Nothing)) in
168     returnDs ([(setImpInline no_hdrs id, rhs)], empty, empty)
169 dsCImport id (CFunction target) cconv safety no_hdrs
170   = dsFCall id (CCall (CCallSpec target cconv safety)) no_hdrs
171 dsCImport id CWrapper cconv _ _
172   = dsFExportDynamic id cconv
173
174 setImpInline :: Bool    -- True <=> No #include headers 
175                         -- in the foreign import declaration
176              -> Id -> Id
177 -- If there is a #include header in the foreign import
178 -- we make the worker non-inlinable, because we currently
179 -- don't keep the #include stuff in the CCallId, and hence
180 -- it won't be visible in the importing module, which can be
181 -- fatal. 
182 -- (The #include stuff is just collected from the foreign import
183 --  decls in a module.)
184 -- If you want to do cross-module inlining of the c-calls themselves,
185 -- put the #include stuff in the package spec, not the foreign 
186 -- import decl.
187 setImpInline True  id = id
188 setImpInline False id = id `setInlinePragma` NeverActive
189 \end{code}
190
191
192 %************************************************************************
193 %*                                                                      *
194 \subsection{Foreign calls}
195 %*                                                                      *
196 %************************************************************************
197
198 \begin{code}
199 dsFCall fn_id fcall no_hdrs
200   = let
201         ty                   = idType fn_id
202         (tvs, fun_ty)        = tcSplitForAllTys ty
203         (arg_tys, io_res_ty) = tcSplitFunTys fun_ty
204                 -- Must use tcSplit* functions because we want to 
205                 -- see that (IO t) in the corner
206     in
207     newSysLocalsDs arg_tys                      `thenDs` \ args ->
208     mapAndUnzipDs unboxArg (map Var args)       `thenDs` \ (val_args, arg_wrappers) ->
209
210     let
211         work_arg_ids  = [v | Var v <- val_args] -- All guaranteed to be vars
212
213         -- These are the ids we pass to boxResult, which are used to decide
214         -- whether to touch# an argument after the call (used to keep
215         -- ForeignObj#s live across a 'safe' foreign import).
216         maybe_arg_ids | unsafe_call fcall = work_arg_ids
217                       | otherwise         = []
218
219         forDotnet = 
220          case fcall of
221            DNCall{} -> True
222            _        -> False
223
224         topConDs
225           | forDotnet = 
226              dsLookupGlobalId checkDotnetResName `thenDs` \ check_id -> 
227              return (Just check_id)
228           | otherwise = return Nothing
229              
230         augmentResultDs
231           | forDotnet = 
232                 newSysLocalDs addrPrimTy `thenDs` \ err_res -> 
233                 returnDs (\ (mb_res_ty, resWrap) ->
234                               case mb_res_ty of
235                                 Nothing -> (Just (mkTyConApp (tupleTyCon Unboxed 1)
236                                                              [ addrPrimTy ]),
237                                                  resWrap)
238                                 Just x  -> (Just (mkTyConApp (tupleTyCon Unboxed 2)
239                                                              [ x, addrPrimTy ]),
240                                                  resWrap))
241           | otherwise = returnDs id
242     in
243     augmentResultDs                                  `thenDs` \ augment -> 
244     topConDs                                         `thenDs` \ topCon -> 
245     boxResult maybe_arg_ids augment topCon io_res_ty `thenDs` \ (ccall_result_ty, res_wrapper) ->
246
247     newUnique                                   `thenDs` \ ccall_uniq ->
248     newUnique                                   `thenDs` \ work_uniq ->
249     let
250         -- Build the worker
251         worker_ty     = mkForAllTys tvs (mkFunTys (map idType work_arg_ids) ccall_result_ty)
252         the_ccall_app = mkFCall ccall_uniq fcall val_args ccall_result_ty
253         work_rhs      = mkLams tvs (mkLams work_arg_ids the_ccall_app)
254         work_id       = setImpInline no_hdrs $  -- See comments with setImpInline
255                         mkSysLocal (encodeFS FSLIT("$wccall")) work_uniq worker_ty
256
257         -- Build the wrapper
258         work_app     = mkApps (mkVarApps (Var work_id) tvs) val_args
259         wrapper_body = foldr ($) (res_wrapper work_app) arg_wrappers
260         wrap_rhs     = mkInlineMe (mkLams (tvs ++ args) wrapper_body)
261     in
262     returnDs ([(work_id, work_rhs), (fn_id, wrap_rhs)], empty, empty)
263
264 unsafe_call (CCall (CCallSpec _ _ safety)) = playSafe safety
265 unsafe_call (DNCall _)                     = False
266 \end{code}
267
268
269 %************************************************************************
270 %*                                                                      *
271 \subsection{Foreign export}
272 %*                                                                      *
273 %************************************************************************
274
275 The function that does most of the work for `@foreign export@' declarations.
276 (see below for the boilerplate code a `@foreign export@' declaration expands
277  into.)
278
279 For each `@foreign export foo@' in a module M we generate:
280 \begin{itemize}
281 \item a C function `@foo@', which calls
282 \item a Haskell stub `@M.$ffoo@', which calls
283 \end{itemize}
284 the user-written Haskell function `@M.foo@'.
285
286 \begin{code}
287 dsFExport :: Id                 -- Either the exported Id, 
288                                 -- or the foreign-export-dynamic constructor
289           -> Type               -- The type of the thing callable from C
290           -> CLabelString       -- The name to export to C land
291           -> CCallConv
292           -> Bool               -- True => foreign export dynamic
293                                 --         so invoke IO action that's hanging off 
294                                 --         the first argument's stable pointer
295           -> DsM ( SDoc         -- contents of Module_stub.h
296                  , SDoc         -- contents of Module_stub.c
297                  , [MachRep]    -- primitive arguments expected by stub function
298                  , Int          -- size of args to stub function
299                  )
300
301 dsFExport fn_id ty ext_name cconv isDyn
302    = 
303      let
304         (_tvs,sans_foralls)             = tcSplitForAllTys ty
305         (fe_arg_tys', orig_res_ty)      = tcSplitFunTys sans_foralls
306         -- We must use tcSplits here, because we want to see 
307         -- the (IO t) in the corner of the type!
308         fe_arg_tys | isDyn     = tail fe_arg_tys'
309                    | otherwise = fe_arg_tys'
310      in
311         -- Look at the result type of the exported function, orig_res_ty
312         -- If it's IO t, return         (t, True)
313         -- If it's plain t, return      (t, False)
314      (case tcSplitTyConApp_maybe orig_res_ty of
315         -- We must use tcSplit here so that we see the (IO t) in
316         -- the type.  [IO t is transparent to plain splitTyConApp.]
317
318         Just (ioTyCon, [res_ty])
319               -> ASSERT( ioTyCon `hasKey` ioTyConKey )
320                  -- The function already returns IO t
321                  returnDs (res_ty, True)
322
323         other -> -- The function returns t
324                  returnDs (orig_res_ty, False)
325      )
326                                         `thenDs` \ (res_ty,             -- t
327                                                     is_IO_res_ty) ->    -- Bool
328      returnDs $
329        mkFExportCBits ext_name 
330                       (if isDyn then Nothing else Just fn_id)
331                       fe_arg_tys res_ty is_IO_res_ty cconv
332 \end{code}
333
334 @foreign export dynamic@ lets you dress up Haskell IO actions
335 of some fixed type behind an externally callable interface (i.e.,
336 as a C function pointer). Useful for callbacks and stuff.
337
338 \begin{verbatim}
339 foreign export dynamic f :: (Addr -> Int -> IO Int) -> IO Addr
340
341 -- Haskell-visible constructor, which is generated from the above:
342 -- SUP: No check for NULL from createAdjustor anymore???
343
344 f :: (Addr -> Int -> IO Int) -> IO Addr
345 f cback =
346    bindIO (newStablePtr cback)
347           (\StablePtr sp# -> IO (\s1# ->
348               case _ccall_ createAdjustor cconv sp# ``f_helper'' s1# of
349                  (# s2#, a# #) -> (# s2#, A# a# #)))
350
351 foreign export "f_helper" f_helper :: StablePtr (Addr -> Int -> IO Int) -> Addr -> Int -> IO Int
352 -- `special' foreign export that invokes the closure pointed to by the
353 -- first argument.
354 \end{verbatim}
355
356 \begin{code}
357 dsFExportDynamic :: Id
358                  -> CCallConv
359                  -> DsM ([Binding], SDoc, SDoc)
360 dsFExportDynamic id cconv
361   =  newSysLocalDs ty                            `thenDs` \ fe_id ->
362      getModuleDs                                `thenDs` \ mod_name -> 
363      let 
364         -- hack: need to get at the name of the C stub we're about to generate.
365        fe_nm       = mkFastString (moduleString mod_name ++ "_" ++ toCName fe_id)
366      in
367      newSysLocalDs arg_ty                       `thenDs` \ cback ->
368      dsLookupGlobalId newStablePtrName          `thenDs` \ newStablePtrId ->
369      dsLookupTyCon stablePtrTyConName           `thenDs` \ stable_ptr_tycon ->
370      let
371         mk_stbl_ptr_app = mkApps (Var newStablePtrId) [ Type arg_ty, Var cback ]
372         stable_ptr_ty   = mkTyConApp stable_ptr_tycon [arg_ty]
373         export_ty       = mkFunTy stable_ptr_ty arg_ty
374      in
375      dsLookupGlobalId bindIOName                `thenDs` \ bindIOId ->
376      newSysLocalDs stable_ptr_ty                `thenDs` \ stbl_value ->
377      dsFExport id export_ty fe_nm cconv True    
378                 `thenDs` \ (h_code, c_code, arg_reps, args_size) ->
379      let
380       stbl_app cont ret_ty = mkApps (Var bindIOId)
381                                     [ Type stable_ptr_ty
382                                     , Type ret_ty       
383                                     , mk_stbl_ptr_app
384                                     , cont
385                                     ]
386        {-
387         The arguments to the external function which will
388         create a little bit of (template) code on the fly
389         for allowing the (stable pointed) Haskell closure
390         to be entered using an external calling convention
391         (stdcall, ccall).
392        -}
393       adj_args      = [ mkIntLitInt (ccallConvToInt cconv)
394                       , Var stbl_value
395                       , mkLit (MachLabel fe_nm mb_sz_args)
396                       , mkLit (mkStringLit arg_type_info)
397                       ]
398         -- name of external entry point providing these services.
399         -- (probably in the RTS.) 
400       adjustor   = FSLIT("createAdjustor")
401       
402       arg_type_info = map repCharCode arg_reps
403       repCharCode F32 = 'f'
404       repCharCode F64 = 'd'
405       repCharCode I64 = 'l'
406       repCharCode _   = 'i'
407
408         -- Determine the number of bytes of arguments to the stub function,
409         -- so that we can attach the '@N' suffix to its label if it is a
410         -- stdcall on Windows.
411       mb_sz_args = case cconv of
412                       StdCallConv -> Just args_size
413                       _           -> Nothing
414
415      in
416      dsCCall adjustor adj_args PlayRisky io_res_ty      `thenDs` \ ccall_adj ->
417         -- PlayRisky: the adjustor doesn't allocate in the Haskell heap or do a callback
418      let ccall_adj_ty = exprType ccall_adj
419          ccall_io_adj = mkLams [stbl_value]                  $
420                         Note (Coerce io_res_ty ccall_adj_ty)
421                              ccall_adj
422          io_app = mkLams tvs     $
423                   mkLams [cback] $
424                   stbl_app ccall_io_adj res_ty
425          fed = (id `setInlinePragma` NeverActive, io_app)
426                 -- Never inline the f.e.d. function, because the litlit
427                 -- might not be in scope in other modules.
428      in
429      returnDs ([fed], h_code, c_code)
430
431  where
432   ty                    = idType id
433   (tvs,sans_foralls)    = tcSplitForAllTys ty
434   ([arg_ty], io_res_ty) = tcSplitFunTys sans_foralls
435   [res_ty]              = tcTyConAppArgs io_res_ty
436         -- Must use tcSplit* to see the (IO t), which is a newtype
437
438 toCName :: Id -> String
439 toCName i = showSDoc (pprCode CStyle (ppr (idName i)))
440 \end{code}
441
442 %*
443 %
444 \subsection{Generating @foreign export@ stubs}
445 %
446 %*
447
448 For each @foreign export@ function, a C stub function is generated.
449 The C stub constructs the application of the exported Haskell function 
450 using the hugs/ghc rts invocation API.
451
452 \begin{code}
453 mkFExportCBits :: FastString
454                -> Maybe Id      -- Just==static, Nothing==dynamic
455                -> [Type] 
456                -> Type 
457                -> Bool          -- True <=> returns an IO type
458                -> CCallConv 
459                -> (SDoc, 
460                    SDoc,
461                    [MachRep],   -- the argument reps
462                    Int          -- total size of arguments
463                   )
464 mkFExportCBits c_nm maybe_target arg_htys res_hty is_IO_res_ty cc 
465  = (header_bits, c_bits, 
466     [rep | (_,_,_,rep) <- arg_info],  -- just the real args
467     sum [ machRepByteWidth rep | (_,_,_,rep) <- aug_arg_info] -- all the args
468     )
469  where
470   -- list the arguments to the C function
471   arg_info :: [(SDoc,           -- arg name
472                 SDoc,           -- C type
473                 Type,           -- Haskell type
474                 MachRep)]       -- the MachRep
475   arg_info  = [ (text ('a':show n), showStgType ty, ty, 
476                  typeMachRep (getPrimTyOf ty))
477               | (ty,n) <- zip arg_htys [1..] ]
478
479   -- add some auxiliary args; the stable ptr in the wrapper case, and
480   -- a slot for the dummy return address in the wrapper + ccall case
481   aug_arg_info
482     | isNothing maybe_target = stable_ptr_arg : insertRetAddr cc arg_info
483     | otherwise              = arg_info
484
485   stable_ptr_arg = 
486         (text "the_stableptr", text "StgStablePtr", undefined,
487          typeMachRep (mkStablePtrPrimTy alphaTy))
488
489   -- stuff to do with the return type of the C function
490   res_hty_is_unit = res_hty `coreEqType` unitTy -- Look through any newtypes
491
492   cResType | res_hty_is_unit = text "void"
493            | otherwise       = showStgType res_hty
494
495   -- Now we can cook up the prototype for the exported function.
496   pprCconv = case cc of
497                 CCallConv   -> empty
498                 StdCallConv -> text (ccallConvAttribute cc)
499
500   header_bits = ptext SLIT("extern") <+> fun_proto <> semi
501
502   fun_proto = cResType <+> pprCconv <+> ftext c_nm <>
503               parens (hsep (punctuate comma (map (\(nm,ty,_,_) -> ty <+> nm) 
504                                                  aug_arg_info)))
505
506   -- the target which will form the root of what we ask rts_evalIO to run
507   the_cfun
508      = case maybe_target of
509           Nothing    -> text "(StgClosure*)deRefStablePtr(the_stableptr)"
510           Just hs_fn -> char '&' <> ppr hs_fn <> text "_closure"
511
512   -- the expression we give to rts_evalIO
513   expr_to_run
514      = foldl appArg the_cfun arg_info -- NOT aug_arg_info
515        where
516           appArg acc (arg_cname, _, arg_hty, _) 
517              = text "rts_apply" 
518                <> parens (acc <> comma <> mkHObj arg_hty <> parens arg_cname)
519
520   -- various other bits for inside the fn
521   declareResult = text "HaskellObj ret;"
522   declareCResult | res_hty_is_unit = empty
523                  | otherwise       = cResType <+> text "cret;"
524
525   assignCResult | res_hty_is_unit = empty
526                 | otherwise       =
527                         text "cret=" <> unpackHObj res_hty <> parens (text "ret") <> semi
528
529   -- an extern decl for the fn being called
530   extern_decl
531      = case maybe_target of
532           Nothing -> empty
533           Just hs_fn -> text "extern StgClosure " <> ppr hs_fn <> text "_closure" <> semi
534
535    
536    -- Initialise foreign exports by registering a stable pointer from an
537    -- __attribute__((constructor)) function.
538    -- The alternative is to do this from stginit functions generated in
539    -- codeGen/CodeGen.lhs; however, stginit functions have a negative impact
540    -- on binary sizes and link times because the static linker will think that
541    -- all modules that are imported directly or indirectly are actually used by
542    -- the program.
543    -- (this is bad for big umbrella modules like Graphics.Rendering.OpenGL)
544
545   initialiser
546      = case maybe_target of
547           Nothing -> empty
548           Just hs_fn ->
549             vcat
550              [ text "static void stginit_export_" <> ppr hs_fn
551                   <> text "() __attribute__((constructor));"
552              , text "static void stginit_export_" <> ppr hs_fn <> text "()"
553              , braces (text "getStablePtr"
554                 <> parens (text "(StgPtr) &" <> ppr hs_fn <> text "_closure")
555                 <> semi)
556              ]
557
558   -- finally, the whole darn thing
559   c_bits =
560     space $$
561     extern_decl $$
562     fun_proto  $$
563     vcat 
564      [ lbrace
565      ,   text "SchedulerStatus rc;"
566      ,   declareResult
567      ,   declareCResult
568      ,   text "rts_lock();"
569           -- create the application + perform it.
570      ,   text "rc=rts_evalIO" <> parens (
571                 text "rts_apply" <> parens (
572                     text "(HaskellObj)"
573                  <> text (if is_IO_res_ty 
574                                 then "runIO_closure" 
575                                 else "runNonIO_closure")
576                  <> comma
577                  <> expr_to_run
578                 ) <+> comma
579                <> text "&ret"
580              ) <> semi
581      ,   text "rts_checkSchedStatus" <> parens (doubleQuotes (ftext c_nm)
582                                                 <> comma <> text "rc") <> semi
583      ,   assignCResult
584      ,   text "rts_unlock();"
585      ,   if res_hty_is_unit then empty
586             else text "return cret;"
587      , rbrace
588      ] $$
589     initialiser
590
591 -- NB. the calculation here isn't strictly speaking correct.
592 -- We have a primitive Haskell type (eg. Int#, Double#), and
593 -- we want to know the size, when passed on the C stack, of
594 -- the associated C type (eg. HsInt, HsDouble).  We don't have
595 -- this information to hand, but we know what GHC's conventions
596 -- are for passing around the primitive Haskell types, so we
597 -- use that instead.  I hope the two coincide --SDM
598 typeMachRep ty = argMachRep (typeCgRep ty)
599
600 mkHObj :: Type -> SDoc
601 mkHObj t = text "rts_mk" <> text (showFFIType t)
602
603 unpackHObj :: Type -> SDoc
604 unpackHObj t = text "rts_get" <> text (showFFIType t)
605
606 showStgType :: Type -> SDoc
607 showStgType t = text "Hs" <> text (showFFIType t)
608
609 showFFIType :: Type -> String
610 showFFIType t = getOccString (getName tc)
611  where
612   tc = case tcSplitTyConApp_maybe (repType t) of
613             Just (tc,_) -> tc
614             Nothing     -> pprPanic "showFFIType" (ppr t)
615
616 #if !defined(x86_64_TARGET_ARCH)
617 insertRetAddr CCallConv args = ret_addr_arg : args
618 insertRetAddr _ args = args
619 #else
620 -- On x86_64 we insert the return address after the 6th
621 -- integer argument, because this is the point at which we
622 -- need to flush a register argument to the stack (See rts/Adjustor.c for
623 -- details).
624 insertRetAddr CCallConv args = go 0 args
625   where  go 6 args = ret_addr_arg : args
626          go n (arg@(_,_,_,rep):args)
627           | I64 <- rep = arg : go (n+1) args
628           | otherwise  = arg : go n     args
629          go n [] = []
630 insertRetAddr _ args = args
631 #endif
632
633 ret_addr_arg = (text "original_return_addr", text "void*", undefined, 
634                 typeMachRep addrPrimTy)
635
636 -- This function returns the primitive type associated with the boxed
637 -- type argument to a foreign export (eg. Int ==> Int#).  It assumes
638 -- that all the types we are interested in have a single constructor
639 -- with a single primitive-typed argument, which is true for all of the legal
640 -- foreign export argument types (see TcType.legalFEArgTyCon).
641 getPrimTyOf :: Type -> Type
642 getPrimTyOf ty =
643   case splitProductType_maybe (repType ty) of
644      Just (_, _, data_con, [prim_ty]) ->
645         ASSERT(dataConSourceArity data_con == 1)
646         ASSERT2(isUnLiftedType prim_ty, ppr prim_ty)
647         prim_ty
648      _other -> pprPanic "DsForeign.getPrimTyOf" (ppr ty)
649 \end{code}