[project @ 1997-05-19 00:12:10 by sof]
[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 )
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, maybeAppTyCon,
27                           eqTy, maybeBoxedPrimType, SYN_IE(Type) )
28 import TysPrim          ( byteArrayPrimTy, realWorldTy,  realWorldStatePrimTy,
29                           byteArrayPrimTyCon, mutableByteArrayPrimTyCon )
30 import TysWiredIn       ( getStatePairingConInfo,
31                           realWorldStateTy, stateDataCon, pairDataCon, unitDataCon,
32                           stringTy
33                         )
34 import Util             ( pprPanic, pprError, panic )
35 #if __GLASGOW_HASKELL__ >= 202
36 import Outputable       ( Outputable(..) )
37 #endif
38
39 \end{code}
40
41 Desugaring of @ccall@s consists of adding some state manipulation,
42 unboxing any boxed primitive arguments and boxing the result if
43 desired.
44
45 The state stuff just consists of adding in
46 @PrimIO (\ s -> case s of { S# s# -> ... })@ in an appropriate place.
47
48 The unboxing is straightforward, as all information needed to unbox is
49 available from the type.  For each boxed-primitive argument, we
50 transform:
51 \begin{verbatim}
52    _ccall_ foo [ r, t1, ... tm ] e1 ... em
53    |
54    |
55    V
56    case e1 of { T1# x1# ->
57    ...
58    case em of { Tm# xm# -> xm#
59    ccall# foo [ r, t1#, ... tm# ] x1# ... xm#
60    } ... }
61 \end{verbatim}
62
63 The reboxing of a @_ccall_@ result is a bit tricker: the types don't
64 contain information about the state-pairing functions so we have to
65 keep a list of \tr{(type, s-p-function)} pairs.  We transform as
66 follows:
67 \begin{verbatim}
68    ccall# foo [ r, t1#, ... tm# ] e1# ... em#
69    |
70    |
71    V
72    \ s# -> case (ccall# foo [ r, t1#, ... tm# ] s# e1# ... em#) of
73           (StateAnd<r># result# state#) -> (R# result#, realWorld#)
74 \end{verbatim}
75
76 \begin{code}
77 dsCCall :: FAST_STRING  -- C routine to invoke
78         -> [CoreExpr]   -- Arguments (desugared)
79         -> Bool         -- True <=> might cause Haskell GC
80         -> Bool         -- True <=> really a "_casm_"
81         -> Type         -- Type of the result (a boxed-prim type)
82         -> DsM CoreExpr
83
84 dsCCall label args may_gc is_asm result_ty
85   = newSysLocalDs realWorldStateTy      `thenDs` \ old_s ->
86
87     mapAndUnzipDs unboxArg (Var old_s : args)   `thenDs` \ (final_args, arg_wrappers) ->
88
89     boxResult result_ty                         `thenDs` \ (final_result_ty, res_wrapper) ->
90
91     let
92         the_ccall_op = CCallOp label is_asm may_gc
93                                (map coreExprType final_args)
94                                final_result_ty
95     in
96     mkPrimDs the_ccall_op (map VarArg final_args) `thenDs` \ the_prim_app ->
97     let
98         the_body = foldr ($) (res_wrapper the_prim_app) arg_wrappers
99     in
100     returnDs (Lam (ValBinder old_s) the_body)
101 \end{code}
102
103 \begin{code}
104 unboxArg :: CoreExpr                    -- The supplied argument
105          -> DsM (CoreExpr,              -- To pass as the actual argument
106                  CoreExpr -> CoreExpr   -- Wrapper to unbox the arg
107                 )
108 unboxArg arg
109
110   -- Primitive types
111   -- ADR Question: can this ever be used?  None of the PrimTypes are
112   -- instances of the CCallable class.
113   --
114   -- SOF response:
115   --    Oh yes they are, I've just added them :-) Having _ccall_ and _casm_
116   --  that accept unboxed arguments is a Good Thing if you have a stub generator
117   --  which generates the boiler-plate box-unbox code for you, i.e., it may help
118   --  us nuke this very module :-)
119   --
120   | isPrimType arg_ty
121   = returnDs (arg, \body -> body)
122
123   -- Strings
124   | arg_ty `eqTy` stringTy
125   -- ToDo (ADR): - allow synonyms of Strings too?
126   = newSysLocalDs byteArrayPrimTy               `thenDs` \ prim_arg ->
127     mkAppDs (Var packStringForCId) [VarArg arg] `thenDs` \ pack_appn ->
128     returnDs (Var prim_arg,
129               \body -> Case pack_appn (PrimAlts []
130                                                     (BindDefault prim_arg body))
131     )
132
133   | null data_cons
134     -- oops: we can't see the data constructors!!!
135   = can't_see_datacons_error "argument" arg_ty
136
137   -- Byte-arrays, both mutable and otherwise; hack warning
138   | is_data_type &&
139     length data_con_arg_tys == 2 &&
140     maybeToBool maybe_arg2_tycon &&
141     (arg2_tycon ==  byteArrayPrimTyCon ||
142      arg2_tycon ==  mutableByteArrayPrimTyCon)
143     -- and, of course, it is an instance of CCallable
144   = newSysLocalsDs data_con_arg_tys             `thenDs` \ vars@[ixs_var, arr_cts_var] ->
145     returnDs (Var arr_cts_var,
146               \ body -> Case arg (AlgAlts [(the_data_con,vars,body)]
147                                               NoDefault)
148     )
149
150   -- Data types with a single constructor, which has a single, primitive-typed arg
151   | maybeToBool maybe_boxed_prim_arg_ty
152   = newSysLocalDs the_prim_arg_ty               `thenDs` \ prim_arg ->
153     returnDs (Var prim_arg,
154               \ body -> Case arg (AlgAlts [(box_data_con,[prim_arg],body)]
155                                               NoDefault)
156     )
157
158   | otherwise
159   = pprPanic "unboxArg: " (ppr PprDebug arg_ty)
160   where
161     arg_ty = coreExprType arg
162
163     maybe_boxed_prim_arg_ty = maybeBoxedPrimType arg_ty
164     (Just (box_data_con, the_prim_arg_ty)) = maybe_boxed_prim_arg_ty
165
166     maybe_data_type                        = maybeAppDataTyConExpandingDicts arg_ty
167     is_data_type                           = maybeToBool maybe_data_type
168     (Just (tycon, tycon_arg_tys, data_cons)) = maybe_data_type
169     (the_data_con : other_data_cons)       = data_cons
170
171     data_con_arg_tys = dataConArgTys the_data_con tycon_arg_tys
172     (data_con_arg_ty1 : data_con_arg_ty2 : _) = data_con_arg_tys
173
174     maybe_arg2_tycon = maybeAppTyCon data_con_arg_ty2
175     Just (arg2_tycon,_) = maybe_arg2_tycon
176
177 can't_see_datacons_error thing ty
178   = pprError "ERROR: Can't see the data constructor(s) for _ccall_/_casm_ "
179              (hcat [text thing, text "; type: ", ppr PprForUser ty])
180 \end{code}
181
182
183 \begin{code}
184 boxResult :: Type                               -- Type of desired result
185           -> DsM (Type,                 -- Type of the result of the ccall itself
186                   CoreExpr -> CoreExpr) -- Wrapper for the ccall
187                                                         -- to box the result
188 boxResult result_ty
189   | null data_cons
190   -- oops! can't see the data constructors
191   = can't_see_datacons_error "result" result_ty
192
193   -- Data types with a single constructor, which has a single, primitive-typed arg
194   | (maybeToBool maybe_data_type) &&                            -- Data type
195     (null other_data_cons) &&                                   -- Just one constr
196     not (null data_con_arg_tys) && null other_args_tys  &&      -- Just one arg
197     isPrimType the_prim_result_ty                               -- of primitive type
198   =
199     newSysLocalDs realWorldStatePrimTy                  `thenDs` \ prim_state_id ->
200     newSysLocalDs the_prim_result_ty                    `thenDs` \ prim_result_id ->
201
202     mkConDs stateDataCon [TyArg realWorldTy, VarArg (Var prim_state_id)]  `thenDs` \ new_state ->
203     mkConDs the_data_con (map TyArg tycon_arg_tys ++ [VarArg (Var prim_result_id)]) `thenDs` \ the_result ->
204
205     mkConDs pairDataCon
206             [TyArg result_ty, TyArg realWorldStateTy, VarArg the_result, VarArg new_state]
207                                                         `thenDs` \ the_pair ->
208     let
209         the_alt = (state_and_prim_datacon, [prim_state_id, prim_result_id], the_pair)
210     in
211     returnDs (state_and_prim_ty,
212               \prim_app -> Case prim_app (AlgAlts [the_alt] NoDefault)
213     )
214
215   -- Data types with a single nullary constructor
216   | (maybeToBool maybe_data_type) &&                            -- Data type
217     (null other_data_cons) &&                                   -- Just one constr
218     (null data_con_arg_tys)
219   =
220     newSysLocalDs realWorldStatePrimTy          `thenDs` \ prim_state_id ->
221
222     mkConDs stateDataCon [TyArg realWorldTy, VarArg (Var prim_state_id)]
223                                                 `thenDs` \ new_state ->
224     mkConDs pairDataCon
225             [TyArg result_ty, TyArg realWorldStateTy, VarArg (Var unitDataCon), VarArg new_state]
226                                                 `thenDs` \ the_pair ->
227
228     let
229         the_alt  = (stateDataCon, [prim_state_id], the_pair)
230     in
231     returnDs (realWorldStateTy,
232               \prim_app -> Case prim_app (AlgAlts [the_alt] NoDefault)
233     )
234
235   | otherwise
236   = pprPanic "boxResult: " (ppr PprDebug result_ty)
237
238   where
239     maybe_data_type                        = maybeAppDataTyConExpandingDicts result_ty
240     Just (tycon, tycon_arg_tys, data_cons) = maybe_data_type
241     (the_data_con : other_data_cons)       = data_cons
242
243     data_con_arg_tys                       = dataConArgTys the_data_con tycon_arg_tys
244     (the_prim_result_ty : other_args_tys)  = data_con_arg_tys
245
246     (state_and_prim_datacon, state_and_prim_ty) = getStatePairingConInfo the_prim_result_ty
247 \end{code}
248