2 % (c) The AQUA Project, Glasgow University, 1994-1998
4 \section[DsCCall]{Desugaring \tr{_ccall_}s and \tr{_casm_}s}
15 #include "HsVersions.h"
21 import CoreUtils ( exprType )
22 import Id ( Id, mkWildId, idType )
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(..) )
29 import TcType ( Type, isUnLiftedType, mkFunTys, mkFunTy,
30 tyVarsOfType, mkForAllTys, mkTyConApp,
31 isBoolTy, isUnitTy, isPrimitiveType
33 import Type ( splitTyConApp_maybe, repType, eqType ) -- Sees the representation type
34 import PrimOp ( PrimOp(TouchOp) )
35 import TysPrim ( realWorldStatePrimTy,
36 byteArrayPrimTyCon, mutableByteArrayPrimTyCon,
37 intPrimTy, foreignObjPrimTy
39 import TyCon ( tyConDataCons )
40 import TysWiredIn ( unitDataConId,
41 unboxedSingletonDataCon, unboxedPairDataCon,
42 unboxedSingletonTyCon, unboxedPairTyCon,
43 trueDataCon, falseDataCon,
44 trueDataConId, falseDataConId
46 import Literal ( mkMachInt )
47 import CStrings ( CLabelString )
48 import PrelNames ( Unique, hasKey, ioTyConKey )
49 import VarSet ( varSetElems )
53 Desugaring of @ccall@s consists of adding some state manipulation,
54 unboxing any boxed primitive arguments and boxing the result if
57 The state stuff just consists of adding in
58 @PrimIO (\ s -> case s of { S# s# -> ... })@ in an appropriate place.
60 The unboxing is straightforward, as all information needed to unbox is
61 available from the type. For each boxed-primitive argument, we
64 _ccall_ foo [ r, t1, ... tm ] e1 ... em
68 case e1 of { T1# x1# ->
70 case em of { Tm# xm# -> xm#
71 ccall# foo [ r, t1#, ... tm# ] x1# ... xm#
75 The reboxing of a @_ccall_@ result is a bit tricker: the types don't
76 contain information about the state-pairing functions so we have to
77 keep a list of \tr{(type, s-p-function)} pairs. We transform as
80 ccall# foo [ r, t1#, ... tm# ] e1# ... em#
84 \ s# -> case (ccall# foo [ r, t1#, ... tm# ] s# e1# ... em#) of
85 (StateAnd<r># result# state#) -> (R# result#, realWorld#)
89 dsCCall :: CLabelString -- C routine to invoke
90 -> [CoreExpr] -- Arguments (desugared)
91 -> Safety -- Safety of the call
92 -> Bool -- True <=> really a "_casm_"
93 -> Type -- Type of the result: IO t
96 dsCCall lbl args may_gc is_asm result_ty
97 = mapAndUnzipDs unboxArg args `thenDs` \ (unboxed_args, arg_wrappers) ->
98 boxResult [] result_ty `thenDs` \ (ccall_result_ty, res_wrapper) ->
99 getUniqueDs `thenDs` \ uniq ->
101 target | is_asm = CasmTarget lbl
102 | otherwise = StaticTarget lbl
103 the_fcall = CCall (CCallSpec target CCallConv may_gc)
104 the_prim_app = mkFCall uniq the_fcall unboxed_args ccall_result_ty
106 returnDs (foldr ($) (res_wrapper the_prim_app) arg_wrappers)
108 mkFCall :: Unique -> ForeignCall
109 -> [CoreExpr] -- Args
110 -> Type -- Result type
112 -- Construct the ccall. The only tricky bit is that the ccall Id should have
113 -- no free vars, so if any of the arg tys do we must give it a polymorphic type.
114 -- [I forget *why* it should have no free vars!]
116 -- mkCCall ... [s::StablePtr (a->b), x::Addr, c::Char]
118 -- Here we build a ccall thus
119 -- (ccallid::(forall a b. StablePtr (a -> b) -> Addr -> Char -> IO Addr))
121 mkFCall uniq the_fcall val_args res_ty
122 = mkApps (mkVarApps (Var the_fcall_id) tyvars) val_args
124 arg_tys = map exprType val_args
125 body_ty = (mkFunTys arg_tys res_ty)
126 tyvars = varSetElems (tyVarsOfType body_ty)
127 ty = mkForAllTys tyvars body_ty
128 the_fcall_id = mkFCallId uniq the_fcall ty
132 unboxArg :: CoreExpr -- The supplied argument
133 -> DsM (CoreExpr, -- To pass as the actual argument
134 CoreExpr -> CoreExpr -- Wrapper to unbox the arg
136 -- Example: if the arg is e::Int, unboxArg will return
137 -- (x#::Int#, \W. case x of I# x# -> W)
138 -- where W is a CoreExpr that probably mentions x#
141 -- Primtive types: nothing to unbox
142 | isPrimitiveType arg_ty
143 = returnDs (arg, \body -> body)
147 = newSysLocalDs intPrimTy `thenDs` \ prim_arg ->
148 returnDs (Var prim_arg,
149 \ body -> Case (Case arg (mkWildId arg_ty)
150 [(DataAlt falseDataCon,[],mkIntLit 0),
151 (DataAlt trueDataCon, [],mkIntLit 1)])
156 -- Data types with a single constructor, which has a single, primitive-typed arg
157 -- This deals with Int, Float etc
158 | is_product_type && data_con_arity == 1
159 = ASSERT(isUnLiftedType data_con_arg_ty1 ) -- Typechecker ensures this
160 newSysLocalDs arg_ty `thenDs` \ case_bndr ->
161 newSysLocalDs data_con_arg_ty1 `thenDs` \ prim_arg ->
162 returnDs (Var prim_arg,
163 \ body -> Case arg case_bndr [(DataAlt data_con,[prim_arg],body)]
166 -- Byte-arrays, both mutable and otherwise; hack warning
168 data_con_arity == 3 &&
169 maybeToBool maybe_arg3_tycon &&
170 (arg3_tycon == byteArrayPrimTyCon ||
171 arg3_tycon == mutableByteArrayPrimTyCon)
172 -- and, of course, it is an instance of CCallable
173 = newSysLocalDs arg_ty `thenDs` \ case_bndr ->
174 newSysLocalsDs data_con_arg_tys `thenDs` \ vars@[l_var, r_var, arr_cts_var] ->
175 returnDs (Var arr_cts_var,
176 \ body -> Case arg case_bndr [(DataAlt data_con,vars,body)]
180 = getSrcLocDs `thenDs` \ l ->
181 pprPanic "unboxArg: " (ppr l <+> ppr arg_ty)
183 arg_ty = repType (exprType arg)
184 -- The repType looks through any newtype or
185 -- implicit-parameter wrappings on the argument.
186 maybe_product_type = splitProductType_maybe arg_ty
187 is_product_type = maybeToBool maybe_product_type
188 Just (_, _, data_con, data_con_arg_tys) = maybe_product_type
189 data_con_arity = dataConSourceArity data_con
190 (data_con_arg_ty1 : _) = data_con_arg_tys
192 (_ : _ : data_con_arg_ty3 : _) = data_con_arg_tys
193 maybe_arg3_tycon = splitTyConApp_maybe data_con_arg_ty3
194 Just (arg3_tycon,_) = maybe_arg3_tycon
199 boxResult :: [Id] -> Type -> DsM (Type, CoreExpr -> CoreExpr)
201 -- Takes the result of the user-level ccall:
203 -- or maybe just t for an side-effect-free call
204 -- Returns a wrapper for the primitive ccall itself, along with the
205 -- type of the result of the primitive ccall. This result type
206 -- will be of the form
207 -- State# RealWorld -> (# State# RealWorld, t' #)
208 -- where t' is the unwrapped form of t. If t is simply (), then
209 -- the result type will be
210 -- State# RealWorld -> (# State# RealWorld #)
212 -- Here is where we arrange that ForeignPtrs which are passed to a 'safe'
213 -- foreign import don't get finalized until the call returns. For each
214 -- argument of type ForeignObj# we arrange to touch# the argument after
215 -- the call. The arg_ids passed in are the Ids passed to the actual ccall.
217 boxResult arg_ids result_ty
218 = case splitTyConApp_maybe result_ty of
220 -- The result is IO t, so wrap the result in an IO constructor
221 Just (io_tycon, [io_res_ty]) | io_tycon `hasKey` ioTyConKey
222 -> mk_alt return_result
223 (resultWrapper io_res_ty) `thenDs` \ (ccall_res_ty, the_alt) ->
224 newSysLocalDs realWorldStatePrimTy `thenDs` \ state_id ->
226 io_data_con = head (tyConDataCons io_tycon)
228 mkApps (Var (dataConWrapId io_data_con))
231 Case (App the_call (Var state_id))
232 (mkWildId ccall_res_ty)
236 returnDs (realWorldStatePrimTy `mkFunTy` ccall_res_ty, wrap)
238 return_result state ans = mkConApp unboxedPairDataCon
239 [Type realWorldStatePrimTy, Type io_res_ty,
242 -- It isn't, so do unsafePerformIO
243 -- It's not conveniently available, so we inline it
244 other -> mk_alt return_result
245 (resultWrapper result_ty) `thenDs` \ (ccall_res_ty, the_alt) ->
247 wrap = \ the_call -> Case (App the_call (Var realWorldPrimId))
248 (mkWildId ccall_res_ty)
251 returnDs (realWorldStatePrimTy `mkFunTy` ccall_res_ty, wrap)
253 return_result state ans = ans
255 mk_alt return_result (Nothing, wrap_result)
256 = -- The ccall returns ()
258 rhs_fun state_id = return_result (Var state_id)
259 (wrap_result (panic "boxResult"))
261 newSysLocalDs realWorldStatePrimTy `thenDs` \ state_id ->
262 mkTouches arg_ids state_id rhs_fun `thenDs` \ the_rhs ->
264 ccall_res_ty = mkTyConApp unboxedSingletonTyCon [realWorldStatePrimTy]
265 the_alt = (DataAlt unboxedSingletonDataCon, [state_id], the_rhs)
267 returnDs (ccall_res_ty, the_alt)
269 mk_alt return_result (Just prim_res_ty, wrap_result)
270 = -- The ccall returns a non-() value
271 newSysLocalDs prim_res_ty `thenDs` \ result_id ->
273 rhs_fun state_id = return_result (Var state_id)
274 (wrap_result (Var result_id))
276 newSysLocalDs realWorldStatePrimTy `thenDs` \ state_id ->
277 mkTouches arg_ids state_id rhs_fun `thenDs` \ the_rhs ->
279 ccall_res_ty = mkTyConApp unboxedPairTyCon [realWorldStatePrimTy, prim_res_ty]
280 the_alt = (DataAlt unboxedPairDataCon, [state_id, result_id], the_rhs)
282 returnDs (ccall_res_ty, the_alt)
284 touchzh = mkPrimOpId TouchOp
286 mkTouches [] s cont = returnDs (cont s)
287 mkTouches (v:vs) s cont
288 | not (idType v `eqType` foreignObjPrimTy) = mkTouches vs s cont
289 | otherwise = newSysLocalDs realWorldStatePrimTy `thenDs` \s' ->
290 mkTouches vs s' cont `thenDs` \ rest ->
291 returnDs (Case (mkApps (Var touchzh) [Type foreignObjPrimTy,
293 [(DEFAULT, [], rest)])
295 resultWrapper :: Type
296 -> (Maybe Type, -- Type of the expected result, if any
297 CoreExpr -> CoreExpr) -- Wrapper for the result
298 resultWrapper result_ty
299 -- Base case 1: primitive types
300 | isPrimitiveType result_ty_rep
301 = (Just result_ty, \e -> e)
303 -- Base case 2: the unit type ()
304 | isUnitTy result_ty_rep
305 = (Nothing, \e -> Var unitDataConId)
307 -- Base case 3: the boolean type ()
308 | isBoolTy result_ty_rep
309 = (Just intPrimTy, \e -> Case e (mkWildId intPrimTy)
310 [(DEFAULT ,[],Var trueDataConId ),
311 (LitAlt (mkMachInt 0),[],Var falseDataConId)])
313 -- Data types with a single constructor, which has a single arg
314 | Just (_, tycon_arg_tys, data_con, data_con_arg_tys) <- splitProductType_maybe result_ty_rep,
315 dataConSourceArity data_con == 1
317 (maybe_ty, wrapper) = resultWrapper unwrapped_res_ty
318 (unwrapped_res_ty : _) = data_con_arg_tys
320 (maybe_ty, \e -> mkApps (Var (dataConWrapId data_con))
321 (map Type tycon_arg_tys ++ [wrapper e]))
324 = pprPanic "resultWrapper" (ppr result_ty)
326 result_ty_rep = repType result_ty