[project @ 2003-09-16 13:03:37 by simonmar]
[ghc-hetmet.git] / ghc / compiler / deSugar / DsCCall.lhs
1 %
2 % (c) The AQUA Project, Glasgow University, 1994-1998
3 %
4 \section[DsCCall]{Desugaring C calls}
5
6 \begin{code}
7 module DsCCall 
8         ( dsCCall
9         , mkFCall
10         , unboxArg
11         , boxResult
12         , resultWrapper
13         ) where
14
15 #include "HsVersions.h"
16
17 import CoreSyn
18
19 import DsMonad
20
21 import CoreUtils        ( exprType, mkCoerce2 )
22 import Id               ( Id, mkWildId )
23 import MkId             ( mkFCallId, realWorldPrimId, mkPrimOpId )
24 import Maybes           ( maybeToBool )
25 import ForeignCall      ( ForeignCall(..), CCallSpec(..), CCallTarget(..), Safety, CCallConv(..) )
26 import DataCon          ( splitProductType_maybe, dataConSourceArity, dataConWrapId )
27 import ForeignCall      ( ForeignCall, CCallTarget(..) )
28
29 import TcType           ( tcSplitTyConApp_maybe )
30 import Type             ( Type, isUnLiftedType, mkFunTys, mkFunTy,
31                           tyVarsOfType, mkForAllTys, mkTyConApp, 
32                           isPrimitiveType, splitTyConApp_maybe, 
33                           splitNewType_maybe, splitForAllTy_maybe,
34                           isUnboxedTupleType
35                         )
36
37 import PrimOp           ( PrimOp(..) )
38 import TysPrim          ( realWorldStatePrimTy, intPrimTy,
39                           byteArrayPrimTyCon, mutableByteArrayPrimTyCon,
40                           addrPrimTy
41                         )
42 import TyCon            ( TyCon, tyConDataCons, tyConName )
43 import TysWiredIn       ( unitDataConId,
44                           unboxedSingletonDataCon, unboxedPairDataCon,
45                           unboxedSingletonTyCon, unboxedPairTyCon,
46                           trueDataCon, falseDataCon, 
47                           trueDataConId, falseDataConId,
48                           listTyCon, charTyCon, 
49                           tupleTyCon, tupleCon
50                         )
51 import BasicTypes       ( Boxity(..) )
52 import Literal          ( mkMachInt )
53 import CStrings         ( CLabelString )
54 import PrelNames        ( Unique, hasKey, ioTyConKey, boolTyConKey, unitTyConKey,
55                           int8TyConKey, int16TyConKey, int32TyConKey,
56                           word8TyConKey, word16TyConKey, word32TyConKey
57                           -- dotnet interop
58                           , marshalStringName, unmarshalStringName
59                           , marshalObjectName, unmarshalObjectName
60                           , objectTyConName
61                         )
62 import VarSet           ( varSetElems )
63 import Constants        ( wORD_SIZE)
64 import Outputable
65 \end{code}
66
67 Desugaring of @ccall@s consists of adding some state manipulation,
68 unboxing any boxed primitive arguments and boxing the result if
69 desired.
70
71 The state stuff just consists of adding in
72 @PrimIO (\ s -> case s of { S# s# -> ... })@ in an appropriate place.
73
74 The unboxing is straightforward, as all information needed to unbox is
75 available from the type.  For each boxed-primitive argument, we
76 transform:
77 \begin{verbatim}
78    _ccall_ foo [ r, t1, ... tm ] e1 ... em
79    |
80    |
81    V
82    case e1 of { T1# x1# ->
83    ...
84    case em of { Tm# xm# -> xm#
85    ccall# foo [ r, t1#, ... tm# ] x1# ... xm#
86    } ... }
87 \end{verbatim}
88
89 The reboxing of a @_ccall_@ result is a bit tricker: the types don't
90 contain information about the state-pairing functions so we have to
91 keep a list of \tr{(type, s-p-function)} pairs.  We transform as
92 follows:
93 \begin{verbatim}
94    ccall# foo [ r, t1#, ... tm# ] e1# ... em#
95    |
96    |
97    V
98    \ s# -> case (ccall# foo [ r, t1#, ... tm# ] s# e1# ... em#) of
99           (StateAnd<r># result# state#) -> (R# result#, realWorld#)
100 \end{verbatim}
101
102 \begin{code}
103 dsCCall :: CLabelString -- C routine to invoke
104         -> [CoreExpr]   -- Arguments (desugared)
105         -> Safety       -- Safety of the call
106         -> Type         -- Type of the result: IO t
107         -> DsM CoreExpr
108
109 dsCCall lbl args may_gc result_ty
110   = mapAndUnzipDs unboxArg args        `thenDs` \ (unboxed_args, arg_wrappers) ->
111     boxResult [] id Nothing result_ty  `thenDs` \ (ccall_result_ty, res_wrapper) ->
112     getUniqueDs                        `thenDs` \ uniq ->
113     let
114         target = StaticTarget lbl
115         the_fcall    = CCall (CCallSpec target CCallConv may_gc)
116         the_prim_app = mkFCall uniq the_fcall unboxed_args ccall_result_ty
117     in
118     returnDs (foldr ($) (res_wrapper the_prim_app) arg_wrappers)
119
120 mkFCall :: Unique -> ForeignCall 
121         -> [CoreExpr]   -- Args
122         -> Type         -- Result type
123         -> CoreExpr
124 -- Construct the ccall.  The only tricky bit is that the ccall Id should have
125 -- no free vars, so if any of the arg tys do we must give it a polymorphic type.
126 --      [I forget *why* it should have no free vars!]
127 -- For example:
128 --      mkCCall ... [s::StablePtr (a->b), x::Addr, c::Char]
129 --
130 -- Here we build a ccall thus
131 --      (ccallid::(forall a b.  StablePtr (a -> b) -> Addr -> Char -> IO Addr))
132 --                      a b s x c
133 mkFCall uniq the_fcall val_args res_ty
134   = mkApps (mkVarApps (Var the_fcall_id) tyvars) val_args
135   where
136     arg_tys = map exprType val_args
137     body_ty = (mkFunTys arg_tys res_ty)
138     tyvars  = varSetElems (tyVarsOfType body_ty)
139     ty      = mkForAllTys tyvars body_ty
140     the_fcall_id = mkFCallId uniq the_fcall ty
141 \end{code}
142
143 \begin{code}
144 unboxArg :: CoreExpr                    -- The supplied argument
145          -> DsM (CoreExpr,              -- To pass as the actual argument
146                  CoreExpr -> CoreExpr   -- Wrapper to unbox the arg
147                 )
148 -- Example: if the arg is e::Int, unboxArg will return
149 --      (x#::Int#, \W. case x of I# x# -> W)
150 -- where W is a CoreExpr that probably mentions x#
151
152 unboxArg arg
153   -- Primtive types: nothing to unbox
154   | isPrimitiveType arg_ty
155   = returnDs (arg, \body -> body)
156
157   -- Recursive newtypes
158   | Just rep_ty <- splitNewType_maybe arg_ty
159   = unboxArg (mkCoerce2 rep_ty arg_ty arg)
160       
161   -- Booleans
162   | Just (tc,_) <- splitTyConApp_maybe arg_ty, 
163     tc `hasKey` boolTyConKey
164   = newSysLocalDs intPrimTy             `thenDs` \ prim_arg ->
165     returnDs (Var prim_arg,
166               \ body -> Case (Case arg (mkWildId arg_ty)
167                                        [(DataAlt falseDataCon,[],mkIntLit 0),
168                                         (DataAlt trueDataCon, [],mkIntLit 1)])
169                              prim_arg 
170                              [(DEFAULT,[],body)])
171
172   -- Data types with a single constructor, which has a single, primitive-typed arg
173   -- This deals with Int, Float etc; also Ptr, ForeignPtr
174   | is_product_type && data_con_arity == 1 
175   = ASSERT(isUnLiftedType data_con_arg_ty1 )    -- Typechecker ensures this
176     newSysLocalDs arg_ty                `thenDs` \ case_bndr ->
177     newSysLocalDs data_con_arg_ty1      `thenDs` \ prim_arg ->
178     returnDs (Var prim_arg,
179               \ body -> Case arg case_bndr [(DataAlt data_con,[prim_arg],body)]
180     )
181
182   -- Byte-arrays, both mutable and otherwise; hack warning
183   -- We're looking for values of type ByteArray, MutableByteArray
184   --    data ByteArray          ix = ByteArray        ix ix ByteArray#
185   --    data MutableByteArray s ix = MutableByteArray ix ix (MutableByteArray# s)
186   | is_product_type &&
187     data_con_arity == 3 &&
188     maybeToBool maybe_arg3_tycon &&
189     (arg3_tycon ==  byteArrayPrimTyCon ||
190      arg3_tycon ==  mutableByteArrayPrimTyCon)
191     -- and, of course, it is an instance of CCallable
192   = newSysLocalDs arg_ty                `thenDs` \ case_bndr ->
193     newSysLocalsDs data_con_arg_tys     `thenDs` \ vars@[l_var, r_var, arr_cts_var] ->
194     returnDs (Var arr_cts_var,
195               \ body -> Case arg case_bndr [(DataAlt data_con,vars,body)]
196     )
197
198   | Just (tc, [arg_ty]) <- splitTyConApp_maybe arg_ty,
199     tc == listTyCon,
200     Just (cc,[]) <- splitTyConApp_maybe arg_ty,
201     cc == charTyCon
202     -- String; dotnet only
203   = dsLookupGlobalId marshalStringName `thenDs` \ unpack_id ->
204     newSysLocalDs addrPrimTy           `thenDs` \ prim_string ->
205     returnDs (Var prim_string,
206               \ body ->
207                 let
208                  io_ty = exprType body
209                  (Just (_,[io_arg])) = tcSplitTyConApp_maybe io_ty
210                 in
211                 mkApps (Var unpack_id)
212                        [ Type io_arg
213                        , arg
214                        , Lam prim_string body
215                        ])
216   | Just (tc, [arg_ty]) <- splitTyConApp_maybe arg_ty,
217     tyConName tc == objectTyConName
218     -- Object; dotnet only
219   = dsLookupGlobalId marshalObjectName `thenDs` \ unpack_id ->
220     newSysLocalDs addrPrimTy           `thenDs` \ prim_obj  ->
221     returnDs (Var prim_obj,
222               \ body ->
223                 let
224                  io_ty = exprType body
225                  (Just (_,[io_arg])) = tcSplitTyConApp_maybe io_ty
226                 in
227                 mkApps (Var unpack_id)
228                        [ Type io_arg
229                        , arg
230                        , Lam prim_obj body
231                        ])
232
233   | otherwise
234   = getSrcLocDs `thenDs` \ l ->
235     pprPanic "unboxArg: " (ppr l <+> ppr arg_ty)
236   where
237     arg_ty                                      = exprType arg
238     maybe_product_type                          = splitProductType_maybe arg_ty
239     is_product_type                             = maybeToBool maybe_product_type
240     Just (_, _, data_con, data_con_arg_tys)     = maybe_product_type
241     data_con_arity                              = dataConSourceArity data_con
242     (data_con_arg_ty1 : _)                      = data_con_arg_tys
243
244     (_ : _ : data_con_arg_ty3 : _) = data_con_arg_tys
245     maybe_arg3_tycon               = splitTyConApp_maybe data_con_arg_ty3
246     Just (arg3_tycon,_)            = maybe_arg3_tycon
247 \end{code}
248
249
250 \begin{code}
251 boxResult :: [Id]
252           -> ((Maybe Type, CoreExpr -> CoreExpr) -> (Maybe Type, CoreExpr -> CoreExpr))
253           -> Maybe Id
254           -> Type
255           -> DsM (Type, CoreExpr -> CoreExpr)
256
257 -- Takes the result of the user-level ccall: 
258 --      either (IO t), 
259 --      or maybe just t for an side-effect-free call
260 -- Returns a wrapper for the primitive ccall itself, along with the
261 -- type of the result of the primitive ccall.  This result type
262 -- will be of the form  
263 --      State# RealWorld -> (# State# RealWorld, t' #)
264 -- where t' is the unwrapped form of t.  If t is simply (), then
265 -- the result type will be 
266 --      State# RealWorld -> (# State# RealWorld #)
267
268 boxResult arg_ids augment mbTopCon result_ty
269   = case tcSplitTyConApp_maybe result_ty of
270         -- This split absolutely has to be a tcSplit, because we must
271         -- see the IO type; and it's a newtype which is transparent to splitTyConApp.
272
273         -- The result is IO t, so wrap the result in an IO constructor
274         Just (io_tycon, [io_res_ty]) | io_tycon `hasKey` ioTyConKey
275                 -> resultWrapper io_res_ty             `thenDs` \ res ->
276                    let aug_res          = augment res
277                        extra_result_tys =
278                          case aug_res of
279                            (Just ty,_) 
280                              | isUnboxedTupleType ty ->
281                                 let (Just (_, ls)) = splitTyConApp_maybe ty in tail ls
282                            _ -> []
283                    in
284                    mk_alt (return_result extra_result_tys) aug_res 
285                                                         `thenDs` \ (ccall_res_ty, the_alt) ->
286                    newSysLocalDs  realWorldStatePrimTy  `thenDs` \ state_id ->
287                    let
288                         io_data_con = head (tyConDataCons io_tycon)
289                         toIOCon = 
290                           case mbTopCon of
291                             Nothing -> dataConWrapId io_data_con
292                             Just x  -> x
293                         wrap = \ the_call -> 
294                                  mkApps (Var toIOCon)
295                                            [ Type io_res_ty, 
296                                              Lam state_id $
297                                               Case (App the_call (Var state_id))
298                                                    (mkWildId ccall_res_ty)
299                                                    [the_alt]
300                                            ]
301                    in
302                    returnDs (realWorldStatePrimTy `mkFunTy` ccall_res_ty, wrap)
303                 where
304                    return_result ts state anss 
305                      = mkConApp (tupleCon Unboxed (2 + length ts))
306                                 (Type realWorldStatePrimTy : Type io_res_ty : map Type ts ++
307                                  state : anss) 
308         -- It isn't, so do unsafePerformIO
309         -- It's not conveniently available, so we inline it
310         other -> resultWrapper result_ty            `thenDs` \ res ->
311                  mk_alt return_result (augment res) `thenDs` \ (ccall_res_ty, the_alt) ->
312                  let
313                     wrap = \ the_call -> Case (App the_call (Var realWorldPrimId)) 
314                                               (mkWildId ccall_res_ty)
315                                               [the_alt]
316                  in
317                  returnDs (realWorldStatePrimTy `mkFunTy` ccall_res_ty, wrap)
318               where
319                  return_result state [ans] = ans
320                  return_result _ _ = panic "return_result: expected single result"
321   where
322     mk_alt return_result (Nothing, wrap_result)
323         =       -- The ccall returns ()
324           newSysLocalDs realWorldStatePrimTy    `thenDs` \ state_id ->
325           let
326                 the_rhs = return_result (Var state_id) 
327                                         [wrap_result (panic "boxResult")]
328
329                 ccall_res_ty = mkTyConApp unboxedSingletonTyCon [realWorldStatePrimTy]
330                 the_alt      = (DataAlt unboxedSingletonDataCon, [state_id], the_rhs)
331           in
332           returnDs (ccall_res_ty, the_alt)
333
334     mk_alt return_result (Just prim_res_ty, wrap_result)
335                 -- The ccall returns a non-() value
336         | isUnboxedTupleType prim_res_ty
337         = let
338                 (Just (_, ls@(prim_res_ty1:extras))) = splitTyConApp_maybe prim_res_ty
339                 arity = 1 + length ls
340           in
341           mapDs newSysLocalDs ls                `thenDs` \ args_ids@(result_id:as) ->
342           newSysLocalDs realWorldStatePrimTy    `thenDs` \ state_id ->
343           let
344                 the_rhs = return_result (Var state_id) 
345                                         (wrap_result (Var result_id) : map Var as)
346                 ccall_res_ty = mkTyConApp (tupleTyCon Unboxed arity)
347                                           (realWorldStatePrimTy : ls)
348                 the_alt      = ( DataAlt (tupleCon Unboxed arity)
349                                , (state_id : args_ids)
350                                , the_rhs
351                                )
352           in
353           returnDs (ccall_res_ty, the_alt)
354         | otherwise
355         =       
356           newSysLocalDs prim_res_ty             `thenDs` \ result_id ->
357           newSysLocalDs realWorldStatePrimTy    `thenDs` \ state_id ->
358           let
359                 the_rhs = return_result (Var state_id) 
360                                         [wrap_result (Var result_id)]
361
362                 ccall_res_ty = mkTyConApp unboxedPairTyCon [realWorldStatePrimTy, prim_res_ty]
363                 the_alt      = (DataAlt unboxedPairDataCon, [state_id, result_id], the_rhs)
364           in
365           returnDs (ccall_res_ty, the_alt)
366
367
368 resultWrapper :: Type
369               -> DsM (Maybe Type,               -- Type of the expected result, if any
370                       CoreExpr -> CoreExpr)     -- Wrapper for the result 
371 resultWrapper result_ty
372   -- Base case 1: primitive types
373   | isPrimitiveType result_ty
374   = returnDs (Just result_ty, \e -> e)
375
376   -- Base case 2: the unit type ()
377   | Just (tc,_) <- maybe_tc_app, tc `hasKey` unitTyConKey
378   = returnDs (Nothing, \e -> Var unitDataConId)
379
380   -- Base case 3: the boolean type
381   | Just (tc,_) <- maybe_tc_app, tc `hasKey` boolTyConKey
382   = returnDs
383      (Just intPrimTy, \e -> Case e (mkWildId intPrimTy)
384                                    [(DEFAULT             ,[],Var trueDataConId ),
385                                     (LitAlt (mkMachInt 0),[],Var falseDataConId)])
386
387   -- Recursive newtypes
388   | Just rep_ty <- splitNewType_maybe result_ty
389   = resultWrapper rep_ty `thenDs` \ (maybe_ty, wrapper) ->
390     returnDs (maybe_ty, \e -> mkCoerce2 result_ty rep_ty (wrapper e))
391
392   -- The type might contain foralls (eg. for dummy type arguments,
393   -- referring to 'Ptr a' is legal).
394   | Just (tyvar, rest) <- splitForAllTy_maybe result_ty
395   = resultWrapper rest `thenDs` \ (maybe_ty, wrapper) ->
396     returnDs (maybe_ty, \e -> Lam tyvar (wrapper e))
397
398   -- Data types with a single constructor, which has a single arg
399   -- This includes types like Ptr and ForeignPtr
400   | Just (tycon, tycon_arg_tys, data_con, data_con_arg_tys) <- splitProductType_maybe result_ty,
401     dataConSourceArity data_con == 1
402   = let
403         (unwrapped_res_ty : _) = data_con_arg_tys
404         narrow_wrapper         = maybeNarrow tycon
405     in
406     resultWrapper unwrapped_res_ty `thenDs` \ (maybe_ty, wrapper) ->
407     returnDs
408       (maybe_ty, \e -> mkApps (Var (dataConWrapId data_con)) 
409                               (map Type tycon_arg_tys ++ [wrapper (narrow_wrapper e)]))
410
411     -- Strings; 'dotnet' only.
412   | Just (tc, [arg_ty]) <- maybe_tc_app,               tc == listTyCon,
413     Just (cc,[])        <- splitTyConApp_maybe arg_ty, cc == charTyCon
414   = dsLookupGlobalId unmarshalStringName        `thenDs` \ pack_id ->
415     returnDs (Just addrPrimTy,
416               \ e -> App (Var pack_id) e)
417
418     -- Objects; 'dotnet' only.
419   | Just (tc, [arg_ty]) <- maybe_tc_app, 
420     tyConName tc == objectTyConName
421   = dsLookupGlobalId unmarshalObjectName        `thenDs` \ pack_id ->
422     returnDs (Just addrPrimTy,
423               \ e -> App (Var pack_id) e)
424
425   | otherwise
426   = pprPanic "resultWrapper" (ppr result_ty)
427   where
428     maybe_tc_app = splitTyConApp_maybe result_ty
429
430 -- When the result of a foreign call is smaller than the word size, we
431 -- need to sign- or zero-extend the result up to the word size.  The C
432 -- standard appears to say that this is the responsibility of the
433 -- caller, not the callee.
434
435 maybeNarrow :: TyCon -> (CoreExpr -> CoreExpr)
436 maybeNarrow tycon
437   | tycon `hasKey` int8TyConKey   = \e -> App (Var (mkPrimOpId Narrow8IntOp)) e
438   | tycon `hasKey` int16TyConKey  = \e -> App (Var (mkPrimOpId Narrow16IntOp)) e
439   | tycon `hasKey` int32TyConKey
440          && wORD_SIZE > 4         = \e -> App (Var (mkPrimOpId Narrow32IntOp)) e
441
442   | tycon `hasKey` word8TyConKey  = \e -> App (Var (mkPrimOpId Narrow8WordOp)) e
443   | tycon `hasKey` word16TyConKey = \e -> App (Var (mkPrimOpId Narrow16WordOp)) e
444   | tycon `hasKey` word32TyConKey
445          && wORD_SIZE > 4         = \e -> App (Var (mkPrimOpId Narrow32WordOp)) e
446   | otherwise                     = id
447 \end{code}