[project @ 2000-03-25 12:38:40 by panne]
[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, mkCCall, boxResult, unboxArg, wrapUnboxedValue )
16 import DsMonad
17 import DsUtils
18
19 import HsSyn            ( ExtName(..), ForeignDecl(..), isDynamicExtName, ForKind(..) )
20 import HsDecls          ( extNameStatic )
21 import CallConv
22 import TcHsSyn          ( TypecheckedForeignDecl )
23 import CoreUtils        ( exprType, mkInlineMe )
24 import DataCon          ( DataCon, dataConWrapId )
25 import Id               ( Id, idType, idName, mkWildId, mkVanillaId )
26 import MkId             ( mkCCallOpId, mkWorkerId )
27 import Literal          ( Literal(..) )
28 import Module           ( Module, moduleUserString )
29 import Name             ( mkGlobalName, nameModule, nameOccName, getOccString, 
30                           mkForeignExportOcc, isLocalName,
31                           NamedThing(..), Provenance(..), ExportFlag(..)
32                         )
33 import PrelInfo         ( deRefStablePtr_NAME, bindIO_NAME, makeStablePtr_NAME, realWorldPrimId )
34 import Type             ( splitAlgTyConApp_maybe,  unUsgTy,
35                           splitTyConApp_maybe, splitFunTys, splitForAllTys,
36                           Type, mkFunTys, mkForAllTys, mkTyConApp,
37                           mkTyVarTy, mkFunTy, splitAppTy
38                         )
39 import PprType          ( {- instance Outputable Type -} )
40 import PrimOp           ( PrimOp(..), CCall(..), CCallTarget(..) )
41 import Var              ( TyVar )
42 import TysPrim          ( realWorldStatePrimTy, addrPrimTy )
43 import TysWiredIn       ( unitTyCon, addrTy, stablePtrTyCon,
44                           unboxedTupleCon, addrDataCon
45                         )
46 import Unique
47 import Maybes           ( maybeToBool )
48 import Outputable
49
50 #if __GLASGOW_HASKELL__ >= 404
51 import GlaExts          ( fromInt )
52 #endif
53 \end{code}
54
55 Desugaring of @foreign@ declarations is naturally split up into
56 parts, an @import@ and an @export@  part. A @foreign import@ 
57 declaration
58 \begin{verbatim}
59   foreign import cc nm f :: prim_args -> IO prim_res
60 \end{verbatim}
61 is the same as
62 \begin{verbatim}
63   f :: prim_args -> IO prim_res
64   f a1 ... an = _ccall_ nm cc a1 ... an
65 \end{verbatim}
66 so we reuse the desugaring code in @DsCCall@ to deal with these.
67
68 \begin{code}
69 dsForeigns :: Module
70            -> [TypecheckedForeignDecl] 
71            -> DsM ( [CoreBind]        -- desugared foreign imports
72                   , [CoreBind]        -- helper functions for foreign exports
73                   , SDoc              -- Header file prototypes for
74                                       -- "foreign exported" functions.
75                   , SDoc              -- C stubs to use when calling
76                                       -- "foreign exported" functions.
77                   )
78 dsForeigns mod_name fos = foldlDs combine ([],[],empty,empty) fos
79  where
80   combine (acc_fi, acc_fe, acc_h, acc_c) fo@(ForeignDecl i imp_exp _ ext_nm cconv _) 
81     | isForeignImport =   -- foreign import (dynamic)?
82         dsFImport i (idType i) uns ext_nm cconv  `thenDs` \ bs -> 
83         returnDs (bs ++ acc_fi, acc_fe, acc_h, acc_c)
84     | isForeignLabel = 
85         dsFLabel i ext_nm `thenDs` \ b -> 
86         returnDs (b:acc_fi, acc_fe, acc_h, acc_c)
87     | isDynamicExtName ext_nm =
88         dsFExportDynamic i (idType i) mod_name ext_nm cconv  `thenDs` \ (fi,fe,h,c) -> 
89         returnDs (fi:acc_fi, fe:acc_fe, h $$ acc_h, c $$ acc_c)
90
91     | otherwise        =  -- foreign export
92         dsFExport i (idType i) mod_name ext_nm cconv False   `thenDs` \ (fe,h,c) ->
93         returnDs (acc_fi, fe:acc_fe, h $$ acc_h, c $$ acc_c)
94    where
95     isForeignImport = 
96         case imp_exp of
97           FoImport _ -> True
98           _          -> False
99
100     isForeignLabel = 
101         case imp_exp of
102           FoLabel -> True
103           _       -> False
104
105     (FoImport uns)   = imp_exp
106
107 \end{code}
108
109 Desugaring foreign imports is just the matter of creating a binding
110 that on its RHS unboxes its arguments, performs the external call
111 (using the @CCallOp@ primop), before boxing the result up and returning it.
112
113 However, we create a worker/wrapper pair, thus:
114
115         foreign import f :: Int -> IO Int
116 ==>
117         f x = IO ( \s -> case x of { I# x# ->
118                          case fw s x# of { (# s1, y# #) ->
119                          (# s1, I# y# #)}})
120
121         fw s x# = ccall f s x#
122
123 The strictness/CPR analyser won't do this automatically because it doesn't look
124 inside returned tuples; but inlining this wrapper is a Really Good Idea 
125 because it exposes the boxing to the call site.
126                         
127
128 \begin{code}
129 dsFImport :: Id
130           -> Type               -- Type of foreign import.
131           -> Bool               -- True <=> might cause Haskell GC
132           -> ExtName
133           -> CallConv
134           -> DsM [CoreBind]
135 dsFImport fn_id ty may_not_gc ext_name cconv 
136   = let
137         (tvs, arg_tys, mbIoDataCon, io_res_ty) = splitForeignTyDs ty
138         is_io_action                           = maybeToBool mbIoDataCon
139     in
140     newSysLocalsDs arg_tys                      `thenDs` \ args ->
141     newSysLocalDs realWorldStatePrimTy          `thenDs` \ old_s ->
142     mapAndUnzipDs unboxArg (map Var args)       `thenDs` \ (unboxed_args, arg_wrappers) ->
143
144     (if not is_io_action then
145        newSysLocalDs realWorldStatePrimTy       `thenDs` \ state_tok ->
146        wrapUnboxedValue io_res_ty               `thenDs` \ (ccall_result_ty, v, res_v) ->
147        returnDs ( ccall_result_ty
148                 , \ prim_app -> Case prim_app  (mkWildId ccall_result_ty)
149                                     [(DataAlt (unboxedTupleCon 2), [state_tok, v], res_v)])
150      else
151        boxResult io_res_ty)                     `thenDs` \ (ccall_result_ty, res_wrapper) ->
152
153     (case ext_name of
154        Dynamic       -> getUniqueDs `thenDs` \ u -> 
155                         returnDs (DynamicTarget u)
156        ExtName fs _  -> returnDs (StaticTarget fs))     `thenDs` \ lbl ->
157
158     getUniqueDs                                         `thenDs` \ ccall_uniq ->
159     getUniqueDs                                         `thenDs` \ work_uniq ->
160     let
161         the_state_arg | is_io_action = old_s
162                       | otherwise    = realWorldPrimId
163
164         -- Build the worker
165         val_args      = Var the_state_arg : unboxed_args
166         work_arg_ids  = [v | Var v <- val_args]         -- All guaranteed to be vars
167         worker_ty     = mkForAllTys tvs (mkFunTys (map idType work_arg_ids) ccall_result_ty)
168         the_ccall     = CCall lbl False (not may_not_gc) cconv
169         the_ccall_app = mkCCall ccall_uniq the_ccall val_args ccall_result_ty
170         work_rhs      = mkLams tvs (mkLams work_arg_ids the_ccall_app)
171         work_id       = mkWorkerId work_uniq fn_id worker_ty
172
173         -- Build the wrapper
174         work_app     = mkApps (mkVarApps (Var work_id) tvs) val_args
175         wrapper_body = foldr ($) (res_wrapper work_app) arg_wrappers
176         io_app       = case mbIoDataCon of
177                            Nothing        -> wrapper_body
178                            Just ioDataCon -> mkApps (Var (dataConWrapId ioDataCon)) 
179                                                     [Type io_res_ty, Lam old_s wrapper_body]
180         wrap_rhs = mkInlineMe (mkLams (tvs ++ args) io_app)
181     in
182     returnDs [NonRec fn_id wrap_rhs, NonRec work_id work_rhs]
183 \end{code}
184
185 Given the type of a foreign import declaration, split it up into
186 its constituent parts.
187
188 \begin{code}
189 splitForeignTyDs :: Type -> ([TyVar], [Type], Maybe DataCon, Type)
190 splitForeignTyDs ty
191   = case splitAlgTyConApp_maybe res_ty of
192        Just (_,(io_res_ty:_),(ioCon:_)) ->   -- .... -> IO t
193              (tvs, arg_tys, Just ioCon, io_res_ty)
194        _   ->                                -- .... -> t
195              (tvs, arg_tys, Nothing, res_ty)
196   where
197    (arg_tys, res_ty)   = splitFunTys sans_foralls
198    (tvs, sans_foralls) = splitForAllTys ty
199 \end{code}
200
201 foreign labels 
202
203 \begin{code}
204 dsFLabel :: Id -> ExtName -> DsM CoreBind
205 dsFLabel nm ext_name = returnDs (NonRec nm fo_rhs)
206   where
207    fo_rhs = mkConApp addrDataCon [mkLit (MachLitLit enm addrPrimTy)]
208    enm    = extNameStatic ext_name
209 \end{code}
210
211 The function that does most of the work for `@foreign export@' declarations.
212 (see below for the boilerplate code a `@foreign export@' declaration expands
213  into.)
214
215 For each `@foreign export foo@' in a module M we generate:
216 \begin{itemize}
217 \item a C function `@foo@', which calls
218 \item a Haskell stub `@M.$ffoo@', which calls
219 \end{itemize}
220 the user-written Haskell function `@M.foo@'.
221
222 \begin{code}
223 dsFExport :: Id
224           -> Type               -- Type of foreign export.
225           -> Module
226           -> ExtName
227           -> CallConv
228           -> Bool               -- True => invoke IO action that's hanging off 
229                                 -- the first argument's stable pointer
230           -> DsM ( CoreBind
231                  , SDoc
232                  , SDoc
233                  )
234 dsFExport i ty mod_name ext_name cconv isDyn =
235      getUniqueDs                                        `thenDs` \ uniq ->
236      getSrcLocDs                                        `thenDs` \ src_loc ->
237      let
238         f_helper_glob = mkVanillaId helper_name helper_ty
239                       where
240                         name                = idName i
241                         mod     
242                          | isLocalName name = mod_name
243                          | otherwise        = nameModule name
244
245                         occ                 = mkForeignExportOcc (nameOccName name)
246                         prov                = LocalDef src_loc Exported
247                         helper_name         = mkGlobalName uniq mod occ prov
248      in
249      newSysLocalsDs fe_arg_tys                          `thenDs` \ fe_args ->
250      (if isDyn then 
251         newSysLocalDs stbl_ptr_ty                       `thenDs` \ stbl_ptr ->
252         newSysLocalDs stbl_ptr_to_ty                    `thenDs` \ stbl_value ->
253         dsLookupGlobalValue deRefStablePtr_NAME         `thenDs` \ deRefStablePtrId ->
254         let
255          the_deref_app = mkApps (Var deRefStablePtrId)
256                                 [ Type stbl_ptr_to_ty, Var stbl_ptr ]
257         in
258         newSysLocalDs (exprType the_deref_app)   `thenDs` \ x_deref_app ->
259         dsLookupGlobalValue bindIO_NAME                  `thenDs` \ bindIOId ->
260         newSysLocalDs (mkFunTy stbl_ptr_to_ty 
261                                (mkTyConApp ioTyCon [res_ty])) `thenDs` \ x_cont ->
262         let
263          stbl_app      = \ cont -> 
264                 bindNonRec x_cont   (mkLams [stbl_value] cont) $
265                 bindNonRec x_deref_app the_deref_app  
266                            (mkApps (Var bindIOId)
267                                      [ Type stbl_ptr_to_ty
268                                      , Type res_ty
269                                      , Var x_deref_app
270                                      , Var x_cont])
271         in
272         returnDs (stbl_value, stbl_app, stbl_ptr)
273       else
274         returnDs (i, 
275                   \ body -> body,
276                   panic "stbl_ptr"  -- should never be touched.
277                   ))                    `thenDs` \ (i, getFun_wrapper, stbl_ptr) ->
278      let
279       wrapper_args
280        | isDyn      = stbl_ptr:fe_args
281        | otherwise  = fe_args
282
283       wrapper_arg_tys
284        | isDyn      = stbl_ptr_ty:helper_arg_tys
285        | otherwise  = helper_arg_tys
286
287       the_app  = 
288          getFun_wrapper $
289          mkApps (Var i) (map (Type . mkTyVarTy) tvs ++ map Var fe_args)
290      in
291      getModuleDs                        `thenDs` \ mod -> 
292      getUniqueDs                        `thenDs` \ uniq ->
293      let
294       the_body = mkLams (tvs ++ wrapper_args) the_app
295       c_nm     = extNameStatic ext_name
296
297       (h_stub, c_stub) = fexportEntry (moduleUserString mod)
298                                       c_nm f_helper_glob
299                                       wrapper_arg_tys the_result_ty cconv isDyn
300      in
301      returnDs (NonRec f_helper_glob the_body, h_stub, c_stub)
302
303   where
304
305    (tvs,sans_foralls)                   = splitForAllTys ty
306    (fe_arg_tys', io_res)                = splitFunTys sans_foralls
307
308
309    Just (ioTyCon, [res_ty])             = splitTyConApp_maybe io_res
310
311    (_, stbl_ptr_ty')                    = splitForAllTys stbl_ptr_ty
312    (_, stbl_ptr_to_ty)                  = splitAppTy stbl_ptr_ty'
313
314    fe_arg_tys
315      | isDyn        = tail fe_arg_tys'
316      | otherwise    = fe_arg_tys'
317
318    (stbl_ptr_ty, helper_arg_tys) = 
319      case fe_arg_tys' of
320        (x:xs) | isDyn -> (x,xs)
321        ls             -> (error "stbl_ptr_ty", ls)
322
323    helper_ty      =  
324         mkForAllTys tvs $
325         mkFunTys arg_tys io_res
326         where
327           arg_tys
328            | isDyn      = stbl_ptr_ty : helper_arg_tys
329            | otherwise  = helper_arg_tys
330
331    the_result_ty =
332      case splitTyConApp_maybe io_res of
333        Just (_,[res_ty]) ->
334          case splitTyConApp_maybe res_ty of
335            Just (tc,_) | getUnique tc /= getUnique unitTyCon -> Just res_ty
336            _                                                 -> Nothing
337        _                 -> Nothing
338    
339 \end{code}
340
341 @foreign export dynamic@ lets you dress up Haskell IO actions
342 of some fixed type behind an externally callable interface (i.e.,
343 as a C function pointer). Useful for callbacks and stuff.
344
345 \begin{verbatim}
346 foreign export stdcall f :: (Addr -> Int -> IO Int) -> IO Addr
347
348 -- Haskell-visible constructor, which is generated from the
349 -- above:
350
351 f :: (Addr -> Int -> IO Int) -> IO Addr
352 f cback = IO ( \ s1# ->
353   case makeStablePtr# cback s1# of { StateAndStablePtr# s2# sp# ->
354   case _ccall_ "mkAdjustor" sp# ``f_helper'' s2# of
355     StateAndAddr# s3# a# ->
356     case addr2Int# a# of
357       0# -> IOfail s# err
358       _  -> 
359          let
360           a :: Addr
361           a = A# a#
362          in
363          IOok s3# a)
364
365 foreign export "f_helper" f_helper :: StablePtr (Addr -> Int -> IO Int) -> Addr -> Int -> IO Int
366 -- `special' foreign export that invokes the closure pointed to by the
367 -- first argument.
368 \end{verbatim}
369
370 \begin{code}
371 dsFExportDynamic :: Id
372                  -> Type                -- Type of foreign export.
373                  -> Module
374                  -> ExtName
375                  -> CallConv
376                  -> DsM (CoreBind, CoreBind, SDoc, SDoc)
377 dsFExportDynamic i ty mod_name ext_name cconv =
378      newSysLocalDs ty                                    `thenDs` \ fe_id ->
379      let 
380         -- hack: need to get at the name of the C stub we're about to generate.
381        fe_nm       = toCName fe_id
382        fe_ext_name = ExtName (_PK_ fe_nm) Nothing
383      in
384      dsFExport  i export_ty mod_name fe_ext_name cconv True
385      `thenDs` \ (fe@(NonRec fe_helper fe_expr), h_code, c_code) ->
386      newSysLocalDs arg_ty                                   `thenDs` \ cback ->
387      dsLookupGlobalValue makeStablePtr_NAME        `thenDs` \ makeStablePtrId ->
388      let
389         mk_stbl_ptr_app    = mkApps (Var makeStablePtrId) [ Type arg_ty, Var cback ]
390         mk_stbl_ptr_app_ty = exprType mk_stbl_ptr_app
391      in
392      newSysLocalDs mk_stbl_ptr_app_ty                   `thenDs` \ x_mk_stbl_ptr_app ->
393      dsLookupGlobalValue bindIO_NAME                    `thenDs` \ bindIOId ->
394      newSysLocalDs (mkTyConApp stablePtrTyCon [arg_ty]) `thenDs` \ stbl_value ->
395      let
396       stbl_app      = \ x_cont cont ret_ty -> 
397         bindNonRec x_cont            cont            $
398         bindNonRec x_mk_stbl_ptr_app mk_stbl_ptr_app $
399                    (mkApps (Var bindIOId)
400                            [ Type (mkTyConApp stablePtrTyCon [arg_ty])
401                            , Type ret_ty
402                            , Var x_mk_stbl_ptr_app
403                            , Var x_cont
404                            ])
405
406        {-
407         The arguments to the external function which will
408         create a little bit of (template) code on the fly
409         for allowing the (stable pointed) Haskell closure
410         to be entered using an external calling convention
411         (stdcall, ccall).
412        -}
413       adj_args      = [ mkIntLitInt (callConvToInt cconv)
414                       , Var stbl_value
415                       , mkLit (MachLitLit (_PK_ fe_nm) addrPrimTy)
416                       ]
417         -- name of external entry point providing these services.
418         -- (probably in the RTS.) 
419       adjustor      = SLIT("createAdjustor")
420      in
421      dsCCall adjustor adj_args False False addrTy `thenDs` \ ccall_adj ->
422      let ccall_adj_ty = exprType ccall_adj
423      in
424      newSysLocalDs ccall_adj_ty                   `thenDs` \ x_ccall_adj ->
425      let ccall_io_adj = 
426             mkLams [stbl_value]              $
427             bindNonRec x_ccall_adj ccall_adj $
428             Note (Coerce (mkTyConApp ioTyCon [res_ty]) (unUsgTy ccall_adj_ty))
429                  (Var x_ccall_adj)
430      in
431      newSysLocalDs (exprType ccall_io_adj)        `thenDs` \ x_ccall_io_adj ->
432      let io_app = mkLams tvs     $
433                   mkLams [cback] $
434                   stbl_app x_ccall_io_adj ccall_io_adj addrTy
435      in
436      returnDs (NonRec i io_app, fe, h_code, c_code)
437
438  where
439   (tvs,sans_foralls)               = splitForAllTys ty
440   ([arg_ty], io_res)               = splitFunTys sans_foralls
441
442   Just (ioTyCon, [res_ty])         = splitTyConApp_maybe io_res
443
444   export_ty                        = mkFunTy (mkTyConApp stablePtrTyCon [arg_ty]) arg_ty
445
446 toCName :: Id -> String
447 toCName i = showSDoc (pprCode CStyle (ppr (idName i)))
448
449 \end{code}
450
451 %*
452 %
453 \subsection{Generating @foreign export@ stubs}
454 %
455 %*
456
457 For each @foreign export@ function, a C stub function is generated.
458 The C stub constructs the application of the exported Haskell function 
459 using the hugs/ghc rts invocation API.
460
461 \begin{code}
462 fexportEntry :: String
463              -> FAST_STRING
464              -> Id 
465              -> [Type] 
466              -> Maybe Type 
467              -> CallConv 
468              -> Bool
469              -> (SDoc, SDoc)
470 fexportEntry mod_nm c_nm helper args res cc isDyn = (header_bits, c_bits)
471  where
472    -- name of the (Haskell) helper function generated by the desugarer.
473   h_nm      = ppr helper <> text "_closure"
474    -- prototype for the exported function.
475   header_bits = ptext SLIT("extern") <+> fun_proto <> semi
476
477   fun_proto = cResType <+> pprCconv <+> ptext c_nm <>
478               parens (hsep (punctuate comma (zipWith (<+>) cParamTypes proto_args)))
479
480   c_bits =
481     externDecl $$
482     fun_proto  $$
483     vcat 
484      [ lbrace
485      ,   text "SchedulerStatus rc;"
486      ,   declareResult
487           -- create the application + perform it.
488      ,   text "rc=rts_evalIO" <> 
489                   parens (foldl appArg (text "(StgClosure*)&" <> h_nm) (zip args c_args) <> comma <> text "&ret") <> semi
490      ,   returnResult
491      , rbrace
492      ]
493
494   appArg acc (a,c_a) =
495      text "rts_apply" <> parens (acc <> comma <> mkHObj a <> parens c_a)
496
497   cParamTypes  = map showStgType real_args
498
499   cResType = 
500    case res of
501      Nothing -> text "void"
502      Just t  -> showStgType t
503
504   pprCconv
505    | cc == cCallConv = empty
506    | otherwise       = pprCallConv cc
507      
508   declareResult  = text "HaskellObj ret;"
509
510   externDecl     = mkExtern (text "HaskellObj") h_nm
511
512   mkExtern ty nm = text "extern" <+> ty <+> nm <> semi
513
514   returnResult = 
515     text "rts_checkSchedStatus" <> 
516     parens (doubleQuotes (text mod_nm <> char '.' <> ptext c_nm) <> comma <> text "rc") <> semi $$
517     (case res of
518       Nothing -> text "return"
519       Just _  -> text "return" <> parens (res_name)) <> semi
520
521   res_name = 
522     case res of
523       Nothing -> empty
524       Just t  -> unpackHObj t <> parens (text "ret")
525
526   c_args = mkCArgNames 0 args
527
528   {-
529    If we're generating an entry point for a 'foreign export ccall dynamic',
530    then we receive the return address of the C function that wants to
531    invoke a Haskell function as any other C function, as second arg.
532    This arg is unused within the body of the generated C stub, but
533    needed by the Adjustor.c code to get the stack cleanup right.
534   -}
535   (proto_args, real_args)
536     | cc == cCallConv && isDyn = ( text "a0" : text "a_" : mkCArgNames 1 (tail args)
537                                 , head args : addrTy : tail args)
538     | otherwise = (mkCArgNames 0 args, args)
539
540 mkCArgNames :: Int -> [a] -> [SDoc]
541 mkCArgNames n as = zipWith (\ _ n -> text ('a':show n)) as [n..] 
542
543 mkHObj :: Type -> SDoc
544 mkHObj t = text "rts_mk" <> text (showFFIType t)
545
546 unpackHObj :: Type -> SDoc
547 unpackHObj t = text "rts_get" <> text (showFFIType t)
548
549 showStgType :: Type -> SDoc
550 showStgType t = text "Stg" <> text (showFFIType t)
551
552 showFFIType :: Type -> String
553 showFFIType t = getOccString (getName tc)
554  where
555   tc = case splitTyConApp_maybe t of
556             Just (tc,_) -> tc
557             Nothing     -> pprPanic "showFFIType" (ppr t)
558 \end{code}