2 % (c) The University of Glasgow 2006
3 % (c) The AQUA Project, Glasgow University, 1998
6 Desugaring foreign declarations (see also DsCCall).
10 -- The above warning supression flag is a temporary kludge.
11 -- While working on this module you are encouraged to remove it and fix
12 -- any warnings in the module. See
13 -- http://hackage.haskell.org/trac/ghc/wiki/Commentary/CodingStyle#Warnings
16 module DsForeign ( dsForeigns ) where
18 #include "HsVersions.h"
19 import TcRnMonad -- temp
55 Desugaring of @foreign@ declarations is naturally split up into
56 parts, an @import@ and an @export@ part. A @foreign import@
59 foreign import cc nm f :: prim_args -> IO prim_res
63 f :: prim_args -> IO prim_res
64 f a1 ... an = _ccall_ nm cc a1 ... an
66 so we reuse the desugaring code in @DsCCall@ to deal with these.
69 type Binding = (Id, CoreExpr) -- No rec/nonrec structure;
70 -- the occurrence analyser will sort it all out
72 dsForeigns :: [LForeignDecl Id]
73 -> DsM (ForeignStubs, [Binding])
75 = return (NoStubs, [])
77 fives <- mapM do_ldecl fos
79 (hs, cs, idss, bindss) = unzip4 fives
81 fe_init_code = map foreignExportInitialiser fe_ids
85 (vcat cs $$ vcat fe_init_code),
88 do_ldecl (L loc decl) = putSrcSpanDs loc (do_decl decl)
90 do_decl (ForeignImport id _ spec) = do
91 traceIf (text "fi start" <+> ppr id)
92 (bs, h, c) <- dsFImport (unLoc id) spec
93 traceIf (text "fi end" <+> ppr id)
96 do_decl (ForeignExport (L _ id) _ (CExport (CExportStatic ext_nm cconv))) = do
97 (h, c, _, _) <- dsFExport id (idType id) ext_nm cconv False
98 return (h, c, [id], [])
102 %************************************************************************
104 \subsection{Foreign import}
106 %************************************************************************
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 -> DsM ([Binding], SDoc, SDoc)
130 dsFImport id (CImport cconv safety header lib spec) = do
131 (ids, h, c) <- dsCImport id spec cconv safety
134 -- FIXME: the `lib' field is needed for .NET ILX generation when invoking
135 -- routines that are external to the .NET runtime, but GHC doesn't
136 -- support such calls yet; if `nullFastString lib', the value was not given
137 dsFImport id (DNImport spec) = do
138 (ids, h, c) <- dsFCall id (DNCall spec)
145 -> DsM ([Binding], SDoc, SDoc)
146 dsCImport id (CLabel cid) _ _ = do
147 (resTy, foRhs) <- resultWrapper (idType id)
148 ASSERT(fromJust resTy `coreEqType` addrPrimTy) -- typechecker ensures this
149 let rhs = foRhs (mkLit (MachLabel cid Nothing)) in
150 return ([(id, rhs)], empty, empty)
151 dsCImport id (CFunction target) cconv safety
152 = dsFCall id (CCall (CCallSpec target cconv safety))
153 dsCImport id CWrapper cconv _
154 = dsFExportDynamic id cconv
158 %************************************************************************
160 \subsection{Foreign calls}
162 %************************************************************************
165 dsFCall fn_id fcall = do
168 (tvs, fun_ty) = tcSplitForAllTys ty
169 (arg_tys, io_res_ty) = tcSplitFunTys fun_ty
170 -- Must use tcSplit* functions because we want to
171 -- see that (IO t) in the corner
173 args <- newSysLocalsDs arg_tys
174 (val_args, arg_wrappers) <- mapAndUnzipM unboxArg (map Var args)
177 work_arg_ids = [v | Var v <- val_args] -- All guaranteed to be vars
185 | forDotnet = Just <$> dsLookupGlobalId checkDotnetResName
186 | otherwise = return Nothing
190 err_res <- newSysLocalDs addrPrimTy
191 return (\ (mb_res_ty, resWrap) ->
193 Nothing -> (Just (mkTyConApp (tupleTyCon Unboxed 1)
196 Just x -> (Just (mkTyConApp (tupleTyCon Unboxed 2)
199 | otherwise = return id
201 augment <- augmentResultDs
203 (ccall_result_ty, res_wrapper) <- boxResult augment topCon io_res_ty
205 ccall_uniq <- newUnique
206 work_uniq <- newUnique
209 worker_ty = mkForAllTys tvs (mkFunTys (map idType work_arg_ids) ccall_result_ty)
210 the_ccall_app = mkFCall ccall_uniq fcall val_args ccall_result_ty
211 work_rhs = mkLams tvs (mkLams work_arg_ids the_ccall_app)
212 work_id = mkSysLocal FSLIT("$wccall") work_uniq worker_ty
215 work_app = mkApps (mkVarApps (Var work_id) tvs) val_args
216 wrapper_body = foldr ($) (res_wrapper work_app) arg_wrappers
217 wrap_rhs = mkInlineMe (mkLams (tvs ++ args) wrapper_body)
219 return ([(work_id, work_rhs), (fn_id, wrap_rhs)], empty, empty)
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
251 , String -- string describing type to pass to createAdj.
252 , Int -- size of args to stub function
255 dsFExport fn_id ty ext_name cconv isDyn= do
257 (_tvs,sans_foralls) = tcSplitForAllTys ty
258 (fe_arg_tys', orig_res_ty) = tcSplitFunTys sans_foralls
259 -- We must use tcSplits here, because we want to see
260 -- the (IO t) in the corner of the type!
261 fe_arg_tys | isDyn = tail fe_arg_tys'
262 | otherwise = fe_arg_tys'
264 -- Look at the result type of the exported function, orig_res_ty
265 -- If it's IO t, return (t, True)
266 -- If it's plain t, return (t, False)
268 is_IO_res_ty) <- -- Bool
269 case tcSplitIOType_maybe orig_res_ty of
270 Just (ioTyCon, res_ty, co) -> return (res_ty, True)
271 -- The function already returns IO t
272 -- ToDo: what about the coercion?
273 Nothing -> return (orig_res_ty, False)
274 -- The function returns t
277 mkFExportCBits ext_name
278 (if isDyn then Nothing else Just fn_id)
279 fe_arg_tys res_ty is_IO_res_ty cconv
282 @foreign import "wrapper"@ (previously "foreign export dynamic") lets
283 you dress up Haskell IO actions of some fixed type behind an
284 externally callable interface (i.e., as a C function pointer). Useful
285 for callbacks and stuff.
288 type Fun = Bool -> Int -> IO Int
289 foreign import "wrapper" f :: Fun -> IO (FunPtr Fun)
291 -- Haskell-visible constructor, which is generated from the above:
292 -- SUP: No check for NULL from createAdjustor anymore???
294 f :: Fun -> IO (FunPtr Fun)
296 bindIO (newStablePtr cback)
297 (\StablePtr sp# -> IO (\s1# ->
298 case _ccall_ createAdjustor cconv sp# ``f_helper'' <arg info> s1# of
299 (# s2#, a# #) -> (# s2#, A# a# #)))
301 foreign import "&f_helper" f_helper :: FunPtr (StablePtr Fun -> Fun)
303 -- and the helper in C:
305 f_helper(StablePtr s, HsBool b, HsInt i)
307 rts_evalIO(rts_apply(rts_apply(deRefStablePtr(s),
308 rts_mkBool(b)), rts_mkInt(i)));
313 dsFExportDynamic :: Id
315 -> DsM ([Binding], SDoc, SDoc)
316 dsFExportDynamic id cconv = do
317 fe_id <- newSysLocalDs ty
320 -- hack: need to get at the name of the C stub we're about to generate.
321 fe_nm = mkFastString (unpackFS (zEncodeFS (moduleNameFS (moduleName mod))) ++ "_" ++ toCName fe_id)
323 cback <- newSysLocalDs arg_ty
324 newStablePtrId <- dsLookupGlobalId newStablePtrName
325 stable_ptr_tycon <- dsLookupTyCon stablePtrTyConName
327 stable_ptr_ty = mkTyConApp stable_ptr_tycon [arg_ty]
328 export_ty = mkFunTy stable_ptr_ty arg_ty
329 bindIOId <- dsLookupGlobalId bindIOName
330 stbl_value <- newSysLocalDs stable_ptr_ty
331 (h_code, c_code, typestring, args_size) <- dsFExport id export_ty fe_nm cconv True
334 The arguments to the external function which will
335 create a little bit of (template) code on the fly
336 for allowing the (stable pointed) Haskell closure
337 to be entered using an external calling convention
340 adj_args = [ mkIntLitInt (ccallConvToInt cconv)
342 , mkLit (MachLabel fe_nm mb_sz_args)
343 , mkLit (mkStringLit typestring)
345 -- name of external entry point providing these services.
346 -- (probably in the RTS.)
347 adjustor = FSLIT("createAdjustor")
349 -- Determine the number of bytes of arguments to the stub function,
350 -- so that we can attach the '@N' suffix to its label if it is a
351 -- stdcall on Windows.
352 mb_sz_args = case cconv of
353 StdCallConv -> Just args_size
356 ccall_adj <- dsCCall adjustor adj_args PlayRisky (mkTyConApp io_tc [res_ty])
357 -- PlayRisky: the adjustor doesn't allocate in the Haskell heap or do a callback
359 let io_app = mkLams tvs $
361 mkCoerceI (mkSymCoI co) $
362 mkApps (Var bindIOId)
365 , mkApps (Var newStablePtrId) [ Type arg_ty, Var cback ]
366 , Lam stbl_value ccall_adj
369 fed = (id `setInlinePragma` NeverActive, io_app)
370 -- Never inline the f.e.d. function, because the litlit
371 -- might not be in scope in other modules.
373 return ([fed], h_code, c_code)
377 (tvs,sans_foralls) = tcSplitForAllTys ty
378 ([arg_ty], fn_res_ty) = tcSplitFunTys sans_foralls
379 Just (io_tc, res_ty, co) = tcSplitIOType_maybe fn_res_ty
380 -- Must have an IO type; hence Just
381 -- co : fn_res_ty ~ IO res_ty
383 toCName :: Id -> String
384 toCName i = showSDoc (pprCode CStyle (ppr (idName i)))
389 \subsection{Generating @foreign export@ stubs}
393 For each @foreign export@ function, a C stub function is generated.
394 The C stub constructs the application of the exported Haskell function
395 using the hugs/ghc rts invocation API.
398 mkFExportCBits :: FastString
399 -> Maybe Id -- Just==static, Nothing==dynamic
402 -> Bool -- True <=> returns an IO type
406 String, -- the argument reps
407 Int -- total size of arguments
409 mkFExportCBits c_nm maybe_target arg_htys res_hty is_IO_res_ty cc
410 = (header_bits, c_bits, type_string,
411 sum [ machRepByteWidth rep | (_,_,_,rep) <- aug_arg_info] -- all the args
414 -- list the arguments to the C function
415 arg_info :: [(SDoc, -- arg name
417 Type, -- Haskell type
418 MachRep)] -- the MachRep
419 arg_info = [ let stg_type = showStgType ty in
420 (arg_cname n stg_type,
423 typeMachRep (getPrimTyOf ty))
424 | (ty,n) <- zip arg_htys [1::Int ..] ]
427 | libffi = char '*' <> parens (stg_ty <> char '*') <>
428 ptext SLIT("args") <> brackets (int (n-1))
429 | otherwise = text ('a':show n)
431 -- generate a libffi-style stub if this is a "wrapper" and libffi is enabled
432 libffi = cLibFFI && isNothing maybe_target
435 -- libffi needs to know the result type too:
436 | libffi = primTyDescChar res_hty : arg_type_string
437 | otherwise = arg_type_string
439 arg_type_string = [primTyDescChar ty | (_,_,ty,_) <- arg_info]
440 -- just the real args
442 -- add some auxiliary args; the stable ptr in the wrapper case, and
443 -- a slot for the dummy return address in the wrapper + ccall case
445 | isNothing maybe_target = stable_ptr_arg : insertRetAddr cc arg_info
446 | otherwise = arg_info
449 (text "the_stableptr", text "StgStablePtr", undefined,
450 typeMachRep (mkStablePtrPrimTy alphaTy))
452 -- stuff to do with the return type of the C function
453 res_hty_is_unit = res_hty `coreEqType` unitTy -- Look through any newtypes
455 cResType | res_hty_is_unit = text "void"
456 | otherwise = showStgType res_hty
458 -- Now we can cook up the prototype for the exported function.
459 pprCconv = case cc of
461 StdCallConv -> text (ccallConvAttribute cc)
463 header_bits = ptext SLIT("extern") <+> fun_proto <> semi
466 | null aug_arg_info = text "void"
467 | otherwise = hsep $ punctuate comma
468 $ map (\(nm,ty,_,_) -> ty <+> nm) aug_arg_info
472 = ptext SLIT("void") <+> ftext c_nm <>
473 parens (ptext SLIT("void *cif STG_UNUSED, void* resp, void** args, void* the_stableptr"))
475 = cResType <+> pprCconv <+> ftext c_nm <> parens fun_args
477 -- the target which will form the root of what we ask rts_evalIO to run
479 = case maybe_target of
480 Nothing -> text "(StgClosure*)deRefStablePtr(the_stableptr)"
481 Just hs_fn -> char '&' <> ppr hs_fn <> text "_closure"
483 cap = text "cap" <> comma
485 -- the expression we give to rts_evalIO
487 = foldl appArg the_cfun arg_info -- NOT aug_arg_info
489 appArg acc (arg_cname, _, arg_hty, _)
491 <> parens (cap <> acc <> comma <> mkHObj arg_hty <> parens (cap <> arg_cname))
493 -- various other bits for inside the fn
494 declareResult = text "HaskellObj ret;"
495 declareCResult | res_hty_is_unit = empty
496 | otherwise = cResType <+> text "cret;"
498 assignCResult | res_hty_is_unit = empty
500 text "cret=" <> unpackHObj res_hty <> parens (text "ret") <> semi
502 -- an extern decl for the fn being called
504 = case maybe_target of
506 Just hs_fn -> text "extern StgClosure " <> ppr hs_fn <> text "_closure" <> semi
509 -- finally, the whole darn thing
516 , ptext SLIT("Capability *cap;")
519 , text "cap = rts_lock();"
520 -- create the application + perform it.
521 , ptext SLIT("cap=rts_evalIO") <> parens (
523 ptext SLIT("rts_apply") <> parens (
526 <> ptext (if is_IO_res_ty
527 then SLIT("runIO_closure")
528 else SLIT("runNonIO_closure"))
534 , ptext SLIT("rts_checkSchedStatus") <> parens (doubleQuotes (ftext c_nm)
535 <> comma <> text "cap") <> semi
537 , ptext SLIT("rts_unlock(cap);")
538 , if res_hty_is_unit then empty
540 then char '*' <> parens (cResType <> char '*') <>
541 ptext SLIT("resp = cret;")
542 else ptext SLIT("return cret;")
547 foreignExportInitialiser :: Id -> SDoc
548 foreignExportInitialiser hs_fn =
549 -- Initialise foreign exports by registering a stable pointer from an
550 -- __attribute__((constructor)) function.
551 -- The alternative is to do this from stginit functions generated in
552 -- codeGen/CodeGen.lhs; however, stginit functions have a negative impact
553 -- on binary sizes and link times because the static linker will think that
554 -- all modules that are imported directly or indirectly are actually used by
556 -- (this is bad for big umbrella modules like Graphics.Rendering.OpenGL)
558 [ text "static void stginit_export_" <> ppr hs_fn
559 <> text "() __attribute__((constructor));"
560 , text "static void stginit_export_" <> ppr hs_fn <> text "()"
561 , braces (text "getStablePtr"
562 <> parens (text "(StgPtr) &" <> ppr hs_fn <> text "_closure")
567 -- NB. the calculation here isn't strictly speaking correct.
568 -- We have a primitive Haskell type (eg. Int#, Double#), and
569 -- we want to know the size, when passed on the C stack, of
570 -- the associated C type (eg. HsInt, HsDouble). We don't have
571 -- this information to hand, but we know what GHC's conventions
572 -- are for passing around the primitive Haskell types, so we
573 -- use that instead. I hope the two coincide --SDM
574 typeMachRep ty = argMachRep (typeCgRep ty)
576 mkHObj :: Type -> SDoc
577 mkHObj t = text "rts_mk" <> text (showFFIType t)
579 unpackHObj :: Type -> SDoc
580 unpackHObj t = text "rts_get" <> text (showFFIType t)
582 showStgType :: Type -> SDoc
583 showStgType t = text "Hs" <> text (showFFIType t)
585 showFFIType :: Type -> String
586 showFFIType t = getOccString (getName tc)
588 tc = case tcSplitTyConApp_maybe (repType t) of
590 Nothing -> pprPanic "showFFIType" (ppr t)
592 #if !defined(x86_64_TARGET_ARCH)
593 insertRetAddr CCallConv args = ret_addr_arg : args
594 insertRetAddr _ args = args
596 -- On x86_64 we insert the return address after the 6th
597 -- integer argument, because this is the point at which we
598 -- need to flush a register argument to the stack (See rts/Adjustor.c for
600 insertRetAddr CCallConv args = go 0 args
601 where go 6 args = ret_addr_arg : args
602 go n (arg@(_,_,_,rep):args)
603 | I64 <- rep = arg : go (n+1) args
604 | otherwise = arg : go n args
606 insertRetAddr _ args = args
609 ret_addr_arg = (text "original_return_addr", text "void*", undefined,
610 typeMachRep addrPrimTy)
612 -- This function returns the primitive type associated with the boxed
613 -- type argument to a foreign export (eg. Int ==> Int#).
614 getPrimTyOf :: Type -> Type
616 | isBoolTy rep_ty = intPrimTy
617 -- Except for Bool, the types we are interested in have a single constructor
618 -- with a single primitive-typed argument (see TcType.legalFEArgTyCon).
620 case splitProductType_maybe rep_ty of
621 Just (_, _, data_con, [prim_ty]) ->
622 ASSERT(dataConSourceArity data_con == 1)
623 ASSERT2(isUnLiftedType prim_ty, ppr prim_ty)
625 _other -> pprPanic "DsForeign.getPrimTyOf" (ppr ty)
629 -- represent a primitive type as a Char, for building a string that
630 -- described the foreign function type. The types are size-dependent,
631 -- e.g. 'W' is a signed 32-bit integer.
632 primTyDescChar :: Type -> Char
634 | ty `coreEqType` unitTy = 'v'
636 = case typePrimRep (getPrimTyOf ty) of
637 IntRep -> signed_word
638 WordRep -> unsigned_word
644 _ -> pprPanic "primTyDescChar" (ppr ty)
646 (signed_word, unsigned_word)
647 | wORD_SIZE == 4 = ('W','w')
648 | wORD_SIZE == 8 = ('L','l')
649 | otherwise = panic "primTyDescChar"