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 ( mkCCallOpId, realWorldPrimId, mkPrimOpId )
24 import Maybes ( maybeToBool )
25 import PrimOp ( CCall(..), CCallTarget(..) )
26 import DataCon ( splitProductType_maybe, dataConSourceArity, dataConWrapId )
28 import Type ( isUnLiftedType, splitAlgTyConApp_maybe, mkFunTys,
29 splitTyConApp_maybe, tyVarsOfType, mkForAllTys,
30 isNewType, repType, isUnLiftedType, mkFunTy, mkTyConApp,
33 import PrimOp ( PrimOp(TouchOp) )
34 import TysPrim ( realWorldStatePrimTy,
35 byteArrayPrimTyCon, mutableByteArrayPrimTyCon,
36 intPrimTy, foreignObjPrimTy
38 import TysWiredIn ( unitDataConId,
39 unboxedSingletonDataCon, unboxedPairDataCon,
40 unboxedSingletonTyCon, unboxedPairTyCon,
41 boolTy, trueDataCon, falseDataCon,
42 trueDataConId, falseDataConId, unitTy
44 import Literal ( mkMachInt )
45 import CStrings ( CLabelString )
46 import PrelNames ( Unique, hasKey, ioTyConKey )
47 import VarSet ( varSetElems )
51 Desugaring of @ccall@s consists of adding some state manipulation,
52 unboxing any boxed primitive arguments and boxing the result if
55 The state stuff just consists of adding in
56 @PrimIO (\ s -> case s of { S# s# -> ... })@ in an appropriate place.
58 The unboxing is straightforward, as all information needed to unbox is
59 available from the type. For each boxed-primitive argument, we
62 _ccall_ foo [ r, t1, ... tm ] e1 ... em
66 case e1 of { T1# x1# ->
68 case em of { Tm# xm# -> xm#
69 ccall# foo [ r, t1#, ... tm# ] x1# ... xm#
73 The reboxing of a @_ccall_@ result is a bit tricker: the types don't
74 contain information about the state-pairing functions so we have to
75 keep a list of \tr{(type, s-p-function)} pairs. We transform as
78 ccall# foo [ r, t1#, ... tm# ] e1# ... em#
82 \ s# -> case (ccall# foo [ r, t1#, ... tm# ] s# e1# ... em#) of
83 (StateAnd<r># result# state#) -> (R# result#, realWorld#)
87 dsCCall :: CLabelString -- C routine to invoke
88 -> [CoreExpr] -- Arguments (desugared)
89 -> Bool -- True <=> might cause Haskell GC
90 -> Bool -- True <=> really a "_casm_"
91 -> Type -- Type of the result: IO t
94 dsCCall lbl args may_gc is_asm result_ty
95 = mapAndUnzipDs unboxArg args `thenDs` \ (unboxed_args, arg_wrappers) ->
96 boxResult [] result_ty `thenDs` \ (ccall_result_ty, res_wrapper) ->
97 getUniqueDs `thenDs` \ uniq ->
99 the_ccall = CCall (StaticTarget lbl) is_asm may_gc cCallConv
100 the_prim_app = mkCCall uniq the_ccall unboxed_args ccall_result_ty
102 returnDs (foldr ($) (res_wrapper the_prim_app) arg_wrappers)
104 mkCCall :: Unique -> CCall
105 -> [CoreExpr] -- Args
106 -> Type -- Result type
108 -- Construct the ccall. The only tricky bit is that the ccall Id should have
109 -- no free vars, so if any of the arg tys do we must give it a polymorphic type.
110 -- [I forget *why* it should have no free vars!]
112 -- mkCCall ... [s::StablePtr (a->b), x::Addr, c::Char]
114 -- Here we build a ccall thus
115 -- (ccallid::(forall a b. StablePtr (a -> b) -> Addr -> Char -> IO Addr))
117 mkCCall uniq the_ccall val_args res_ty
118 = mkApps (mkVarApps (Var the_ccall_id) tyvars) val_args
120 arg_tys = map exprType val_args
121 body_ty = (mkFunTys arg_tys res_ty)
122 tyvars = varSetElems (tyVarsOfType body_ty)
123 ty = mkForAllTys tyvars body_ty
124 the_ccall_id = mkCCallOpId uniq the_ccall ty
128 unboxArg :: CoreExpr -- The supplied argument
129 -> DsM (CoreExpr, -- To pass as the actual argument
130 CoreExpr -> CoreExpr -- Wrapper to unbox the arg
132 -- Example: if the arg is e::Int, unboxArg will return
133 -- (x#::Int#, \W. case x of I# x# -> W)
134 -- where W is a CoreExpr that probably mentions x#
137 -- Unlifted types: nothing to unbox
138 | isUnLiftedType arg_ty
139 = returnDs (arg, \body -> body)
143 = unboxArg (mkCoerce (repType arg_ty) arg_ty arg)
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)])
155 -- Data types with a single constructor, which has a single, primitive-typed arg
156 -- This deals with Int, Float etc
157 | is_product_type && data_con_arity == 1
158 = ASSERT(isUnLiftedType data_con_arg_ty1 ) -- Typechecker ensures this
159 newSysLocalDs arg_ty `thenDs` \ case_bndr ->
160 newSysLocalDs data_con_arg_ty1 `thenDs` \ prim_arg ->
161 returnDs (Var prim_arg,
162 \ body -> Case arg case_bndr [(DataAlt data_con,[prim_arg],body)]
165 -- Byte-arrays, both mutable and otherwise; hack warning
167 data_con_arity == 3 &&
168 maybeToBool maybe_arg3_tycon &&
169 (arg3_tycon == byteArrayPrimTyCon ||
170 arg3_tycon == mutableByteArrayPrimTyCon)
171 -- and, of course, it is an instance of CCallable
172 = newSysLocalDs arg_ty `thenDs` \ case_bndr ->
173 newSysLocalsDs data_con_arg_tys `thenDs` \ vars@[l_var, r_var, arr_cts_var] ->
174 returnDs (Var arr_cts_var,
175 \ body -> Case arg case_bndr [(DataAlt data_con,vars,body)]
179 = getSrcLocDs `thenDs` \ l ->
180 pprPanic "unboxArg: " (ppr l <+> ppr arg_ty)
182 arg_ty = exprType arg
183 maybe_product_type = splitProductType_maybe arg_ty
184 is_product_type = maybeToBool maybe_product_type
185 Just (_, _, data_con, data_con_arg_tys) = maybe_product_type
186 data_con_arity = dataConSourceArity data_con
187 (data_con_arg_ty1 : _) = data_con_arg_tys
189 (_ : _ : data_con_arg_ty3 : _) = data_con_arg_tys
190 maybe_arg3_tycon = splitTyConApp_maybe data_con_arg_ty3
191 Just (arg3_tycon,_) = maybe_arg3_tycon
196 boxResult :: [Id] -> Type -> DsM (Type, CoreExpr -> CoreExpr)
198 -- Takes the result of the user-level ccall:
200 -- or maybe just t for an side-effect-free call
201 -- Returns a wrapper for the primitive ccall itself, along with the
202 -- type of the result of the primitive ccall. This result type
203 -- will be of the form
204 -- State# RealWorld -> (# State# RealWorld, t' #)
205 -- where t' is the unwrapped form of t. If t is simply (), then
206 -- the result type will be
207 -- State# RealWorld -> (# State# RealWorld #)
209 -- Here is where we arrange that ForeignPtrs which are passed to a 'safe'
210 -- foreign import don't get finalized until the call returns. For each
211 -- argument of type ForeignObj# we arrange to touch# the argument after
212 -- the call. The arg_ids passed in are the Ids passed to the actual ccall.
214 boxResult arg_ids result_ty
215 = case splitAlgTyConApp_maybe result_ty of
217 -- The result is IO t, so wrap the result in an IO constructor
218 Just (io_tycon, [io_res_ty], [io_data_con]) | io_tycon `hasKey` ioTyConKey
219 -> mk_alt return_result
220 (resultWrapper io_res_ty) `thenDs` \ (ccall_res_ty, the_alt) ->
221 newSysLocalDs realWorldStatePrimTy `thenDs` \ state_id ->
224 mkApps (Var (dataConWrapId io_data_con))
227 Case (App the_call (Var state_id))
228 (mkWildId ccall_res_ty)
232 returnDs (realWorldStatePrimTy `mkFunTy` ccall_res_ty, wrap)
234 return_result state ans = mkConApp unboxedPairDataCon
235 [Type realWorldStatePrimTy, Type io_res_ty,
238 -- It isn't, so do unsafePerformIO
239 -- It's not conveniently available, so we inline it
240 other -> mk_alt return_result
241 (resultWrapper result_ty) `thenDs` \ (ccall_res_ty, the_alt) ->
243 wrap = \ the_call -> Case (App the_call (Var realWorldPrimId))
244 (mkWildId ccall_res_ty)
247 returnDs (realWorldStatePrimTy `mkFunTy` ccall_res_ty, wrap)
249 return_result state ans = ans
251 mk_alt return_result (Nothing, wrap_result)
252 = -- The ccall returns ()
254 rhs_fun state_id = return_result (Var state_id)
255 (wrap_result (panic "boxResult"))
257 newSysLocalDs realWorldStatePrimTy `thenDs` \ state_id ->
258 mkTouches arg_ids state_id rhs_fun `thenDs` \ the_rhs ->
260 ccall_res_ty = mkTyConApp unboxedSingletonTyCon [realWorldStatePrimTy]
261 the_alt = (DataAlt unboxedSingletonDataCon, [state_id], the_rhs)
263 returnDs (ccall_res_ty, the_alt)
265 mk_alt return_result (Just prim_res_ty, wrap_result)
266 = -- The ccall returns a non-() value
267 newSysLocalDs prim_res_ty `thenDs` \ result_id ->
269 rhs_fun state_id = return_result (Var state_id)
270 (wrap_result (Var result_id))
272 newSysLocalDs realWorldStatePrimTy `thenDs` \ state_id ->
273 mkTouches arg_ids state_id rhs_fun `thenDs` \ the_rhs ->
275 ccall_res_ty = mkTyConApp unboxedPairTyCon [realWorldStatePrimTy, prim_res_ty]
276 the_alt = (DataAlt unboxedPairDataCon, [state_id, result_id], the_rhs)
278 returnDs (ccall_res_ty, the_alt)
280 touchzh = mkPrimOpId TouchOp
282 mkTouches [] s cont = returnDs (cont s)
283 mkTouches (v:vs) s cont
284 | idType v /= foreignObjPrimTy = mkTouches vs s cont
285 | otherwise = newSysLocalDs realWorldStatePrimTy `thenDs` \s' ->
286 mkTouches vs s' cont `thenDs` \ rest ->
287 returnDs (Case (mkApps (Var touchzh) [Type foreignObjPrimTy,
289 [(DEFAULT, [], rest)])
291 resultWrapper :: Type
292 -> (Maybe Type, -- Type of the expected result, if any
293 CoreExpr -> CoreExpr) -- Wrapper for the result
294 resultWrapper result_ty
295 -- Base case 1: primitive types
296 | isUnLiftedType result_ty
297 = (Just result_ty, \e -> e)
299 -- Base case 1: the unit type ()
300 | result_ty == unitTy
301 = (Nothing, \e -> Var unitDataConId)
303 | result_ty == boolTy
304 = (Just intPrimTy, \e -> Case e (mkWildId intPrimTy)
305 [(LitAlt (mkMachInt 0),[],Var falseDataConId),
306 (DEFAULT ,[],Var trueDataConId )])
308 -- Data types with a single constructor, which has a single arg
309 | is_product_type && data_con_arity == 1
311 (maybe_ty, wrapper) = resultWrapper unwrapped_res_ty
312 (unwrapped_res_ty : _) = data_con_arg_tys
314 (maybe_ty, \e -> mkApps (Var (dataConWrapId data_con))
315 (map Type tycon_arg_tys ++ [wrapper e]))
318 | isNewType result_ty
320 rep_ty = repType result_ty
321 (maybe_ty, wrapper) = resultWrapper rep_ty
323 (maybe_ty, \e -> mkCoerce result_ty rep_ty (wrapper e))
326 = pprPanic "resultWrapper" (ppr result_ty)
328 maybe_product_type = splitProductType_maybe result_ty
329 is_product_type = maybeToBool maybe_product_type
330 Just (_, tycon_arg_tys, data_con, data_con_arg_tys) = maybe_product_type
331 data_con_arity = dataConSourceArity data_con