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 )
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 )
43 import PrelNames ( hasKey, ioTyConKey, newStablePtrName, bindIOName )
44 import BasicTypes ( Activation( NeverActive ) )
46 import Maybe ( fromJust )
50 Desugaring of @foreign@ declarations is naturally split up into
51 parts, an @import@ and an @export@ part. A @foreign import@
54 foreign import cc nm f :: prim_args -> IO prim_res
58 f :: prim_args -> IO prim_res
59 f a1 ... an = _ccall_ nm cc a1 ... an
61 so we reuse the desugaring code in @DsCCall@ to deal with these.
64 type Binding = (Id, CoreExpr) -- No rec/nonrec structure;
65 -- the occurrence analyser will sort it all out
67 dsForeigns :: [TypecheckedForeignDecl]
68 -> DsM (ForeignStubs, [Binding])
70 = returnDs (NoStubs, [])
72 = foldlDs combine (ForeignStubs empty empty [] [], []) fos
74 combine (ForeignStubs acc_h acc_c acc_hdrs acc_feb, acc_f)
75 (ForeignImport id _ spec depr loc)
76 = dsFImport id spec `thenDs` \(bs, h, c, hd) ->
77 warnDepr depr loc `thenDs` \_ ->
78 returnDs (ForeignStubs (h $$ acc_h) (c $$ acc_c) (hd ++ acc_hdrs) acc_feb,
81 combine (ForeignStubs acc_h acc_c acc_hdrs acc_feb, acc_f)
82 (ForeignExport id _ (CExport (CExportStatic ext_nm cconv)) depr loc)
83 = dsFExport id (idType id)
84 ext_nm cconv False `thenDs` \(h, c) ->
85 warnDepr depr loc `thenDs` \_ ->
86 returnDs (ForeignStubs (h $$ acc_h) (c $$ acc_c) acc_hdrs (id:acc_feb),
89 warnDepr False _ = returnDs ()
90 warnDepr True loc = dsWarn (loc, msg)
92 msg = ptext SLIT("foreign declaration uses deprecated non-standard syntax")
96 %************************************************************************
98 \subsection{Foreign import}
100 %************************************************************************
102 Desugaring foreign imports is just the matter of creating a binding
103 that on its RHS unboxes its arguments, performs the external call
104 (using the @CCallOp@ primop), before boxing the result up and returning it.
106 However, we create a worker/wrapper pair, thus:
108 foreign import f :: Int -> IO Int
110 f x = IO ( \s -> case x of { I# x# ->
111 case fw s x# of { (# s1, y# #) ->
114 fw s x# = ccall f s x#
116 The strictness/CPR analyser won't do this automatically because it doesn't look
117 inside returned tuples; but inlining this wrapper is a Really Good Idea
118 because it exposes the boxing to the call site.
123 -> DsM ([Binding], SDoc, SDoc, [FastString])
124 dsFImport id (CImport cconv safety header lib spec)
125 = dsCImport id spec cconv safety no_hdrs `thenDs` \(ids, h, c) ->
126 returnDs (ids, h, c, if no_hdrs then [] else [header])
128 no_hdrs = nullFastString header
130 -- FIXME: the `lib' field is needed for .NET ILX generation when invoking
131 -- routines that are external to the .NET runtime, but GHC doesn't
132 -- support such calls yet; if `nullFastString lib', the value was not given
133 dsFImport id (DNImport spec)
134 = dsFCall id (DNCall spec) True {- No headers -} `thenDs` \(ids, h, c) ->
135 returnDs (ids, h, c, [])
141 -> Bool -- True <=> no headers in the f.i decl
142 -> DsM ([Binding], SDoc, SDoc)
143 dsCImport id (CLabel cid) _ _ no_hdrs
144 = ASSERT(fromJust resTy `eqType` addrPrimTy) -- typechecker ensures this
145 returnDs ([(setImpInline no_hdrs id, rhs)], empty, empty)
147 (resTy, foRhs) = resultWrapper (idType id)
148 rhs = foRhs (mkLit (MachLabel cid))
149 dsCImport id (CFunction target) cconv safety no_hdrs
150 = dsFCall id (CCall (CCallSpec target cconv safety)) no_hdrs
151 dsCImport id CWrapper cconv _ _
152 = dsFExportDynamic id cconv
154 setImpInline :: Bool -- True <=> No #include headers
155 -- in the foreign import declaration
157 -- If there is a #include header in the foreign import
158 -- we make the worker non-inlinable, because we currently
159 -- don't keep the #include stuff in the CCallId, and hence
160 -- it won't be visible in the importing module, which can be
162 -- (The #include stuff is just collected from the foreign import
163 -- decls in a module.)
164 -- If you want to do cross-module inlining of the c-calls themselves,
165 -- put the #include stuff in the package spec, not the foreign
167 setImpInline True id = id
168 setImpInline False id = id `setInlinePragma` NeverActive
172 %************************************************************************
174 \subsection{Foreign calls}
176 %************************************************************************
179 dsFCall fn_id fcall no_hdrs
182 (tvs, fun_ty) = tcSplitForAllTys ty
183 (arg_tys, io_res_ty) = tcSplitFunTys fun_ty
184 -- Must use tcSplit* functions because we want to
185 -- see that (IO t) in the corner
187 newSysLocalsDs arg_tys `thenDs` \ args ->
188 mapAndUnzipDs unboxArg (map Var args) `thenDs` \ (val_args, arg_wrappers) ->
191 work_arg_ids = [v | Var v <- val_args] -- All guaranteed to be vars
193 -- These are the ids we pass to boxResult, which are used to decide
194 -- whether to touch# an argument after the call (used to keep
195 -- ForeignObj#s live across a 'safe' foreign import).
196 maybe_arg_ids | unsafe_call fcall = work_arg_ids
199 boxResult maybe_arg_ids io_res_ty `thenDs` \ (ccall_result_ty, res_wrapper) ->
201 getUniqueDs `thenDs` \ ccall_uniq ->
202 getUniqueDs `thenDs` \ work_uniq ->
205 worker_ty = mkForAllTys tvs (mkFunTys (map idType work_arg_ids) ccall_result_ty)
206 the_ccall_app = mkFCall ccall_uniq fcall val_args ccall_result_ty
207 work_rhs = mkLams tvs (mkLams work_arg_ids the_ccall_app)
208 work_id = setImpInline no_hdrs $ -- See comments with setImpInline
209 mkSysLocal (encodeFS FSLIT("$wccall")) work_uniq worker_ty
212 work_app = mkApps (mkVarApps (Var work_id) tvs) val_args
213 wrapper_body = foldr ($) (res_wrapper work_app) arg_wrappers
214 wrap_rhs = mkInlineMe (mkLams (tvs ++ args) wrapper_body)
216 returnDs ([(work_id, work_rhs), (fn_id, wrap_rhs)], empty, empty)
218 unsafe_call (CCall (CCallSpec _ _ safety)) = playSafe safety
219 unsafe_call (DNCall _) = False
223 %************************************************************************
225 \subsection{Foreign export}
227 %************************************************************************
229 The function that does most of the work for `@foreign export@' declarations.
230 (see below for the boilerplate code a `@foreign export@' declaration expands
233 For each `@foreign export foo@' in a module M we generate:
235 \item a C function `@foo@', which calls
236 \item a Haskell stub `@M.$ffoo@', which calls
238 the user-written Haskell function `@M.foo@'.
241 dsFExport :: Id -- Either the exported Id,
242 -- or the foreign-export-dynamic constructor
243 -> Type -- The type of the thing callable from C
244 -> CLabelString -- The name to export to C land
246 -> Bool -- True => foreign export dynamic
247 -- so invoke IO action that's hanging off
248 -- the first argument's stable pointer
249 -> DsM ( SDoc -- contents of Module_stub.h
250 , SDoc -- contents of Module_stub.c
253 dsFExport fn_id ty ext_name cconv isDyn
256 (tvs,sans_foralls) = tcSplitForAllTys ty
257 (fe_arg_tys', orig_res_ty) = tcSplitFunTys sans_foralls
258 -- We must use tcSplits here, because we want to see
259 -- the (IO t) in the corner of the type!
260 fe_arg_tys | isDyn = tail fe_arg_tys'
261 | otherwise = fe_arg_tys'
263 -- Look at the result type of the exported function, orig_res_ty
264 -- If it's IO t, return (t, True)
265 -- If it's plain t, return (t, False)
266 (case tcSplitTyConApp_maybe orig_res_ty of
267 -- We must use tcSplit here so that we see the (IO t) in
268 -- the type. [IO t is transparent to plain splitTyConApp.]
270 Just (ioTyCon, [res_ty])
271 -> ASSERT( ioTyCon `hasKey` ioTyConKey )
272 -- The function already returns IO t
273 returnDs (res_ty, True)
275 other -> -- The function returns t
276 returnDs (orig_res_ty, False)
278 `thenDs` \ (res_ty, -- t
279 is_IO_res_ty) -> -- Bool
282 = mkFExportCBits ext_name
283 (if isDyn then Nothing else Just fn_id)
284 fe_arg_tys res_ty is_IO_res_ty cconv
286 returnDs (h_stub, c_stub)
289 @foreign export dynamic@ lets you dress up Haskell IO actions
290 of some fixed type behind an externally callable interface (i.e.,
291 as a C function pointer). Useful for callbacks and stuff.
294 foreign export dynamic f :: (Addr -> Int -> IO Int) -> IO Addr
296 -- Haskell-visible constructor, which is generated from the above:
297 -- SUP: No check for NULL from createAdjustor anymore???
299 f :: (Addr -> Int -> IO Int) -> IO Addr
301 bindIO (newStablePtr cback)
302 (\StablePtr sp# -> IO (\s1# ->
303 case _ccall_ createAdjustor cconv sp# ``f_helper'' s1# of
304 (# s2#, a# #) -> (# s2#, A# a# #)))
306 foreign export "f_helper" f_helper :: StablePtr (Addr -> Int -> IO Int) -> Addr -> Int -> IO Int
307 -- `special' foreign export that invokes the closure pointed to by the
312 dsFExportDynamic :: Id
314 -> DsM ([Binding], SDoc, SDoc)
315 dsFExportDynamic id cconv
316 = newSysLocalDs ty `thenDs` \ fe_id ->
317 getModuleDs `thenDs` \ mod_name ->
319 -- hack: need to get at the name of the C stub we're about to generate.
320 fe_nm = mkFastString (moduleString mod_name ++ "_" ++ toCName fe_id)
322 dsFExport id export_ty fe_nm cconv True `thenDs` \ (h_code, c_code) ->
323 newSysLocalDs arg_ty `thenDs` \ cback ->
324 dsLookupGlobalId newStablePtrName `thenDs` \ newStablePtrId ->
326 mk_stbl_ptr_app = mkApps (Var newStablePtrId) [ Type arg_ty, Var cback ]
328 dsLookupGlobalId bindIOName `thenDs` \ bindIOId ->
329 newSysLocalDs (mkTyConApp stablePtrTyCon [arg_ty]) `thenDs` \ stbl_value ->
332 = mkApps (Var bindIOId)
333 [ Type (mkTyConApp stablePtrTyCon [arg_ty])
340 The arguments to the external function which will
341 create a little bit of (template) code on the fly
342 for allowing the (stable pointed) Haskell closure
343 to be entered using an external calling convention
346 adj_args = [ mkIntLitInt (ccallConvToInt cconv)
348 , mkLit (MachLabel fe_nm)
350 -- name of external entry point providing these services.
351 -- (probably in the RTS.)
352 adjustor = FSLIT("createAdjustor")
354 dsCCall adjustor adj_args PlayRisky False io_res_ty `thenDs` \ ccall_adj ->
355 -- PlayRisky: the adjustor doesn't allocate in the Haskell heap or do a callback
356 let ccall_adj_ty = exprType ccall_adj
357 ccall_io_adj = mkLams [stbl_value] $
358 Note (Coerce io_res_ty ccall_adj_ty)
360 io_app = mkLams tvs $
362 stbl_app ccall_io_adj res_ty
363 fed = (id `setInlinePragma` NeverActive, io_app)
364 -- Never inline the f.e.d. function, because the litlit
365 -- might not be in scope in other modules.
367 returnDs ([fed], h_code, c_code)
371 (tvs,sans_foralls) = tcSplitForAllTys ty
372 ([arg_ty], io_res_ty) = tcSplitFunTys sans_foralls
373 [res_ty] = tcTyConAppArgs io_res_ty
374 -- Must use tcSplit* to see the (IO t), which is a newtype
375 export_ty = mkFunTy (mkTyConApp stablePtrTyCon [arg_ty]) arg_ty
377 toCName :: Id -> String
378 toCName i = showSDoc (pprCode CStyle (ppr (idName i)))
383 \subsection{Generating @foreign export@ stubs}
387 For each @foreign export@ function, a C stub function is generated.
388 The C stub constructs the application of the exported Haskell function
389 using the hugs/ghc rts invocation API.
392 mkFExportCBits :: FastString
393 -> Maybe Id -- Just==static, Nothing==dynamic
396 -> Bool -- True <=> returns an IO type
399 mkFExportCBits c_nm maybe_target arg_htys res_hty is_IO_res_ty cc
400 = (header_bits, c_bits)
402 -- Create up types and names for the real args
403 arg_cnames, arg_ctys :: [SDoc]
404 arg_cnames = mkCArgNames 1 arg_htys
405 arg_ctys = map showStgType arg_htys
407 -- and also for auxiliary ones; the stable ptr in the dynamic case, and
408 -- a slot for the dummy return address in the dynamic + ccall case
409 extra_cnames_and_ctys
410 = case maybe_target of
411 Nothing -> [(text "the_stableptr", text "StgStablePtr")]
414 case (maybe_target, cc) of
415 (Nothing, CCallConv) -> [(text "original_return_addr", text "void*")]
418 all_cnames_and_ctys :: [(SDoc, SDoc)]
420 = extra_cnames_and_ctys ++ zip arg_cnames arg_ctys
422 -- stuff to do with the return type of the C function
423 res_hty_is_unit = res_hty `eqType` unitTy -- Look through any newtypes
425 cResType | res_hty_is_unit = text "void"
426 | otherwise = showStgType res_hty
428 -- Now we can cook up the prototype for the exported function.
429 pprCconv = case cc of
431 StdCallConv -> text (ccallConvAttribute cc)
433 header_bits = ptext SLIT("extern") <+> fun_proto <> semi
435 fun_proto = cResType <+> pprCconv <+> ftext c_nm <>
436 parens (hsep (punctuate comma (map (\(nm,ty) -> ty <+> nm)
437 all_cnames_and_ctys)))
439 -- the target which will form the root of what we ask rts_evalIO to run
441 = case maybe_target of
442 Nothing -> text "(StgClosure*)deRefStablePtr(the_stableptr)"
443 Just hs_fn -> char '&' <> ppr hs_fn <> text "_closure"
445 -- the expression we give to rts_evalIO
447 = foldl appArg the_cfun (zip arg_cnames arg_htys)
449 appArg acc (arg_cname, arg_hty)
451 <> parens (acc <> comma <> mkHObj arg_hty <> parens arg_cname)
453 -- various other bits for inside the fn
454 declareResult = text "HaskellObj ret;"
455 declareCResult | res_hty_is_unit = empty
456 | otherwise = cResType <+> text "cret;"
458 assignCResult | res_hty_is_unit = empty
460 text "cret=" <> unpackHObj res_hty <> parens (text "ret") <> semi
462 -- an extern decl for the fn being called
464 = case maybe_target of
466 Just hs_fn -> text "extern StgClosure " <> ppr hs_fn <> text "_closure" <> semi
468 -- finally, the whole darn thing
475 , text "SchedulerStatus rc;"
479 -- create the application + perform it.
480 , text "rc=rts_evalIO" <> parens (
481 text "rts_apply" <> parens (
483 <> text (if is_IO_res_ty
485 else "runNonIO_closure")
491 , text "rts_checkSchedStatus" <> parens (doubleQuotes (ftext c_nm)
492 <> comma <> text "rc") <> semi
494 , text "rts_unlock();"
495 , if res_hty_is_unit then empty
496 else text "return cret;"
501 mkCArgNames :: Int -> [a] -> [SDoc]
502 mkCArgNames n as = zipWith (\ _ n -> text ('a':show n)) as [n..]
504 mkHObj :: Type -> SDoc
505 mkHObj t = text "rts_mk" <> text (showFFIType t)
507 unpackHObj :: Type -> SDoc
508 unpackHObj t = text "rts_get" <> text (showFFIType t)
510 showStgType :: Type -> SDoc
511 showStgType t = text "Hs" <> text (showFFIType t)
513 showFFIType :: Type -> String
514 showFFIType t = getOccString (getName tc)
516 tc = case tcSplitTyConApp_maybe (repType t) of
518 Nothing -> pprPanic "showFFIType" (ppr t)