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 ( mkWildId )
23 import MkId ( mkCCallOpId, realWorldPrimId )
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 TysPrim ( realWorldStatePrimTy,
34 byteArrayPrimTyCon, mutableByteArrayPrimTyCon, intPrimTy
36 import TysWiredIn ( unitDataConId,
37 unboxedSingletonDataCon, unboxedPairDataCon,
38 unboxedSingletonTyCon, unboxedPairTyCon,
39 boolTy, trueDataCon, falseDataCon,
40 trueDataConId, falseDataConId, unitTy
42 import Literal ( mkMachInt )
43 import CStrings ( CLabelString )
44 import PrelNames ( Unique, hasKey, ioTyConKey )
45 import VarSet ( varSetElems )
49 Desugaring of @ccall@s consists of adding some state manipulation,
50 unboxing any boxed primitive arguments and boxing the result if
53 The state stuff just consists of adding in
54 @PrimIO (\ s -> case s of { S# s# -> ... })@ in an appropriate place.
56 The unboxing is straightforward, as all information needed to unbox is
57 available from the type. For each boxed-primitive argument, we
60 _ccall_ foo [ r, t1, ... tm ] e1 ... em
64 case e1 of { T1# x1# ->
66 case em of { Tm# xm# -> xm#
67 ccall# foo [ r, t1#, ... tm# ] x1# ... xm#
71 The reboxing of a @_ccall_@ result is a bit tricker: the types don't
72 contain information about the state-pairing functions so we have to
73 keep a list of \tr{(type, s-p-function)} pairs. We transform as
76 ccall# foo [ r, t1#, ... tm# ] e1# ... em#
80 \ s# -> case (ccall# foo [ r, t1#, ... tm# ] s# e1# ... em#) of
81 (StateAnd<r># result# state#) -> (R# result#, realWorld#)
85 dsCCall :: CLabelString -- C routine to invoke
86 -> [CoreExpr] -- Arguments (desugared)
87 -> Bool -- True <=> might cause Haskell GC
88 -> Bool -- True <=> really a "_casm_"
89 -> Type -- Type of the result: IO t
92 dsCCall lbl args may_gc is_asm result_ty
93 = mapAndUnzipDs unboxArg args `thenDs` \ (unboxed_args, arg_wrappers) ->
94 boxResult result_ty `thenDs` \ (ccall_result_ty, res_wrapper) ->
95 getUniqueDs `thenDs` \ uniq ->
97 the_ccall = CCall (StaticTarget lbl) is_asm may_gc cCallConv
98 the_prim_app = mkCCall uniq the_ccall unboxed_args ccall_result_ty
100 returnDs (foldr ($) (res_wrapper the_prim_app) arg_wrappers)
102 mkCCall :: Unique -> CCall
103 -> [CoreExpr] -- Args
104 -> Type -- Result type
106 -- Construct the ccall. The only tricky bit is that the ccall Id should have
107 -- no free vars, so if any of the arg tys do we must give it a polymorphic type.
108 -- [I forget *why* it should have no free vars!]
110 -- mkCCall ... [s::StablePtr (a->b), x::Addr, c::Char]
112 -- Here we build a ccall thus
113 -- (ccallid::(forall a b. StablePtr (a -> b) -> Addr -> Char -> IO Addr))
115 mkCCall uniq the_ccall val_args res_ty
116 = mkApps (mkVarApps (Var the_ccall_id) tyvars) val_args
118 arg_tys = map exprType val_args
119 body_ty = (mkFunTys arg_tys res_ty)
120 tyvars = varSetElems (tyVarsOfType body_ty)
121 ty = mkForAllTys tyvars body_ty
122 the_ccall_id = mkCCallOpId uniq the_ccall ty
126 unboxArg :: CoreExpr -- The supplied argument
127 -> DsM (CoreExpr, -- To pass as the actual argument
128 CoreExpr -> CoreExpr -- Wrapper to unbox the arg
130 -- Example: if the arg is e::Int, unboxArg will return
131 -- (x#::Int#, \W. case x of I# x# -> W)
132 -- where W is a CoreExpr that probably mentions x#
135 -- Unlifted types: nothing to unbox
136 | isUnLiftedType arg_ty
137 = returnDs (arg, \body -> body)
141 = unboxArg (mkCoerce (repType arg_ty) arg_ty arg)
145 = newSysLocalDs intPrimTy `thenDs` \ prim_arg ->
146 returnDs (Var prim_arg,
147 \ body -> Case (Case arg (mkWildId arg_ty)
148 [(DataAlt falseDataCon,[],mkIntLit 0),
149 (DataAlt trueDataCon, [],mkIntLit 1)])
153 -- Data types with a single constructor, which has a single, primitive-typed arg
154 -- This deals with Int, Float etc
155 | is_product_type && data_con_arity == 1
156 = ASSERT(isUnLiftedType data_con_arg_ty1 ) -- Typechecker ensures this
157 newSysLocalDs arg_ty `thenDs` \ case_bndr ->
158 newSysLocalDs data_con_arg_ty1 `thenDs` \ prim_arg ->
159 returnDs (Var prim_arg,
160 \ body -> Case arg case_bndr [(DataAlt data_con,[prim_arg],body)]
163 -- Byte-arrays, both mutable and otherwise; hack warning
165 data_con_arity == 3 &&
166 maybeToBool maybe_arg3_tycon &&
167 (arg3_tycon == byteArrayPrimTyCon ||
168 arg3_tycon == mutableByteArrayPrimTyCon)
169 -- and, of course, it is an instance of CCallable
170 = newSysLocalDs arg_ty `thenDs` \ case_bndr ->
171 newSysLocalsDs data_con_arg_tys `thenDs` \ vars@[l_var, r_var, arr_cts_var] ->
172 returnDs (Var arr_cts_var,
173 \ body -> Case arg case_bndr [(DataAlt data_con,vars,body)]
177 = getSrcLocDs `thenDs` \ l ->
178 pprPanic "unboxArg: " (ppr l <+> ppr arg_ty)
180 arg_ty = exprType arg
181 maybe_product_type = splitProductType_maybe arg_ty
182 is_product_type = maybeToBool maybe_product_type
183 Just (_, _, data_con, data_con_arg_tys) = maybe_product_type
184 data_con_arity = dataConSourceArity data_con
185 (data_con_arg_ty1 : _) = data_con_arg_tys
187 (_ : _ : data_con_arg_ty3 : _) = data_con_arg_tys
188 maybe_arg3_tycon = splitTyConApp_maybe data_con_arg_ty3
189 Just (arg3_tycon,_) = maybe_arg3_tycon
194 boxResult :: Type -> DsM (Type, CoreExpr -> CoreExpr)
196 -- Takes the result of the user-level ccall:
198 -- or maybe just t for an side-effect-free call
199 -- Returns a wrapper for the primitive ccall itself, along with the
200 -- type of the result of the primitive ccall. This result type
201 -- will be of the form
202 -- State# RealWorld -> (# State# RealWorld, t' #)
203 -- where t' is the unwrapped form of t. If t is simply (), then
204 -- the result type will be
205 -- State# RealWorld -> (# State# RealWorld #)
208 = case splitAlgTyConApp_maybe result_ty of
210 -- The result is IO t, so wrap the result in an IO constructor
211 Just (io_tycon, [io_res_ty], [io_data_con]) | io_tycon `hasKey` ioTyConKey
212 -> mk_alt return_result
213 (resultWrapper io_res_ty) `thenDs` \ (ccall_res_ty, the_alt) ->
214 newSysLocalDs realWorldStatePrimTy `thenDs` \ state_id ->
216 wrap = \ the_call -> mkApps (Var (dataConWrapId io_data_con))
217 [Type io_res_ty, Lam state_id $
218 Case (App the_call (Var state_id))
219 (mkWildId ccall_res_ty)
222 returnDs (realWorldStatePrimTy `mkFunTy` ccall_res_ty, wrap)
224 return_result state ans = mkConApp unboxedPairDataCon
225 [Type realWorldStatePrimTy, Type io_res_ty,
228 -- It isn't, so do unsafePerformIO
229 -- It's not conveniently available, so we inline it
230 other -> mk_alt return_result
231 (resultWrapper result_ty) `thenDs` \ (ccall_res_ty, the_alt) ->
233 wrap = \ the_call -> Case (App the_call (Var realWorldPrimId))
234 (mkWildId ccall_res_ty)
237 returnDs (realWorldStatePrimTy `mkFunTy` ccall_res_ty, wrap)
239 return_result state ans = ans
241 mk_alt return_result (Nothing, wrap_result)
242 = -- The ccall returns ()
243 newSysLocalDs realWorldStatePrimTy `thenDs` \ state_id ->
245 the_rhs = return_result (Var state_id) (wrap_result (panic "boxResult"))
246 ccall_res_ty = mkTyConApp unboxedSingletonTyCon [realWorldStatePrimTy]
247 the_alt = (DataAlt unboxedSingletonDataCon, [state_id], the_rhs)
249 returnDs (ccall_res_ty, the_alt)
251 mk_alt return_result (Just prim_res_ty, wrap_result)
252 = -- The ccall returns a non-() value
253 newSysLocalDs realWorldStatePrimTy `thenDs` \ state_id ->
254 newSysLocalDs prim_res_ty `thenDs` \ result_id ->
256 the_rhs = return_result (Var state_id) (wrap_result (Var result_id))
257 ccall_res_ty = mkTyConApp unboxedPairTyCon [realWorldStatePrimTy, prim_res_ty]
258 the_alt = (DataAlt unboxedPairDataCon, [state_id, result_id], the_rhs)
260 returnDs (ccall_res_ty, the_alt)
263 resultWrapper :: Type
264 -> (Maybe Type, -- Type of the expected result, if any
265 CoreExpr -> CoreExpr) -- Wrapper for the result
266 resultWrapper result_ty
267 -- Base case 1: primitive types
268 | isUnLiftedType result_ty
269 = (Just result_ty, \e -> e)
271 -- Base case 1: the unit type ()
272 | result_ty == unitTy
273 = (Nothing, \e -> Var unitDataConId)
275 | result_ty == boolTy
276 = (Just intPrimTy, \e -> Case e (mkWildId intPrimTy)
277 [(LitAlt (mkMachInt 0),[],Var falseDataConId),
278 (DEFAULT ,[],Var trueDataConId )])
280 -- Data types with a single constructor, which has a single arg
281 | is_product_type && data_con_arity == 1
283 (maybe_ty, wrapper) = resultWrapper unwrapped_res_ty
284 (unwrapped_res_ty : _) = data_con_arg_tys
286 (maybe_ty, \e -> mkApps (Var (dataConWrapId data_con))
287 (map Type tycon_arg_tys ++ [wrapper e]))
290 | isNewType result_ty
292 rep_ty = repType result_ty
293 (maybe_ty, wrapper) = resultWrapper rep_ty
295 (maybe_ty, \e -> mkCoerce result_ty rep_ty (wrapper e))
298 = pprPanic "resultWrapper" (ppr result_ty)
300 maybe_product_type = splitProductType_maybe result_ty
301 is_product_type = maybeToBool maybe_product_type
302 Just (_, tycon_arg_tys, data_con, data_con_arg_tys) = maybe_product_type
303 data_con_arity = dataConSourceArity data_con