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