[project @ 2001-09-07 12:30:15 by simonpj]
[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, 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(..) )
28
29 import TcType           ( tcSplitTyConApp_maybe )
30 import Type             ( Type, isUnLiftedType, mkFunTys, mkFunTy,
31                           tyVarsOfType, mkForAllTys, mkTyConApp, 
32                           isPrimitiveType, eqType,
33                           splitTyConApp_maybe, splitNewType_maybe
34                         )
35
36 import PrimOp           ( PrimOp(TouchOp) )
37 import TysPrim          ( realWorldStatePrimTy,
38                           byteArrayPrimTyCon, mutableByteArrayPrimTyCon,
39                           intPrimTy, foreignObjPrimTy
40                         )
41 import TyCon            ( tyConDataCons )
42 import TysWiredIn       ( unitDataConId,
43                           unboxedSingletonDataCon, unboxedPairDataCon,
44                           unboxedSingletonTyCon, unboxedPairTyCon,
45                           trueDataCon, falseDataCon, 
46                           trueDataConId, falseDataConId 
47                         )
48 import Literal          ( mkMachInt )
49 import CStrings         ( CLabelString )
50 import PrelNames        ( Unique, hasKey, ioTyConKey, boolTyConKey, unitTyConKey )
51 import VarSet           ( varSetElems )
52 import Outputable
53 \end{code}
54
55 Desugaring of @ccall@s consists of adding some state manipulation,
56 unboxing any boxed primitive arguments and boxing the result if
57 desired.
58
59 The state stuff just consists of adding in
60 @PrimIO (\ s -> case s of { S# s# -> ... })@ in an appropriate place.
61
62 The unboxing is straightforward, as all information needed to unbox is
63 available from the type.  For each boxed-primitive argument, we
64 transform:
65 \begin{verbatim}
66    _ccall_ foo [ r, t1, ... tm ] e1 ... em
67    |
68    |
69    V
70    case e1 of { T1# x1# ->
71    ...
72    case em of { Tm# xm# -> xm#
73    ccall# foo [ r, t1#, ... tm# ] x1# ... xm#
74    } ... }
75 \end{verbatim}
76
77 The reboxing of a @_ccall_@ result is a bit tricker: the types don't
78 contain information about the state-pairing functions so we have to
79 keep a list of \tr{(type, s-p-function)} pairs.  We transform as
80 follows:
81 \begin{verbatim}
82    ccall# foo [ r, t1#, ... tm# ] e1# ... em#
83    |
84    |
85    V
86    \ s# -> case (ccall# foo [ r, t1#, ... tm# ] s# e1# ... em#) of
87           (StateAnd<r># result# state#) -> (R# result#, realWorld#)
88 \end{verbatim}
89
90 \begin{code}
91 dsCCall :: CLabelString -- C routine to invoke
92         -> [CoreExpr]   -- Arguments (desugared)
93         -> Safety       -- Safety of the call
94         -> Bool         -- True <=> really a "_casm_"
95         -> Type         -- Type of the result: IO t
96         -> DsM CoreExpr
97
98 dsCCall lbl args may_gc is_asm result_ty
99   = mapAndUnzipDs unboxArg args `thenDs` \ (unboxed_args, arg_wrappers) ->
100     boxResult [] result_ty      `thenDs` \ (ccall_result_ty, res_wrapper) ->
101     getUniqueDs                 `thenDs` \ uniq ->
102     let
103         target | is_asm    = CasmTarget lbl
104                | otherwise = StaticTarget lbl
105         the_fcall    = CCall (CCallSpec target CCallConv may_gc)
106         the_prim_app = mkFCall uniq the_fcall unboxed_args ccall_result_ty
107     in
108     returnDs (foldr ($) (res_wrapper the_prim_app) arg_wrappers)
109
110 mkFCall :: Unique -> ForeignCall 
111         -> [CoreExpr]   -- Args
112         -> Type         -- Result type
113         -> CoreExpr
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!]
117 -- For example:
118 --      mkCCall ... [s::StablePtr (a->b), x::Addr, c::Char]
119 --
120 -- Here we build a ccall thus
121 --      (ccallid::(forall a b.  StablePtr (a -> b) -> Addr -> Char -> IO Addr))
122 --                      a b s x c
123 mkFCall uniq the_fcall val_args res_ty
124   = mkApps (mkVarApps (Var the_fcall_id) tyvars) val_args
125   where
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
131 \end{code}
132
133 \begin{code}
134 unboxArg :: CoreExpr                    -- The supplied argument
135          -> DsM (CoreExpr,              -- To pass as the actual argument
136                  CoreExpr -> CoreExpr   -- Wrapper to unbox the arg
137                 )
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#
141
142 unboxArg arg
143   -- Primtive types: nothing to unbox
144   | isPrimitiveType arg_ty
145   = returnDs (arg, \body -> body)
146
147   -- Recursive newtypes
148   | Just rep_ty <- splitNewType_maybe arg_ty
149   = unboxArg (mkCoerce rep_ty arg_ty arg)
150       
151   -- Booleans
152   | Just (tc,_) <- splitTyConApp_maybe arg_ty, 
153     tc `hasKey` boolTyConKey
154   = newSysLocalDs intPrimTy             `thenDs` \ prim_arg ->
155     returnDs (Var prim_arg,
156               \ body -> Case (Case arg (mkWildId arg_ty)
157                                        [(DataAlt falseDataCon,[],mkIntLit 0),
158                                         (DataAlt trueDataCon, [],mkIntLit 1)])
159                              prim_arg 
160                              [(DEFAULT,[],body)])
161
162   -- Data types with a single constructor, which has a single, primitive-typed arg
163   -- This deals with Int, Float etc
164   | is_product_type && data_con_arity == 1 
165   = ASSERT(isUnLiftedType data_con_arg_ty1 )    -- Typechecker ensures this
166     newSysLocalDs arg_ty                `thenDs` \ case_bndr ->
167     newSysLocalDs data_con_arg_ty1      `thenDs` \ prim_arg ->
168     returnDs (Var prim_arg,
169               \ body -> Case arg case_bndr [(DataAlt data_con,[prim_arg],body)]
170     )
171
172   -- Byte-arrays, both mutable and otherwise; hack warning
173   -- We're looking for values of type ByteArray, MutableByteArray
174   --    data ByteArray          ix = ByteArray        ix ix ByteArray#
175   --    data MutableByteArray s ix = MutableByteArray ix ix (MutableByteArray# s)
176   | is_product_type &&
177     data_con_arity == 3 &&
178     maybeToBool maybe_arg3_tycon &&
179     (arg3_tycon ==  byteArrayPrimTyCon ||
180      arg3_tycon ==  mutableByteArrayPrimTyCon)
181     -- and, of course, it is an instance of CCallable
182   = newSysLocalDs arg_ty                `thenDs` \ case_bndr ->
183     newSysLocalsDs data_con_arg_tys     `thenDs` \ vars@[l_var, r_var, arr_cts_var] ->
184     returnDs (Var arr_cts_var,
185               \ body -> Case arg case_bndr [(DataAlt data_con,vars,body)]
186     )
187
188   | otherwise
189   = getSrcLocDs `thenDs` \ l ->
190     pprPanic "unboxArg: " (ppr l <+> ppr arg_ty)
191   where
192     arg_ty                                      = exprType arg
193     maybe_product_type                          = splitProductType_maybe arg_ty
194     is_product_type                             = maybeToBool maybe_product_type
195     Just (_, _, data_con, data_con_arg_tys)     = maybe_product_type
196     data_con_arity                              = dataConSourceArity data_con
197     (data_con_arg_ty1 : _)                      = data_con_arg_tys
198
199     (_ : _ : data_con_arg_ty3 : _) = data_con_arg_tys
200     maybe_arg3_tycon               = splitTyConApp_maybe data_con_arg_ty3
201     Just (arg3_tycon,_)            = maybe_arg3_tycon
202 \end{code}
203
204
205 \begin{code}
206 boxResult :: [Id] -> Type -> DsM (Type, CoreExpr -> CoreExpr)
207
208 -- Takes the result of the user-level ccall: 
209 --      either (IO t), 
210 --      or maybe just t for an side-effect-free call
211 -- Returns a wrapper for the primitive ccall itself, along with the
212 -- type of the result of the primitive ccall.  This result type
213 -- will be of the form  
214 --      State# RealWorld -> (# State# RealWorld, t' #)
215 -- where t' is the unwrapped form of t.  If t is simply (), then
216 -- the result type will be 
217 --      State# RealWorld -> (# State# RealWorld #)
218
219 -- Here is where we arrange that ForeignPtrs which are passed to a 'safe'
220 -- foreign import don't get finalized until the call returns.  For each
221 -- argument of type ForeignObj# we arrange to touch# the argument after
222 -- the call.  The arg_ids passed in are the Ids passed to the actual ccall.
223
224 boxResult arg_ids result_ty
225   = case tcSplitTyConApp_maybe result_ty of
226         -- This split absolutely has to be a tcSplit, because we must
227         -- see the IO type; and it's a newtype which is transparent to splitTyConApp.
228
229         -- The result is IO t, so wrap the result in an IO constructor
230         Just (io_tycon, [io_res_ty]) | io_tycon `hasKey` ioTyConKey
231                 -> mk_alt return_result 
232                           (resultWrapper io_res_ty)     `thenDs` \ (ccall_res_ty, the_alt) ->
233                    newSysLocalDs  realWorldStatePrimTy   `thenDs` \ state_id ->
234                    let
235                         io_data_con = head (tyConDataCons io_tycon)
236                         wrap = \ the_call -> 
237                                  mkApps (Var (dataConWrapId io_data_con))
238                                            [ Type io_res_ty, 
239                                              Lam state_id $
240                                               Case (App the_call (Var state_id))
241                                                    (mkWildId ccall_res_ty)
242                                                    [the_alt]
243                                            ]
244                    in
245                    returnDs (realWorldStatePrimTy `mkFunTy` ccall_res_ty, wrap)
246                 where
247                    return_result state ans = mkConApp unboxedPairDataCon 
248                                                       [Type realWorldStatePrimTy, Type io_res_ty, 
249                                                        state, ans]
250
251         -- It isn't, so do unsafePerformIO
252         -- It's not conveniently available, so we inline it
253         other -> mk_alt return_result
254                         (resultWrapper result_ty) `thenDs` \ (ccall_res_ty, the_alt) ->
255                  let
256                     wrap = \ the_call -> Case (App the_call (Var realWorldPrimId)) 
257                                               (mkWildId ccall_res_ty)
258                                               [the_alt]
259                  in
260                  returnDs (realWorldStatePrimTy `mkFunTy` ccall_res_ty, wrap)
261               where
262                  return_result state ans = ans
263   where
264     mk_alt return_result (Nothing, wrap_result)
265         =       -- The ccall returns ()
266           let
267                 rhs_fun state_id = return_result (Var state_id) 
268                                         (wrap_result (panic "boxResult"))
269           in
270           newSysLocalDs realWorldStatePrimTy    `thenDs` \ state_id ->
271           mkTouches arg_ids state_id rhs_fun    `thenDs` \ the_rhs ->
272           let
273                 ccall_res_ty = mkTyConApp unboxedSingletonTyCon [realWorldStatePrimTy]
274                 the_alt      = (DataAlt unboxedSingletonDataCon, [state_id], the_rhs)
275           in
276           returnDs (ccall_res_ty, the_alt)
277
278     mk_alt return_result (Just prim_res_ty, wrap_result)
279         =       -- The ccall returns a non-() value
280           newSysLocalDs prim_res_ty             `thenDs` \ result_id ->
281           let
282                 rhs_fun state_id = return_result (Var state_id) 
283                                         (wrap_result (Var result_id))
284           in
285           newSysLocalDs realWorldStatePrimTy    `thenDs` \ state_id ->
286           mkTouches arg_ids state_id rhs_fun    `thenDs` \ the_rhs ->
287           let
288                 ccall_res_ty = mkTyConApp unboxedPairTyCon [realWorldStatePrimTy, prim_res_ty]
289                 the_alt      = (DataAlt unboxedPairDataCon, [state_id, result_id], the_rhs)
290           in
291           returnDs (ccall_res_ty, the_alt)
292
293 touchzh = mkPrimOpId TouchOp
294
295 mkTouches []     s cont = returnDs (cont s)
296 mkTouches (v:vs) s cont
297   | not (idType v `eqType` foreignObjPrimTy) = mkTouches vs s cont
298   | otherwise = newSysLocalDs realWorldStatePrimTy `thenDs` \s' -> 
299                 mkTouches vs s' cont `thenDs` \ rest ->
300                 returnDs (Case (mkApps (Var touchzh) [Type foreignObjPrimTy, 
301                                                       Var v, Var s]) s' 
302                                 [(DEFAULT, [], rest)])
303
304 resultWrapper :: Type
305               -> (Maybe Type,           -- Type of the expected result, if any
306                   CoreExpr -> CoreExpr) -- Wrapper for the result 
307 resultWrapper result_ty
308   -- Base case 1: primitive types
309   | isPrimitiveType result_ty
310   = (Just result_ty, \e -> e)
311
312   -- Base case 2: the unit type ()
313   | Just (tc,_) <- maybe_tc_app, tc `hasKey` unitTyConKey
314   = (Nothing, \e -> Var unitDataConId)
315
316   -- Base case 3: the boolean type
317   | Just (tc,_) <- maybe_tc_app, tc `hasKey` boolTyConKey
318   = (Just intPrimTy, \e -> Case e (mkWildId intPrimTy)
319                                   [(DEFAULT             ,[],Var trueDataConId ),
320                                    (LitAlt (mkMachInt 0),[],Var falseDataConId)])
321
322   -- Recursive newtypes
323   | Just rep_ty <- splitNewType_maybe result_ty
324   = let
325         (maybe_ty, wrapper) = resultWrapper rep_ty
326     in
327     (maybe_ty, \e -> mkCoerce result_ty rep_ty (wrapper e))
328
329   -- Data types with a single constructor, which has a single arg
330   | Just (_, tycon_arg_tys, data_con, data_con_arg_tys) <- splitProductType_maybe result_ty,
331     dataConSourceArity data_con == 1
332   = let
333         (maybe_ty, wrapper)    = resultWrapper unwrapped_res_ty
334         (unwrapped_res_ty : _) = data_con_arg_tys
335     in
336     (maybe_ty, \e -> mkApps (Var (dataConWrapId data_con)) 
337                             (map Type tycon_arg_tys ++ [wrapper e]))
338
339   | otherwise
340   = pprPanic "resultWrapper" (ppr result_ty)
341   where
342     maybe_tc_app = splitTyConApp_maybe result_ty
343 \end{code}