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 ( moduleString )
32 import Name ( getOccString, NamedThing(..) )
33 import OccName ( encodeFS )
34 import Type ( repType, coreEqType )
35 import TcType ( Type, mkFunTys, mkForAllTys, mkTyConApp,
36 mkFunTy, tcSplitTyConApp_maybe,
37 tcSplitForAllTys, tcSplitFunTys, tcTyConAppArgs,
40 import BasicTypes ( Boxity(..) )
41 import HscTypes ( ForeignStubs(..) )
42 import ForeignCall ( ForeignCall(..), CCallSpec(..),
44 CExportSpec(..), CLabelString,
45 CCallConv(..), ccallConvToInt,
48 import TysWiredIn ( unitTy, tupleTyCon )
49 import TysPrim ( addrPrimTy, mkStablePtrPrimTy, alphaTy )
50 import PrelNames ( hasKey, ioTyConKey, stablePtrTyConName, newStablePtrName, bindIOName,
52 import BasicTypes ( Activation( NeverActive ) )
53 import SrcLoc ( Located(..), unLoc )
55 import Maybe ( fromJust, isNothing )
59 Desugaring of @foreign@ declarations is naturally split up into
60 parts, an @import@ and an @export@ part. A @foreign import@
63 foreign import cc nm f :: prim_args -> IO prim_res
67 f :: prim_args -> IO prim_res
68 f a1 ... an = _ccall_ nm cc a1 ... an
70 so we reuse the desugaring code in @DsCCall@ to deal with these.
73 type Binding = (Id, CoreExpr) -- No rec/nonrec structure;
74 -- the occurrence analyser will sort it all out
76 dsForeigns :: [LForeignDecl Id]
77 -> DsM (ForeignStubs, [Binding])
79 = returnDs (NoStubs, [])
81 = foldlDs combine (ForeignStubs empty empty [] [], []) fos
83 combine stubs (L loc decl) = putSrcSpanDs loc (combine1 stubs decl)
85 combine1 (ForeignStubs acc_h acc_c acc_hdrs acc_feb, acc_f)
86 (ForeignImport id _ spec depr)
87 = traceIf (text "fi start" <+> ppr id) `thenDs` \ _ ->
88 dsFImport (unLoc id) spec `thenDs` \ (bs, h, c, mbhd) ->
89 warnDepr depr `thenDs` \ _ ->
90 traceIf (text "fi end" <+> ppr id) `thenDs` \ _ ->
91 returnDs (ForeignStubs (h $$ acc_h)
97 combine1 (ForeignStubs acc_h acc_c acc_hdrs acc_feb, acc_f)
98 (ForeignExport (L _ id) _ (CExport (CExportStatic ext_nm cconv)) depr)
99 = dsFExport id (idType id)
100 ext_nm cconv False `thenDs` \(h, c, _, _) ->
101 warnDepr depr `thenDs` \_ ->
102 returnDs (ForeignStubs (h $$ acc_h) (c $$ acc_c) acc_hdrs (id:acc_feb),
110 warnDepr False = returnDs ()
111 warnDepr True = dsWarn msg
113 msg = ptext SLIT("foreign declaration uses deprecated non-standard syntax")
117 %************************************************************************
119 \subsection{Foreign import}
121 %************************************************************************
123 Desugaring foreign imports is just the matter of creating a binding
124 that on its RHS unboxes its arguments, performs the external call
125 (using the @CCallOp@ primop), before boxing the result up and returning it.
127 However, we create a worker/wrapper pair, thus:
129 foreign import f :: Int -> IO Int
131 f x = IO ( \s -> case x of { I# x# ->
132 case fw s x# of { (# s1, y# #) ->
135 fw s x# = ccall f s x#
137 The strictness/CPR analyser won't do this automatically because it doesn't look
138 inside returned tuples; but inlining this wrapper is a Really Good Idea
139 because it exposes the boxing to the call site.
144 -> DsM ([Binding], SDoc, SDoc, Maybe FastString)
145 dsFImport id (CImport cconv safety header lib spec)
146 = dsCImport id spec cconv safety no_hdrs `thenDs` \(ids, h, c) ->
147 returnDs (ids, h, c, if no_hdrs then Nothing else Just header)
149 no_hdrs = nullFastString header
151 -- FIXME: the `lib' field is needed for .NET ILX generation when invoking
152 -- routines that are external to the .NET runtime, but GHC doesn't
153 -- support such calls yet; if `nullFastString lib', the value was not given
154 dsFImport id (DNImport spec)
155 = dsFCall id (DNCall spec) True {- No headers -} `thenDs` \(ids, h, c) ->
156 returnDs (ids, h, c, Nothing)
162 -> Bool -- True <=> no headers in the f.i decl
163 -> DsM ([Binding], SDoc, SDoc)
164 dsCImport id (CLabel cid) _ _ no_hdrs
165 = resultWrapper (idType id) `thenDs` \ (resTy, foRhs) ->
166 ASSERT(fromJust resTy `coreEqType` addrPrimTy) -- typechecker ensures this
167 let rhs = foRhs (mkLit (MachLabel cid Nothing)) in
168 returnDs ([(setImpInline no_hdrs id, rhs)], empty, empty)
169 dsCImport id (CFunction target) cconv safety no_hdrs
170 = dsFCall id (CCall (CCallSpec target cconv safety)) no_hdrs
171 dsCImport id CWrapper cconv _ _
172 = dsFExportDynamic id cconv
174 setImpInline :: Bool -- True <=> No #include headers
175 -- in the foreign import declaration
177 -- If there is a #include header in the foreign import
178 -- we make the worker non-inlinable, because we currently
179 -- don't keep the #include stuff in the CCallId, and hence
180 -- it won't be visible in the importing module, which can be
182 -- (The #include stuff is just collected from the foreign import
183 -- decls in a module.)
184 -- If you want to do cross-module inlining of the c-calls themselves,
185 -- put the #include stuff in the package spec, not the foreign
187 setImpInline True id = id
188 setImpInline False id = id `setInlinePragma` NeverActive
192 %************************************************************************
194 \subsection{Foreign calls}
196 %************************************************************************
199 dsFCall fn_id fcall no_hdrs
202 (tvs, fun_ty) = tcSplitForAllTys ty
203 (arg_tys, io_res_ty) = tcSplitFunTys fun_ty
204 -- Must use tcSplit* functions because we want to
205 -- see that (IO t) in the corner
207 newSysLocalsDs arg_tys `thenDs` \ args ->
208 mapAndUnzipDs unboxArg (map Var args) `thenDs` \ (val_args, arg_wrappers) ->
211 work_arg_ids = [v | Var v <- val_args] -- All guaranteed to be vars
220 dsLookupGlobalId checkDotnetResName `thenDs` \ check_id ->
221 return (Just check_id)
222 | otherwise = return Nothing
226 newSysLocalDs addrPrimTy `thenDs` \ err_res ->
227 returnDs (\ (mb_res_ty, resWrap) ->
229 Nothing -> (Just (mkTyConApp (tupleTyCon Unboxed 1)
232 Just x -> (Just (mkTyConApp (tupleTyCon Unboxed 2)
235 | otherwise = returnDs id
237 augmentResultDs `thenDs` \ augment ->
238 topConDs `thenDs` \ topCon ->
239 boxResult augment topCon io_res_ty `thenDs` \ (ccall_result_ty, res_wrapper) ->
241 newUnique `thenDs` \ ccall_uniq ->
242 newUnique `thenDs` \ work_uniq ->
245 worker_ty = mkForAllTys tvs (mkFunTys (map idType work_arg_ids) ccall_result_ty)
246 the_ccall_app = mkFCall ccall_uniq fcall val_args ccall_result_ty
247 work_rhs = mkLams tvs (mkLams work_arg_ids the_ccall_app)
248 work_id = setImpInline no_hdrs $ -- See comments with setImpInline
249 mkSysLocal (encodeFS FSLIT("$wccall")) work_uniq worker_ty
252 work_app = mkApps (mkVarApps (Var work_id) tvs) val_args
253 wrapper_body = foldr ($) (res_wrapper work_app) arg_wrappers
254 wrap_rhs = mkInlineMe (mkLams (tvs ++ args) wrapper_body)
256 returnDs ([(work_id, work_rhs), (fn_id, wrap_rhs)], empty, empty)
258 unsafe_call (CCall (CCallSpec _ _ safety)) = playSafe safety
259 unsafe_call (DNCall _) = False
263 %************************************************************************
265 \subsection{Foreign export}
267 %************************************************************************
269 The function that does most of the work for `@foreign export@' declarations.
270 (see below for the boilerplate code a `@foreign export@' declaration expands
273 For each `@foreign export foo@' in a module M we generate:
275 \item a C function `@foo@', which calls
276 \item a Haskell stub `@M.$ffoo@', which calls
278 the user-written Haskell function `@M.foo@'.
281 dsFExport :: Id -- Either the exported Id,
282 -- or the foreign-export-dynamic constructor
283 -> Type -- The type of the thing callable from C
284 -> CLabelString -- The name to export to C land
286 -> Bool -- True => foreign export dynamic
287 -- so invoke IO action that's hanging off
288 -- the first argument's stable pointer
289 -> DsM ( SDoc -- contents of Module_stub.h
290 , SDoc -- contents of Module_stub.c
291 , [MachRep] -- primitive arguments expected by stub function
292 , Int -- size of args to stub function
295 dsFExport fn_id ty ext_name cconv isDyn
298 (_tvs,sans_foralls) = tcSplitForAllTys ty
299 (fe_arg_tys', orig_res_ty) = tcSplitFunTys sans_foralls
300 -- We must use tcSplits here, because we want to see
301 -- the (IO t) in the corner of the type!
302 fe_arg_tys | isDyn = tail fe_arg_tys'
303 | otherwise = fe_arg_tys'
305 -- Look at the result type of the exported function, orig_res_ty
306 -- If it's IO t, return (t, True)
307 -- If it's plain t, return (t, False)
308 (case tcSplitTyConApp_maybe orig_res_ty of
309 -- We must use tcSplit here so that we see the (IO t) in
310 -- the type. [IO t is transparent to plain splitTyConApp.]
312 Just (ioTyCon, [res_ty])
313 -> ASSERT( ioTyCon `hasKey` ioTyConKey )
314 -- The function already returns IO t
315 returnDs (res_ty, True)
317 other -> -- The function returns t
318 returnDs (orig_res_ty, False)
320 `thenDs` \ (res_ty, -- t
321 is_IO_res_ty) -> -- Bool
323 mkFExportCBits ext_name
324 (if isDyn then Nothing else Just fn_id)
325 fe_arg_tys res_ty is_IO_res_ty cconv
328 @foreign export dynamic@ lets you dress up Haskell IO actions
329 of some fixed type behind an externally callable interface (i.e.,
330 as a C function pointer). Useful for callbacks and stuff.
333 foreign export dynamic f :: (Addr -> Int -> IO Int) -> IO Addr
335 -- Haskell-visible constructor, which is generated from the above:
336 -- SUP: No check for NULL from createAdjustor anymore???
338 f :: (Addr -> Int -> IO Int) -> IO Addr
340 bindIO (newStablePtr cback)
341 (\StablePtr sp# -> IO (\s1# ->
342 case _ccall_ createAdjustor cconv sp# ``f_helper'' s1# of
343 (# s2#, a# #) -> (# s2#, A# a# #)))
345 foreign export "f_helper" f_helper :: StablePtr (Addr -> Int -> IO Int) -> Addr -> Int -> IO Int
346 -- `special' foreign export that invokes the closure pointed to by the
351 dsFExportDynamic :: Id
353 -> DsM ([Binding], SDoc, SDoc)
354 dsFExportDynamic id cconv
355 = newSysLocalDs ty `thenDs` \ fe_id ->
356 getModuleDs `thenDs` \ mod_name ->
358 -- hack: need to get at the name of the C stub we're about to generate.
359 fe_nm = mkFastString (moduleString mod_name ++ "_" ++ toCName fe_id)
361 newSysLocalDs arg_ty `thenDs` \ cback ->
362 dsLookupGlobalId newStablePtrName `thenDs` \ newStablePtrId ->
363 dsLookupTyCon stablePtrTyConName `thenDs` \ stable_ptr_tycon ->
365 mk_stbl_ptr_app = mkApps (Var newStablePtrId) [ Type arg_ty, Var cback ]
366 stable_ptr_ty = mkTyConApp stable_ptr_tycon [arg_ty]
367 export_ty = mkFunTy stable_ptr_ty arg_ty
369 dsLookupGlobalId bindIOName `thenDs` \ bindIOId ->
370 newSysLocalDs stable_ptr_ty `thenDs` \ stbl_value ->
371 dsFExport id export_ty fe_nm cconv True
372 `thenDs` \ (h_code, c_code, arg_reps, args_size) ->
374 stbl_app cont ret_ty = mkApps (Var bindIOId)
381 The arguments to the external function which will
382 create a little bit of (template) code on the fly
383 for allowing the (stable pointed) Haskell closure
384 to be entered using an external calling convention
387 adj_args = [ mkIntLitInt (ccallConvToInt cconv)
389 , mkLit (MachLabel fe_nm mb_sz_args)
390 , mkLit (mkStringLit arg_type_info)
392 -- name of external entry point providing these services.
393 -- (probably in the RTS.)
394 adjustor = FSLIT("createAdjustor")
396 arg_type_info = map repCharCode arg_reps
397 repCharCode F32 = 'f'
398 repCharCode F64 = 'd'
399 repCharCode I64 = 'l'
402 -- Determine the number of bytes of arguments to the stub function,
403 -- so that we can attach the '@N' suffix to its label if it is a
404 -- stdcall on Windows.
405 mb_sz_args = case cconv of
406 StdCallConv -> Just args_size
410 dsCCall adjustor adj_args PlayRisky io_res_ty `thenDs` \ ccall_adj ->
411 -- PlayRisky: the adjustor doesn't allocate in the Haskell heap or do a callback
412 let ccall_adj_ty = exprType ccall_adj
413 ccall_io_adj = mkLams [stbl_value] $
414 Note (Coerce io_res_ty ccall_adj_ty)
416 io_app = mkLams tvs $
418 stbl_app ccall_io_adj res_ty
419 fed = (id `setInlinePragma` NeverActive, io_app)
420 -- Never inline the f.e.d. function, because the litlit
421 -- might not be in scope in other modules.
423 returnDs ([fed], h_code, c_code)
427 (tvs,sans_foralls) = tcSplitForAllTys ty
428 ([arg_ty], io_res_ty) = tcSplitFunTys sans_foralls
429 [res_ty] = tcTyConAppArgs io_res_ty
430 -- Must use tcSplit* to see the (IO t), which is a newtype
432 toCName :: Id -> String
433 toCName i = showSDoc (pprCode CStyle (ppr (idName i)))
438 \subsection{Generating @foreign export@ stubs}
442 For each @foreign export@ function, a C stub function is generated.
443 The C stub constructs the application of the exported Haskell function
444 using the hugs/ghc rts invocation API.
447 mkFExportCBits :: FastString
448 -> Maybe Id -- Just==static, Nothing==dynamic
451 -> Bool -- True <=> returns an IO type
455 [MachRep], -- the argument reps
456 Int -- total size of arguments
458 mkFExportCBits c_nm maybe_target arg_htys res_hty is_IO_res_ty cc
459 = (header_bits, c_bits,
460 [rep | (_,_,_,rep) <- arg_info], -- just the real args
461 sum [ machRepByteWidth rep | (_,_,_,rep) <- aug_arg_info] -- all the args
464 -- list the arguments to the C function
465 arg_info :: [(SDoc, -- arg name
467 Type, -- Haskell type
468 MachRep)] -- the MachRep
469 arg_info = [ (text ('a':show n), showStgType ty, ty,
470 typeMachRep (getPrimTyOf ty))
471 | (ty,n) <- zip arg_htys [1..] ]
473 -- add some auxiliary args; the stable ptr in the wrapper case, and
474 -- a slot for the dummy return address in the wrapper + ccall case
476 | isNothing maybe_target = stable_ptr_arg : insertRetAddr cc arg_info
477 | otherwise = arg_info
480 (text "the_stableptr", text "StgStablePtr", undefined,
481 typeMachRep (mkStablePtrPrimTy alphaTy))
483 -- stuff to do with the return type of the C function
484 res_hty_is_unit = res_hty `coreEqType` unitTy -- Look through any newtypes
486 cResType | res_hty_is_unit = text "void"
487 | otherwise = showStgType res_hty
489 -- Now we can cook up the prototype for the exported function.
490 pprCconv = case cc of
492 StdCallConv -> text (ccallConvAttribute cc)
494 header_bits = ptext SLIT("extern") <+> fun_proto <> semi
496 fun_proto = cResType <+> pprCconv <+> ftext c_nm <>
497 parens (hsep (punctuate comma (map (\(nm,ty,_,_) -> ty <+> nm)
500 -- the target which will form the root of what we ask rts_evalIO to run
502 = case maybe_target of
503 Nothing -> text "(StgClosure*)deRefStablePtr(the_stableptr)"
504 Just hs_fn -> char '&' <> ppr hs_fn <> text "_closure"
506 -- the expression we give to rts_evalIO
508 = foldl appArg the_cfun arg_info -- NOT aug_arg_info
510 appArg acc (arg_cname, _, arg_hty, _)
512 <> parens (acc <> comma <> mkHObj arg_hty <> parens arg_cname)
514 -- various other bits for inside the fn
515 declareResult = text "HaskellObj ret;"
516 declareCResult | res_hty_is_unit = empty
517 | otherwise = cResType <+> text "cret;"
519 assignCResult | res_hty_is_unit = empty
521 text "cret=" <> unpackHObj res_hty <> parens (text "ret") <> semi
523 -- an extern decl for the fn being called
525 = case maybe_target of
527 Just hs_fn -> text "extern StgClosure " <> ppr hs_fn <> text "_closure" <> semi
530 -- Initialise foreign exports by registering a stable pointer from an
531 -- __attribute__((constructor)) function.
532 -- The alternative is to do this from stginit functions generated in
533 -- codeGen/CodeGen.lhs; however, stginit functions have a negative impact
534 -- on binary sizes and link times because the static linker will think that
535 -- all modules that are imported directly or indirectly are actually used by
537 -- (this is bad for big umbrella modules like Graphics.Rendering.OpenGL)
540 = case maybe_target of
544 [ text "static void stginit_export_" <> ppr hs_fn
545 <> text "() __attribute__((constructor));"
546 , text "static void stginit_export_" <> ppr hs_fn <> text "()"
547 , braces (text "getStablePtr"
548 <> parens (text "(StgPtr) &" <> ppr hs_fn <> text "_closure")
552 -- finally, the whole darn thing
559 , text "SchedulerStatus rc;"
563 -- create the application + perform it.
564 , text "rc=rts_evalIO" <> parens (
565 text "rts_apply" <> parens (
567 <> text (if is_IO_res_ty
569 else "runNonIO_closure")
575 , text "rts_checkSchedStatus" <> parens (doubleQuotes (ftext c_nm)
576 <> comma <> text "rc") <> semi
578 , text "rts_unlock();"
579 , if res_hty_is_unit then empty
580 else text "return cret;"
585 -- NB. the calculation here isn't strictly speaking correct.
586 -- We have a primitive Haskell type (eg. Int#, Double#), and
587 -- we want to know the size, when passed on the C stack, of
588 -- the associated C type (eg. HsInt, HsDouble). We don't have
589 -- this information to hand, but we know what GHC's conventions
590 -- are for passing around the primitive Haskell types, so we
591 -- use that instead. I hope the two coincide --SDM
592 typeMachRep ty = argMachRep (typeCgRep ty)
594 mkHObj :: Type -> SDoc
595 mkHObj t = text "rts_mk" <> text (showFFIType t)
597 unpackHObj :: Type -> SDoc
598 unpackHObj t = text "rts_get" <> text (showFFIType t)
600 showStgType :: Type -> SDoc
601 showStgType t = text "Hs" <> text (showFFIType t)
603 showFFIType :: Type -> String
604 showFFIType t = getOccString (getName tc)
606 tc = case tcSplitTyConApp_maybe (repType t) of
608 Nothing -> pprPanic "showFFIType" (ppr t)
610 #if !defined(x86_64_TARGET_ARCH)
611 insertRetAddr CCallConv args = ret_addr_arg : args
612 insertRetAddr _ args = args
614 -- On x86_64 we insert the return address after the 6th
615 -- integer argument, because this is the point at which we
616 -- need to flush a register argument to the stack (See rts/Adjustor.c for
618 insertRetAddr CCallConv args = go 0 args
619 where go 6 args = ret_addr_arg : args
620 go n (arg@(_,_,_,rep):args)
621 | I64 <- rep = arg : go (n+1) args
622 | otherwise = arg : go n args
624 insertRetAddr _ args = args
627 ret_addr_arg = (text "original_return_addr", text "void*", undefined,
628 typeMachRep addrPrimTy)
630 -- This function returns the primitive type associated with the boxed
631 -- type argument to a foreign export (eg. Int ==> Int#). It assumes
632 -- that all the types we are interested in have a single constructor
633 -- with a single primitive-typed argument, which is true for all of the legal
634 -- foreign export argument types (see TcType.legalFEArgTyCon).
635 getPrimTyOf :: Type -> Type
637 case splitProductType_maybe (repType ty) of
638 Just (_, _, data_con, [prim_ty]) ->
639 ASSERT(dataConSourceArity data_con == 1)
640 ASSERT2(isUnLiftedType prim_ty, ppr prim_ty)
642 _other -> pprPanic "DsForeign.getPrimTyOf" (ppr ty)