0fcfdd5b91707f365674043c47f5f8dee6860e42
[ghc-hetmet.git] / ghc / compiler / deSugar / DsCCall.lhs
1 %
2 % (c) The AQUA Project, Glasgow University, 1994-1998
3 %
4 \section[DsCCall]{Desugaring \tr{_ccall_}s and \tr{_casm_}s}
5
6 \begin{code}
7 module DsCCall 
8         ( dsCCall
9         , mkFCall
10         , unboxArg
11         , boxResult
12         , resultWrapper
13         ) where
14
15 #include "HsVersions.h"
16
17 import CoreSyn
18
19 import DsMonad
20
21 import CoreUtils        ( exprType, mkCoerce2 )
22 import Id               ( Id, mkWildId )
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(..) )
28
29 import TcType           ( tcSplitTyConApp_maybe )
30 import Type             ( Type, isUnLiftedType, mkFunTys, mkFunTy,
31                           tyVarsOfType, mkForAllTys, mkTyConApp, 
32                           isPrimitiveType, splitTyConApp_maybe, 
33                           splitNewType_maybe, splitForAllTy_maybe,
34                         )
35
36 import PrimOp           ( PrimOp(..) )
37 import TysPrim          ( realWorldStatePrimTy, intPrimTy,
38                           byteArrayPrimTyCon, mutableByteArrayPrimTyCon
39                         )
40 import TyCon            ( TyCon, tyConDataCons )
41 import TysWiredIn       ( unitDataConId,
42                           unboxedSingletonDataCon, unboxedPairDataCon,
43                           unboxedSingletonTyCon, unboxedPairTyCon,
44                           trueDataCon, falseDataCon, 
45                           trueDataConId, falseDataConId 
46                         )
47 import Literal          ( mkMachInt )
48 import CStrings         ( CLabelString )
49 import PrelNames        ( Unique, hasKey, ioTyConKey, boolTyConKey, unitTyConKey,
50                           int8TyConKey, int16TyConKey, int32TyConKey,
51                           word8TyConKey, word16TyConKey, word32TyConKey
52                         )
53 import VarSet           ( varSetElems )
54 import Constants        ( wORD_SIZE)
55 import Outputable
56 \end{code}
57
58 Desugaring of @ccall@s consists of adding some state manipulation,
59 unboxing any boxed primitive arguments and boxing the result if
60 desired.
61
62 The state stuff just consists of adding in
63 @PrimIO (\ s -> case s of { S# s# -> ... })@ in an appropriate place.
64
65 The unboxing is straightforward, as all information needed to unbox is
66 available from the type.  For each boxed-primitive argument, we
67 transform:
68 \begin{verbatim}
69    _ccall_ foo [ r, t1, ... tm ] e1 ... em
70    |
71    |
72    V
73    case e1 of { T1# x1# ->
74    ...
75    case em of { Tm# xm# -> xm#
76    ccall# foo [ r, t1#, ... tm# ] x1# ... xm#
77    } ... }
78 \end{verbatim}
79
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
83 follows:
84 \begin{verbatim}
85    ccall# foo [ r, t1#, ... tm# ] e1# ... em#
86    |
87    |
88    V
89    \ s# -> case (ccall# foo [ r, t1#, ... tm# ] s# e1# ... em#) of
90           (StateAnd<r># result# state#) -> (R# result#, realWorld#)
91 \end{verbatim}
92
93 \begin{code}
94 dsCCall :: CLabelString -- C routine to invoke
95         -> [CoreExpr]   -- Arguments (desugared)
96         -> Safety       -- Safety of the call
97         -> Bool         -- True <=> really a "_casm_"
98         -> Type         -- Type of the result: IO t
99         -> DsM CoreExpr
100
101 dsCCall lbl args may_gc is_asm result_ty
102   = mapAndUnzipDs unboxArg args `thenDs` \ (unboxed_args, arg_wrappers) ->
103     boxResult [] result_ty      `thenDs` \ (ccall_result_ty, res_wrapper) ->
104     getUniqueDs                 `thenDs` \ uniq ->
105     let
106         target | is_asm    = CasmTarget lbl
107                | otherwise = StaticTarget lbl
108         the_fcall    = CCall (CCallSpec target CCallConv may_gc)
109         the_prim_app = mkFCall uniq the_fcall unboxed_args ccall_result_ty
110     in
111     returnDs (foldr ($) (res_wrapper the_prim_app) arg_wrappers)
112
113 mkFCall :: Unique -> ForeignCall 
114         -> [CoreExpr]   -- Args
115         -> Type         -- Result type
116         -> CoreExpr
117 -- Construct the ccall.  The only tricky bit is that the ccall Id should have
118 -- no free vars, so if any of the arg tys do we must give it a polymorphic type.
119 --      [I forget *why* it should have no free vars!]
120 -- For example:
121 --      mkCCall ... [s::StablePtr (a->b), x::Addr, c::Char]
122 --
123 -- Here we build a ccall thus
124 --      (ccallid::(forall a b.  StablePtr (a -> b) -> Addr -> Char -> IO Addr))
125 --                      a b s x c
126 mkFCall uniq the_fcall val_args res_ty
127   = mkApps (mkVarApps (Var the_fcall_id) tyvars) val_args
128   where
129     arg_tys = map exprType val_args
130     body_ty = (mkFunTys arg_tys res_ty)
131     tyvars  = varSetElems (tyVarsOfType body_ty)
132     ty      = mkForAllTys tyvars body_ty
133     the_fcall_id = mkFCallId uniq the_fcall ty
134 \end{code}
135
136 \begin{code}
137 unboxArg :: CoreExpr                    -- The supplied argument
138          -> DsM (CoreExpr,              -- To pass as the actual argument
139                  CoreExpr -> CoreExpr   -- Wrapper to unbox the arg
140                 )
141 -- Example: if the arg is e::Int, unboxArg will return
142 --      (x#::Int#, \W. case x of I# x# -> W)
143 -- where W is a CoreExpr that probably mentions x#
144
145 unboxArg arg
146   -- Primtive types: nothing to unbox
147   | isPrimitiveType arg_ty
148   = returnDs (arg, \body -> body)
149
150   -- Recursive newtypes
151   | Just rep_ty <- splitNewType_maybe arg_ty
152   = unboxArg (mkCoerce2 rep_ty arg_ty arg)
153       
154   -- Booleans
155   | Just (tc,_) <- splitTyConApp_maybe arg_ty, 
156     tc `hasKey` boolTyConKey
157   = newSysLocalDs intPrimTy             `thenDs` \ prim_arg ->
158     returnDs (Var prim_arg,
159               \ body -> Case (Case arg (mkWildId arg_ty)
160                                        [(DataAlt falseDataCon,[],mkIntLit 0),
161                                         (DataAlt trueDataCon, [],mkIntLit 1)])
162                              prim_arg 
163                              [(DEFAULT,[],body)])
164
165   -- Data types with a single constructor, which has a single, primitive-typed arg
166   -- This deals with Int, Float etc
167   | is_product_type && data_con_arity == 1 
168   = ASSERT(isUnLiftedType data_con_arg_ty1 )    -- Typechecker ensures this
169     newSysLocalDs arg_ty                `thenDs` \ case_bndr ->
170     newSysLocalDs data_con_arg_ty1      `thenDs` \ prim_arg ->
171     returnDs (Var prim_arg,
172               \ body -> Case arg case_bndr [(DataAlt data_con,[prim_arg],body)]
173     )
174
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)
179   | is_product_type &&
180     data_con_arity == 3 &&
181     maybeToBool maybe_arg3_tycon &&
182     (arg3_tycon ==  byteArrayPrimTyCon ||
183      arg3_tycon ==  mutableByteArrayPrimTyCon)
184     -- and, of course, it is an instance of CCallable
185   = newSysLocalDs arg_ty                `thenDs` \ case_bndr ->
186     newSysLocalsDs data_con_arg_tys     `thenDs` \ vars@[l_var, r_var, arr_cts_var] ->
187     returnDs (Var arr_cts_var,
188               \ body -> Case arg case_bndr [(DataAlt data_con,vars,body)]
189     )
190
191   | otherwise
192   = getSrcLocDs `thenDs` \ l ->
193     pprPanic "unboxArg: " (ppr l <+> ppr arg_ty)
194   where
195     arg_ty                                      = exprType arg
196     maybe_product_type                          = splitProductType_maybe arg_ty
197     is_product_type                             = maybeToBool maybe_product_type
198     Just (_, _, data_con, data_con_arg_tys)     = maybe_product_type
199     data_con_arity                              = dataConSourceArity data_con
200     (data_con_arg_ty1 : _)                      = data_con_arg_tys
201
202     (_ : _ : data_con_arg_ty3 : _) = data_con_arg_tys
203     maybe_arg3_tycon               = splitTyConApp_maybe data_con_arg_ty3
204     Just (arg3_tycon,_)            = maybe_arg3_tycon
205 \end{code}
206
207
208 \begin{code}
209 boxResult :: [Id] -> Type -> DsM (Type, CoreExpr -> CoreExpr)
210
211 -- Takes the result of the user-level ccall: 
212 --      either (IO t), 
213 --      or maybe just t for an side-effect-free call
214 -- Returns a wrapper for the primitive ccall itself, along with the
215 -- type of the result of the primitive ccall.  This result type
216 -- will be of the form  
217 --      State# RealWorld -> (# State# RealWorld, t' #)
218 -- where t' is the unwrapped form of t.  If t is simply (), then
219 -- the result type will be 
220 --      State# RealWorld -> (# State# RealWorld #)
221
222 boxResult arg_ids result_ty
223   = case tcSplitTyConApp_maybe result_ty of
224         -- This split absolutely has to be a tcSplit, because we must
225         -- see the IO type; and it's a newtype which is transparent to splitTyConApp.
226
227         -- The result is IO t, so wrap the result in an IO constructor
228         Just (io_tycon, [io_res_ty]) | io_tycon `hasKey` ioTyConKey
229                 -> mk_alt return_result 
230                           (resultWrapper io_res_ty)     `thenDs` \ (ccall_res_ty, the_alt) ->
231                    newSysLocalDs  realWorldStatePrimTy   `thenDs` \ state_id ->
232                    let
233                         io_data_con = head (tyConDataCons io_tycon)
234                         wrap = \ the_call -> 
235                                  mkApps (Var (dataConWrapId io_data_con))
236                                            [ Type io_res_ty, 
237                                              Lam state_id $
238                                               Case (App the_call (Var state_id))
239                                                    (mkWildId ccall_res_ty)
240                                                    [the_alt]
241                                            ]
242                    in
243                    returnDs (realWorldStatePrimTy `mkFunTy` ccall_res_ty, wrap)
244                 where
245                    return_result state ans = mkConApp unboxedPairDataCon 
246                                                       [Type realWorldStatePrimTy, Type io_res_ty, 
247                                                        state, ans]
248
249         -- It isn't, so do unsafePerformIO
250         -- It's not conveniently available, so we inline it
251         other -> mk_alt return_result
252                         (resultWrapper result_ty) `thenDs` \ (ccall_res_ty, the_alt) ->
253                  let
254                     wrap = \ the_call -> Case (App the_call (Var realWorldPrimId)) 
255                                               (mkWildId ccall_res_ty)
256                                               [the_alt]
257                  in
258                  returnDs (realWorldStatePrimTy `mkFunTy` ccall_res_ty, wrap)
259               where
260                  return_result state ans = ans
261   where
262     mk_alt return_result (Nothing, wrap_result)
263         =       -- The ccall returns ()
264           newSysLocalDs realWorldStatePrimTy    `thenDs` \ state_id ->
265           let
266                 the_rhs = return_result (Var state_id) 
267                                         (wrap_result (panic "boxResult"))
268
269                 ccall_res_ty = mkTyConApp unboxedSingletonTyCon [realWorldStatePrimTy]
270                 the_alt      = (DataAlt unboxedSingletonDataCon, [state_id], the_rhs)
271           in
272           returnDs (ccall_res_ty, the_alt)
273
274     mk_alt return_result (Just prim_res_ty, wrap_result)
275         =       -- The ccall returns a non-() value
276           newSysLocalDs prim_res_ty             `thenDs` \ result_id ->
277           newSysLocalDs realWorldStatePrimTy    `thenDs` \ state_id ->
278           let
279                 the_rhs = return_result (Var state_id) 
280                                         (wrap_result (Var result_id))
281
282                 ccall_res_ty = mkTyConApp unboxedPairTyCon [realWorldStatePrimTy, prim_res_ty]
283                 the_alt      = (DataAlt unboxedPairDataCon, [state_id, result_id], the_rhs)
284           in
285           returnDs (ccall_res_ty, the_alt)
286
287
288 resultWrapper :: Type
289               -> (Maybe Type,           -- Type of the expected result, if any
290                   CoreExpr -> CoreExpr) -- Wrapper for the result 
291 resultWrapper result_ty
292   -- Base case 1: primitive types
293   | isPrimitiveType result_ty
294   = (Just result_ty, \e -> e)
295
296   -- Base case 2: the unit type ()
297   | Just (tc,_) <- maybe_tc_app, tc `hasKey` unitTyConKey
298   = (Nothing, \e -> Var unitDataConId)
299
300   -- Base case 3: the boolean type
301   | Just (tc,_) <- maybe_tc_app, tc `hasKey` boolTyConKey
302   = (Just intPrimTy, \e -> Case e (mkWildId intPrimTy)
303                                   [(DEFAULT             ,[],Var trueDataConId ),
304                                    (LitAlt (mkMachInt 0),[],Var falseDataConId)])
305
306   -- Recursive newtypes
307   | Just rep_ty <- splitNewType_maybe result_ty
308   = let
309         (maybe_ty, wrapper) = resultWrapper rep_ty
310     in
311     (maybe_ty, \e -> mkCoerce2 result_ty rep_ty (wrapper e))
312
313   -- The type might contain foralls (eg. for dummy type arguments,
314   -- referring to 'Ptr a' is legal).
315   | Just (tyvar, rest) <- splitForAllTy_maybe result_ty
316   = let
317         (maybe_ty, wrapper) = resultWrapper rest
318     in
319     (maybe_ty, \e -> Lam tyvar (wrapper e))
320
321   -- Data types with a single constructor, which has a single arg
322   | Just (tycon, tycon_arg_tys, data_con, data_con_arg_tys) <- splitProductType_maybe result_ty,
323     dataConSourceArity data_con == 1
324   = let
325         (maybe_ty, wrapper)    = resultWrapper unwrapped_res_ty
326         (unwrapped_res_ty : _) = data_con_arg_tys
327         narrow_wrapper         = maybeNarrow tycon
328     in
329     (maybe_ty, \e -> mkApps (Var (dataConWrapId data_con)) 
330                             (map Type tycon_arg_tys ++ [wrapper (narrow_wrapper e)]))
331
332   | otherwise
333   = pprPanic "resultWrapper" (ppr result_ty)
334   where
335     maybe_tc_app = splitTyConApp_maybe result_ty
336
337 -- When the result of a foreign call is smaller than the word size, we
338 -- need to sign- or zero-extend the result up to the word size.  The C
339 -- standard appears to say that this is the responsibility of the
340 -- caller, not the callee.
341
342 maybeNarrow :: TyCon -> (CoreExpr -> CoreExpr)
343 maybeNarrow tycon
344   | tycon `hasKey` int8TyConKey   = \e -> App (Var (mkPrimOpId Narrow8IntOp)) e
345   | tycon `hasKey` int16TyConKey  = \e -> App (Var (mkPrimOpId Narrow16IntOp)) e
346   | tycon `hasKey` int32TyConKey
347          && wORD_SIZE > 4         = \e -> App (Var (mkPrimOpId Narrow32IntOp)) e
348
349   | tycon `hasKey` word8TyConKey  = \e -> App (Var (mkPrimOpId Narrow8WordOp)) e
350   | tycon `hasKey` word16TyConKey = \e -> App (Var (mkPrimOpId Narrow16WordOp)) e
351   | tycon `hasKey` word32TyConKey
352          && wORD_SIZE > 4         = \e -> App (Var (mkPrimOpId Narrow32WordOp)) e
353   | otherwise                     = id
354 \end{code}