[project @ 2003-05-29 14:39:26 by sof]
[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 BasicTypes       ( Boxity(..) )
34 import HscTypes         ( ForeignStubs(..) )
35 import ForeignCall      ( ForeignCall(..), CCallSpec(..), 
36                           Safety(..), playSafe,
37                           CExportSpec(..),
38                           CCallConv(..), ccallConvToInt,
39                           ccallConvAttribute
40                         )
41 import CStrings         ( CLabelString )
42 import TysWiredIn       ( unitTy, stablePtrTyCon, tupleTyCon )
43 import TysPrim          ( addrPrimTy, mkStablePtrPrimTy, alphaTy )
44 import PrimRep          ( getPrimRepSizeInBytes )
45 import PrelNames        ( hasKey, ioTyConKey, newStablePtrName, bindIOName,
46                           checkDotnetResName )
47 import BasicTypes       ( Activation( NeverActive ) )
48 import Outputable
49 import Maybe            ( fromJust )
50 import FastString
51 \end{code}
52
53 Desugaring of @foreign@ declarations is naturally split up into
54 parts, an @import@ and an @export@  part. A @foreign import@ 
55 declaration
56 \begin{verbatim}
57   foreign import cc nm f :: prim_args -> IO prim_res
58 \end{verbatim}
59 is the same as
60 \begin{verbatim}
61   f :: prim_args -> IO prim_res
62   f a1 ... an = _ccall_ nm cc a1 ... an
63 \end{verbatim}
64 so we reuse the desugaring code in @DsCCall@ to deal with these.
65
66 \begin{code}
67 type Binding = (Id, CoreExpr)   -- No rec/nonrec structure;
68                                 -- the occurrence analyser will sort it all out
69
70 dsForeigns :: [TypecheckedForeignDecl] 
71            -> DsM (ForeignStubs, [Binding])
72 dsForeigns [] 
73   = returnDs (NoStubs, [])
74 dsForeigns fos
75   = foldlDs combine (ForeignStubs empty empty [] [], []) fos
76  where
77   combine (ForeignStubs acc_h acc_c acc_hdrs acc_feb, acc_f) 
78           (ForeignImport id _ spec depr loc)
79     = dsFImport id spec            `thenDs` \ (bs, h, c, mbhd) -> 
80       warnDepr depr loc            `thenDs` \ _                ->
81       returnDs (ForeignStubs (h $$ acc_h)
82                              (c $$ acc_c)
83                              (addH mbhd acc_hdrs)
84                              acc_feb, 
85                 bs ++ acc_f)
86
87   combine (ForeignStubs acc_h acc_c acc_hdrs acc_feb, acc_f) 
88           (ForeignExport id _ (CExport (CExportStatic ext_nm cconv)) depr loc)
89     = dsFExport id (idType id) 
90                 ext_nm cconv False                 `thenDs` \(h, c, _) ->
91       warnDepr depr loc                            `thenDs` \_              ->
92       returnDs (ForeignStubs (h $$ acc_h) (c $$ acc_c) acc_hdrs (id:acc_feb), 
93                 acc_f)
94
95   addH Nothing  ls = ls
96   addH (Just e) ls
97    | e `elem` ls = ls
98    | otherwise   = e:ls
99
100   warnDepr False _   = returnDs ()
101   warnDepr True  loc = dsWarn (loc, msg)
102    where
103     msg = ptext SLIT("foreign declaration uses deprecated non-standard syntax")
104 \end{code}
105
106
107 %************************************************************************
108 %*                                                                      *
109 \subsection{Foreign import}
110 %*                                                                      *
111 %************************************************************************
112
113 Desugaring foreign imports is just the matter of creating a binding
114 that on its RHS unboxes its arguments, performs the external call
115 (using the @CCallOp@ primop), before boxing the result up and returning it.
116
117 However, we create a worker/wrapper pair, thus:
118
119         foreign import f :: Int -> IO Int
120 ==>
121         f x = IO ( \s -> case x of { I# x# ->
122                          case fw s x# of { (# s1, y# #) ->
123                          (# s1, I# y# #)}})
124
125         fw s x# = ccall f s x#
126
127 The strictness/CPR analyser won't do this automatically because it doesn't look
128 inside returned tuples; but inlining this wrapper is a Really Good Idea 
129 because it exposes the boxing to the call site.
130
131 \begin{code}
132 dsFImport :: Id
133           -> ForeignImport
134           -> DsM ([Binding], SDoc, SDoc, Maybe FastString)
135 dsFImport id (CImport cconv safety header lib spec)
136   = dsCImport id spec cconv safety no_hdrs        `thenDs` \(ids, h, c) ->
137     returnDs (ids, h, c, if no_hdrs then Nothing else Just header)
138   where
139     no_hdrs = nullFastString header
140
141   -- FIXME: the `lib' field is needed for .NET ILX generation when invoking
142   --        routines that are external to the .NET runtime, but GHC doesn't
143   --        support such calls yet; if `nullFastString lib', the value was not given
144 dsFImport id (DNImport spec)
145   = dsFCall id (DNCall spec) True {- No headers -} `thenDs` \(ids, h, c) ->
146     returnDs (ids, h, c, Nothing)
147
148 dsCImport :: Id
149           -> CImportSpec
150           -> CCallConv
151           -> Safety
152           -> Bool       -- True <=> no headers in the f.i decl
153           -> DsM ([Binding], SDoc, SDoc)
154 dsCImport id (CLabel cid) _ _ no_hdrs
155  = resultWrapper (idType id) `thenDs` \ (resTy, foRhs) ->
156    ASSERT(fromJust resTy `eqType` addrPrimTy)    -- typechecker ensures this
157     let rhs = foRhs (mkLit (MachLabel cid Nothing)) in
158     returnDs ([(setImpInline no_hdrs id, rhs)], empty, empty)
159 dsCImport id (CFunction target) cconv safety no_hdrs
160   = dsFCall id (CCall (CCallSpec target cconv safety)) no_hdrs
161 dsCImport id CWrapper cconv _ _
162   = dsFExportDynamic id cconv
163
164 setImpInline :: Bool    -- True <=> No #include headers 
165                         -- in the foreign import declaration
166              -> Id -> Id
167 -- If there is a #include header in the foreign import
168 -- we make the worker non-inlinable, because we currently
169 -- don't keep the #include stuff in the CCallId, and hence
170 -- it won't be visible in the importing module, which can be
171 -- fatal. 
172 -- (The #include stuff is just collected from the foreign import
173 --  decls in a module.)
174 -- If you want to do cross-module inlining of the c-calls themselves,
175 -- put the #include stuff in the package spec, not the foreign 
176 -- import decl.
177 setImpInline True  id = id
178 setImpInline False id = id `setInlinePragma` NeverActive
179 \end{code}
180
181
182 %************************************************************************
183 %*                                                                      *
184 \subsection{Foreign calls}
185 %*                                                                      *
186 %************************************************************************
187
188 \begin{code}
189 dsFCall fn_id fcall no_hdrs
190   = let
191         ty                   = idType fn_id
192         (tvs, fun_ty)        = tcSplitForAllTys ty
193         (arg_tys, io_res_ty) = tcSplitFunTys fun_ty
194                 -- Must use tcSplit* functions because we want to 
195                 -- see that (IO t) in the corner
196     in
197     newSysLocalsDs arg_tys                      `thenDs` \ args ->
198     mapAndUnzipDs unboxArg (map Var args)       `thenDs` \ (val_args, arg_wrappers) ->
199
200     let
201         work_arg_ids  = [v | Var v <- val_args] -- All guaranteed to be vars
202
203         -- These are the ids we pass to boxResult, which are used to decide
204         -- whether to touch# an argument after the call (used to keep
205         -- ForeignObj#s live across a 'safe' foreign import).
206         maybe_arg_ids | unsafe_call fcall = work_arg_ids
207                       | otherwise         = []
208
209         forDotnet = 
210          case fcall of
211            DNCall{} -> True
212            _        -> False
213
214         topConDs
215           | forDotnet = 
216              dsLookupGlobalId checkDotnetResName `thenDs` \ check_id -> 
217              return (Just check_id)
218           | otherwise = return Nothing
219              
220         augmentResultDs
221           | forDotnet = 
222                 newSysLocalDs addrPrimTy `thenDs` \ err_res -> 
223                 returnDs (\ (mb_res_ty, resWrap) ->
224                               case mb_res_ty of
225                                 Nothing -> (Just (mkTyConApp (tupleTyCon Unboxed 1)
226                                                              [ addrPrimTy ]),
227                                                  resWrap)
228                                 Just x  -> (Just (mkTyConApp (tupleTyCon Unboxed 2)
229                                                              [ x, addrPrimTy ]),
230                                                  resWrap))
231           | otherwise = returnDs id
232     in
233     augmentResultDs                                  `thenDs` \ augment -> 
234     topConDs                                         `thenDs` \ topCon -> 
235     boxResult maybe_arg_ids augment topCon io_res_ty `thenDs` \ (ccall_result_ty, res_wrapper) ->
236
237     getUniqueDs                                 `thenDs` \ ccall_uniq ->
238     getUniqueDs                                 `thenDs` \ work_uniq ->
239     let
240         -- Build the worker
241         worker_ty     = mkForAllTys tvs (mkFunTys (map idType work_arg_ids) ccall_result_ty)
242         the_ccall_app = mkFCall ccall_uniq fcall val_args ccall_result_ty
243         work_rhs      = mkLams tvs (mkLams work_arg_ids the_ccall_app)
244         work_id       = setImpInline no_hdrs $  -- See comments with setImpInline
245                         mkSysLocal (encodeFS FSLIT("$wccall")) work_uniq worker_ty
246
247         -- Build the wrapper
248         work_app     = mkApps (mkVarApps (Var work_id) tvs) val_args
249         wrapper_body = foldr ($) (res_wrapper work_app) arg_wrappers
250         wrap_rhs     = mkInlineMe (mkLams (tvs ++ args) wrapper_body)
251     in
252     returnDs ([(work_id, work_rhs), (fn_id, wrap_rhs)], empty, empty)
253
254 unsafe_call (CCall (CCallSpec _ _ safety)) = playSafe safety
255 unsafe_call (DNCall _)                     = False
256 \end{code}
257
258
259 %************************************************************************
260 %*                                                                      *
261 \subsection{Foreign export}
262 %*                                                                      *
263 %************************************************************************
264
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
267  into.)
268
269 For each `@foreign export foo@' in a module M we generate:
270 \begin{itemize}
271 \item a C function `@foo@', which calls
272 \item a Haskell stub `@M.$ffoo@', which calls
273 \end{itemize}
274 the user-written Haskell function `@M.foo@'.
275
276 \begin{code}
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
281           -> CCallConv
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                  , [Type]       -- arguments expected by stub function.
288                  )
289
290 dsFExport fn_id ty ext_name cconv isDyn
291    = 
292      let
293         (tvs,sans_foralls)              = tcSplitForAllTys ty
294         (fe_arg_tys', orig_res_ty)      = tcSplitFunTys sans_foralls
295         -- We must use tcSplits here, because we want to see 
296         -- the (IO t) in the corner of the type!
297         fe_arg_tys | isDyn     = tail fe_arg_tys'
298                    | otherwise = fe_arg_tys'
299      in
300         -- Look at the result type of the exported function, orig_res_ty
301         -- If it's IO t, return         (t, True)
302         -- If it's plain t, return      (t, False)
303      (case tcSplitTyConApp_maybe orig_res_ty of
304         -- We must use tcSplit here so that we see the (IO t) in
305         -- the type.  [IO t is transparent to plain splitTyConApp.]
306
307         Just (ioTyCon, [res_ty])
308               -> ASSERT( ioTyCon `hasKey` ioTyConKey )
309                  -- The function already returns IO t
310                  returnDs (res_ty, True)
311
312         other -> -- The function returns t
313                  returnDs (orig_res_ty, False)
314      )
315                                         `thenDs` \ (res_ty,             -- t
316                                                     is_IO_res_ty) ->    -- Bool
317      returnDs $
318        mkFExportCBits ext_name 
319                       (if isDyn then Nothing else Just fn_id)
320                       fe_arg_tys res_ty is_IO_res_ty cconv
321 \end{code}
322
323 @foreign export dynamic@ lets you dress up Haskell IO actions
324 of some fixed type behind an externally callable interface (i.e.,
325 as a C function pointer). Useful for callbacks and stuff.
326
327 \begin{verbatim}
328 foreign export dynamic f :: (Addr -> Int -> IO Int) -> IO Addr
329
330 -- Haskell-visible constructor, which is generated from the above:
331 -- SUP: No check for NULL from createAdjustor anymore???
332
333 f :: (Addr -> Int -> IO Int) -> IO Addr
334 f cback =
335    bindIO (newStablePtr cback)
336           (\StablePtr sp# -> IO (\s1# ->
337               case _ccall_ createAdjustor cconv sp# ``f_helper'' s1# of
338                  (# s2#, a# #) -> (# s2#, A# a# #)))
339
340 foreign export "f_helper" f_helper :: StablePtr (Addr -> Int -> IO Int) -> Addr -> Int -> IO Int
341 -- `special' foreign export that invokes the closure pointed to by the
342 -- first argument.
343 \end{verbatim}
344
345 \begin{code}
346 dsFExportDynamic :: Id
347                  -> CCallConv
348                  -> DsM ([Binding], SDoc, SDoc)
349 dsFExportDynamic id cconv
350   =  newSysLocalDs ty                            `thenDs` \ fe_id ->
351      getModuleDs                                `thenDs` \ mod_name -> 
352      let 
353         -- hack: need to get at the name of the C stub we're about to generate.
354        fe_nm       = mkFastString (moduleString mod_name ++ "_" ++ toCName fe_id)
355      in
356      dsFExport id export_ty fe_nm cconv True    `thenDs` \ (h_code, c_code, stub_args) ->
357      newSysLocalDs arg_ty                       `thenDs` \ cback ->
358      dsLookupGlobalId newStablePtrName  `thenDs` \ newStablePtrId ->
359      let
360         mk_stbl_ptr_app    = mkApps (Var newStablePtrId) [ Type arg_ty, Var cback ]
361      in
362      dsLookupGlobalId bindIOName                        `thenDs` \ bindIOId ->
363      newSysLocalDs (mkTyConApp stablePtrTyCon [arg_ty]) `thenDs` \ stbl_value ->
364      let
365       stbl_app cont ret_ty 
366         = mkApps (Var bindIOId)
367                  [ Type (mkTyConApp stablePtrTyCon [arg_ty])
368                  , Type ret_ty
369                  , mk_stbl_ptr_app
370                  , cont
371                  ]
372
373        {-
374         The arguments to the external function which will
375         create a little bit of (template) code on the fly
376         for allowing the (stable pointed) Haskell closure
377         to be entered using an external calling convention
378         (stdcall, ccall).
379        -}
380       adj_args      = [ mkIntLitInt (ccallConvToInt cconv)
381                       , Var stbl_value
382                       , mkLit (MachLabel fe_nm mb_sz_args)
383                       ]
384         -- name of external entry point providing these services.
385         -- (probably in the RTS.) 
386       adjustor      = FSLIT("createAdjustor")
387       
388       mb_sz_args =
389         case cconv of
390           StdCallConv -> Just (sum (map (getPrimRepSizeInBytes . typePrimRep) stub_args))
391           _ -> Nothing
392      in
393      dsCCall adjustor adj_args PlayRisky False io_res_ty        `thenDs` \ ccall_adj ->
394         -- PlayRisky: the adjustor doesn't allocate in the Haskell heap or do a callback
395      let ccall_adj_ty = exprType ccall_adj
396          ccall_io_adj = mkLams [stbl_value]                  $
397                         Note (Coerce io_res_ty ccall_adj_ty)
398                              ccall_adj
399          io_app = mkLams tvs     $
400                   mkLams [cback] $
401                   stbl_app ccall_io_adj res_ty
402          fed = (id `setInlinePragma` NeverActive, io_app)
403                 -- Never inline the f.e.d. function, because the litlit
404                 -- might not be in scope in other modules.
405      in
406      returnDs ([fed], h_code, c_code)
407
408  where
409   ty                    = idType id
410   (tvs,sans_foralls)    = tcSplitForAllTys ty
411   ([arg_ty], io_res_ty) = tcSplitFunTys sans_foralls
412   [res_ty]              = tcTyConAppArgs io_res_ty
413         -- Must use tcSplit* to see the (IO t), which is a newtype
414   export_ty             = mkFunTy (mkTyConApp stablePtrTyCon [arg_ty]) arg_ty
415
416 toCName :: Id -> String
417 toCName i = showSDoc (pprCode CStyle (ppr (idName i)))
418 \end{code}
419
420 %*
421 %
422 \subsection{Generating @foreign export@ stubs}
423 %
424 %*
425
426 For each @foreign export@ function, a C stub function is generated.
427 The C stub constructs the application of the exported Haskell function 
428 using the hugs/ghc rts invocation API.
429
430 \begin{code}
431 mkFExportCBits :: FastString
432                -> Maybe Id      -- Just==static, Nothing==dynamic
433                -> [Type] 
434                -> Type 
435                -> Bool          -- True <=> returns an IO type
436                -> CCallConv 
437                -> (SDoc, SDoc, [Type])
438 mkFExportCBits c_nm maybe_target arg_htys res_hty is_IO_res_ty cc 
439  = (header_bits, c_bits, all_arg_tys)
440  where
441   -- Create up types and names for the real args
442   arg_cnames, arg_ctys :: [SDoc]
443   arg_cnames = mkCArgNames 1 arg_htys
444   arg_ctys   = map showStgType arg_htys
445
446   -- and also for auxiliary ones; the stable ptr in the dynamic case, and
447   -- a slot for the dummy return address in the dynamic + ccall case
448   extra_cnames_and_tys
449      = case maybe_target of
450           Nothing -> [((text "the_stableptr", text "StgStablePtr"), mkStablePtrPrimTy alphaTy)]
451           other   -> []
452        ++
453        case (maybe_target, cc) of
454           (Nothing, CCallConv) -> [((text "original_return_addr", text "void*"), addrPrimTy)]
455           other                -> []
456
457   all_cnames_and_ctys :: [(SDoc, SDoc)]
458   all_cnames_and_ctys 
459      = map fst extra_cnames_and_tys ++ zip arg_cnames arg_ctys
460
461   all_arg_tys
462      = map snd extra_cnames_and_tys ++ arg_htys
463
464   -- stuff to do with the return type of the C function
465   res_hty_is_unit = res_hty `eqType` unitTy     -- Look through any newtypes
466
467   cResType | res_hty_is_unit = text "void"
468            | otherwise       = showStgType res_hty
469
470   -- Now we can cook up the prototype for the exported function.
471   pprCconv = case cc of
472                 CCallConv   -> empty
473                 StdCallConv -> text (ccallConvAttribute cc)
474
475   header_bits = ptext SLIT("extern") <+> fun_proto <> semi
476
477   fun_proto = cResType <+> pprCconv <+> ftext c_nm <>
478               parens (hsep (punctuate comma (map (\(nm,ty) -> ty <+> nm) 
479                                                  all_cnames_and_ctys)))
480
481   -- the target which will form the root of what we ask rts_evalIO to run
482   the_cfun
483      = case maybe_target of
484           Nothing    -> text "(StgClosure*)deRefStablePtr(the_stableptr)"
485           Just hs_fn -> char '&' <> ppr hs_fn <> text "_closure"
486
487   -- the expression we give to rts_evalIO
488   expr_to_run
489      = foldl appArg the_cfun (zip arg_cnames arg_htys)
490        where
491           appArg acc (arg_cname, arg_hty) 
492              = text "rts_apply" 
493                <> parens (acc <> comma <> mkHObj arg_hty <> parens arg_cname)
494
495   -- various other bits for inside the fn
496   declareResult = text "HaskellObj ret;"
497   declareCResult | res_hty_is_unit = empty
498                  | otherwise       = cResType <+> text "cret;"
499
500   assignCResult | res_hty_is_unit = empty
501                 | otherwise       =
502                         text "cret=" <> unpackHObj res_hty <> parens (text "ret") <> semi
503
504   -- an extern decl for the fn being called
505   extern_decl
506      = case maybe_target of
507           Nothing -> empty
508           Just hs_fn -> text "extern StgClosure " <> ppr hs_fn <> text "_closure" <> semi
509
510   -- finally, the whole darn thing
511   c_bits =
512     space $$
513     extern_decl $$
514     fun_proto  $$
515     vcat 
516      [ lbrace
517      ,   text "SchedulerStatus rc;"
518      ,   declareResult
519      ,   declareCResult
520      ,   text "rts_lock();"
521           -- create the application + perform it.
522      ,   text "rc=rts_evalIO" <> parens (
523                 text "rts_apply" <> parens (
524                     text "(HaskellObj)"
525                  <> text (if is_IO_res_ty 
526                                 then "runIO_closure" 
527                                 else "runNonIO_closure")
528                  <> comma
529                  <> expr_to_run
530                 ) <+> comma
531                <> text "&ret"
532              ) <> semi
533      ,   text "rts_checkSchedStatus" <> parens (doubleQuotes (ftext c_nm)
534                                                 <> comma <> text "rc") <> semi
535      ,   assignCResult
536      ,   text "rts_unlock();"
537      ,   if res_hty_is_unit then empty
538             else text "return cret;"
539      , rbrace
540      ]
541
542
543 mkCArgNames :: Int -> [a] -> [SDoc]
544 mkCArgNames n as = zipWith (\ _ n -> text ('a':show n)) as [n..] 
545
546 mkHObj :: Type -> SDoc
547 mkHObj t = text "rts_mk" <> text (showFFIType t)
548
549 unpackHObj :: Type -> SDoc
550 unpackHObj t = text "rts_get" <> text (showFFIType t)
551
552 showStgType :: Type -> SDoc
553 showStgType t = text "Hs" <> text (showFFIType t)
554
555 showFFIType :: Type -> String
556 showFFIType t = getOccString (getName tc)
557  where
558   tc = case tcSplitTyConApp_maybe (repType t) of
559             Just (tc,_) -> tc
560             Nothing     -> pprPanic "showFFIType" (ppr t)
561 \end{code}