2 % (c) The University of Glasgow 2006
3 % (c) The AQUA Project, Glasgow University, 1994-1998
6 Desugaring foreign calls
10 -- The above warning supression flag is a temporary kludge.
11 -- While working on this module you are encouraged to remove it and fix
12 -- any warnings in the module. See
13 -- http://hackage.haskell.org/trac/ghc/wiki/Commentary/CodingStyle#Warnings
24 #include "HsVersions.h"
58 Desugaring of @ccall@s consists of adding some state manipulation,
59 unboxing any boxed primitive arguments and boxing the result if
62 The state stuff just consists of adding in
63 @PrimIO (\ s -> case s of { S# s# -> ... })@ in an appropriate place.
65 The unboxing is straightforward, as all information needed to unbox is
66 available from the type. For each boxed-primitive argument, we
69 _ccall_ foo [ r, t1, ... tm ] e1 ... em
73 case e1 of { T1# x1# ->
75 case em of { Tm# xm# -> xm#
76 ccall# foo [ r, t1#, ... tm# ] x1# ... xm#
80 The reboxing of a @_ccall_@ result is a bit tricker: the types don't
81 contain information about the state-pairing functions so we have to
82 keep a list of \tr{(type, s-p-function)} pairs. We transform as
85 ccall# foo [ r, t1#, ... tm# ] e1# ... em#
89 \ s# -> case (ccall# foo [ r, t1#, ... tm# ] s# e1# ... em#) of
90 (StateAnd<r># result# state#) -> (R# result#, realWorld#)
94 dsCCall :: CLabelString -- C routine to invoke
95 -> [CoreExpr] -- Arguments (desugared)
96 -> Safety -- Safety of the call
97 -> Type -- Type of the result: IO t
98 -> DsM CoreExpr -- Result, of type ???
100 dsCCall lbl args may_gc result_ty
101 = do (unboxed_args, arg_wrappers) <- mapAndUnzipM unboxArg args
102 (ccall_result_ty, res_wrapper) <- boxResult id Nothing result_ty
105 target = StaticTarget lbl
106 the_fcall = CCall (CCallSpec target CCallConv may_gc)
107 the_prim_app = mkFCall uniq the_fcall unboxed_args ccall_result_ty
108 return (foldr ($) (res_wrapper the_prim_app) arg_wrappers)
110 mkFCall :: Unique -> ForeignCall
111 -> [CoreExpr] -- Args
112 -> Type -- Result type
114 -- Construct the ccall. The only tricky bit is that the ccall Id should have
115 -- no free vars, so if any of the arg tys do we must give it a polymorphic type.
116 -- [I forget *why* it should have no free vars!]
118 -- mkCCall ... [s::StablePtr (a->b), x::Addr, c::Char]
120 -- Here we build a ccall thus
121 -- (ccallid::(forall a b. StablePtr (a -> b) -> Addr -> Char -> IO Addr))
123 mkFCall uniq the_fcall val_args res_ty
124 = mkApps (mkVarApps (Var the_fcall_id) tyvars) val_args
126 arg_tys = map exprType val_args
127 body_ty = (mkFunTys arg_tys res_ty)
128 tyvars = varSetElems (tyVarsOfType body_ty)
129 ty = mkForAllTys tyvars body_ty
130 the_fcall_id = mkFCallId uniq the_fcall ty
134 unboxArg :: CoreExpr -- The supplied argument
135 -> DsM (CoreExpr, -- To pass as the actual argument
136 CoreExpr -> CoreExpr -- Wrapper to unbox the arg
138 -- Example: if the arg is e::Int, unboxArg will return
139 -- (x#::Int#, \W. case x of I# x# -> W)
140 -- where W is a CoreExpr that probably mentions x#
143 -- Primtive types: nothing to unbox
144 | isPrimitiveType arg_ty
145 = return (arg, \body -> body)
147 -- Recursive newtypes
148 | Just(rep_ty, co) <- splitNewTypeRepCo_maybe arg_ty
149 = unboxArg (mkCoerce co arg)
152 | Just (tc,_) <- splitTyConApp_maybe arg_ty,
153 tc `hasKey` boolTyConKey
154 = do prim_arg <- newSysLocalDs intPrimTy
155 return (Var prim_arg,
156 \ body -> Case (Case arg (mkWildId arg_ty) intPrimTy
157 [(DataAlt falseDataCon,[],mkIntLit 0),
158 (DataAlt trueDataCon, [],mkIntLit 1)])
159 -- In increasing tag order!
164 -- Data types with a single constructor, which has a single, primitive-typed arg
165 -- This deals with Int, Float etc; also Ptr, ForeignPtr
166 | is_product_type && data_con_arity == 1
167 = ASSERT2(isUnLiftedType data_con_arg_ty1, pprType arg_ty)
168 -- Typechecker ensures this
169 do case_bndr <- newSysLocalDs arg_ty
170 prim_arg <- newSysLocalDs data_con_arg_ty1
171 return (Var prim_arg,
172 \ body -> Case arg case_bndr (exprType body) [(DataAlt data_con,[prim_arg],body)]
175 -- Byte-arrays, both mutable and otherwise; hack warning
176 -- We're looking for values of type ByteArray, MutableByteArray
177 -- data ByteArray ix = ByteArray ix ix ByteArray#
178 -- data MutableByteArray s ix = MutableByteArray ix ix (MutableByteArray# s)
180 data_con_arity == 3 &&
181 maybeToBool maybe_arg3_tycon &&
182 (arg3_tycon == byteArrayPrimTyCon ||
183 arg3_tycon == mutableByteArrayPrimTyCon)
184 = do case_bndr <- newSysLocalDs arg_ty
185 vars@[l_var, r_var, arr_cts_var] <- newSysLocalsDs data_con_arg_tys
186 return (Var arr_cts_var,
187 \ body -> Case arg case_bndr (exprType body) [(DataAlt data_con,vars,body)]
190 ----- Cases for .NET; almost certainly bit-rotted ---------
191 | Just (tc, [arg_ty]) <- splitTyConApp_maybe arg_ty,
193 Just (cc,[]) <- splitTyConApp_maybe arg_ty,
195 -- String; dotnet only
196 = do unpack_id <- dsLookupGlobalId marshalStringName
197 prim_string <- newSysLocalDs addrPrimTy
198 return (Var prim_string,
201 io_ty = exprType body
202 Just (_,io_arg,_) = tcSplitIOType_maybe io_ty
204 mkApps (Var unpack_id)
207 , Lam prim_string body
209 | Just (tc, [arg_ty]) <- splitTyConApp_maybe arg_ty,
210 tyConName tc == objectTyConName
211 -- Object; dotnet only
212 = do unpack_id <- dsLookupGlobalId marshalObjectName
213 prim_obj <- newSysLocalDs addrPrimTy
214 return (Var prim_obj,
217 io_ty = exprType body
218 Just (_,io_arg,_) = tcSplitIOType_maybe io_ty
220 mkApps (Var unpack_id)
225 --------------- End of cases for .NET --------------------
228 = do l <- getSrcSpanDs
229 pprPanic "unboxArg: " (ppr l <+> ppr arg_ty)
231 arg_ty = exprType arg
232 maybe_product_type = splitProductType_maybe arg_ty
233 is_product_type = maybeToBool maybe_product_type
234 Just (_, _, data_con, data_con_arg_tys) = maybe_product_type
235 data_con_arity = dataConSourceArity data_con
236 (data_con_arg_ty1 : _) = data_con_arg_tys
238 (_ : _ : data_con_arg_ty3 : _) = data_con_arg_tys
239 maybe_arg3_tycon = splitTyConApp_maybe data_con_arg_ty3
240 Just (arg3_tycon,_) = maybe_arg3_tycon
245 boxResult :: ((Maybe Type, CoreExpr -> CoreExpr)
246 -> (Maybe Type, CoreExpr -> CoreExpr))
249 -> DsM (Type, CoreExpr -> CoreExpr)
251 -- Takes the result of the user-level ccall:
253 -- or maybe just t for an side-effect-free call
254 -- Returns a wrapper for the primitive ccall itself, along with the
255 -- type of the result of the primitive ccall. This result type
256 -- will be of the form
257 -- State# RealWorld -> (# State# RealWorld, t' #)
258 -- where t' is the unwrapped form of t. If t is simply (), then
259 -- the result type will be
260 -- State# RealWorld -> (# State# RealWorld #)
262 -- The gruesome 'augment' and 'mbTopCon' are to do with .NET foreign calls
263 -- It looks a mess: I wonder if it could be refactored.
265 boxResult augment mbTopCon result_ty
266 | Just (io_tycon, io_res_ty, co) <- tcSplitIOType_maybe result_ty
267 -- isIOType_maybe handles the case where the type is a
268 -- simple wrapping of IO. E.g.
269 -- newtype Wrap a = W (IO a)
270 -- No coercion necessary because its a non-recursive newtype
271 -- (If we wanted to handle a *recursive* newtype too, we'd need
272 -- another case, and a coercion.)
273 -- The result is IO t, so wrap the result in an IO constructor
274 = do { res <- resultWrapper io_res_ty
275 ; let aug_res = augment res
279 | isUnboxedTupleType ty
280 -> let (Just (_, ls)) = splitTyConApp_maybe ty in tail ls
283 return_result state anss
284 = mkConApp (tupleCon Unboxed (2 + length extra_result_tys))
285 (map Type (realWorldStatePrimTy : io_res_ty : extra_result_tys)
288 ; (ccall_res_ty, the_alt) <- mk_alt return_result aug_res
290 ; state_id <- newSysLocalDs realWorldStatePrimTy
291 ; let io_data_con = head (tyConDataCons io_tycon)
292 toIOCon = mbTopCon `orElse` dataConWrapId io_data_con
294 wrap the_call = mkCoerceI (mkSymCoI co) $
298 Case (App the_call (Var state_id))
299 (mkWildId ccall_res_ty)
300 (coreAltType the_alt)
304 ; return (realWorldStatePrimTy `mkFunTy` ccall_res_ty, wrap) }
306 boxResult augment mbTopCon result_ty
307 = do -- It isn't IO, so do unsafePerformIO
308 -- It's not conveniently available, so we inline it
309 res <- resultWrapper result_ty
310 (ccall_res_ty, the_alt) <- mk_alt return_result (augment res)
312 wrap = \ the_call -> Case (App the_call (Var realWorldPrimId))
313 (mkWildId ccall_res_ty)
314 (coreAltType the_alt)
316 return (realWorldStatePrimTy `mkFunTy` ccall_res_ty, wrap)
318 return_result state [ans] = ans
319 return_result _ _ = panic "return_result: expected single result"
322 mk_alt return_result (Nothing, wrap_result)
323 = do -- The ccall returns ()
324 state_id <- newSysLocalDs realWorldStatePrimTy
326 the_rhs = return_result (Var state_id)
327 [wrap_result (panic "boxResult")]
329 ccall_res_ty = mkTyConApp unboxedSingletonTyCon [realWorldStatePrimTy]
330 the_alt = (DataAlt unboxedSingletonDataCon, [state_id], the_rhs)
332 return (ccall_res_ty, the_alt)
334 mk_alt return_result (Just prim_res_ty, wrap_result)
335 -- The ccall returns a non-() value
336 | isUnboxedTupleType prim_res_ty= do
338 Just (_, ls) = splitTyConApp_maybe prim_res_ty
339 arity = 1 + length ls
340 args_ids@(result_id:as) <- mapM newSysLocalDs ls
341 state_id <- newSysLocalDs realWorldStatePrimTy
343 the_rhs = return_result (Var state_id)
344 (wrap_result (Var result_id) : map Var as)
345 ccall_res_ty = mkTyConApp (tupleTyCon Unboxed arity)
346 (realWorldStatePrimTy : ls)
347 the_alt = ( DataAlt (tupleCon Unboxed arity)
348 , (state_id : args_ids)
351 return (ccall_res_ty, the_alt)
354 result_id <- newSysLocalDs prim_res_ty
355 state_id <- newSysLocalDs realWorldStatePrimTy
357 the_rhs = return_result (Var state_id)
358 [wrap_result (Var result_id)]
359 ccall_res_ty = mkTyConApp unboxedPairTyCon [realWorldStatePrimTy, prim_res_ty]
360 the_alt = (DataAlt unboxedPairDataCon, [state_id, result_id], the_rhs)
361 return (ccall_res_ty, the_alt)
364 resultWrapper :: Type
365 -> DsM (Maybe Type, -- Type of the expected result, if any
366 CoreExpr -> CoreExpr) -- Wrapper for the result
367 -- resultWrapper deals with the result *value*
368 -- E.g. foreign import foo :: Int -> IO T
369 -- Then resultWrapper deals with marshalling the 'T' part
370 resultWrapper result_ty
371 -- Base case 1: primitive types
372 | isPrimitiveType result_ty
373 = return (Just result_ty, \e -> e)
375 -- Base case 2: the unit type ()
376 | Just (tc,_) <- maybe_tc_app, tc `hasKey` unitTyConKey
377 = return (Nothing, \e -> Var unitDataConId)
379 -- Base case 3: the boolean type
380 | Just (tc,_) <- maybe_tc_app, tc `hasKey` boolTyConKey
382 (Just intPrimTy, \e -> Case e (mkWildId intPrimTy)
384 [(DEFAULT ,[],Var trueDataConId ),
385 (LitAlt (mkMachInt 0),[],Var falseDataConId)])
387 -- Recursive newtypes
388 | Just (rep_ty, co) <- splitNewTypeRepCo_maybe result_ty
389 = do (maybe_ty, wrapper) <- resultWrapper rep_ty
390 return (maybe_ty, \e -> mkCoerce (mkSymCoercion co) (wrapper e))
392 -- The type might contain foralls (eg. for dummy type arguments,
393 -- referring to 'Ptr a' is legal).
394 | Just (tyvar, rest) <- splitForAllTy_maybe result_ty
395 = do (maybe_ty, wrapper) <- resultWrapper rest
396 return (maybe_ty, \e -> Lam tyvar (wrapper e))
398 -- Data types with a single constructor, which has a single arg
399 -- This includes types like Ptr and ForeignPtr
400 | Just (tycon, tycon_arg_tys, data_con, data_con_arg_tys) <- splitProductType_maybe result_ty,
401 dataConSourceArity data_con == 1
403 (unwrapped_res_ty : _) = data_con_arg_tys
404 narrow_wrapper = maybeNarrow tycon
405 (maybe_ty, wrapper) <- resultWrapper unwrapped_res_ty
407 (maybe_ty, \e -> mkApps (Var (dataConWrapId data_con))
408 (map Type tycon_arg_tys ++ [wrapper (narrow_wrapper e)]))
410 -- Strings; 'dotnet' only.
411 | Just (tc, [arg_ty]) <- maybe_tc_app, tc == listTyCon,
412 Just (cc,[]) <- splitTyConApp_maybe arg_ty, cc == charTyCon
413 = do pack_id <- dsLookupGlobalId unmarshalStringName
414 return (Just addrPrimTy,
415 \ e -> App (Var pack_id) e)
417 -- Objects; 'dotnet' only.
418 | Just (tc, [arg_ty]) <- maybe_tc_app,
419 tyConName tc == objectTyConName
420 = do pack_id <- dsLookupGlobalId unmarshalObjectName
421 return (Just addrPrimTy,
422 \ e -> App (Var pack_id) e)
425 = pprPanic "resultWrapper" (ppr result_ty)
427 maybe_tc_app = splitTyConApp_maybe result_ty
429 -- When the result of a foreign call is smaller than the word size, we
430 -- need to sign- or zero-extend the result up to the word size. The C
431 -- standard appears to say that this is the responsibility of the
432 -- caller, not the callee.
434 maybeNarrow :: TyCon -> (CoreExpr -> CoreExpr)
436 | tycon `hasKey` int8TyConKey = \e -> App (Var (mkPrimOpId Narrow8IntOp)) e
437 | tycon `hasKey` int16TyConKey = \e -> App (Var (mkPrimOpId Narrow16IntOp)) e
438 | tycon `hasKey` int32TyConKey
439 && wORD_SIZE > 4 = \e -> App (Var (mkPrimOpId Narrow32IntOp)) e
441 | tycon `hasKey` word8TyConKey = \e -> App (Var (mkPrimOpId Narrow8WordOp)) e
442 | tycon `hasKey` word16TyConKey = \e -> App (Var (mkPrimOpId Narrow16WordOp)) e
443 | tycon `hasKey` word32TyConKey
444 && wORD_SIZE > 4 = \e -> App (Var (mkPrimOpId Narrow32WordOp)) e