9ef96010edc162792ae7107e931acc7021b8e089
[ghc-hetmet.git] / ghc / compiler / deSugar / DsCCall.lhs
1 %
2 % (c) The AQUA Project, Glasgow University, 1994-1996
3 %
4 \section[DsCCall]{Desugaring \tr{_ccall_}s and \tr{_casm_}s}
5
6 \begin{code}
7 #include "HsVersions.h"
8
9 module DsCCall ( dsCCall ) where
10
11 IMP_Ubiq()
12
13 import CoreSyn
14
15 import DsMonad
16 import DsUtils
17
18 import CoreUtils        ( coreExprType )
19 import Id               ( dataConArgTys, mkTupleCon )
20 import Maybes           ( maybeToBool )
21 import PprStyle         ( PprStyle(..) )
22 import PprType          ( GenType{-instances-} )
23 import Pretty
24 import PrelVals         ( packStringForCId )
25 import PrimOp           ( PrimOp(..) )
26 import Type             ( isPrimType, maybeAppDataTyConExpandingDicts, eqTy, maybeBoxedPrimType )
27 import TysPrim          ( byteArrayPrimTy, realWorldTy,  realWorldStatePrimTy )
28 import TysWiredIn       ( getStatePairingConInfo,
29                           realWorldStateTy, stateDataCon,
30                           stringTy
31                         )
32 import Util             ( pprPanic, pprError, panic )
33 \end{code}
34
35 Desugaring of @ccall@s consists of adding some state manipulation,
36 unboxing any boxed primitive arguments and boxing the result if
37 desired.
38
39 The state stuff just consists of adding in
40 @\ s -> case s of { S# s# -> ... }@ in an appropriate place.
41
42 The unboxing is straightforward, as all information needed to unbox is
43 available from the type.  For each boxed-primitive argument, we
44 transform:
45 \begin{verbatim}
46    _ccall_ foo [ r, t1, ... tm ] e1 ... em
47    |
48    |
49    V
50    case e1 of { T1# x1# ->
51    ...
52    case em of { Tm# xm# -> xm#
53    ccall# foo [ r, t1#, ... tm# ] x1# ... xm#
54    } ... }
55 \end{verbatim}
56
57 The reboxing of a @_ccall_@ result is a bit tricker: the types don't
58 contain information about the state-pairing functions so we have to
59 keep a list of \tr{(type, s-p-function)} pairs.  We transform as
60 follows:
61 \begin{verbatim}
62    ccall# foo [ r, t1#, ... tm# ] e1# ... em#
63    |
64    |
65    V
66    \ s# -> case (ccall# foo [ r, t1#, ... tm# ] s# e1# ... em#) of
67           (StateAnd<r># result# state#) -> (R# result#, realWorld#)
68 \end{verbatim}
69
70 \begin{code}
71 dsCCall :: FAST_STRING          -- C routine to invoke
72         -> [CoreExpr]   -- Arguments (desugared)
73         -> Bool                 -- True <=> might cause Haskell GC
74         -> Bool                 -- True <=> really a "_casm_"
75         -> Type         -- Type of the result (a boxed-prim type)
76         -> DsM CoreExpr
77
78 dsCCall label args may_gc is_asm result_ty
79   = newSysLocalDs realWorldStateTy      `thenDs` \ old_s ->
80
81     mapAndUnzipDs unboxArg (Var old_s : args)   `thenDs` \ (final_args, arg_wrappers) ->
82
83     boxResult result_ty                         `thenDs` \ (final_result_ty, res_wrapper) ->
84
85     let
86         the_ccall_op = CCallOp label is_asm may_gc
87                                (map coreExprType final_args)
88                                final_result_ty
89     in
90     mkPrimDs the_ccall_op (map VarArg final_args) `thenDs` \ the_prim_app ->
91     let
92         the_body = foldr apply (res_wrapper the_prim_app) arg_wrappers
93     in
94     returnDs (Lam (ValBinder old_s) the_body)
95   where
96     apply f x = f x
97 \end{code}
98
99 \begin{code}
100 unboxArg :: CoreExpr                    -- The supplied argument
101          -> DsM (CoreExpr,                      -- To pass as the actual argument
102                  CoreExpr -> CoreExpr   -- Wrapper to unbox the arg
103                 )
104 unboxArg arg
105
106   -- Primitive types
107   -- ADR Question: can this ever be used?  None of the PrimTypes are
108   -- instances of the CCallable class.
109   | isPrimType arg_ty
110   = returnDs (arg, \body -> body)
111
112   -- Strings
113   | arg_ty `eqTy` stringTy
114   -- ToDo (ADR): - allow synonyms of Strings too?
115   = newSysLocalDs byteArrayPrimTy               `thenDs` \ prim_arg ->
116     mkAppDs (Var packStringForCId) [VarArg arg] `thenDs` \ pack_appn ->
117     returnDs (Var prim_arg,
118               \body -> Case pack_appn (PrimAlts []
119                                                     (BindDefault prim_arg body))
120     )
121
122   | null data_cons
123     -- oops: we can't see the data constructors!!!
124   = can't_see_datacons_error "argument" arg_ty
125
126   -- Byte-arrays, both mutable and otherwise
127   -- (HACKy method -- but we really don't want the TyCons wired-in...) [WDP 94/10]
128   | is_data_type &&
129     length data_con_arg_tys == 2 &&
130     not (isPrimType data_con_arg_ty1) &&
131     isPrimType data_con_arg_ty2
132     -- and, of course, it is an instance of CCallable
133 --  ( tycon == byteArrayTyCon ||
134 --    tycon == mutableByteArrayTyCon )
135   = newSysLocalsDs data_con_arg_tys             `thenDs` \ vars@[ixs_var, arr_cts_var] ->
136     returnDs (Var arr_cts_var,
137               \ body -> Case arg (AlgAlts [(the_data_con,vars,body)]
138                                               NoDefault)
139     )
140
141   -- Data types with a single constructor, which has a single, primitive-typed arg
142   | maybeToBool maybe_boxed_prim_arg_ty
143   = newSysLocalDs the_prim_arg_ty               `thenDs` \ prim_arg ->
144     returnDs (Var prim_arg,
145               \ body -> Case arg (AlgAlts [(box_data_con,[prim_arg],body)]
146                                               NoDefault)
147     )
148
149   | otherwise
150   = pprPanic "unboxArg: " (ppr PprDebug arg_ty)
151   where
152     arg_ty = coreExprType arg
153
154     maybe_boxed_prim_arg_ty = maybeBoxedPrimType arg_ty
155     (Just (box_data_con, the_prim_arg_ty)) = maybe_boxed_prim_arg_ty
156
157     maybe_data_type                        = maybeAppDataTyConExpandingDicts arg_ty
158     is_data_type                           = maybeToBool maybe_data_type
159     (Just (tycon, tycon_arg_tys, data_cons)) = maybe_data_type
160     (the_data_con : other_data_cons)       = data_cons
161
162     data_con_arg_tys = dataConArgTys the_data_con tycon_arg_tys
163     (data_con_arg_ty1 : data_con_arg_ty2 : _) = data_con_arg_tys
164
165 can't_see_datacons_error thing ty
166   = pprError "ERROR: Can't see the data constructor(s) for _ccall_/_casm_ "
167              (ppBesides [ppStr thing, ppStr "; type: ", ppr PprForUser ty])
168 \end{code}
169
170
171 \begin{code}
172 tuple_con_2 = mkTupleCon 2 -- out here to avoid CAF (sigh)
173 covar_tuple_con_0 = Var (mkTupleCon 0) -- ditto
174
175 boxResult :: Type                               -- Type of desired result
176           -> DsM (Type,                 -- Type of the result of the ccall itself
177                   CoreExpr -> CoreExpr) -- Wrapper for the ccall
178                                                         -- to box the result
179 boxResult result_ty
180   | null data_cons
181   -- oops! can't see the data constructors
182   = can't_see_datacons_error "result" result_ty
183
184   -- Data types with a single constructor, which has a single, primitive-typed arg
185   | (maybeToBool maybe_data_type) &&                            -- Data type
186     (null other_data_cons) &&                                   -- Just one constr
187     not (null data_con_arg_tys) && null other_args_tys  &&      -- Just one arg
188     isPrimType the_prim_result_ty                               -- of primitive type
189   =
190     newSysLocalDs realWorldStatePrimTy                  `thenDs` \ prim_state_id ->
191     newSysLocalDs the_prim_result_ty                    `thenDs` \ prim_result_id ->
192
193     mkConDs stateDataCon [TyArg realWorldTy, VarArg (Var prim_state_id)]  `thenDs` \ new_state ->
194     mkConDs the_data_con (map TyArg tycon_arg_tys ++ [VarArg (Var prim_result_id)]) `thenDs` \ the_result ->
195
196     mkConDs tuple_con_2
197             [TyArg result_ty, TyArg realWorldStateTy, VarArg the_result, VarArg new_state]
198                                                         `thenDs` \ the_pair ->
199     let
200         the_alt = (state_and_prim_datacon, [prim_state_id, prim_result_id], the_pair)
201     in
202     returnDs (state_and_prim_ty,
203               \prim_app -> Case prim_app (AlgAlts [the_alt] NoDefault)
204     )
205
206   -- Data types with a single nullary constructor
207   | (maybeToBool maybe_data_type) &&                            -- Data type
208     (null other_data_cons) &&                                   -- Just one constr
209     (null data_con_arg_tys)
210   =
211     newSysLocalDs realWorldStatePrimTy          `thenDs` \ prim_state_id ->
212
213     mkConDs stateDataCon [TyArg realWorldTy, VarArg (Var prim_state_id)]
214                                                 `thenDs` \ new_state ->
215     mkConDs tuple_con_2
216             [TyArg result_ty, TyArg realWorldStateTy, VarArg covar_tuple_con_0, VarArg new_state]
217                                                 `thenDs` \ the_pair ->
218
219     let
220         the_alt  = (stateDataCon, [prim_state_id], the_pair)
221     in
222     returnDs (realWorldStateTy,
223               \prim_app -> Case prim_app (AlgAlts [the_alt] NoDefault)
224     )
225
226   | otherwise
227   = pprPanic "boxResult: " (ppr PprDebug result_ty)
228
229   where
230     maybe_data_type                        = maybeAppDataTyConExpandingDicts result_ty
231     Just (tycon, tycon_arg_tys, data_cons) = maybe_data_type
232     (the_data_con : other_data_cons)       = data_cons
233
234     data_con_arg_tys                       = dataConArgTys the_data_con tycon_arg_tys
235     (the_prim_result_ty : other_args_tys)  = data_con_arg_tys
236
237     (state_and_prim_datacon, state_and_prim_ty) = getStatePairingConInfo the_prim_result_ty
238 \end{code}
239