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