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, mkFCall, boxResult, unboxArg, resultWrapper )
18 import HsSyn ( ForeignDecl(..), ForeignExport(..),
19 ForeignImport(..), CImportSpec(..) )
20 import TcHsSyn ( TypecheckedForeignDecl )
21 import CoreUtils ( exprType, mkInlineMe )
22 import Id ( Id, idType, idName, mkSysLocal, setInlinePragma )
23 import Literal ( Literal(..) )
24 import Module ( moduleString )
25 import Name ( getOccString, NamedThing(..) )
26 import OccName ( encodeFS )
27 import Type ( repType, eqType, typePrimRep )
28 import TcType ( Type, mkFunTys, mkForAllTys, mkTyConApp,
29 mkFunTy, tcSplitTyConApp_maybe,
30 tcSplitForAllTys, tcSplitFunTys, tcTyConAppArgs,
33 import HscTypes ( ForeignStubs(..) )
34 import ForeignCall ( ForeignCall(..), CCallSpec(..),
37 CCallConv(..), ccallConvToInt,
40 import CStrings ( CLabelString )
41 import TysWiredIn ( unitTy, stablePtrTyCon )
42 import TysPrim ( addrPrimTy, mkStablePtrPrimTy, alphaTy )
43 import PrimRep ( getPrimRepSizeInBytes )
44 import PrelNames ( hasKey, ioTyConKey, newStablePtrName, bindIOName )
45 import BasicTypes ( Activation( NeverActive ) )
47 import Maybe ( fromJust )
51 Desugaring of @foreign@ declarations is naturally split up into
52 parts, an @import@ and an @export@ part. A @foreign import@
55 foreign import cc nm f :: prim_args -> IO prim_res
59 f :: prim_args -> IO prim_res
60 f a1 ... an = _ccall_ nm cc a1 ... an
62 so we reuse the desugaring code in @DsCCall@ to deal with these.
65 type Binding = (Id, CoreExpr) -- No rec/nonrec structure;
66 -- the occurrence analyser will sort it all out
68 dsForeigns :: [TypecheckedForeignDecl]
69 -> DsM (ForeignStubs, [Binding])
71 = returnDs (NoStubs, [])
73 = foldlDs combine (ForeignStubs empty empty [] [], []) fos
75 combine (ForeignStubs acc_h acc_c acc_hdrs acc_feb, acc_f)
76 (ForeignImport id _ spec depr loc)
77 = dsFImport id spec `thenDs` \ (bs, h, c, mbhd) ->
78 warnDepr depr loc `thenDs` \ _ ->
79 returnDs (ForeignStubs (h $$ acc_h)
85 combine (ForeignStubs acc_h acc_c acc_hdrs acc_feb, acc_f)
86 (ForeignExport id _ (CExport (CExportStatic ext_nm cconv)) depr loc)
87 = dsFExport id (idType id)
88 ext_nm cconv False `thenDs` \(h, c, _) ->
89 warnDepr depr loc `thenDs` \_ ->
90 returnDs (ForeignStubs (h $$ acc_h) (c $$ acc_c) acc_hdrs (id:acc_feb),
98 warnDepr False _ = returnDs ()
99 warnDepr True loc = dsWarn (loc, msg)
101 msg = ptext SLIT("foreign declaration uses deprecated non-standard syntax")
105 %************************************************************************
107 \subsection{Foreign import}
109 %************************************************************************
111 Desugaring foreign imports is just the matter of creating a binding
112 that on its RHS unboxes its arguments, performs the external call
113 (using the @CCallOp@ primop), before boxing the result up and returning it.
115 However, we create a worker/wrapper pair, thus:
117 foreign import f :: Int -> IO Int
119 f x = IO ( \s -> case x of { I# x# ->
120 case fw s x# of { (# s1, y# #) ->
123 fw s x# = ccall f s x#
125 The strictness/CPR analyser won't do this automatically because it doesn't look
126 inside returned tuples; but inlining this wrapper is a Really Good Idea
127 because it exposes the boxing to the call site.
132 -> DsM ([Binding], SDoc, SDoc, Maybe FastString)
133 dsFImport id (CImport cconv safety header lib spec)
134 = dsCImport id spec cconv safety no_hdrs `thenDs` \(ids, h, c) ->
135 returnDs (ids, h, c, if no_hdrs then Nothing else Just header)
137 no_hdrs = nullFastString header
139 -- FIXME: the `lib' field is needed for .NET ILX generation when invoking
140 -- routines that are external to the .NET runtime, but GHC doesn't
141 -- support such calls yet; if `nullFastString lib', the value was not given
142 dsFImport id (DNImport spec)
143 = dsFCall id (DNCall spec) True {- No headers -} `thenDs` \(ids, h, c) ->
144 returnDs (ids, h, c, Nothing)
150 -> Bool -- True <=> no headers in the f.i decl
151 -> DsM ([Binding], SDoc, SDoc)
152 dsCImport id (CLabel cid) _ _ no_hdrs
153 = ASSERT(fromJust resTy `eqType` addrPrimTy) -- typechecker ensures this
154 returnDs ([(setImpInline no_hdrs id, rhs)], empty, empty)
156 (resTy, foRhs) = resultWrapper (idType id)
157 rhs = foRhs (mkLit (MachLabel cid Nothing))
158 dsCImport id (CFunction target) cconv safety no_hdrs
159 = dsFCall id (CCall (CCallSpec target cconv safety)) no_hdrs
160 dsCImport id CWrapper cconv _ _
161 = dsFExportDynamic id cconv
163 setImpInline :: Bool -- True <=> No #include headers
164 -- in the foreign import declaration
166 -- If there is a #include header in the foreign import
167 -- we make the worker non-inlinable, because we currently
168 -- don't keep the #include stuff in the CCallId, and hence
169 -- it won't be visible in the importing module, which can be
171 -- (The #include stuff is just collected from the foreign import
172 -- decls in a module.)
173 -- If you want to do cross-module inlining of the c-calls themselves,
174 -- put the #include stuff in the package spec, not the foreign
176 setImpInline True id = id
177 setImpInline False id = id `setInlinePragma` NeverActive
181 %************************************************************************
183 \subsection{Foreign calls}
185 %************************************************************************
188 dsFCall fn_id fcall no_hdrs
191 (tvs, fun_ty) = tcSplitForAllTys ty
192 (arg_tys, io_res_ty) = tcSplitFunTys fun_ty
193 -- Must use tcSplit* functions because we want to
194 -- see that (IO t) in the corner
196 newSysLocalsDs arg_tys `thenDs` \ args ->
197 mapAndUnzipDs unboxArg (map Var args) `thenDs` \ (val_args, arg_wrappers) ->
200 work_arg_ids = [v | Var v <- val_args] -- All guaranteed to be vars
202 -- These are the ids we pass to boxResult, which are used to decide
203 -- whether to touch# an argument after the call (used to keep
204 -- ForeignObj#s live across a 'safe' foreign import).
205 maybe_arg_ids | unsafe_call fcall = work_arg_ids
208 boxResult maybe_arg_ids io_res_ty `thenDs` \ (ccall_result_ty, res_wrapper) ->
210 getUniqueDs `thenDs` \ ccall_uniq ->
211 getUniqueDs `thenDs` \ work_uniq ->
214 worker_ty = mkForAllTys tvs (mkFunTys (map idType work_arg_ids) ccall_result_ty)
215 the_ccall_app = mkFCall ccall_uniq fcall val_args ccall_result_ty
216 work_rhs = mkLams tvs (mkLams work_arg_ids the_ccall_app)
217 work_id = setImpInline no_hdrs $ -- See comments with setImpInline
218 mkSysLocal (encodeFS FSLIT("$wccall")) work_uniq worker_ty
221 work_app = mkApps (mkVarApps (Var work_id) tvs) val_args
222 wrapper_body = foldr ($) (res_wrapper work_app) arg_wrappers
223 wrap_rhs = mkInlineMe (mkLams (tvs ++ args) wrapper_body)
225 returnDs ([(work_id, work_rhs), (fn_id, wrap_rhs)], empty, empty)
227 unsafe_call (CCall (CCallSpec _ _ safety)) = playSafe safety
228 unsafe_call (DNCall _) = False
232 %************************************************************************
234 \subsection{Foreign export}
236 %************************************************************************
238 The function that does most of the work for `@foreign export@' declarations.
239 (see below for the boilerplate code a `@foreign export@' declaration expands
242 For each `@foreign export foo@' in a module M we generate:
244 \item a C function `@foo@', which calls
245 \item a Haskell stub `@M.$ffoo@', which calls
247 the user-written Haskell function `@M.foo@'.
250 dsFExport :: Id -- Either the exported Id,
251 -- or the foreign-export-dynamic constructor
252 -> Type -- The type of the thing callable from C
253 -> CLabelString -- The name to export to C land
255 -> Bool -- True => foreign export dynamic
256 -- so invoke IO action that's hanging off
257 -- the first argument's stable pointer
258 -> DsM ( SDoc -- contents of Module_stub.h
259 , SDoc -- contents of Module_stub.c
260 , [Type] -- arguments expected by stub function.
263 dsFExport fn_id ty ext_name cconv isDyn
266 (tvs,sans_foralls) = tcSplitForAllTys ty
267 (fe_arg_tys', orig_res_ty) = tcSplitFunTys sans_foralls
268 -- We must use tcSplits here, because we want to see
269 -- the (IO t) in the corner of the type!
270 fe_arg_tys | isDyn = tail fe_arg_tys'
271 | otherwise = fe_arg_tys'
273 -- Look at the result type of the exported function, orig_res_ty
274 -- If it's IO t, return (t, True)
275 -- If it's plain t, return (t, False)
276 (case tcSplitTyConApp_maybe orig_res_ty of
277 -- We must use tcSplit here so that we see the (IO t) in
278 -- the type. [IO t is transparent to plain splitTyConApp.]
280 Just (ioTyCon, [res_ty])
281 -> ASSERT( ioTyCon `hasKey` ioTyConKey )
282 -- The function already returns IO t
283 returnDs (res_ty, True)
285 other -> -- The function returns t
286 returnDs (orig_res_ty, False)
288 `thenDs` \ (res_ty, -- t
289 is_IO_res_ty) -> -- Bool
291 mkFExportCBits ext_name
292 (if isDyn then Nothing else Just fn_id)
293 fe_arg_tys res_ty is_IO_res_ty cconv
296 @foreign export dynamic@ lets you dress up Haskell IO actions
297 of some fixed type behind an externally callable interface (i.e.,
298 as a C function pointer). Useful for callbacks and stuff.
301 foreign export dynamic f :: (Addr -> Int -> IO Int) -> IO Addr
303 -- Haskell-visible constructor, which is generated from the above:
304 -- SUP: No check for NULL from createAdjustor anymore???
306 f :: (Addr -> Int -> IO Int) -> IO Addr
308 bindIO (newStablePtr cback)
309 (\StablePtr sp# -> IO (\s1# ->
310 case _ccall_ createAdjustor cconv sp# ``f_helper'' s1# of
311 (# s2#, a# #) -> (# s2#, A# a# #)))
313 foreign export "f_helper" f_helper :: StablePtr (Addr -> Int -> IO Int) -> Addr -> Int -> IO Int
314 -- `special' foreign export that invokes the closure pointed to by the
319 dsFExportDynamic :: Id
321 -> DsM ([Binding], SDoc, SDoc)
322 dsFExportDynamic id cconv
323 = newSysLocalDs ty `thenDs` \ fe_id ->
324 getModuleDs `thenDs` \ mod_name ->
326 -- hack: need to get at the name of the C stub we're about to generate.
327 fe_nm = mkFastString (moduleString mod_name ++ "_" ++ toCName fe_id)
329 dsFExport id export_ty fe_nm cconv True `thenDs` \ (h_code, c_code, stub_args) ->
330 newSysLocalDs arg_ty `thenDs` \ cback ->
331 dsLookupGlobalId newStablePtrName `thenDs` \ newStablePtrId ->
333 mk_stbl_ptr_app = mkApps (Var newStablePtrId) [ Type arg_ty, Var cback ]
335 dsLookupGlobalId bindIOName `thenDs` \ bindIOId ->
336 newSysLocalDs (mkTyConApp stablePtrTyCon [arg_ty]) `thenDs` \ stbl_value ->
339 = mkApps (Var bindIOId)
340 [ Type (mkTyConApp stablePtrTyCon [arg_ty])
347 The arguments to the external function which will
348 create a little bit of (template) code on the fly
349 for allowing the (stable pointed) Haskell closure
350 to be entered using an external calling convention
353 adj_args = [ mkIntLitInt (ccallConvToInt cconv)
355 , mkLit (MachLabel fe_nm mb_sz_args)
357 -- name of external entry point providing these services.
358 -- (probably in the RTS.)
359 adjustor = FSLIT("createAdjustor")
363 StdCallConv -> Just (sum (map (getPrimRepSizeInBytes . typePrimRep) stub_args))
366 dsCCall adjustor adj_args PlayRisky False io_res_ty `thenDs` \ ccall_adj ->
367 -- PlayRisky: the adjustor doesn't allocate in the Haskell heap or do a callback
368 let ccall_adj_ty = exprType ccall_adj
369 ccall_io_adj = mkLams [stbl_value] $
370 Note (Coerce io_res_ty ccall_adj_ty)
372 io_app = mkLams tvs $
374 stbl_app ccall_io_adj res_ty
375 fed = (id `setInlinePragma` NeverActive, io_app)
376 -- Never inline the f.e.d. function, because the litlit
377 -- might not be in scope in other modules.
379 returnDs ([fed], h_code, c_code)
383 (tvs,sans_foralls) = tcSplitForAllTys ty
384 ([arg_ty], io_res_ty) = tcSplitFunTys sans_foralls
385 [res_ty] = tcTyConAppArgs io_res_ty
386 -- Must use tcSplit* to see the (IO t), which is a newtype
387 export_ty = mkFunTy (mkTyConApp stablePtrTyCon [arg_ty]) arg_ty
389 toCName :: Id -> String
390 toCName i = showSDoc (pprCode CStyle (ppr (idName i)))
395 \subsection{Generating @foreign export@ stubs}
399 For each @foreign export@ function, a C stub function is generated.
400 The C stub constructs the application of the exported Haskell function
401 using the hugs/ghc rts invocation API.
404 mkFExportCBits :: FastString
405 -> Maybe Id -- Just==static, Nothing==dynamic
408 -> Bool -- True <=> returns an IO type
410 -> (SDoc, SDoc, [Type])
411 mkFExportCBits c_nm maybe_target arg_htys res_hty is_IO_res_ty cc
412 = (header_bits, c_bits, all_arg_tys)
414 -- Create up types and names for the real args
415 arg_cnames, arg_ctys :: [SDoc]
416 arg_cnames = mkCArgNames 1 arg_htys
417 arg_ctys = map showStgType arg_htys
419 -- and also for auxiliary ones; the stable ptr in the dynamic case, and
420 -- a slot for the dummy return address in the dynamic + ccall case
422 = case maybe_target of
423 Nothing -> [((text "the_stableptr", text "StgStablePtr"), mkStablePtrPrimTy alphaTy)]
426 case (maybe_target, cc) of
427 (Nothing, CCallConv) -> [((text "original_return_addr", text "void*"), addrPrimTy)]
430 all_cnames_and_ctys :: [(SDoc, SDoc)]
432 = map fst extra_cnames_and_tys ++ zip arg_cnames arg_ctys
435 = map snd extra_cnames_and_tys ++ arg_htys
437 -- stuff to do with the return type of the C function
438 res_hty_is_unit = res_hty `eqType` unitTy -- Look through any newtypes
440 cResType | res_hty_is_unit = text "void"
441 | otherwise = showStgType res_hty
443 -- Now we can cook up the prototype for the exported function.
444 pprCconv = case cc of
446 StdCallConv -> text (ccallConvAttribute cc)
448 header_bits = ptext SLIT("extern") <+> fun_proto <> semi
450 fun_proto = cResType <+> pprCconv <+> ftext c_nm <>
451 parens (hsep (punctuate comma (map (\(nm,ty) -> ty <+> nm)
452 all_cnames_and_ctys)))
454 -- the target which will form the root of what we ask rts_evalIO to run
456 = case maybe_target of
457 Nothing -> text "(StgClosure*)deRefStablePtr(the_stableptr)"
458 Just hs_fn -> char '&' <> ppr hs_fn <> text "_closure"
460 -- the expression we give to rts_evalIO
462 = foldl appArg the_cfun (zip arg_cnames arg_htys)
464 appArg acc (arg_cname, arg_hty)
466 <> parens (acc <> comma <> mkHObj arg_hty <> parens arg_cname)
468 -- various other bits for inside the fn
469 declareResult = text "HaskellObj ret;"
470 declareCResult | res_hty_is_unit = empty
471 | otherwise = cResType <+> text "cret;"
473 assignCResult | res_hty_is_unit = empty
475 text "cret=" <> unpackHObj res_hty <> parens (text "ret") <> semi
477 -- an extern decl for the fn being called
479 = case maybe_target of
481 Just hs_fn -> text "extern StgClosure " <> ppr hs_fn <> text "_closure" <> semi
483 -- finally, the whole darn thing
490 , text "SchedulerStatus rc;"
494 -- create the application + perform it.
495 , text "rc=rts_evalIO" <> parens (
496 text "rts_apply" <> parens (
498 <> text (if is_IO_res_ty
500 else "runNonIO_closure")
506 , text "rts_checkSchedStatus" <> parens (doubleQuotes (ftext c_nm)
507 <> comma <> text "rc") <> semi
509 , text "rts_unlock();"
510 , if res_hty_is_unit then empty
511 else text "return cret;"
516 mkCArgNames :: Int -> [a] -> [SDoc]
517 mkCArgNames n as = zipWith (\ _ n -> text ('a':show n)) as [n..]
519 mkHObj :: Type -> SDoc
520 mkHObj t = text "rts_mk" <> text (showFFIType t)
522 unpackHObj :: Type -> SDoc
523 unpackHObj t = text "rts_get" <> text (showFFIType t)
525 showStgType :: Type -> SDoc
526 showStgType t = text "Hs" <> text (showFFIType t)
528 showFFIType :: Type -> String
529 showFFIType t = getOccString (getName tc)
531 tc = case tcSplitTyConApp_maybe (repType t) of
533 Nothing -> pprPanic "showFFIType" (ppr t)