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