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, mkCoerce )
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(..) )
28 import TcType ( isUnLiftedType, mkFunTys,
29 tcSplitTyConApp_maybe, tyVarsOfType, mkForAllTys, isPrimitiveType,
30 isUnLiftedType, mkFunTy, mkTyConApp,
31 tcEqType, isBoolTy, isUnitTy,
34 import Type ( repType )
35 import PrimOp ( PrimOp(TouchOp) )
36 import TysPrim ( realWorldStatePrimTy,
37 byteArrayPrimTyCon, mutableByteArrayPrimTyCon,
38 intPrimTy, foreignObjPrimTy
40 import TyCon ( tyConDataCons )
41 import TysWiredIn ( unitDataConId,
42 unboxedSingletonDataCon, unboxedPairDataCon,
43 unboxedSingletonTyCon, unboxedPairTyCon,
44 trueDataCon, falseDataCon,
45 trueDataConId, falseDataConId
47 import Literal ( mkMachInt )
48 import CStrings ( CLabelString )
49 import PrelNames ( Unique, hasKey, ioTyConKey )
50 import VarSet ( varSetElems )
54 Desugaring of @ccall@s consists of adding some state manipulation,
55 unboxing any boxed primitive arguments and boxing the result if
58 The state stuff just consists of adding in
59 @PrimIO (\ s -> case s of { S# s# -> ... })@ in an appropriate place.
61 The unboxing is straightforward, as all information needed to unbox is
62 available from the type. For each boxed-primitive argument, we
65 _ccall_ foo [ r, t1, ... tm ] e1 ... em
69 case e1 of { T1# x1# ->
71 case em of { Tm# xm# -> xm#
72 ccall# foo [ r, t1#, ... tm# ] x1# ... xm#
76 The reboxing of a @_ccall_@ result is a bit tricker: the types don't
77 contain information about the state-pairing functions so we have to
78 keep a list of \tr{(type, s-p-function)} pairs. We transform as
81 ccall# foo [ r, t1#, ... tm# ] e1# ... em#
85 \ s# -> case (ccall# foo [ r, t1#, ... tm# ] s# e1# ... em#) of
86 (StateAnd<r># result# state#) -> (R# result#, realWorld#)
90 dsCCall :: CLabelString -- C routine to invoke
91 -> [CoreExpr] -- Arguments (desugared)
92 -> Safety -- Safety of the call
93 -> Bool -- True <=> really a "_casm_"
94 -> Type -- Type of the result: IO t
97 dsCCall lbl args may_gc is_asm result_ty
98 = mapAndUnzipDs unboxArg args `thenDs` \ (unboxed_args, arg_wrappers) ->
99 boxResult [] result_ty `thenDs` \ (ccall_result_ty, res_wrapper) ->
100 getUniqueDs `thenDs` \ uniq ->
102 target | is_asm = CasmTarget lbl
103 | otherwise = StaticTarget lbl
104 the_fcall = CCall (CCallSpec target CCallConv may_gc)
105 the_prim_app = mkFCall uniq the_fcall unboxed_args ccall_result_ty
107 returnDs (foldr ($) (res_wrapper the_prim_app) arg_wrappers)
109 mkFCall :: Unique -> ForeignCall
110 -> [CoreExpr] -- Args
111 -> Type -- Result type
113 -- Construct the ccall. The only tricky bit is that the ccall Id should have
114 -- no free vars, so if any of the arg tys do we must give it a polymorphic type.
115 -- [I forget *why* it should have no free vars!]
117 -- mkCCall ... [s::StablePtr (a->b), x::Addr, c::Char]
119 -- Here we build a ccall thus
120 -- (ccallid::(forall a b. StablePtr (a -> b) -> Addr -> Char -> IO Addr))
122 mkFCall uniq the_fcall val_args res_ty
123 = mkApps (mkVarApps (Var the_fcall_id) tyvars) val_args
125 arg_tys = map exprType val_args
126 body_ty = (mkFunTys arg_tys res_ty)
127 tyvars = varSetElems (tyVarsOfType body_ty)
128 ty = mkForAllTys tyvars body_ty
129 the_fcall_id = mkFCallId uniq the_fcall ty
133 unboxArg :: CoreExpr -- The supplied argument
134 -> DsM (CoreExpr, -- To pass as the actual argument
135 CoreExpr -> CoreExpr -- Wrapper to unbox the arg
137 -- Example: if the arg is e::Int, unboxArg will return
138 -- (x#::Int#, \W. case x of I# x# -> W)
139 -- where W is a CoreExpr that probably mentions x#
142 -- Primtive types: nothing to unbox
143 | isPrimitiveType arg_ty
144 = returnDs (arg, \body -> body)
148 = newSysLocalDs intPrimTy `thenDs` \ prim_arg ->
149 returnDs (Var prim_arg,
150 \ body -> Case (Case arg (mkWildId arg_ty)
151 [(DataAlt falseDataCon,[],mkIntLit 0),
152 (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 = exprType arg
184 maybe_product_type = splitProductType_maybe arg_ty
185 is_product_type = maybeToBool maybe_product_type
186 Just (_, _, data_con, data_con_arg_tys) = maybe_product_type
187 data_con_arity = dataConSourceArity data_con
188 (data_con_arg_ty1 : _) = data_con_arg_tys
190 (_ : _ : data_con_arg_ty3 : _) = data_con_arg_tys
191 maybe_arg3_tycon = tcSplitTyConApp_maybe data_con_arg_ty3
192 Just (arg3_tycon,_) = maybe_arg3_tycon
197 boxResult :: [Id] -> Type -> DsM (Type, CoreExpr -> CoreExpr)
199 -- Takes the result of the user-level ccall:
201 -- or maybe just t for an side-effect-free call
202 -- Returns a wrapper for the primitive ccall itself, along with the
203 -- type of the result of the primitive ccall. This result type
204 -- will be of the form
205 -- State# RealWorld -> (# State# RealWorld, t' #)
206 -- where t' is the unwrapped form of t. If t is simply (), then
207 -- the result type will be
208 -- State# RealWorld -> (# State# RealWorld #)
210 -- Here is where we arrange that ForeignPtrs which are passed to a 'safe'
211 -- foreign import don't get finalized until the call returns. For each
212 -- argument of type ForeignObj# we arrange to touch# the argument after
213 -- the call. The arg_ids passed in are the Ids passed to the actual ccall.
215 boxResult arg_ids result_ty
216 = case tcSplitTyConApp_maybe result_ty of
218 -- The result is IO t, so wrap the result in an IO constructor
219 Just (io_tycon, [io_res_ty]) | io_tycon `hasKey` ioTyConKey
220 -> mk_alt return_result
221 (resultWrapper io_res_ty) `thenDs` \ (ccall_res_ty, the_alt) ->
222 newSysLocalDs realWorldStatePrimTy `thenDs` \ state_id ->
224 io_data_con = head (tyConDataCons io_tycon)
226 mkApps (Var (dataConWrapId io_data_con))
229 Case (App the_call (Var state_id))
230 (mkWildId ccall_res_ty)
234 returnDs (realWorldStatePrimTy `mkFunTy` ccall_res_ty, wrap)
236 return_result state ans = mkConApp unboxedPairDataCon
237 [Type realWorldStatePrimTy, Type io_res_ty,
240 -- It isn't, so do unsafePerformIO
241 -- It's not conveniently available, so we inline it
242 other -> mk_alt return_result
243 (resultWrapper result_ty) `thenDs` \ (ccall_res_ty, the_alt) ->
245 wrap = \ the_call -> Case (App the_call (Var realWorldPrimId))
246 (mkWildId ccall_res_ty)
249 returnDs (realWorldStatePrimTy `mkFunTy` ccall_res_ty, wrap)
251 return_result state ans = ans
253 mk_alt return_result (Nothing, wrap_result)
254 = -- The ccall returns ()
256 rhs_fun state_id = return_result (Var state_id)
257 (wrap_result (panic "boxResult"))
259 newSysLocalDs realWorldStatePrimTy `thenDs` \ state_id ->
260 mkTouches arg_ids state_id rhs_fun `thenDs` \ the_rhs ->
262 ccall_res_ty = mkTyConApp unboxedSingletonTyCon [realWorldStatePrimTy]
263 the_alt = (DataAlt unboxedSingletonDataCon, [state_id], the_rhs)
265 returnDs (ccall_res_ty, the_alt)
267 mk_alt return_result (Just prim_res_ty, wrap_result)
268 = -- The ccall returns a non-() value
269 newSysLocalDs prim_res_ty `thenDs` \ result_id ->
271 rhs_fun state_id = return_result (Var state_id)
272 (wrap_result (Var result_id))
274 newSysLocalDs realWorldStatePrimTy `thenDs` \ state_id ->
275 mkTouches arg_ids state_id rhs_fun `thenDs` \ the_rhs ->
277 ccall_res_ty = mkTyConApp unboxedPairTyCon [realWorldStatePrimTy, prim_res_ty]
278 the_alt = (DataAlt unboxedPairDataCon, [state_id, result_id], the_rhs)
280 returnDs (ccall_res_ty, the_alt)
282 touchzh = mkPrimOpId TouchOp
284 mkTouches [] s cont = returnDs (cont s)
285 mkTouches (v:vs) s cont
286 | not (idType v `tcEqType` foreignObjPrimTy) = mkTouches vs s cont
287 | otherwise = newSysLocalDs realWorldStatePrimTy `thenDs` \s' ->
288 mkTouches vs s' cont `thenDs` \ rest ->
289 returnDs (Case (mkApps (Var touchzh) [Type foreignObjPrimTy,
291 [(DEFAULT, [], rest)])
293 resultWrapper :: Type
294 -> (Maybe Type, -- Type of the expected result, if any
295 CoreExpr -> CoreExpr) -- Wrapper for the result
296 resultWrapper result_ty
297 -- Base case 1: primitive types
298 | isPrimitiveType result_ty
299 = (Just result_ty, \e -> e)
301 -- Base case 1: the unit type ()
303 = (Nothing, \e -> Var unitDataConId)
306 = (Just intPrimTy, \e -> Case e (mkWildId intPrimTy)
307 [(DEFAULT ,[],Var trueDataConId ),
308 (LitAlt (mkMachInt 0),[],Var falseDataConId)])
310 -- Data types with a single constructor, which has a single arg
311 | is_product_type && data_con_arity == 1
313 (maybe_ty, wrapper) = resultWrapper unwrapped_res_ty
314 (unwrapped_res_ty : _) = data_con_arg_tys
316 (maybe_ty, \e -> mkApps (Var (dataConWrapId data_con))
317 (map Type tycon_arg_tys ++ [wrapper e]))
320 = pprPanic "resultWrapper" (ppr result_ty)
322 maybe_product_type = splitProductType_maybe result_ty
323 is_product_type = maybeToBool maybe_product_type
324 Just (_, tycon_arg_tys, data_con, data_con_arg_tys) = maybe_product_type
325 data_con_arity = dataConSourceArity data_con