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(..) )
29 import TcType ( tcSplitTyConApp_maybe )
30 import Type ( Type, isUnLiftedType, mkFunTys, mkFunTy,
31 tyVarsOfType, mkForAllTys, mkTyConApp,
32 isPrimitiveType, eqType,
33 splitTyConApp_maybe, splitNewType_maybe
36 import PrimOp ( PrimOp(..) )
37 import TysPrim ( realWorldStatePrimTy,
38 byteArrayPrimTyCon, mutableByteArrayPrimTyCon,
39 intPrimTy, foreignObjPrimTy
41 import TyCon ( TyCon, tyConDataCons )
42 import TysWiredIn ( unitDataConId,
43 unboxedSingletonDataCon, unboxedPairDataCon,
44 unboxedSingletonTyCon, unboxedPairTyCon,
45 trueDataCon, falseDataCon,
46 trueDataConId, falseDataConId
48 import Literal ( mkMachInt )
49 import CStrings ( CLabelString )
50 import PrelNames ( Unique, hasKey, ioTyConKey, boolTyConKey, unitTyConKey,
51 int8TyConKey, int16TyConKey, int32TyConKey,
52 word8TyConKey, word16TyConKey, word32TyConKey
54 import VarSet ( varSetElems )
55 import Constants ( wORD_SIZE)
59 Desugaring of @ccall@s consists of adding some state manipulation,
60 unboxing any boxed primitive arguments and boxing the result if
63 The state stuff just consists of adding in
64 @PrimIO (\ s -> case s of { S# s# -> ... })@ in an appropriate place.
66 The unboxing is straightforward, as all information needed to unbox is
67 available from the type. For each boxed-primitive argument, we
70 _ccall_ foo [ r, t1, ... tm ] e1 ... em
74 case e1 of { T1# x1# ->
76 case em of { Tm# xm# -> xm#
77 ccall# foo [ r, t1#, ... tm# ] x1# ... xm#
81 The reboxing of a @_ccall_@ result is a bit tricker: the types don't
82 contain information about the state-pairing functions so we have to
83 keep a list of \tr{(type, s-p-function)} pairs. We transform as
86 ccall# foo [ r, t1#, ... tm# ] e1# ... em#
90 \ s# -> case (ccall# foo [ r, t1#, ... tm# ] s# e1# ... em#) of
91 (StateAnd<r># result# state#) -> (R# result#, realWorld#)
95 dsCCall :: CLabelString -- C routine to invoke
96 -> [CoreExpr] -- Arguments (desugared)
97 -> Safety -- Safety of the call
98 -> Bool -- True <=> really a "_casm_"
99 -> Type -- Type of the result: IO t
102 dsCCall lbl args may_gc is_asm result_ty
103 = mapAndUnzipDs unboxArg args `thenDs` \ (unboxed_args, arg_wrappers) ->
104 boxResult [] result_ty `thenDs` \ (ccall_result_ty, res_wrapper) ->
105 getUniqueDs `thenDs` \ uniq ->
107 target | is_asm = CasmTarget lbl
108 | otherwise = StaticTarget lbl
109 the_fcall = CCall (CCallSpec target CCallConv may_gc)
110 the_prim_app = mkFCall uniq the_fcall unboxed_args ccall_result_ty
112 returnDs (foldr ($) (res_wrapper the_prim_app) arg_wrappers)
114 mkFCall :: Unique -> ForeignCall
115 -> [CoreExpr] -- Args
116 -> Type -- Result type
118 -- Construct the ccall. The only tricky bit is that the ccall Id should have
119 -- no free vars, so if any of the arg tys do we must give it a polymorphic type.
120 -- [I forget *why* it should have no free vars!]
122 -- mkCCall ... [s::StablePtr (a->b), x::Addr, c::Char]
124 -- Here we build a ccall thus
125 -- (ccallid::(forall a b. StablePtr (a -> b) -> Addr -> Char -> IO Addr))
127 mkFCall uniq the_fcall val_args res_ty
128 = mkApps (mkVarApps (Var the_fcall_id) tyvars) val_args
130 arg_tys = map exprType val_args
131 body_ty = (mkFunTys arg_tys res_ty)
132 tyvars = varSetElems (tyVarsOfType body_ty)
133 ty = mkForAllTys tyvars body_ty
134 the_fcall_id = mkFCallId uniq the_fcall ty
138 unboxArg :: CoreExpr -- The supplied argument
139 -> DsM (CoreExpr, -- To pass as the actual argument
140 CoreExpr -> CoreExpr -- Wrapper to unbox the arg
142 -- Example: if the arg is e::Int, unboxArg will return
143 -- (x#::Int#, \W. case x of I# x# -> W)
144 -- where W is a CoreExpr that probably mentions x#
147 -- Primtive types: nothing to unbox
148 | isPrimitiveType arg_ty
149 = returnDs (arg, \body -> body)
151 -- Recursive newtypes
152 | Just rep_ty <- splitNewType_maybe arg_ty
153 = unboxArg (mkCoerce rep_ty arg_ty arg)
156 | Just (tc,_) <- splitTyConApp_maybe arg_ty,
157 tc `hasKey` boolTyConKey
158 = newSysLocalDs intPrimTy `thenDs` \ prim_arg ->
159 returnDs (Var prim_arg,
160 \ body -> Case (Case arg (mkWildId arg_ty)
161 [(DataAlt falseDataCon,[],mkIntLit 0),
162 (DataAlt trueDataCon, [],mkIntLit 1)])
166 -- Data types with a single constructor, which has a single, primitive-typed arg
167 -- This deals with Int, Float etc
168 | is_product_type && data_con_arity == 1
169 = ASSERT(isUnLiftedType data_con_arg_ty1 ) -- Typechecker ensures this
170 newSysLocalDs arg_ty `thenDs` \ case_bndr ->
171 newSysLocalDs data_con_arg_ty1 `thenDs` \ prim_arg ->
172 returnDs (Var prim_arg,
173 \ body -> Case arg case_bndr [(DataAlt data_con,[prim_arg],body)]
176 -- Byte-arrays, both mutable and otherwise; hack warning
177 -- We're looking for values of type ByteArray, MutableByteArray
178 -- data ByteArray ix = ByteArray ix ix ByteArray#
179 -- data MutableByteArray s ix = MutableByteArray ix ix (MutableByteArray# s)
181 data_con_arity == 3 &&
182 maybeToBool maybe_arg3_tycon &&
183 (arg3_tycon == byteArrayPrimTyCon ||
184 arg3_tycon == mutableByteArrayPrimTyCon)
185 -- and, of course, it is an instance of CCallable
186 = newSysLocalDs arg_ty `thenDs` \ case_bndr ->
187 newSysLocalsDs data_con_arg_tys `thenDs` \ vars@[l_var, r_var, arr_cts_var] ->
188 returnDs (Var arr_cts_var,
189 \ body -> Case arg case_bndr [(DataAlt data_con,vars,body)]
193 = getSrcLocDs `thenDs` \ l ->
194 pprPanic "unboxArg: " (ppr l <+> ppr arg_ty)
196 arg_ty = exprType arg
197 maybe_product_type = splitProductType_maybe arg_ty
198 is_product_type = maybeToBool maybe_product_type
199 Just (_, _, data_con, data_con_arg_tys) = maybe_product_type
200 data_con_arity = dataConSourceArity data_con
201 (data_con_arg_ty1 : _) = data_con_arg_tys
203 (_ : _ : data_con_arg_ty3 : _) = data_con_arg_tys
204 maybe_arg3_tycon = splitTyConApp_maybe data_con_arg_ty3
205 Just (arg3_tycon,_) = maybe_arg3_tycon
210 boxResult :: [Id] -> Type -> DsM (Type, CoreExpr -> CoreExpr)
212 -- Takes the result of the user-level ccall:
214 -- or maybe just t for an side-effect-free call
215 -- Returns a wrapper for the primitive ccall itself, along with the
216 -- type of the result of the primitive ccall. This result type
217 -- will be of the form
218 -- State# RealWorld -> (# State# RealWorld, t' #)
219 -- where t' is the unwrapped form of t. If t is simply (), then
220 -- the result type will be
221 -- State# RealWorld -> (# State# RealWorld #)
223 -- Here is where we arrange that ForeignPtrs which are passed to a 'safe'
224 -- foreign import don't get finalized until the call returns. For each
225 -- argument of type ForeignObj# we arrange to touch# the argument after
226 -- the call. The arg_ids passed in are the Ids passed to the actual ccall.
228 boxResult arg_ids result_ty
229 = case tcSplitTyConApp_maybe result_ty of
230 -- This split absolutely has to be a tcSplit, because we must
231 -- see the IO type; and it's a newtype which is transparent to splitTyConApp.
233 -- The result is IO t, so wrap the result in an IO constructor
234 Just (io_tycon, [io_res_ty]) | io_tycon `hasKey` ioTyConKey
235 -> mk_alt return_result
236 (resultWrapper io_res_ty) `thenDs` \ (ccall_res_ty, the_alt) ->
237 newSysLocalDs realWorldStatePrimTy `thenDs` \ state_id ->
239 io_data_con = head (tyConDataCons io_tycon)
241 mkApps (Var (dataConWrapId io_data_con))
244 Case (App the_call (Var state_id))
245 (mkWildId ccall_res_ty)
249 returnDs (realWorldStatePrimTy `mkFunTy` ccall_res_ty, wrap)
251 return_result state ans = mkConApp unboxedPairDataCon
252 [Type realWorldStatePrimTy, Type io_res_ty,
255 -- It isn't, so do unsafePerformIO
256 -- It's not conveniently available, so we inline it
257 other -> mk_alt return_result
258 (resultWrapper result_ty) `thenDs` \ (ccall_res_ty, the_alt) ->
260 wrap = \ the_call -> Case (App the_call (Var realWorldPrimId))
261 (mkWildId ccall_res_ty)
264 returnDs (realWorldStatePrimTy `mkFunTy` ccall_res_ty, wrap)
266 return_result state ans = ans
268 mk_alt return_result (Nothing, wrap_result)
269 = -- The ccall returns ()
271 rhs_fun state_id = return_result (Var state_id)
272 (wrap_result (panic "boxResult"))
274 newSysLocalDs realWorldStatePrimTy `thenDs` \ state_id ->
275 mkTouches arg_ids state_id rhs_fun `thenDs` \ the_rhs ->
277 ccall_res_ty = mkTyConApp unboxedSingletonTyCon [realWorldStatePrimTy]
278 the_alt = (DataAlt unboxedSingletonDataCon, [state_id], the_rhs)
280 returnDs (ccall_res_ty, the_alt)
282 mk_alt return_result (Just prim_res_ty, wrap_result)
283 = -- The ccall returns a non-() value
284 newSysLocalDs prim_res_ty `thenDs` \ result_id ->
286 rhs_fun state_id = return_result (Var state_id)
287 (wrap_result (Var result_id))
289 newSysLocalDs realWorldStatePrimTy `thenDs` \ state_id ->
290 mkTouches arg_ids state_id rhs_fun `thenDs` \ the_rhs ->
292 ccall_res_ty = mkTyConApp unboxedPairTyCon [realWorldStatePrimTy, prim_res_ty]
293 the_alt = (DataAlt unboxedPairDataCon, [state_id, result_id], the_rhs)
295 returnDs (ccall_res_ty, the_alt)
297 touchzh = mkPrimOpId TouchOp
299 mkTouches [] s cont = returnDs (cont s)
300 mkTouches (v:vs) s cont
301 | not (idType v `eqType` foreignObjPrimTy) = mkTouches vs s cont
302 | otherwise = newSysLocalDs realWorldStatePrimTy `thenDs` \s' ->
303 mkTouches vs s' cont `thenDs` \ rest ->
304 returnDs (Case (mkApps (Var touchzh) [Type foreignObjPrimTy,
306 [(DEFAULT, [], rest)])
308 resultWrapper :: Type
309 -> (Maybe Type, -- Type of the expected result, if any
310 CoreExpr -> CoreExpr) -- Wrapper for the result
311 resultWrapper result_ty
312 -- Base case 1: primitive types
313 | isPrimitiveType result_ty
314 = (Just result_ty, \e -> e)
316 -- Base case 2: the unit type ()
317 | Just (tc,_) <- maybe_tc_app, tc `hasKey` unitTyConKey
318 = (Nothing, \e -> Var unitDataConId)
320 -- Base case 3: the boolean type
321 | Just (tc,_) <- maybe_tc_app, tc `hasKey` boolTyConKey
322 = (Just intPrimTy, \e -> Case e (mkWildId intPrimTy)
323 [(DEFAULT ,[],Var trueDataConId ),
324 (LitAlt (mkMachInt 0),[],Var falseDataConId)])
326 -- Recursive newtypes
327 | Just rep_ty <- splitNewType_maybe result_ty
329 (maybe_ty, wrapper) = resultWrapper rep_ty
331 (maybe_ty, \e -> mkCoerce result_ty rep_ty (wrapper e))
333 -- Data types with a single constructor, which has a single arg
334 | Just (tycon, tycon_arg_tys, data_con, data_con_arg_tys) <- splitProductType_maybe result_ty,
335 dataConSourceArity data_con == 1
337 (maybe_ty, wrapper) = resultWrapper unwrapped_res_ty
338 (unwrapped_res_ty : _) = data_con_arg_tys
339 narrow_wrapper = maybeNarrow tycon
341 (maybe_ty, \e -> mkApps (Var (dataConWrapId data_con))
342 (map Type tycon_arg_tys ++ [wrapper (narrow_wrapper e)]))
345 = pprPanic "resultWrapper" (ppr result_ty)
347 maybe_tc_app = splitTyConApp_maybe result_ty
349 -- When the result of a foreign call is smaller than the word size, we
350 -- need to sign- or zero-extend the result up to the word size. The C
351 -- standard appears to say that this is the responsibility of the
352 -- caller, not the callee.
354 maybeNarrow :: TyCon -> (CoreExpr -> CoreExpr)
356 | tycon `hasKey` int8TyConKey = \e -> App (Var (mkPrimOpId Narrow8IntOp)) e
357 | tycon `hasKey` int16TyConKey = \e -> App (Var (mkPrimOpId Narrow16IntOp)) e
358 | tycon `hasKey` int32TyConKey
359 && wORD_SIZE > 4 = \e -> App (Var (mkPrimOpId Narrow32IntOp)) e
361 | tycon `hasKey` word8TyConKey = \e -> App (Var (mkPrimOpId Narrow8WordOp)) e
362 | tycon `hasKey` word16TyConKey = \e -> App (Var (mkPrimOpId Narrow16WordOp)) e
363 | tycon `hasKey` word32TyConKey
364 && wORD_SIZE > 4 = \e -> App (Var (mkPrimOpId Narrow32WordOp)) e