2 % (c) The AQUA Project, Glasgow University, 1994-1998
4 \section[DsCCall]{Desugaring \tr{_ccall_}s and \tr{_casm_}s}
15 #include "HsVersions.h"
22 import CoreUtils ( exprType, mkCoerce )
23 import Id ( Id, mkWildId )
24 import MkId ( mkCCallOpId, realWorldPrimId )
25 import Maybes ( maybeToBool )
26 import PrimOp ( PrimOp(..), CCall(..), CCallTarget(..) )
27 import DataCon ( DataCon, splitProductType_maybe, dataConSourceArity, dataConWrapId )
29 import Type ( isUnLiftedType, splitAlgTyConApp_maybe, mkFunTys,
30 splitTyConApp_maybe, tyVarsOfType, mkForAllTys,
31 isNewType, repType, isUnLiftedType, mkFunTy,
34 import TysPrim ( byteArrayPrimTy, realWorldStatePrimTy,
35 byteArrayPrimTyCon, mutableByteArrayPrimTyCon, intPrimTy
37 import TysWiredIn ( unitDataConId, stringTy,
39 mkUnboxedTupleTy, unboxedTupleCon,
40 boolTy, trueDataCon, falseDataCon, trueDataConId, falseDataConId,
43 import Literal ( mkMachInt )
44 import CStrings ( CLabelString )
45 import Unique ( Unique, Uniquable(..), ioTyConKey )
46 import VarSet ( varSetElems )
50 Desugaring of @ccall@s consists of adding some state manipulation,
51 unboxing any boxed primitive arguments and boxing the result if
54 The state stuff just consists of adding in
55 @PrimIO (\ s -> case s of { S# s# -> ... })@ in an appropriate place.
57 The unboxing is straightforward, as all information needed to unbox is
58 available from the type. For each boxed-primitive argument, we
61 _ccall_ foo [ r, t1, ... tm ] e1 ... em
65 case e1 of { T1# x1# ->
67 case em of { Tm# xm# -> xm#
68 ccall# foo [ r, t1#, ... tm# ] x1# ... xm#
72 The reboxing of a @_ccall_@ result is a bit tricker: the types don't
73 contain information about the state-pairing functions so we have to
74 keep a list of \tr{(type, s-p-function)} pairs. We transform as
77 ccall# foo [ r, t1#, ... tm# ] e1# ... em#
81 \ s# -> case (ccall# foo [ r, t1#, ... tm# ] s# e1# ... em#) of
82 (StateAnd<r># result# state#) -> (R# result#, realWorld#)
86 dsCCall :: CLabelString -- C routine to invoke
87 -> [CoreExpr] -- Arguments (desugared)
88 -> Bool -- True <=> might cause Haskell GC
89 -> Bool -- True <=> really a "_casm_"
90 -> Type -- Type of the result: IO t
93 dsCCall lbl args may_gc is_asm result_ty
94 = mapAndUnzipDs unboxArg args `thenDs` \ (unboxed_args, arg_wrappers) ->
95 boxResult result_ty `thenDs` \ (ccall_result_ty, res_wrapper) ->
96 getUniqueDs `thenDs` \ uniq ->
98 the_ccall = CCall (StaticTarget lbl) is_asm may_gc cCallConv
99 the_prim_app = mkCCall uniq the_ccall unboxed_args ccall_result_ty
101 returnDs (foldr ($) (res_wrapper the_prim_app) arg_wrappers)
103 mkCCall :: Unique -> CCall
104 -> [CoreExpr] -- Args
105 -> Type -- Result type
107 -- Construct the ccall. The only tricky bit is that the ccall Id should have
108 -- no free vars, so if any of the arg tys do we must give it a polymorphic type.
109 -- [I forget *why* it should have no free vars!]
111 -- mkCCall ... [s::StablePtr (a->b), x::Addr, c::Char]
113 -- Here we build a ccall thus
114 -- (ccallid::(forall a b. StablePtr (a -> b) -> Addr -> Char -> IO Addr))
116 mkCCall uniq the_ccall val_args res_ty
117 = mkApps (mkVarApps (Var the_ccall_id) tyvars) val_args
119 arg_tys = map exprType val_args
120 body_ty = (mkFunTys arg_tys res_ty)
121 tyvars = varSetElems (tyVarsOfType body_ty)
122 ty = mkForAllTys tyvars body_ty
123 the_ccall_id = mkCCallOpId uniq the_ccall ty
127 unboxArg :: CoreExpr -- The supplied argument
128 -> DsM (CoreExpr, -- To pass as the actual argument
129 CoreExpr -> CoreExpr -- Wrapper to unbox the arg
131 -- Example: if the arg is e::Int, unboxArg will return
132 -- (x#::Int#, \W. case x of I# x# -> W)
133 -- where W is a CoreExpr that probably mentions x#
136 -- Unlifted types: nothing to unbox
137 | isUnLiftedType arg_ty
138 = returnDs (arg, \body -> body)
142 = unboxArg (mkCoerce (repType arg_ty) arg_ty arg)
146 = newSysLocalDs intPrimTy `thenDs` \ prim_arg ->
147 returnDs (Var prim_arg,
148 \ body -> Case (Case arg (mkWildId arg_ty)
149 [(DataAlt falseDataCon,[],mkIntLit 0),
150 (DataAlt trueDataCon, [],mkIntLit 1)])
154 -- Data types with a single constructor, which has a single, primitive-typed arg
155 -- This deals with Int, Float etc
156 | is_product_type && data_con_arity == 1
157 = ASSERT(isUnLiftedType data_con_arg_ty1 ) -- Typechecker ensures this
158 newSysLocalDs arg_ty `thenDs` \ case_bndr ->
159 newSysLocalDs data_con_arg_ty1 `thenDs` \ prim_arg ->
160 returnDs (Var prim_arg,
161 \ body -> Case arg case_bndr [(DataAlt data_con,[prim_arg],body)]
164 -- Byte-arrays, both mutable and otherwise; hack warning
166 data_con_arity == 3 &&
167 maybeToBool maybe_arg3_tycon &&
168 (arg3_tycon == byteArrayPrimTyCon ||
169 arg3_tycon == mutableByteArrayPrimTyCon)
170 -- and, of course, it is an instance of CCallable
171 = newSysLocalDs arg_ty `thenDs` \ case_bndr ->
172 newSysLocalsDs data_con_arg_tys `thenDs` \ vars@[l_var, r_var, arr_cts_var] ->
173 returnDs (Var arr_cts_var,
174 \ body -> Case arg case_bndr [(DataAlt data_con,vars,body)]
178 = getSrcLocDs `thenDs` \ l ->
179 pprPanic "unboxArg: " (ppr l <+> ppr arg_ty)
181 arg_ty = exprType arg
182 arg_rep_ty = repType arg_ty
184 maybe_product_type = splitProductType_maybe arg_ty
185 is_product_type = maybeToBool maybe_product_type
186 Just (tycon, _, 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 = splitTyConApp_maybe data_con_arg_ty3
192 Just (arg3_tycon,_) = maybe_arg3_tycon
197 boxResult :: 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 #)
211 = case splitAlgTyConApp_maybe result_ty of
213 -- The result is IO t, so wrap the result in an IO constructor
214 Just (io_tycon, [io_res_ty], [io_data_con]) | getUnique io_tycon == ioTyConKey
215 -> mk_alt return_result
216 (resultWrapper io_res_ty) `thenDs` \ (ccall_res_ty, the_alt) ->
217 newSysLocalDs realWorldStatePrimTy `thenDs` \ state_id ->
219 wrap = \ the_call -> mkApps (Var (dataConWrapId io_data_con))
220 [Type io_res_ty, Lam state_id $
221 Case (App the_call (Var state_id))
222 (mkWildId ccall_res_ty)
225 returnDs (realWorldStatePrimTy `mkFunTy` ccall_res_ty, wrap)
227 return_result state ans = mkConApp unboxedPairDataCon
228 [Type realWorldStatePrimTy, Type io_res_ty,
231 -- It isn't, so do unsafePerformIO
232 -- It's not conveniently available, so we inline it
233 other -> mk_alt return_result
234 (resultWrapper result_ty) `thenDs` \ (ccall_res_ty, the_alt) ->
236 wrap = \ the_call -> Case (App the_call (Var realWorldPrimId))
237 (mkWildId ccall_res_ty)
240 returnDs (realWorldStatePrimTy `mkFunTy` ccall_res_ty, wrap)
242 return_result state ans = ans
244 mk_alt return_result (Nothing, wrap_result)
245 = -- The ccall returns ()
246 newSysLocalDs realWorldStatePrimTy `thenDs` \ state_id ->
248 the_rhs = return_result (Var state_id) (wrap_result (panic "boxResult"))
249 ccall_res_ty = mkUnboxedTupleTy 1 [realWorldStatePrimTy]
250 the_alt = (DataAlt (unboxedTupleCon 1), [state_id], the_rhs)
252 returnDs (ccall_res_ty, the_alt)
254 mk_alt return_result (Just prim_res_ty, wrap_result)
255 = -- The ccall returns a non-() value
256 newSysLocalDs realWorldStatePrimTy `thenDs` \ state_id ->
257 newSysLocalDs prim_res_ty `thenDs` \ result_id ->
259 the_rhs = return_result (Var state_id) (wrap_result (Var result_id))
260 ccall_res_ty = mkUnboxedTupleTy 2 [realWorldStatePrimTy, prim_res_ty]
261 the_alt = (DataAlt unboxedPairDataCon, [state_id, result_id], the_rhs)
263 returnDs (ccall_res_ty, the_alt)
266 resultWrapper :: Type
267 -> (Maybe Type, -- Type of the expected result, if any
268 CoreExpr -> CoreExpr) -- Wrapper for the result
269 resultWrapper result_ty
270 -- Base case 1: primitive types
271 | isUnLiftedType result_ty
272 = (Just result_ty, \e -> e)
274 -- Base case 1: the unit type ()
275 | result_ty == unitTy
276 = (Nothing, \e -> Var unitDataConId)
278 | result_ty == boolTy
279 = (Just intPrimTy, \e -> Case e (mkWildId intPrimTy)
280 [(LitAlt (mkMachInt 0),[],Var falseDataConId),
281 (DEFAULT ,[],Var trueDataConId )])
283 -- Data types with a single constructor, which has a single arg
284 | is_product_type && data_con_arity == 1
286 (maybe_ty, wrapper) = resultWrapper unwrapped_res_ty
287 (unwrapped_res_ty : _) = data_con_arg_tys
289 (maybe_ty, \e -> mkApps (Var (dataConWrapId data_con))
290 (map Type tycon_arg_tys ++ [wrapper e]))
293 | isNewType result_ty
295 rep_ty = repType result_ty
296 (maybe_ty, wrapper) = resultWrapper rep_ty
298 (maybe_ty, \e -> mkCoerce result_ty rep_ty (wrapper e))
301 = pprPanic "resultWrapper" (ppr result_ty)
303 maybe_product_type = splitProductType_maybe result_ty
304 is_product_type = maybeToBool maybe_product_type
305 Just (tycon, tycon_arg_tys, data_con, data_con_arg_tys) = maybe_product_type
306 data_con_arity = dataConSourceArity data_con