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