2 % (c) The AQUA Project, Glasgow University, 1998
4 \section[DsCCall]{Desugaring \tr{foreign} declarations}
6 Expanding out @foreign import@ and @foreign export@ declarations.
9 module DsForeign ( dsForeigns ) where
11 #include "HsVersions.h"
15 import DsCCall ( dsCCall, mkCCall, boxResult, unboxArg, wrapUnboxedValue )
19 import HsSyn ( ExtName(..), ForeignDecl(..), isDynamicExtName, ForKind(..) )
20 import HsDecls ( extNameStatic )
22 import TcHsSyn ( TypecheckedForeignDecl )
23 import CoreUtils ( exprType, mkInlineMe, bindNonRec )
24 import DataCon ( DataCon, dataConWrapId )
25 import Id ( Id, idType, idName, mkWildId, mkVanillaId )
26 import MkId ( mkCCallOpId, mkWorkerId )
27 import Literal ( Literal(..) )
28 import Module ( Module, moduleUserString )
29 import Name ( mkGlobalName, nameModule, nameOccName, getOccString,
30 mkForeignExportOcc, isLocalName,
31 NamedThing(..), Provenance(..), ExportFlag(..)
33 import PrelInfo ( deRefStablePtr_NAME, bindIO_NAME, makeStablePtr_NAME, realWorldPrimId )
34 import Type ( splitAlgTyConApp_maybe, unUsgTy,
35 splitTyConApp_maybe, splitFunTys, splitForAllTys,
36 Type, mkFunTys, mkForAllTys, mkTyConApp,
37 mkTyVarTy, mkFunTy, splitAppTy
39 import PrimOp ( PrimOp(..), CCall(..), CCallTarget(..) )
41 import TysPrim ( realWorldStatePrimTy, addrPrimTy )
42 import TysWiredIn ( unitTyCon, addrTy, stablePtrTyCon,
43 unboxedTupleCon, addrDataCon
46 import Maybes ( maybeToBool )
49 #if __GLASGOW_HASKELL__ >= 404
50 import GlaExts ( fromInt )
54 Desugaring of @foreign@ declarations is naturally split up into
55 parts, an @import@ and an @export@ part. A @foreign import@
58 foreign import cc nm f :: prim_args -> IO prim_res
62 f :: prim_args -> IO prim_res
63 f a1 ... an = _ccall_ nm cc a1 ... an
65 so we reuse the desugaring code in @DsCCall@ to deal with these.
69 -> [TypecheckedForeignDecl]
70 -> DsM ( [CoreBind] -- desugared foreign imports
71 , [CoreBind] -- helper functions for foreign exports
72 , SDoc -- Header file prototypes for
73 -- "foreign exported" functions.
74 , SDoc -- C stubs to use when calling
75 -- "foreign exported" functions.
77 dsForeigns mod_name fos = foldlDs combine ([],[],empty,empty) fos
79 combine (acc_fi, acc_fe, acc_h, acc_c) fo@(ForeignDecl i imp_exp _ ext_nm cconv _)
80 | isForeignImport = -- foreign import (dynamic)?
81 dsFImport i (idType i) uns ext_nm cconv `thenDs` \ bs ->
82 returnDs (bs ++ acc_fi, acc_fe, acc_h, acc_c)
84 dsFLabel i ext_nm `thenDs` \ b ->
85 returnDs (b:acc_fi, acc_fe, acc_h, acc_c)
86 | isDynamicExtName ext_nm =
87 dsFExportDynamic i (idType i) mod_name ext_nm cconv `thenDs` \ (fi,fe,h,c) ->
88 returnDs (fi:acc_fi, fe:acc_fe, h $$ acc_h, c $$ acc_c)
90 | otherwise = -- foreign export
91 dsFExport i (idType i) mod_name ext_nm cconv False `thenDs` \ (fe,h,c) ->
92 returnDs (acc_fi, fe:acc_fe, h $$ acc_h, c $$ acc_c)
104 (FoImport uns) = imp_exp
108 Desugaring foreign imports is just the matter of creating a binding
109 that on its RHS unboxes its arguments, performs the external call
110 (using the @CCallOp@ primop), before boxing the result up and returning it.
112 However, we create a worker/wrapper pair, thus:
114 foreign import f :: Int -> IO Int
116 f x = IO ( \s -> case x of { I# x# ->
117 case fw s x# of { (# s1, y# #) ->
120 fw s x# = ccall f s x#
122 The strictness/CPR analyser won't do this automatically because it doesn't look
123 inside returned tuples; but inlining this wrapper is a Really Good Idea
124 because it exposes the boxing to the call site.
129 -> Type -- Type of foreign import.
130 -> Bool -- True <=> might cause Haskell GC
134 dsFImport fn_id ty may_not_gc ext_name cconv
136 (tvs, arg_tys, mbIoDataCon, io_res_ty) = splitForeignTyDs ty
137 is_io_action = maybeToBool mbIoDataCon
139 newSysLocalsDs arg_tys `thenDs` \ args ->
140 newSysLocalDs realWorldStatePrimTy `thenDs` \ old_s ->
141 mapAndUnzipDs unboxArg (map Var args) `thenDs` \ (unboxed_args, arg_wrappers) ->
143 (if not is_io_action then
144 newSysLocalDs realWorldStatePrimTy `thenDs` \ state_tok ->
145 wrapUnboxedValue io_res_ty `thenDs` \ (ccall_result_ty, v, res_v) ->
146 returnDs ( ccall_result_ty
147 , \ prim_app -> Case prim_app (mkWildId ccall_result_ty)
148 [(DataAlt (unboxedTupleCon 2), [state_tok, v], res_v)])
150 boxResult io_res_ty) `thenDs` \ (ccall_result_ty, res_wrapper) ->
153 Dynamic -> getUniqueDs `thenDs` \ u ->
154 returnDs (DynamicTarget u)
155 ExtName fs _ -> returnDs (StaticTarget fs)) `thenDs` \ lbl ->
157 getUniqueDs `thenDs` \ ccall_uniq ->
158 getUniqueDs `thenDs` \ work_uniq ->
160 the_state_arg | is_io_action = old_s
161 | otherwise = realWorldPrimId
164 val_args = Var the_state_arg : unboxed_args
165 work_arg_ids = [v | Var v <- val_args] -- All guaranteed to be vars
166 worker_ty = mkForAllTys tvs (mkFunTys (map idType work_arg_ids) ccall_result_ty)
167 the_ccall = CCall lbl False (not may_not_gc) cconv
168 the_ccall_app = mkCCall ccall_uniq the_ccall val_args ccall_result_ty
169 work_rhs = mkLams tvs (mkLams work_arg_ids the_ccall_app)
170 work_id = mkWorkerId work_uniq fn_id worker_ty
173 work_app = mkApps (mkVarApps (Var work_id) tvs) val_args
174 wrapper_body = foldr ($) (res_wrapper work_app) arg_wrappers
175 io_app = case mbIoDataCon of
176 Nothing -> wrapper_body
177 Just ioDataCon -> mkApps (Var (dataConWrapId ioDataCon))
178 [Type io_res_ty, Lam old_s wrapper_body]
179 wrap_rhs = mkInlineMe (mkLams (tvs ++ args) io_app)
181 returnDs [NonRec fn_id wrap_rhs, NonRec work_id work_rhs]
184 Given the type of a foreign import declaration, split it up into
185 its constituent parts.
188 splitForeignTyDs :: Type -> ([TyVar], [Type], Maybe DataCon, Type)
190 = case splitAlgTyConApp_maybe res_ty of
191 Just (_,(io_res_ty:_),(ioCon:_)) -> -- .... -> IO t
192 (tvs, arg_tys, Just ioCon, io_res_ty)
194 (tvs, arg_tys, Nothing, res_ty)
196 (arg_tys, res_ty) = splitFunTys sans_foralls
197 (tvs, sans_foralls) = splitForAllTys ty
203 dsFLabel :: Id -> ExtName -> DsM CoreBind
204 dsFLabel nm ext_name = returnDs (NonRec nm fo_rhs)
206 fo_rhs = mkConApp addrDataCon [mkLit (MachLitLit enm addrPrimTy)]
207 enm = extNameStatic ext_name
210 The function that does most of the work for `@foreign export@' declarations.
211 (see below for the boilerplate code a `@foreign export@' declaration expands
214 For each `@foreign export foo@' in a module M we generate:
216 \item a C function `@foo@', which calls
217 \item a Haskell stub `@M.$ffoo@', which calls
219 the user-written Haskell function `@M.foo@'.
223 -> Type -- Type of foreign export.
227 -> Bool -- True => invoke IO action that's hanging off
228 -- the first argument's stable pointer
233 dsFExport i ty mod_name ext_name cconv isDyn =
234 getUniqueDs `thenDs` \ uniq ->
235 getSrcLocDs `thenDs` \ src_loc ->
237 f_helper_glob = mkVanillaId helper_name helper_ty
241 | isLocalName name = mod_name
242 | otherwise = nameModule name
244 occ = mkForeignExportOcc (nameOccName name)
245 prov = LocalDef src_loc Exported
246 helper_name = mkGlobalName uniq mod occ prov
248 newSysLocalsDs fe_arg_tys `thenDs` \ fe_args ->
250 newSysLocalDs stbl_ptr_ty `thenDs` \ stbl_ptr ->
251 newSysLocalDs stbl_ptr_to_ty `thenDs` \ stbl_value ->
252 dsLookupGlobalValue deRefStablePtr_NAME `thenDs` \ deRefStablePtrId ->
254 the_deref_app = mkApps (Var deRefStablePtrId)
255 [ Type stbl_ptr_to_ty, Var stbl_ptr ]
257 newSysLocalDs (exprType the_deref_app) `thenDs` \ x_deref_app ->
258 dsLookupGlobalValue bindIO_NAME `thenDs` \ bindIOId ->
259 newSysLocalDs (mkFunTy stbl_ptr_to_ty
260 (mkTyConApp ioTyCon [res_ty])) `thenDs` \ x_cont ->
263 bindNonRec x_cont (mkLams [stbl_value] cont) $
264 bindNonRec x_deref_app the_deref_app
265 (mkApps (Var bindIOId)
266 [ Type stbl_ptr_to_ty
271 returnDs (stbl_value, stbl_app, stbl_ptr)
275 panic "stbl_ptr" -- should never be touched.
276 )) `thenDs` \ (i, getFun_wrapper, stbl_ptr) ->
279 | isDyn = stbl_ptr:fe_args
280 | otherwise = fe_args
283 | isDyn = stbl_ptr_ty:helper_arg_tys
284 | otherwise = helper_arg_tys
288 mkApps (Var i) (map (Type . mkTyVarTy) tvs ++ map Var fe_args)
290 getModuleDs `thenDs` \ mod ->
291 getUniqueDs `thenDs` \ uniq ->
293 the_body = mkLams (tvs ++ wrapper_args) the_app
294 c_nm = extNameStatic ext_name
296 (h_stub, c_stub) = fexportEntry (moduleUserString mod)
298 wrapper_arg_tys the_result_ty cconv isDyn
300 returnDs (NonRec f_helper_glob the_body, h_stub, c_stub)
304 (tvs,sans_foralls) = splitForAllTys ty
305 (fe_arg_tys', io_res) = splitFunTys sans_foralls
308 Just (ioTyCon, [res_ty]) = splitTyConApp_maybe io_res
310 (_, stbl_ptr_ty') = splitForAllTys stbl_ptr_ty
311 (_, stbl_ptr_to_ty) = splitAppTy stbl_ptr_ty'
314 | isDyn = tail fe_arg_tys'
315 | otherwise = fe_arg_tys'
317 (stbl_ptr_ty, helper_arg_tys) =
319 (x:xs) | isDyn -> (x,xs)
320 ls -> (error "stbl_ptr_ty", ls)
324 mkFunTys arg_tys io_res
327 | isDyn = stbl_ptr_ty : helper_arg_tys
328 | otherwise = helper_arg_tys
331 case splitTyConApp_maybe io_res of
333 case splitTyConApp_maybe res_ty of
334 Just (tc,_) | getUnique tc /= getUnique unitTyCon -> Just res_ty
340 @foreign export dynamic@ lets you dress up Haskell IO actions
341 of some fixed type behind an externally callable interface (i.e.,
342 as a C function pointer). Useful for callbacks and stuff.
345 foreign export stdcall f :: (Addr -> Int -> IO Int) -> IO Addr
347 -- Haskell-visible constructor, which is generated from the
350 f :: (Addr -> Int -> IO Int) -> IO Addr
351 f cback = IO ( \ s1# ->
352 case makeStablePtr# cback s1# of { StateAndStablePtr# s2# sp# ->
353 case _ccall_ "mkAdjustor" sp# ``f_helper'' s2# of
354 StateAndAddr# s3# a# ->
364 foreign export "f_helper" f_helper :: StablePtr (Addr -> Int -> IO Int) -> Addr -> Int -> IO Int
365 -- `special' foreign export that invokes the closure pointed to by the
370 dsFExportDynamic :: Id
371 -> Type -- Type of foreign export.
375 -> DsM (CoreBind, CoreBind, SDoc, SDoc)
376 dsFExportDynamic i ty mod_name ext_name cconv =
377 newSysLocalDs ty `thenDs` \ fe_id ->
379 -- hack: need to get at the name of the C stub we're about to generate.
380 fe_nm = toCName fe_id
381 fe_ext_name = ExtName (_PK_ fe_nm) Nothing
383 dsFExport i export_ty mod_name fe_ext_name cconv True
384 `thenDs` \ (fe@(NonRec fe_helper fe_expr), h_code, c_code) ->
385 newSysLocalDs arg_ty `thenDs` \ cback ->
386 dsLookupGlobalValue makeStablePtr_NAME `thenDs` \ makeStablePtrId ->
388 mk_stbl_ptr_app = mkApps (Var makeStablePtrId) [ Type arg_ty, Var cback ]
389 mk_stbl_ptr_app_ty = exprType mk_stbl_ptr_app
391 newSysLocalDs mk_stbl_ptr_app_ty `thenDs` \ x_mk_stbl_ptr_app ->
392 dsLookupGlobalValue bindIO_NAME `thenDs` \ bindIOId ->
393 newSysLocalDs (mkTyConApp stablePtrTyCon [arg_ty]) `thenDs` \ stbl_value ->
395 stbl_app = \ x_cont cont ret_ty ->
396 bindNonRec x_cont cont $
397 bindNonRec x_mk_stbl_ptr_app mk_stbl_ptr_app $
398 (mkApps (Var bindIOId)
399 [ Type (mkTyConApp stablePtrTyCon [arg_ty])
401 , Var x_mk_stbl_ptr_app
406 The arguments to the external function which will
407 create a little bit of (template) code on the fly
408 for allowing the (stable pointed) Haskell closure
409 to be entered using an external calling convention
412 adj_args = [ mkIntLitInt (callConvToInt cconv)
414 , mkLit (MachLitLit (_PK_ fe_nm) addrPrimTy)
416 -- name of external entry point providing these services.
417 -- (probably in the RTS.)
418 adjustor = SLIT("createAdjustor")
420 dsCCall adjustor adj_args False False addrTy `thenDs` \ ccall_adj ->
421 let ccall_adj_ty = exprType ccall_adj
423 newSysLocalDs ccall_adj_ty `thenDs` \ x_ccall_adj ->
425 mkLams [stbl_value] $
426 bindNonRec x_ccall_adj ccall_adj $
427 Note (Coerce (mkTyConApp ioTyCon [res_ty]) (unUsgTy ccall_adj_ty))
430 newSysLocalDs (exprType ccall_io_adj) `thenDs` \ x_ccall_io_adj ->
431 let io_app = mkLams tvs $
433 stbl_app x_ccall_io_adj ccall_io_adj addrTy
435 returnDs (NonRec i io_app, fe, h_code, c_code)
438 (tvs,sans_foralls) = splitForAllTys ty
439 ([arg_ty], io_res) = splitFunTys sans_foralls
441 Just (ioTyCon, [res_ty]) = splitTyConApp_maybe io_res
443 export_ty = mkFunTy (mkTyConApp stablePtrTyCon [arg_ty]) arg_ty
445 toCName :: Id -> String
446 toCName i = showSDoc (pprCode CStyle (ppr (idName i)))
452 \subsection{Generating @foreign export@ stubs}
456 For each @foreign export@ function, a C stub function is generated.
457 The C stub constructs the application of the exported Haskell function
458 using the hugs/ghc rts invocation API.
461 fexportEntry :: String
469 fexportEntry mod_nm c_nm helper args res cc isDyn = (header_bits, c_bits)
471 -- name of the (Haskell) helper function generated by the desugarer.
472 h_nm = ppr helper <> text "_closure"
473 -- prototype for the exported function.
474 header_bits = ptext SLIT("extern") <+> fun_proto <> semi
476 fun_proto = cResType <+> pprCconv <+> ptext c_nm <>
477 parens (hsep (punctuate comma (zipWith (<+>) cParamTypes proto_args)))
484 , text "SchedulerStatus rc;"
486 -- create the application + perform it.
487 , text "rc=rts_evalIO" <>
488 parens (foldl appArg (text "(StgClosure*)&" <> h_nm) (zip args c_args) <> comma <> text "&ret") <> semi
494 text "rts_apply" <> parens (acc <> comma <> mkHObj a <> parens c_a)
496 cParamTypes = map showStgType real_args
500 Nothing -> text "void"
501 Just t -> showStgType t
504 | cc == cCallConv = empty
505 | otherwise = pprCallConv cc
507 declareResult = text "HaskellObj ret;"
509 externDecl = mkExtern (text "HaskellObj") h_nm
511 mkExtern ty nm = text "extern" <+> ty <+> nm <> semi
514 text "rts_checkSchedStatus" <>
515 parens (doubleQuotes (text mod_nm <> char '.' <> ptext c_nm) <> comma <> text "rc") <> semi $$
517 Nothing -> text "return"
518 Just _ -> text "return" <> parens (res_name)) <> semi
523 Just t -> unpackHObj t <> parens (text "ret")
525 c_args = mkCArgNames 0 args
528 If we're generating an entry point for a 'foreign export ccall dynamic',
529 then we receive the return address of the C function that wants to
530 invoke a Haskell function as any other C function, as second arg.
531 This arg is unused within the body of the generated C stub, but
532 needed by the Adjustor.c code to get the stack cleanup right.
534 (proto_args, real_args)
535 | cc == cCallConv && isDyn = ( text "a0" : text "a_" : mkCArgNames 1 (tail args)
536 , head args : addrTy : tail args)
537 | otherwise = (mkCArgNames 0 args, args)
539 mkCArgNames :: Int -> [a] -> [SDoc]
540 mkCArgNames n as = zipWith (\ _ n -> text ('a':show n)) as [n..]
542 mkHObj :: Type -> SDoc
543 mkHObj t = text "rts_mk" <> text (showFFIType t)
545 unpackHObj :: Type -> SDoc
546 unpackHObj t = text "rts_get" <> text (showFFIType t)
548 showStgType :: Type -> SDoc
549 showStgType t = text "Stg" <> text (showFFIType t)
551 showFFIType :: Type -> String
552 showFFIType t = getOccString (getName tc)
554 tc = case splitTyConApp_maybe t of
556 Nothing -> pprPanic "showFFIType" (ppr t)