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