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 )
29 import ForeignCall ( ForeignCall, CCallTarget(..) )
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,
39 import PrimOp ( PrimOp(..) )
40 import TysPrim ( realWorldStatePrimTy, intPrimTy,
41 byteArrayPrimTyCon, mutableByteArrayPrimTyCon,
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,
53 import BasicTypes ( Boxity(..) )
54 import Literal ( mkMachInt )
55 import PrelNames ( Unique, hasKey, ioTyConKey, boolTyConKey, unitTyConKey,
56 int8TyConKey, int16TyConKey, int32TyConKey,
57 word8TyConKey, word16TyConKey, word32TyConKey
59 , marshalStringName, unmarshalStringName
60 , marshalObjectName, unmarshalObjectName
63 import VarSet ( varSetElems )
64 import Constants ( wORD_SIZE)
73 Desugaring of @ccall@s consists of adding some state manipulation,
74 unboxing any boxed primitive arguments and boxing the result if
77 The state stuff just consists of adding in
78 @PrimIO (\ s -> case s of { S# s# -> ... })@ in an appropriate place.
80 The unboxing is straightforward, as all information needed to unbox is
81 available from the type. For each boxed-primitive argument, we
84 _ccall_ foo [ r, t1, ... tm ] e1 ... em
88 case e1 of { T1# x1# ->
90 case em of { Tm# xm# -> xm#
91 ccall# foo [ r, t1#, ... tm# ] x1# ... xm#
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
100 ccall# foo [ r, t1#, ... tm# ] e1# ... em#
104 \ s# -> case (ccall# foo [ r, t1#, ... tm# ] s# e1# ... em#) of
105 (StateAnd<r># result# state#) -> (R# result#, realWorld#)
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
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 ->
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
124 returnDs (foldr ($) (res_wrapper the_prim_app) arg_wrappers)
126 mkFCall :: Unique -> ForeignCall
127 -> [CoreExpr] -- Args
128 -> Type -- Result type
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!]
134 -- mkCCall ... [s::StablePtr (a->b), x::Addr, c::Char]
136 -- Here we build a ccall thus
137 -- (ccallid::(forall a b. StablePtr (a -> b) -> Addr -> Char -> IO Addr))
139 mkFCall uniq the_fcall val_args res_ty
140 = mkApps (mkVarApps (Var the_fcall_id) tyvars) val_args
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
150 unboxArg :: CoreExpr -- The supplied argument
151 -> DsM (CoreExpr, -- To pass as the actual argument
152 CoreExpr -> CoreExpr -- Wrapper to unbox the arg
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#
159 -- Primtive types: nothing to unbox
160 | isPrimitiveType arg_ty
161 = returnDs (arg, \body -> body)
163 -- Recursive newtypes
164 | Just rep_ty <- splitRecNewType_maybe arg_ty
165 = unboxArg (mkCoerce2 rep_ty arg_ty arg)
168 | Just (tc,_) <- splitTyConApp_maybe arg_ty,
169 tc `hasKey` boolTyConKey
170 = newSysLocalDs intPrimTy `thenDs` \ prim_arg ->
171 returnDs (Var prim_arg,
173 \ body -> Case (Case arg (mkWildId arg_ty) intPrimTy
174 [(DataAlt falseDataCon,[],mkIntLit 0),
175 (DataAlt trueDataCon, [],mkIntLit 1)])
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,
190 \ body -> Case arg case_bndr (exprType body) [(DataAlt data_con,[prim_arg],body)]
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)
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,
207 \ body -> Case arg case_bndr (exprType body) [(DataAlt data_con,vars,body)]
211 | Just (tc, [arg_ty]) <- splitTyConApp_maybe arg_ty,
213 Just (cc,[]) <- splitTyConApp_maybe arg_ty,
215 -- String; dotnet only
216 = dsLookupGlobalId marshalStringName `thenDs` \ unpack_id ->
217 newSysLocalDs addrPrimTy `thenDs` \ prim_string ->
218 returnDs (Var prim_string,
221 io_ty = exprType body
222 (Just (_,[io_arg])) = tcSplitTyConApp_maybe io_ty
224 mkApps (Var unpack_id)
227 , Lam prim_string body
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,
237 io_ty = exprType body
238 (Just (_,[io_arg])) = tcSplitTyConApp_maybe io_ty
240 mkApps (Var unpack_id)
247 = getSrcSpanDs `thenDs` \ l ->
248 pprPanic "unboxArg: " (ppr l <+> ppr arg_ty)
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
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
265 -> ((Maybe Type, CoreExpr -> CoreExpr) -> (Maybe Type, CoreExpr -> CoreExpr))
268 -> DsM (Type, CoreExpr -> CoreExpr)
270 -- Takes the result of the user-level ccall:
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 #)
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.
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
293 | isUnboxedTupleType ty ->
294 let (Just (_, ls)) = splitTyConApp_maybe ty in tail ls
297 mk_alt (return_result extra_result_tys) aug_res
298 `thenDs` \ (ccall_res_ty, the_alt) ->
299 newSysLocalDs realWorldStatePrimTy `thenDs` \ state_id ->
301 io_data_con = head (tyConDataCons io_tycon)
304 Nothing -> dataConWrapId io_data_con
310 Case (App the_call (Var state_id))
311 (mkWildId ccall_res_ty)
313 (coreAltType the_alt)
317 returnDs (realWorldStatePrimTy `mkFunTy` ccall_res_ty, wrap)
319 return_result ts state anss
320 = mkConApp (tupleCon Unboxed (2 + length ts))
321 (Type realWorldStatePrimTy : Type io_res_ty : map Type ts ++
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) ->
328 wrap = \ the_call -> Case (App the_call (Var realWorldPrimId))
329 (mkWildId ccall_res_ty)
331 (coreAltType the_alt)
334 returnDs (realWorldStatePrimTy `mkFunTy` ccall_res_ty, wrap)
336 return_result state [ans] = ans
337 return_result _ _ = panic "return_result: expected single result"
339 mk_alt return_result (Nothing, wrap_result)
340 = -- The ccall returns ()
341 newSysLocalDs realWorldStatePrimTy `thenDs` \ state_id ->
343 the_rhs = return_result (Var state_id)
344 [wrap_result (panic "boxResult")]
346 ccall_res_ty = mkTyConApp unboxedSingletonTyCon [realWorldStatePrimTy]
347 the_alt = (DataAlt unboxedSingletonDataCon, [state_id], the_rhs)
349 returnDs (ccall_res_ty, the_alt)
351 mk_alt return_result (Just prim_res_ty, wrap_result)
352 -- The ccall returns a non-() value
353 | isUnboxedTupleType prim_res_ty
355 Just (_, ls) = splitTyConApp_maybe prim_res_ty
356 arity = 1 + length ls
358 mappM newSysLocalDs ls `thenDs` \ args_ids@(result_id:as) ->
359 newSysLocalDs realWorldStatePrimTy `thenDs` \ state_id ->
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)
370 returnDs (ccall_res_ty, the_alt)
372 = newSysLocalDs prim_res_ty `thenDs` \ result_id ->
373 newSysLocalDs realWorldStatePrimTy `thenDs` \ state_id ->
375 the_rhs = return_result (Var state_id)
376 [wrap_result (Var result_id)]
378 ccall_res_ty = mkTyConApp unboxedPairTyCon [realWorldStatePrimTy, prim_res_ty]
379 the_alt = (DataAlt unboxedPairDataCon, [state_id, result_id], the_rhs)
381 returnDs (ccall_res_ty, the_alt)
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)
392 -- Base case 2: the unit type ()
393 | Just (tc,_) <- maybe_tc_app, tc `hasKey` unitTyConKey
394 = returnDs (Nothing, \e -> Var unitDataConId)
396 -- Base case 3: the boolean type
397 | Just (tc,_) <- maybe_tc_app, tc `hasKey` boolTyConKey
399 (Just intPrimTy, \e -> Case e (mkWildId intPrimTy)
402 [(DEFAULT ,[],Var trueDataConId ),
403 (LitAlt (mkMachInt 0),[],Var falseDataConId)])
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))
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))
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
421 (unwrapped_res_ty : _) = data_con_arg_tys
422 narrow_wrapper = maybeNarrow tycon
424 resultWrapper unwrapped_res_ty `thenDs` \ (maybe_ty, wrapper) ->
426 (maybe_ty, \e -> mkApps (Var (dataConWrapId data_con))
427 (map Type tycon_arg_tys ++ [wrapper (narrow_wrapper e)]))
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)
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)
444 = pprPanic "resultWrapper" (ppr result_ty)
446 maybe_tc_app = splitTyConApp_maybe result_ty
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.
453 maybeNarrow :: TyCon -> (CoreExpr -> CoreExpr)
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
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