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