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