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"
12 import TcRnMonad -- temp
16 import DsCCall ( dsCCall, mkFCall, boxResult, unboxArg, resultWrapper )
19 import HsSyn ( ForeignDecl(..), ForeignExport(..), LForeignDecl,
20 ForeignImport(..), CImportSpec(..) )
21 import DataCon ( splitProductType_maybe )
23 import DataCon ( dataConSourceArity )
24 import Type ( isUnLiftedType )
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, tcSplitIOType_maybe,
36 tcSplitForAllTys, tcSplitFunTys, tcTyConAppArgs,
39 import BasicTypes ( Boxity(..) )
40 import HscTypes ( ForeignStubs(..) )
41 import ForeignCall ( ForeignCall(..), CCallSpec(..),
43 CExportSpec(..), CLabelString,
44 CCallConv(..), ccallConvToInt,
47 import TysWiredIn ( unitTy, tupleTyCon )
48 import TysPrim ( addrPrimTy, mkStablePtrPrimTy, alphaTy )
49 import PrelNames ( stablePtrTyConName, newStablePtrName, bindIOName,
51 import BasicTypes ( Activation( NeverActive ) )
52 import SrcLoc ( Located(..), unLoc )
54 import Maybe ( fromJust, isNothing )
58 Desugaring of @foreign@ declarations is naturally split up into
59 parts, an @import@ and an @export@ part. A @foreign import@
62 foreign import cc nm f :: prim_args -> IO prim_res
66 f :: prim_args -> IO prim_res
67 f a1 ... an = _ccall_ nm cc a1 ... an
69 so we reuse the desugaring code in @DsCCall@ to deal with these.
72 type Binding = (Id, CoreExpr) -- No rec/nonrec structure;
73 -- the occurrence analyser will sort it all out
75 dsForeigns :: [LForeignDecl Id]
76 -> DsM (ForeignStubs, [Binding])
78 = returnDs (NoStubs, [])
80 = foldlDs combine (ForeignStubs empty empty [] [], []) fos
82 combine stubs (L loc decl) = putSrcSpanDs loc (combine1 stubs decl)
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)
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),
109 warnDepr False = returnDs ()
110 warnDepr True = dsWarn msg
112 msg = ptext SLIT("foreign declaration uses deprecated non-standard syntax")
116 %************************************************************************
118 \subsection{Foreign import}
120 %************************************************************************
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.
126 However, we create a worker/wrapper pair, thus:
128 foreign import f :: Int -> IO Int
130 f x = IO ( \s -> case x of { I# x# ->
131 case fw s x# of { (# s1, y# #) ->
134 fw s x# = ccall f s x#
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.
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)
148 no_hdrs = nullFS header
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)
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
173 setImpInline :: Bool -- True <=> No #include headers
174 -- in the foreign import declaration
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
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
186 setImpInline True id = id
187 setImpInline False id = id `setInlinePragma` NeverActive
191 %************************************************************************
193 \subsection{Foreign calls}
195 %************************************************************************
198 dsFCall fn_id fcall no_hdrs
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
206 newSysLocalsDs arg_tys `thenDs` \ args ->
207 mapAndUnzipDs unboxArg (map Var args) `thenDs` \ (val_args, arg_wrappers) ->
210 work_arg_ids = [v | Var v <- val_args] -- All guaranteed to be vars
219 dsLookupGlobalId checkDotnetResName `thenDs` \ check_id ->
220 return (Just check_id)
221 | otherwise = return Nothing
225 newSysLocalDs addrPrimTy `thenDs` \ err_res ->
226 returnDs (\ (mb_res_ty, resWrap) ->
228 Nothing -> (Just (mkTyConApp (tupleTyCon Unboxed 1)
231 Just x -> (Just (mkTyConApp (tupleTyCon Unboxed 2)
234 | otherwise = returnDs id
236 augmentResultDs `thenDs` \ augment ->
237 topConDs `thenDs` \ topCon ->
238 boxResult augment topCon io_res_ty `thenDs` \ (ccall_result_ty, res_wrapper) ->
240 newUnique `thenDs` \ ccall_uniq ->
241 newUnique `thenDs` \ work_uniq ->
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
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)
255 returnDs ([(work_id, work_rhs), (fn_id, wrap_rhs)], empty, empty)
259 %************************************************************************
261 \subsection{Foreign export}
263 %************************************************************************
265 The function that does most of the work for `@foreign export@' declarations.
266 (see below for the boilerplate code a `@foreign export@' declaration expands
269 For each `@foreign export foo@' in a module M we generate:
271 \item a C function `@foo@', which calls
272 \item a Haskell stub `@M.$ffoo@', which calls
274 the user-written Haskell function `@M.foo@'.
277 dsFExport :: Id -- Either the exported Id,
278 -- or the foreign-export-dynamic constructor
279 -> Type -- The type of the thing callable from C
280 -> CLabelString -- The name to export to C land
282 -> Bool -- True => foreign export dynamic
283 -- so invoke IO action that's hanging off
284 -- the first argument's stable pointer
285 -> DsM ( SDoc -- contents of Module_stub.h
286 , SDoc -- contents of Module_stub.c
287 , [MachRep] -- primitive arguments expected by stub function
288 , Int -- size of args to stub function
291 dsFExport fn_id ty ext_name cconv isDyn
294 (_tvs,sans_foralls) = tcSplitForAllTys ty
295 (fe_arg_tys', orig_res_ty) = tcSplitFunTys sans_foralls
296 -- We must use tcSplits here, because we want to see
297 -- the (IO t) in the corner of the type!
298 fe_arg_tys | isDyn = tail fe_arg_tys'
299 | otherwise = fe_arg_tys'
301 -- Look at the result type of the exported function, orig_res_ty
302 -- If it's IO t, return (t, True)
303 -- If it's plain t, return (t, False)
304 (case tcSplitIOType_maybe orig_res_ty of
305 Just (ioTyCon, res_ty) -> returnDs (res_ty, True)
306 -- The function already returns IO t
307 Nothing -> returnDs (orig_res_ty, False)
308 -- The function returns t
309 ) `thenDs` \ (res_ty, -- t
310 is_IO_res_ty) -> -- Bool
312 mkFExportCBits ext_name
313 (if isDyn then Nothing else Just fn_id)
314 fe_arg_tys res_ty is_IO_res_ty cconv
317 @foreign import "wrapper"@ (previously "foreign export dynamic") lets
318 you dress up Haskell IO actions of some fixed type behind an
319 externally callable interface (i.e., as a C function pointer). Useful
320 for callbacks and stuff.
323 type Fun = Bool -> Int -> IO Int
324 foreign import "wrapper" f :: Fun -> IO (FunPtr Fun)
326 -- Haskell-visible constructor, which is generated from the above:
327 -- SUP: No check for NULL from createAdjustor anymore???
329 f :: Fun -> IO (FunPtr Fun)
331 bindIO (newStablePtr cback)
332 (\StablePtr sp# -> IO (\s1# ->
333 case _ccall_ createAdjustor cconv sp# ``f_helper'' s1# of
334 (# s2#, a# #) -> (# s2#, A# a# #)))
336 foreign import "&f_helper" f_helper :: FunPtr (StablePtr Fun -> Fun)
338 -- and the helper in C:
340 f_helper(StablePtr s, HsBool b, HsInt i)
342 rts_evalIO(rts_apply(rts_apply(deRefStablePtr(s),
343 rts_mkBool(b)), rts_mkInt(i)));
348 dsFExportDynamic :: Id
350 -> DsM ([Binding], SDoc, SDoc)
351 dsFExportDynamic id cconv
352 = newSysLocalDs ty `thenDs` \ fe_id ->
353 getModuleDs `thenDs` \ mod_name ->
355 -- hack: need to get at the name of the C stub we're about to generate.
356 fe_nm = mkFastString (unpackFS (zEncodeFS (moduleFS mod_name)) ++ "_" ++ toCName fe_id)
358 newSysLocalDs arg_ty `thenDs` \ cback ->
359 dsLookupGlobalId newStablePtrName `thenDs` \ newStablePtrId ->
360 dsLookupTyCon stablePtrTyConName `thenDs` \ stable_ptr_tycon ->
362 mk_stbl_ptr_app = mkApps (Var newStablePtrId) [ Type arg_ty, Var cback ]
363 stable_ptr_ty = mkTyConApp stable_ptr_tycon [arg_ty]
364 export_ty = mkFunTy stable_ptr_ty arg_ty
366 dsLookupGlobalId bindIOName `thenDs` \ bindIOId ->
367 newSysLocalDs stable_ptr_ty `thenDs` \ stbl_value ->
368 dsFExport id export_ty fe_nm cconv True
369 `thenDs` \ (h_code, c_code, arg_reps, args_size) ->
371 stbl_app cont ret_ty = mkApps (Var bindIOId)
378 The arguments to the external function which will
379 create a little bit of (template) code on the fly
380 for allowing the (stable pointed) Haskell closure
381 to be entered using an external calling convention
384 adj_args = [ mkIntLitInt (ccallConvToInt cconv)
386 , mkLit (MachLabel fe_nm mb_sz_args)
387 , mkLit (mkStringLit arg_type_info)
389 -- name of external entry point providing these services.
390 -- (probably in the RTS.)
391 adjustor = FSLIT("createAdjustor")
393 arg_type_info = map repCharCode arg_reps
394 repCharCode F32 = 'f'
395 repCharCode F64 = 'd'
396 repCharCode I64 = 'l'
399 -- Determine the number of bytes of arguments to the stub function,
400 -- so that we can attach the '@N' suffix to its label if it is a
401 -- stdcall on Windows.
402 mb_sz_args = case cconv of
403 StdCallConv -> Just args_size
407 dsCCall adjustor adj_args PlayRisky io_res_ty `thenDs` \ ccall_adj ->
408 -- PlayRisky: the adjustor doesn't allocate in the Haskell heap or do a callback
409 let ccall_adj_ty = exprType ccall_adj
410 ccall_io_adj = mkLams [stbl_value] $
411 Note (Coerce io_res_ty ccall_adj_ty)
413 io_app = mkLams tvs $
415 stbl_app ccall_io_adj res_ty
416 fed = (id `setInlinePragma` NeverActive, io_app)
417 -- Never inline the f.e.d. function, because the litlit
418 -- might not be in scope in other modules.
420 returnDs ([fed], h_code, c_code)
424 (tvs,sans_foralls) = tcSplitForAllTys ty
425 ([arg_ty], io_res_ty) = tcSplitFunTys sans_foralls
426 [res_ty] = tcTyConAppArgs io_res_ty
427 -- Must use tcSplit* to see the (IO t), which is a newtype
429 toCName :: Id -> String
430 toCName i = showSDoc (pprCode CStyle (ppr (idName i)))
435 \subsection{Generating @foreign export@ stubs}
439 For each @foreign export@ function, a C stub function is generated.
440 The C stub constructs the application of the exported Haskell function
441 using the hugs/ghc rts invocation API.
444 mkFExportCBits :: FastString
445 -> Maybe Id -- Just==static, Nothing==dynamic
448 -> Bool -- True <=> returns an IO type
452 [MachRep], -- the argument reps
453 Int -- total size of arguments
455 mkFExportCBits c_nm maybe_target arg_htys res_hty is_IO_res_ty cc
456 = (header_bits, c_bits,
457 [rep | (_,_,_,rep) <- arg_info], -- just the real args
458 sum [ machRepByteWidth rep | (_,_,_,rep) <- aug_arg_info] -- all the args
461 -- list the arguments to the C function
462 arg_info :: [(SDoc, -- arg name
464 Type, -- Haskell type
465 MachRep)] -- the MachRep
466 arg_info = [ (text ('a':show n), showStgType ty, ty,
467 typeMachRep (getPrimTyOf ty))
468 | (ty,n) <- zip arg_htys [1..] ]
470 -- add some auxiliary args; the stable ptr in the wrapper case, and
471 -- a slot for the dummy return address in the wrapper + ccall case
473 | isNothing maybe_target = stable_ptr_arg : insertRetAddr cc arg_info
474 | otherwise = arg_info
477 (text "the_stableptr", text "StgStablePtr", undefined,
478 typeMachRep (mkStablePtrPrimTy alphaTy))
480 -- stuff to do with the return type of the C function
481 res_hty_is_unit = res_hty `coreEqType` unitTy -- Look through any newtypes
483 cResType | res_hty_is_unit = text "void"
484 | otherwise = showStgType res_hty
486 -- Now we can cook up the prototype for the exported function.
487 pprCconv = case cc of
489 StdCallConv -> text (ccallConvAttribute cc)
491 header_bits = ptext SLIT("extern") <+> fun_proto <> semi
493 fun_proto = cResType <+> pprCconv <+> ftext c_nm <>
494 parens (hsep (punctuate comma (map (\(nm,ty,_,_) -> ty <+> nm)
497 -- the target which will form the root of what we ask rts_evalIO to run
499 = case maybe_target of
500 Nothing -> text "(StgClosure*)deRefStablePtr(the_stableptr)"
501 Just hs_fn -> char '&' <> ppr hs_fn <> text "_closure"
503 cap = text "cap" <> comma
505 -- the expression we give to rts_evalIO
507 = foldl appArg the_cfun arg_info -- NOT aug_arg_info
509 appArg acc (arg_cname, _, arg_hty, _)
511 <> parens (cap <> acc <> comma <> mkHObj arg_hty <> parens (cap <> arg_cname))
513 -- various other bits for inside the fn
514 declareResult = text "HaskellObj ret;"
515 declareCResult | res_hty_is_unit = empty
516 | otherwise = cResType <+> text "cret;"
518 assignCResult | res_hty_is_unit = empty
520 text "cret=" <> unpackHObj res_hty <> parens (text "ret") <> semi
522 -- an extern decl for the fn being called
524 = case maybe_target of
526 Just hs_fn -> text "extern StgClosure " <> ppr hs_fn <> text "_closure" <> semi
529 -- Initialise foreign exports by registering a stable pointer from an
530 -- __attribute__((constructor)) function.
531 -- The alternative is to do this from stginit functions generated in
532 -- codeGen/CodeGen.lhs; however, stginit functions have a negative impact
533 -- on binary sizes and link times because the static linker will think that
534 -- all modules that are imported directly or indirectly are actually used by
536 -- (this is bad for big umbrella modules like Graphics.Rendering.OpenGL)
539 = case maybe_target of
543 [ text "static void stginit_export_" <> ppr hs_fn
544 <> text "() __attribute__((constructor));"
545 , text "static void stginit_export_" <> ppr hs_fn <> text "()"
546 , braces (text "getStablePtr"
547 <> parens (text "(StgPtr) &" <> ppr hs_fn <> text "_closure")
551 -- finally, the whole darn thing
558 , text "Capability *cap;"
561 , text "cap = rts_lock();"
562 -- create the application + perform it.
563 , text "cap=rts_evalIO" <> parens (
565 text "rts_apply" <> parens (
568 <> text (if is_IO_res_ty
570 else "runNonIO_closure")
576 , text "rts_checkSchedStatus" <> parens (doubleQuotes (ftext c_nm)
577 <> comma <> text "cap") <> semi
579 , text "rts_unlock(cap);"
580 , if res_hty_is_unit then empty
581 else text "return cret;"
586 -- NB. the calculation here isn't strictly speaking correct.
587 -- We have a primitive Haskell type (eg. Int#, Double#), and
588 -- we want to know the size, when passed on the C stack, of
589 -- the associated C type (eg. HsInt, HsDouble). We don't have
590 -- this information to hand, but we know what GHC's conventions
591 -- are for passing around the primitive Haskell types, so we
592 -- use that instead. I hope the two coincide --SDM
593 typeMachRep ty = argMachRep (typeCgRep ty)
595 mkHObj :: Type -> SDoc
596 mkHObj t = text "rts_mk" <> text (showFFIType t)
598 unpackHObj :: Type -> SDoc
599 unpackHObj t = text "rts_get" <> text (showFFIType t)
601 showStgType :: Type -> SDoc
602 showStgType t = text "Hs" <> text (showFFIType t)
604 showFFIType :: Type -> String
605 showFFIType t = getOccString (getName tc)
607 tc = case tcSplitTyConApp_maybe (repType t) of
609 Nothing -> pprPanic "showFFIType" (ppr t)
611 #if !defined(x86_64_TARGET_ARCH)
612 insertRetAddr CCallConv args = ret_addr_arg : args
613 insertRetAddr _ args = args
615 -- On x86_64 we insert the return address after the 6th
616 -- integer argument, because this is the point at which we
617 -- need to flush a register argument to the stack (See rts/Adjustor.c for
619 insertRetAddr CCallConv args = go 0 args
620 where go 6 args = ret_addr_arg : args
621 go n (arg@(_,_,_,rep):args)
622 | I64 <- rep = arg : go (n+1) args
623 | otherwise = arg : go n args
625 insertRetAddr _ args = args
628 ret_addr_arg = (text "original_return_addr", text "void*", undefined,
629 typeMachRep addrPrimTy)
631 -- This function returns the primitive type associated with the boxed
632 -- type argument to a foreign export (eg. Int ==> Int#). It assumes
633 -- that all the types we are interested in have a single constructor
634 -- with a single primitive-typed argument, which is true for all of the legal
635 -- foreign export argument types (see TcType.legalFEArgTyCon).
636 getPrimTyOf :: Type -> Type
638 case splitProductType_maybe (repType ty) of
639 Just (_, _, data_con, [prim_ty]) ->
640 ASSERT(dataConSourceArity data_con == 1)
641 ASSERT2(isUnLiftedType prim_ty, ppr prim_ty)
643 _other -> pprPanic "DsForeign.getPrimTyOf" (ppr ty)