9cefb058204d29f008bd495718cfe9eccfeb47b9
[ghc-hetmet.git] / ghc / compiler / deSugar / DsForeign.lhs
1 %
2 % (c) The AQUA Project, Glasgow University, 1998
3 %
4 \section[DsCCall]{Desugaring \tr{foreign} declarations}
5
6 Expanding out @foreign import@ and @foreign export@ declarations.
7
8 \begin{code}
9 module DsForeign ( dsForeigns ) where
10
11 #include "HsVersions.h"
12
13 import CoreSyn
14
15 import DsCCall          ( dsCCall, mkFCall, boxResult, unboxArg, resultWrapper )
16 import DsMonad
17
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,
31                         )
32
33 import HscTypes         ( ForeignStubs(..) )
34 import ForeignCall      ( ForeignCall(..), CCallSpec(..), 
35                           Safety(..), playSafe,
36                           CExportSpec(..),
37                           CCallConv(..), ccallConvToInt,
38                           ccallConvAttribute
39                         )
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 ) )
46 import Outputable
47 import Maybe            ( fromJust )
48 import FastString
49 \end{code}
50
51 Desugaring of @foreign@ declarations is naturally split up into
52 parts, an @import@ and an @export@  part. A @foreign import@ 
53 declaration
54 \begin{verbatim}
55   foreign import cc nm f :: prim_args -> IO prim_res
56 \end{verbatim}
57 is the same as
58 \begin{verbatim}
59   f :: prim_args -> IO prim_res
60   f a1 ... an = _ccall_ nm cc a1 ... an
61 \end{verbatim}
62 so we reuse the desugaring code in @DsCCall@ to deal with these.
63
64 \begin{code}
65 type Binding = (Id, CoreExpr)   -- No rec/nonrec structure;
66                                 -- the occurrence analyser will sort it all out
67
68 dsForeigns :: [TypecheckedForeignDecl] 
69            -> DsM (ForeignStubs, [Binding])
70 dsForeigns [] 
71   = returnDs (NoStubs, [])
72 dsForeigns fos
73   = foldlDs combine (ForeignStubs empty empty [] [], []) fos
74  where
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)
80                              (c $$ acc_c)
81                              (addH mbhd acc_hdrs)
82                              acc_feb, 
83                 bs ++ acc_f)
84
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), 
91                 acc_f)
92
93   addH Nothing  ls = ls
94   addH (Just e) ls
95    | e `elem` ls = ls
96    | otherwise   = e:ls
97
98   warnDepr False _   = returnDs ()
99   warnDepr True  loc = dsWarn (loc, msg)
100    where
101     msg = ptext SLIT("foreign declaration uses deprecated non-standard syntax")
102 \end{code}
103
104
105 %************************************************************************
106 %*                                                                      *
107 \subsection{Foreign import}
108 %*                                                                      *
109 %************************************************************************
110
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.
114
115 However, we create a worker/wrapper pair, thus:
116
117         foreign import f :: Int -> IO Int
118 ==>
119         f x = IO ( \s -> case x of { I# x# ->
120                          case fw s x# of { (# s1, y# #) ->
121                          (# s1, I# y# #)}})
122
123         fw s x# = ccall f s x#
124
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.
128
129 \begin{code}
130 dsFImport :: Id
131           -> ForeignImport
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)
136   where
137     no_hdrs = nullFastString header
138
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)
145
146 dsCImport :: Id
147           -> CImportSpec
148           -> CCallConv
149           -> Safety
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)
155  where
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
162
163 setImpInline :: Bool    -- True <=> No #include headers 
164                         -- in the foreign import declaration
165              -> Id -> Id
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
170 -- fatal. 
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 
175 -- import decl.
176 setImpInline True  id = id
177 setImpInline False id = id `setInlinePragma` NeverActive
178 \end{code}
179
180
181 %************************************************************************
182 %*                                                                      *
183 \subsection{Foreign calls}
184 %*                                                                      *
185 %************************************************************************
186
187 \begin{code}
188 dsFCall fn_id fcall no_hdrs
189   = let
190         ty                   = idType fn_id
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
195     in
196     newSysLocalsDs arg_tys                      `thenDs` \ args ->
197     mapAndUnzipDs unboxArg (map Var args)       `thenDs` \ (val_args, arg_wrappers) ->
198
199     let
200         work_arg_ids  = [v | Var v <- val_args] -- All guaranteed to be vars
201
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
206                       | otherwise         = []
207     in
208     boxResult maybe_arg_ids io_res_ty           `thenDs` \ (ccall_result_ty, res_wrapper) ->
209
210     getUniqueDs                                 `thenDs` \ ccall_uniq ->
211     getUniqueDs                                 `thenDs` \ work_uniq ->
212     let
213         -- Build the worker
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
219
220         -- Build the wrapper
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)
224     in
225     returnDs ([(work_id, work_rhs), (fn_id, wrap_rhs)], empty, empty)
226
227 unsafe_call (CCall (CCallSpec _ _ safety)) = playSafe safety
228 unsafe_call (DNCall _)                     = False
229 \end{code}
230
231
232 %************************************************************************
233 %*                                                                      *
234 \subsection{Foreign export}
235 %*                                                                      *
236 %************************************************************************
237
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
240  into.)
241
242 For each `@foreign export foo@' in a module M we generate:
243 \begin{itemize}
244 \item a C function `@foo@', which calls
245 \item a Haskell stub `@M.$ffoo@', which calls
246 \end{itemize}
247 the user-written Haskell function `@M.foo@'.
248
249 \begin{code}
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
254           -> CCallConv
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.
261                  )
262
263 dsFExport fn_id ty ext_name cconv isDyn
264    = 
265      let
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'
272      in
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.]
279
280         Just (ioTyCon, [res_ty])
281               -> ASSERT( ioTyCon `hasKey` ioTyConKey )
282                  -- The function already returns IO t
283                  returnDs (res_ty, True)
284
285         other -> -- The function returns t
286                  returnDs (orig_res_ty, False)
287      )
288                                         `thenDs` \ (res_ty,             -- t
289                                                     is_IO_res_ty) ->    -- Bool
290      returnDs $
291        mkFExportCBits ext_name 
292                       (if isDyn then Nothing else Just fn_id)
293                       fe_arg_tys res_ty is_IO_res_ty cconv
294 \end{code}
295
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.
299
300 \begin{verbatim}
301 foreign export dynamic f :: (Addr -> Int -> IO Int) -> IO Addr
302
303 -- Haskell-visible constructor, which is generated from the above:
304 -- SUP: No check for NULL from createAdjustor anymore???
305
306 f :: (Addr -> Int -> IO Int) -> IO Addr
307 f cback =
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# #)))
312
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
315 -- first argument.
316 \end{verbatim}
317
318 \begin{code}
319 dsFExportDynamic :: Id
320                  -> CCallConv
321                  -> DsM ([Binding], SDoc, SDoc)
322 dsFExportDynamic id cconv
323   =  newSysLocalDs ty                            `thenDs` \ fe_id ->
324      getModuleDs                                `thenDs` \ mod_name -> 
325      let 
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)
328      in
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 ->
332      let
333         mk_stbl_ptr_app    = mkApps (Var newStablePtrId) [ Type arg_ty, Var cback ]
334      in
335      dsLookupGlobalId bindIOName                        `thenDs` \ bindIOId ->
336      newSysLocalDs (mkTyConApp stablePtrTyCon [arg_ty]) `thenDs` \ stbl_value ->
337      let
338       stbl_app cont ret_ty 
339         = mkApps (Var bindIOId)
340                  [ Type (mkTyConApp stablePtrTyCon [arg_ty])
341                  , Type ret_ty
342                  , mk_stbl_ptr_app
343                  , cont
344                  ]
345
346        {-
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
351         (stdcall, ccall).
352        -}
353       adj_args      = [ mkIntLitInt (ccallConvToInt cconv)
354                       , Var stbl_value
355                       , mkLit (MachLabel fe_nm mb_sz_args)
356                       ]
357         -- name of external entry point providing these services.
358         -- (probably in the RTS.) 
359       adjustor      = FSLIT("createAdjustor")
360       
361       mb_sz_args =
362         case cconv of
363           StdCallConv -> Just (sum (map (getPrimRepSizeInBytes . typePrimRep) stub_args))
364           _ -> Nothing
365      in
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)
371                              ccall_adj
372          io_app = mkLams tvs     $
373                   mkLams [cback] $
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.
378      in
379      returnDs ([fed], h_code, c_code)
380
381  where
382   ty                    = idType id
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
388
389 toCName :: Id -> String
390 toCName i = showSDoc (pprCode CStyle (ppr (idName i)))
391 \end{code}
392
393 %*
394 %
395 \subsection{Generating @foreign export@ stubs}
396 %
397 %*
398
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.
402
403 \begin{code}
404 mkFExportCBits :: FastString
405                -> Maybe Id      -- Just==static, Nothing==dynamic
406                -> [Type] 
407                -> Type 
408                -> Bool          -- True <=> returns an IO type
409                -> CCallConv 
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)
413  where
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
418
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
421   extra_cnames_and_tys
422      = case maybe_target of
423           Nothing -> [((text "the_stableptr", text "StgStablePtr"), mkStablePtrPrimTy alphaTy)]
424           other   -> []
425        ++
426        case (maybe_target, cc) of
427           (Nothing, CCallConv) -> [((text "original_return_addr", text "void*"), addrPrimTy)]
428           other                -> []
429
430   all_cnames_and_ctys :: [(SDoc, SDoc)]
431   all_cnames_and_ctys 
432      = map fst extra_cnames_and_tys ++ zip arg_cnames arg_ctys
433
434   all_arg_tys
435      = map snd extra_cnames_and_tys ++ arg_htys
436
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
439
440   cResType | res_hty_is_unit = text "void"
441            | otherwise       = showStgType res_hty
442
443   -- Now we can cook up the prototype for the exported function.
444   pprCconv = case cc of
445                 CCallConv   -> empty
446                 StdCallConv -> text (ccallConvAttribute cc)
447
448   header_bits = ptext SLIT("extern") <+> fun_proto <> semi
449
450   fun_proto = cResType <+> pprCconv <+> ftext c_nm <>
451               parens (hsep (punctuate comma (map (\(nm,ty) -> ty <+> nm) 
452                                                  all_cnames_and_ctys)))
453
454   -- the target which will form the root of what we ask rts_evalIO to run
455   the_cfun
456      = case maybe_target of
457           Nothing    -> text "(StgClosure*)deRefStablePtr(the_stableptr)"
458           Just hs_fn -> char '&' <> ppr hs_fn <> text "_closure"
459
460   -- the expression we give to rts_evalIO
461   expr_to_run
462      = foldl appArg the_cfun (zip arg_cnames arg_htys)
463        where
464           appArg acc (arg_cname, arg_hty) 
465              = text "rts_apply" 
466                <> parens (acc <> comma <> mkHObj arg_hty <> parens arg_cname)
467
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;"
472
473   assignCResult | res_hty_is_unit = empty
474                 | otherwise       =
475                         text "cret=" <> unpackHObj res_hty <> parens (text "ret") <> semi
476
477   -- an extern decl for the fn being called
478   extern_decl
479      = case maybe_target of
480           Nothing -> empty
481           Just hs_fn -> text "extern StgClosure " <> ppr hs_fn <> text "_closure" <> semi
482
483   -- finally, the whole darn thing
484   c_bits =
485     space $$
486     extern_decl $$
487     fun_proto  $$
488     vcat 
489      [ lbrace
490      ,   text "SchedulerStatus rc;"
491      ,   declareResult
492      ,   declareCResult
493      ,   text "rts_lock();"
494           -- create the application + perform it.
495      ,   text "rc=rts_evalIO" <> parens (
496                 text "rts_apply" <> parens (
497                     text "(HaskellObj)"
498                  <> text (if is_IO_res_ty 
499                                 then "runIO_closure" 
500                                 else "runNonIO_closure")
501                  <> comma
502                  <> expr_to_run
503                 ) <+> comma
504                <> text "&ret"
505              ) <> semi
506      ,   text "rts_checkSchedStatus" <> parens (doubleQuotes (ftext c_nm)
507                                                 <> comma <> text "rc") <> semi
508      ,   assignCResult
509      ,   text "rts_unlock();"
510      ,   if res_hty_is_unit then empty
511             else text "return cret;"
512      , rbrace
513      ]
514
515
516 mkCArgNames :: Int -> [a] -> [SDoc]
517 mkCArgNames n as = zipWith (\ _ n -> text ('a':show n)) as [n..] 
518
519 mkHObj :: Type -> SDoc
520 mkHObj t = text "rts_mk" <> text (showFFIType t)
521
522 unpackHObj :: Type -> SDoc
523 unpackHObj t = text "rts_get" <> text (showFFIType t)
524
525 showStgType :: Type -> SDoc
526 showStgType t = text "Hs" <> text (showFFIType t)
527
528 showFFIType :: Type -> String
529 showFFIType t = getOccString (getName tc)
530  where
531   tc = case tcSplitTyConApp_maybe (repType t) of
532             Just (tc,_) -> tc
533             Nothing     -> pprPanic "showFFIType" (ppr t)
534 \end{code}