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