2 % (c) The AQUA Project, Glasgow University, 1994-1998
4 \section[DsCCall]{Desugaring C calls}
15 #include "HsVersions.h"
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 )
30 import TcType ( tcSplitIOType_maybe )
31 import Type ( Type, isUnLiftedType, mkFunTys, mkFunTy,
32 tyVarsOfType, mkForAllTys, mkTyConApp,
33 isPrimitiveType, splitTyConApp_maybe,
34 splitRecNewType_maybe, splitForAllTy_maybe,
38 import PrimOp ( PrimOp(..) )
39 import TysPrim ( realWorldStatePrimTy, intPrimTy,
40 byteArrayPrimTyCon, mutableByteArrayPrimTyCon,
43 import TyCon ( TyCon, tyConDataCons, tyConName )
44 import TysWiredIn ( unitDataConId,
45 unboxedSingletonDataCon, unboxedPairDataCon,
46 unboxedSingletonTyCon, unboxedPairTyCon,
47 trueDataCon, falseDataCon,
48 trueDataConId, falseDataConId,
49 listTyCon, charTyCon, boolTy,
52 import BasicTypes ( Boxity(..) )
53 import Literal ( mkMachInt )
54 import PrelNames ( Unique, hasKey, boolTyConKey, unitTyConKey,
55 int8TyConKey, int16TyConKey, int32TyConKey,
56 word8TyConKey, word16TyConKey, word32TyConKey
58 , marshalStringName, unmarshalStringName
59 , marshalObjectName, unmarshalObjectName
62 import VarSet ( varSetElems )
63 import Constants ( wORD_SIZE)
72 Desugaring of @ccall@s consists of adding some state manipulation,
73 unboxing any boxed primitive arguments and boxing the result if
76 The state stuff just consists of adding in
77 @PrimIO (\ s -> case s of { S# s# -> ... })@ in an appropriate place.
79 The unboxing is straightforward, as all information needed to unbox is
80 available from the type. For each boxed-primitive argument, we
83 _ccall_ foo [ r, t1, ... tm ] e1 ... em
87 case e1 of { T1# x1# ->
89 case em of { Tm# xm# -> xm#
90 ccall# foo [ r, t1#, ... tm# ] x1# ... xm#
94 The reboxing of a @_ccall_@ result is a bit tricker: the types don't
95 contain information about the state-pairing functions so we have to
96 keep a list of \tr{(type, s-p-function)} pairs. We transform as
99 ccall# foo [ r, t1#, ... tm# ] e1# ... em#
103 \ s# -> case (ccall# foo [ r, t1#, ... tm# ] s# e1# ... em#) of
104 (StateAnd<r># result# state#) -> (R# result#, realWorld#)
108 dsCCall :: CLabelString -- C routine to invoke
109 -> [CoreExpr] -- Arguments (desugared)
110 -> Safety -- Safety of the call
111 -> Type -- Type of the result: IO t
114 dsCCall lbl args may_gc result_ty
115 = mapAndUnzipDs unboxArg args `thenDs` \ (unboxed_args, arg_wrappers) ->
116 boxResult id Nothing result_ty `thenDs` \ (ccall_result_ty, res_wrapper) ->
117 newUnique `thenDs` \ uniq ->
119 target = StaticTarget lbl
120 the_fcall = CCall (CCallSpec target CCallConv may_gc)
121 the_prim_app = mkFCall uniq the_fcall unboxed_args ccall_result_ty
123 returnDs (foldr ($) (res_wrapper the_prim_app) arg_wrappers)
125 mkFCall :: Unique -> ForeignCall
126 -> [CoreExpr] -- Args
127 -> Type -- Result type
129 -- Construct the ccall. The only tricky bit is that the ccall Id should have
130 -- no free vars, so if any of the arg tys do we must give it a polymorphic type.
131 -- [I forget *why* it should have no free vars!]
133 -- mkCCall ... [s::StablePtr (a->b), x::Addr, c::Char]
135 -- Here we build a ccall thus
136 -- (ccallid::(forall a b. StablePtr (a -> b) -> Addr -> Char -> IO Addr))
138 mkFCall uniq the_fcall val_args res_ty
139 = mkApps (mkVarApps (Var the_fcall_id) tyvars) val_args
141 arg_tys = map exprType val_args
142 body_ty = (mkFunTys arg_tys res_ty)
143 tyvars = varSetElems (tyVarsOfType body_ty)
144 ty = mkForAllTys tyvars body_ty
145 the_fcall_id = mkFCallId uniq the_fcall ty
149 unboxArg :: CoreExpr -- The supplied argument
150 -> DsM (CoreExpr, -- To pass as the actual argument
151 CoreExpr -> CoreExpr -- Wrapper to unbox the arg
153 -- Example: if the arg is e::Int, unboxArg will return
154 -- (x#::Int#, \W. case x of I# x# -> W)
155 -- where W is a CoreExpr that probably mentions x#
158 -- Primtive types: nothing to unbox
159 | isPrimitiveType arg_ty
160 = returnDs (arg, \body -> body)
162 -- Recursive newtypes
163 | Just rep_ty <- splitRecNewType_maybe arg_ty
164 = unboxArg (mkCoerce2 rep_ty arg_ty arg)
167 | Just (tc,_) <- splitTyConApp_maybe arg_ty,
168 tc `hasKey` boolTyConKey
169 = newSysLocalDs intPrimTy `thenDs` \ prim_arg ->
170 returnDs (Var prim_arg,
171 \ body -> Case (Case arg (mkWildId arg_ty) intPrimTy
172 [(DataAlt falseDataCon,[],mkIntLit 0),
173 (DataAlt trueDataCon, [],mkIntLit 1)])
174 -- In increasing tag order!
179 -- Data types with a single constructor, which has a single, primitive-typed arg
180 -- This deals with Int, Float etc; also Ptr, ForeignPtr
181 | is_product_type && data_con_arity == 1
182 = ASSERT2(isUnLiftedType data_con_arg_ty1, pprType arg_ty)
183 -- Typechecker ensures this
184 newSysLocalDs arg_ty `thenDs` \ case_bndr ->
185 newSysLocalDs data_con_arg_ty1 `thenDs` \ prim_arg ->
186 returnDs (Var prim_arg,
187 \ body -> Case arg case_bndr (exprType body) [(DataAlt data_con,[prim_arg],body)]
190 -- Byte-arrays, both mutable and otherwise; hack warning
191 -- We're looking for values of type ByteArray, MutableByteArray
192 -- data ByteArray ix = ByteArray ix ix ByteArray#
193 -- data MutableByteArray s ix = MutableByteArray ix ix (MutableByteArray# s)
195 data_con_arity == 3 &&
196 maybeToBool maybe_arg3_tycon &&
197 (arg3_tycon == byteArrayPrimTyCon ||
198 arg3_tycon == mutableByteArrayPrimTyCon)
199 = newSysLocalDs arg_ty `thenDs` \ case_bndr ->
200 newSysLocalsDs data_con_arg_tys `thenDs` \ vars@[l_var, r_var, arr_cts_var] ->
201 returnDs (Var arr_cts_var,
202 \ body -> Case arg case_bndr (exprType body) [(DataAlt data_con,vars,body)]
206 | Just (tc, [arg_ty]) <- splitTyConApp_maybe arg_ty,
208 Just (cc,[]) <- splitTyConApp_maybe arg_ty,
210 -- String; dotnet only
211 = dsLookupGlobalId marshalStringName `thenDs` \ unpack_id ->
212 newSysLocalDs addrPrimTy `thenDs` \ prim_string ->
213 returnDs (Var prim_string,
216 io_ty = exprType body
217 Just (_,io_arg) = tcSplitIOType_maybe io_ty
219 mkApps (Var unpack_id)
222 , Lam prim_string body
224 | Just (tc, [arg_ty]) <- splitTyConApp_maybe arg_ty,
225 tyConName tc == objectTyConName
226 -- Object; dotnet only
227 = dsLookupGlobalId marshalObjectName `thenDs` \ unpack_id ->
228 newSysLocalDs addrPrimTy `thenDs` \ prim_obj ->
229 returnDs (Var prim_obj,
232 io_ty = exprType body
233 Just (_,io_arg) = tcSplitIOType_maybe io_ty
235 mkApps (Var unpack_id)
242 = getSrcSpanDs `thenDs` \ l ->
243 pprPanic "unboxArg: " (ppr l <+> ppr arg_ty)
245 arg_ty = exprType arg
246 maybe_product_type = splitProductType_maybe arg_ty
247 is_product_type = maybeToBool maybe_product_type
248 Just (_, _, data_con, data_con_arg_tys) = maybe_product_type
249 data_con_arity = dataConSourceArity data_con
250 (data_con_arg_ty1 : _) = data_con_arg_tys
252 (_ : _ : data_con_arg_ty3 : _) = data_con_arg_tys
253 maybe_arg3_tycon = splitTyConApp_maybe data_con_arg_ty3
254 Just (arg3_tycon,_) = maybe_arg3_tycon
259 boxResult :: ((Maybe Type, CoreExpr -> CoreExpr) -> (Maybe Type, CoreExpr -> CoreExpr))
262 -> DsM (Type, CoreExpr -> CoreExpr)
264 -- Takes the result of the user-level ccall:
266 -- or maybe just t for an side-effect-free call
267 -- Returns a wrapper for the primitive ccall itself, along with the
268 -- type of the result of the primitive ccall. This result type
269 -- will be of the form
270 -- State# RealWorld -> (# State# RealWorld, t' #)
271 -- where t' is the unwrapped form of t. If t is simply (), then
272 -- the result type will be
273 -- State# RealWorld -> (# State# RealWorld #)
275 -- The gruesome 'augment' and 'mbTopCon' are to do with .NET foreign calls
276 -- It looks a mess: I wonder if it could be refactored.
278 boxResult augment mbTopCon result_ty
279 | Just (io_tycon, io_res_ty) <- tcSplitIOType_maybe result_ty
280 -- isIOType_maybe handles the case where the type is a
281 -- simple wrapping of IO. E.g.
282 -- newtype Wrap a = W (IO a)
283 -- No coercion necessay because its a non-recursive newtype
284 -- (If we wanted to handle a *recursive* newtype too, we'd need
285 -- another case, and a coercion.)
286 = -- The result is IO t, so wrap the result in an IO constructor
288 resultWrapper io_res_ty `thenDs` \ res ->
289 let aug_res = augment res
290 extra_result_tys = case aug_res of
292 | isUnboxedTupleType ty
293 -> let (Just (_, ls)) = splitTyConApp_maybe ty in tail ls
296 return_result state anss
297 = mkConApp (tupleCon Unboxed (2 + length extra_result_tys))
298 (map Type (realWorldStatePrimTy : io_res_ty : extra_result_tys)
301 mk_alt return_result aug_res `thenDs` \ (ccall_res_ty, the_alt) ->
302 newSysLocalDs realWorldStatePrimTy `thenDs` \ state_id ->
304 io_data_con = head (tyConDataCons io_tycon)
305 toIOCon = case mbTopCon of
306 Nothing -> dataConWrapId io_data_con
308 wrap = \ the_call -> mkApps (Var toIOCon)
311 Case (App the_call (Var state_id))
312 (mkWildId ccall_res_ty)
313 (coreAltType the_alt)
317 returnDs (realWorldStatePrimTy `mkFunTy` ccall_res_ty, wrap)
319 boxResult augment mbTopCon result_ty
320 = -- It isn't IO, so do unsafePerformIO
321 -- It's not conveniently available, so we inline it
322 resultWrapper result_ty `thenDs` \ res ->
323 mk_alt return_result (augment res) `thenDs` \ (ccall_res_ty, the_alt) ->
325 wrap = \ the_call -> Case (App the_call (Var realWorldPrimId))
326 (mkWildId ccall_res_ty)
327 (coreAltType the_alt)
330 returnDs (realWorldStatePrimTy `mkFunTy` ccall_res_ty, wrap)
332 return_result state [ans] = ans
333 return_result _ _ = panic "return_result: expected single result"
336 mk_alt return_result (Nothing, wrap_result)
337 = -- The ccall returns ()
338 newSysLocalDs realWorldStatePrimTy `thenDs` \ state_id ->
340 the_rhs = return_result (Var state_id)
341 [wrap_result (panic "boxResult")]
343 ccall_res_ty = mkTyConApp unboxedSingletonTyCon [realWorldStatePrimTy]
344 the_alt = (DataAlt unboxedSingletonDataCon, [state_id], the_rhs)
346 returnDs (ccall_res_ty, the_alt)
348 mk_alt return_result (Just prim_res_ty, wrap_result)
349 -- The ccall returns a non-() value
350 | isUnboxedTupleType prim_res_ty
352 Just (_, ls) = splitTyConApp_maybe prim_res_ty
353 arity = 1 + length ls
355 mappM newSysLocalDs ls `thenDs` \ args_ids@(result_id:as) ->
356 newSysLocalDs realWorldStatePrimTy `thenDs` \ state_id ->
358 the_rhs = return_result (Var state_id)
359 (wrap_result (Var result_id) : map Var as)
360 ccall_res_ty = mkTyConApp (tupleTyCon Unboxed arity)
361 (realWorldStatePrimTy : ls)
362 the_alt = ( DataAlt (tupleCon Unboxed arity)
363 , (state_id : args_ids)
367 returnDs (ccall_res_ty, the_alt)
370 = newSysLocalDs prim_res_ty `thenDs` \ result_id ->
371 newSysLocalDs realWorldStatePrimTy `thenDs` \ state_id ->
373 the_rhs = return_result (Var state_id)
374 [wrap_result (Var result_id)]
375 ccall_res_ty = mkTyConApp unboxedPairTyCon [realWorldStatePrimTy, prim_res_ty]
376 the_alt = (DataAlt unboxedPairDataCon, [state_id, result_id], the_rhs)
378 returnDs (ccall_res_ty, the_alt)
381 resultWrapper :: Type
382 -> DsM (Maybe Type, -- Type of the expected result, if any
383 CoreExpr -> CoreExpr) -- Wrapper for the result
384 resultWrapper result_ty
385 -- Base case 1: primitive types
386 | isPrimitiveType result_ty
387 = returnDs (Just result_ty, \e -> e)
389 -- Base case 2: the unit type ()
390 | Just (tc,_) <- maybe_tc_app, tc `hasKey` unitTyConKey
391 = returnDs (Nothing, \e -> Var unitDataConId)
393 -- Base case 3: the boolean type
394 | Just (tc,_) <- maybe_tc_app, tc `hasKey` boolTyConKey
396 (Just intPrimTy, \e -> Case e (mkWildId intPrimTy)
398 [(DEFAULT ,[],Var trueDataConId ),
399 (LitAlt (mkMachInt 0),[],Var falseDataConId)])
401 -- Recursive newtypes
402 | Just rep_ty <- splitRecNewType_maybe result_ty
403 = resultWrapper rep_ty `thenDs` \ (maybe_ty, wrapper) ->
404 returnDs (maybe_ty, \e -> mkCoerce2 result_ty rep_ty (wrapper e))
406 -- The type might contain foralls (eg. for dummy type arguments,
407 -- referring to 'Ptr a' is legal).
408 | Just (tyvar, rest) <- splitForAllTy_maybe result_ty
409 = resultWrapper rest `thenDs` \ (maybe_ty, wrapper) ->
410 returnDs (maybe_ty, \e -> Lam tyvar (wrapper e))
412 -- Data types with a single constructor, which has a single arg
413 -- This includes types like Ptr and ForeignPtr
414 | Just (tycon, tycon_arg_tys, data_con, data_con_arg_tys) <- splitProductType_maybe result_ty,
415 dataConSourceArity data_con == 1
417 (unwrapped_res_ty : _) = data_con_arg_tys
418 narrow_wrapper = maybeNarrow tycon
420 resultWrapper unwrapped_res_ty `thenDs` \ (maybe_ty, wrapper) ->
422 (maybe_ty, \e -> mkApps (Var (dataConWrapId data_con))
423 (map Type tycon_arg_tys ++ [wrapper (narrow_wrapper e)]))
425 -- Strings; 'dotnet' only.
426 | Just (tc, [arg_ty]) <- maybe_tc_app, tc == listTyCon,
427 Just (cc,[]) <- splitTyConApp_maybe arg_ty, cc == charTyCon
428 = dsLookupGlobalId unmarshalStringName `thenDs` \ pack_id ->
429 returnDs (Just addrPrimTy,
430 \ e -> App (Var pack_id) e)
432 -- Objects; 'dotnet' only.
433 | Just (tc, [arg_ty]) <- maybe_tc_app,
434 tyConName tc == objectTyConName
435 = dsLookupGlobalId unmarshalObjectName `thenDs` \ pack_id ->
436 returnDs (Just addrPrimTy,
437 \ e -> App (Var pack_id) e)
440 = pprPanic "resultWrapper" (ppr result_ty)
442 maybe_tc_app = splitTyConApp_maybe result_ty
444 -- When the result of a foreign call is smaller than the word size, we
445 -- need to sign- or zero-extend the result up to the word size. The C
446 -- standard appears to say that this is the responsibility of the
447 -- caller, not the callee.
449 maybeNarrow :: TyCon -> (CoreExpr -> CoreExpr)
451 | tycon `hasKey` int8TyConKey = \e -> App (Var (mkPrimOpId Narrow8IntOp)) e
452 | tycon `hasKey` int16TyConKey = \e -> App (Var (mkPrimOpId Narrow16IntOp)) e
453 | tycon `hasKey` int32TyConKey
454 && wORD_SIZE > 4 = \e -> App (Var (mkPrimOpId Narrow32IntOp)) e
456 | tycon `hasKey` word8TyConKey = \e -> App (Var (mkPrimOpId Narrow8WordOp)) e
457 | tycon `hasKey` word16TyConKey = \e -> App (Var (mkPrimOpId Narrow16WordOp)) e
458 | tycon `hasKey` word32TyConKey
459 && wORD_SIZE > 4 = \e -> App (Var (mkPrimOpId Narrow32WordOp)) e