[project @ 2003-11-17 14:23:30 by simonmar]
[ghc-hetmet.git] / ghc / compiler / prelude / PrimOp.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
3 %
4 \section[PrimOp]{Primitive operations (machine-level)}
5
6 \begin{code}
7 module PrimOp (
8         PrimOp(..), allThePrimOps,
9         primOpType, primOpSig,
10         primOpTag, maxPrimOpTag, primOpOcc,
11
12         primOpOutOfLine, primOpNeedsWrapper, 
13         primOpOkForSpeculation, primOpIsCheap, primOpIsDupable,
14
15         getPrimOpResultInfo,  PrimOpResultInfo(..)
16     ) where
17
18 #include "HsVersions.h"
19
20 import PrimRep          -- most of it
21 import TysPrim
22 import TysWiredIn
23
24 import NewDemand
25 import Var              ( TyVar )
26 import OccName          ( OccName, pprOccName, mkVarOcc )
27 import TyCon            ( TyCon, isPrimTyCon, tyConPrimRep )
28 import Type             ( Type, mkForAllTys, mkFunTy, mkFunTys, typePrimRep, tyConAppTyCon )
29 import BasicTypes       ( Arity, Boxity(..) )
30 import Outputable
31 import FastTypes
32 \end{code}
33
34 %************************************************************************
35 %*                                                                      *
36 \subsection[PrimOp-datatype]{Datatype for @PrimOp@ (an enumeration)}
37 %*                                                                      *
38 %************************************************************************
39
40 These are in \tr{state-interface.verb} order.
41
42 \begin{code}
43
44 -- supplies: 
45 -- data PrimOp = ...
46 #include "primop-data-decl.hs-incl"
47 \end{code}
48
49 Used for the Ord instance
50
51 \begin{code}
52 primOpTag :: PrimOp -> Int
53 primOpTag op = iBox (tagOf_PrimOp op)
54
55 -- supplies   
56 -- tagOf_PrimOp :: PrimOp -> FastInt
57 #include "primop-tag.hs-incl"
58 tagOf_PrimOp op = pprPanic# "tagOf_PrimOp: pattern-match" (ppr op)
59
60
61 instance Eq PrimOp where
62     op1 == op2 = tagOf_PrimOp op1 ==# tagOf_PrimOp op2
63
64 instance Ord PrimOp where
65     op1 <  op2 =  tagOf_PrimOp op1 <# tagOf_PrimOp op2
66     op1 <= op2 =  tagOf_PrimOp op1 <=# tagOf_PrimOp op2
67     op1 >= op2 =  tagOf_PrimOp op1 >=# tagOf_PrimOp op2
68     op1 >  op2 =  tagOf_PrimOp op1 ># tagOf_PrimOp op2
69     op1 `compare` op2 | op1 < op2  = LT
70                       | op1 == op2 = EQ
71                       | otherwise  = GT
72
73 instance Outputable PrimOp where
74     ppr op = pprPrimOp op
75
76 instance Show PrimOp where
77     showsPrec p op = showsPrecSDoc p (pprPrimOp op)
78 \end{code}
79
80 An @Enum@-derived list would be better; meanwhile... (ToDo)
81
82 \begin{code}
83 allThePrimOps :: [PrimOp]
84 allThePrimOps =
85 #include "primop-list.hs-incl"
86 \end{code}
87
88 %************************************************************************
89 %*                                                                      *
90 \subsection[PrimOp-info]{The essential info about each @PrimOp@}
91 %*                                                                      *
92 %************************************************************************
93
94 The @String@ in the @PrimOpInfos@ is the ``base name'' by which the user may
95 refer to the primitive operation.  The conventional \tr{#}-for-
96 unboxed ops is added on later.
97
98 The reason for the funny characters in the names is so we do not
99 interfere with the programmer's Haskell name spaces.
100
101 We use @PrimKinds@ for the ``type'' information, because they're
102 (slightly) more convenient to use than @TyCons@.
103 \begin{code}
104 data PrimOpInfo
105   = Dyadic      OccName         -- string :: T -> T -> T
106                 Type
107   | Monadic     OccName         -- string :: T -> T
108                 Type
109   | Compare     OccName         -- string :: T -> T -> Bool
110                 Type
111
112   | GenPrimOp   OccName         -- string :: \/a1..an . T1 -> .. -> Tk -> T
113                 [TyVar] 
114                 [Type] 
115                 Type 
116
117 mkDyadic str  ty = Dyadic  (mkVarOcc str) ty
118 mkMonadic str ty = Monadic (mkVarOcc str) ty
119 mkCompare str ty = Compare (mkVarOcc str) ty
120 mkGenPrimOp str tvs tys ty = GenPrimOp (mkVarOcc str) tvs tys ty
121 \end{code}
122
123 %************************************************************************
124 %*                                                                      *
125 \subsubsection{Strictness}
126 %*                                                                      *
127 %************************************************************************
128
129 Not all primops are strict!
130
131 \begin{code}
132 primOpStrictness :: PrimOp -> Arity -> StrictSig
133         -- See Demand.StrictnessInfo for discussion of what the results
134         -- The arity should be the arity of the primop; that's why
135         -- this function isn't exported.
136 #include "primop-strictness.hs-incl"
137 \end{code}
138
139 %************************************************************************
140 %*                                                                      *
141 \subsubsection[PrimOp-comparison]{PrimOpInfo basic comparison ops}
142 %*                                                                      *
143 %************************************************************************
144
145 @primOpInfo@ gives all essential information (from which everything
146 else, notably a type, can be constructed) for each @PrimOp@.
147
148 \begin{code}
149 primOpInfo :: PrimOp -> PrimOpInfo
150 #include "primop-primop-info.hs-incl"
151 \end{code}
152
153 Here are a load of comments from the old primOp info:
154
155 A @Word#@ is an unsigned @Int#@.
156
157 @decodeFloat#@ is given w/ Integer-stuff (it's similar).
158
159 @decodeDouble#@ is given w/ Integer-stuff (it's similar).
160
161 Decoding of floating-point numbers is sorta Integer-related.  Encoding
162 is done with plain ccalls now (see PrelNumExtra.lhs).
163
164 A @Weak@ Pointer is created by the @mkWeak#@ primitive:
165
166         mkWeak# :: k -> v -> f -> State# RealWorld 
167                         -> (# State# RealWorld, Weak# v #)
168
169 In practice, you'll use the higher-level
170
171         data Weak v = Weak# v
172         mkWeak :: k -> v -> IO () -> IO (Weak v)
173
174 The following operation dereferences a weak pointer.  The weak pointer
175 may have been finalized, so the operation returns a result code which
176 must be inspected before looking at the dereferenced value.
177
178         deRefWeak# :: Weak# v -> State# RealWorld ->
179                         (# State# RealWorld, v, Int# #)
180
181 Only look at v if the Int# returned is /= 0 !!
182
183 The higher-level op is
184
185         deRefWeak :: Weak v -> IO (Maybe v)
186
187 Weak pointers can be finalized early by using the finalize# operation:
188         
189         finalizeWeak# :: Weak# v -> State# RealWorld -> 
190                            (# State# RealWorld, Int#, IO () #)
191
192 The Int# returned is either
193
194         0 if the weak pointer has already been finalized, or it has no
195           finalizer (the third component is then invalid).
196
197         1 if the weak pointer is still alive, with the finalizer returned
198           as the third component.
199
200 A {\em stable name/pointer} is an index into a table of stable name
201 entries.  Since the garbage collector is told about stable pointers,
202 it is safe to pass a stable pointer to external systems such as C
203 routines.
204
205 \begin{verbatim}
206 makeStablePtr#  :: a -> State# RealWorld -> (# State# RealWorld, StablePtr# a #)
207 freeStablePtr   :: StablePtr# a -> State# RealWorld -> State# RealWorld
208 deRefStablePtr# :: StablePtr# a -> State# RealWorld -> (# State# RealWorld, a #)
209 eqStablePtr#    :: StablePtr# a -> StablePtr# a -> Int#
210 \end{verbatim}
211
212 It may seem a bit surprising that @makeStablePtr#@ is a @IO@
213 operation since it doesn't (directly) involve IO operations.  The
214 reason is that if some optimisation pass decided to duplicate calls to
215 @makeStablePtr#@ and we only pass one of the stable pointers over, a
216 massive space leak can result.  Putting it into the IO monad
217 prevents this.  (Another reason for putting them in a monad is to
218 ensure correct sequencing wrt the side-effecting @freeStablePtr@
219 operation.)
220
221 An important property of stable pointers is that if you call
222 makeStablePtr# twice on the same object you get the same stable
223 pointer back.
224
225 Note that we can implement @freeStablePtr#@ using @_ccall_@ (and,
226 besides, it's not likely to be used from Haskell) so it's not a
227 primop.
228
229 Question: Why @RealWorld@ - won't any instance of @_ST@ do the job? [ADR]
230
231 Stable Names
232 ~~~~~~~~~~~~
233
234 A stable name is like a stable pointer, but with three important differences:
235
236         (a) You can't deRef one to get back to the original object.
237         (b) You can convert one to an Int.
238         (c) You don't need to 'freeStableName'
239
240 The existence of a stable name doesn't guarantee to keep the object it
241 points to alive (unlike a stable pointer), hence (a).
242
243 Invariants:
244         
245         (a) makeStableName always returns the same value for a given
246             object (same as stable pointers).
247
248         (b) if two stable names are equal, it implies that the objects
249             from which they were created were the same.
250
251         (c) stableNameToInt always returns the same Int for a given
252             stable name.
253
254
255 -- HWL: The first 4 Int# in all par... annotations denote:
256 --   name, granularity info, size of result, degree of parallelism
257 --      Same  structure as _seq_ i.e. returns Int#
258 -- KSW: v, the second arg in parAt# and parAtForNow#, is used only to determine
259 --   `the processor containing the expression v'; it is not evaluated
260
261 These primops are pretty wierd.
262
263         dataToTag# :: a -> Int    (arg must be an evaluated data type)
264         tagToEnum# :: Int -> a    (result type must be an enumerated type)
265
266 The constraints aren't currently checked by the front end, but the
267 code generator will fall over if they aren't satisfied.
268
269 \begin{code}
270 #ifdef DEBUG
271 primOpInfo op = pprPanic "primOpInfo:" (ppr op)
272 #endif
273 \end{code}
274
275 %************************************************************************
276 %*                                                                      *
277 \subsubsection[PrimOp-ool]{Which PrimOps are out-of-line}
278 %*                                                                      *
279 %************************************************************************
280
281 Some PrimOps need to be called out-of-line because they either need to
282 perform a heap check or they block.
283
284
285 \begin{code}
286 primOpOutOfLine :: PrimOp -> Bool
287 #include "primop-out-of-line.hs-incl"
288 \end{code}
289
290
291 primOpOkForSpeculation
292 ~~~~~~~~~~~~~~~~~~~~~~
293 Sometimes we may choose to execute a PrimOp even though it isn't
294 certain that its result will be required; ie execute them
295 ``speculatively''.  The same thing as ``cheap eagerness.'' Usually
296 this is OK, because PrimOps are usually cheap, but it isn't OK for
297 (a)~expensive PrimOps and (b)~PrimOps which can fail.
298
299 PrimOps that have side effects also should not be executed speculatively.
300
301 Ok-for-speculation also means that it's ok *not* to execute the
302 primop. For example
303         case op a b of
304           r -> 3
305 Here the result is not used, so we can discard the primop.  Anything
306 that has side effects mustn't be dicarded in this way, of course!
307
308 See also @primOpIsCheap@ (below).
309
310
311 \begin{code}
312 primOpOkForSpeculation :: PrimOp -> Bool
313         -- See comments with CoreUtils.exprOkForSpeculation
314 primOpOkForSpeculation op 
315   = not (primOpHasSideEffects op || primOpOutOfLine op || primOpCanFail op)
316 \end{code}
317
318
319 primOpIsCheap
320 ~~~~~~~~~~~~~
321 @primOpIsCheap@, as used in \tr{SimplUtils.lhs}.  For now (HACK
322 WARNING), we just borrow some other predicates for a
323 what-should-be-good-enough test.  "Cheap" means willing to call it more
324 than once.  Evaluation order is unaffected.
325
326 \begin{code}
327 primOpIsCheap :: PrimOp -> Bool
328 primOpIsCheap op = False
329         -- March 2001: be less eager to inline PrimOps
330         -- Was: not (primOpHasSideEffects op || primOpOutOfLine op)
331 \end{code}
332
333 primOpIsDupable
334 ~~~~~~~~~~~~~~~
335 primOpIsDupable means that the use of the primop is small enough to
336 duplicate into different case branches.  See CoreUtils.exprIsDupable.
337
338 \begin{code}
339 primOpIsDupable :: PrimOp -> Bool
340         -- See comments with CoreUtils.exprIsDupable
341         -- We say it's dupable it isn't implemented by a C call with a wrapper
342 primOpIsDupable op = not (primOpNeedsWrapper op)
343 \end{code}
344
345
346 \begin{code}
347 primOpCanFail :: PrimOp -> Bool
348 #include "primop-can-fail.hs-incl"
349 \end{code}
350
351 And some primops have side-effects and so, for example, must not be
352 duplicated.
353
354 \begin{code}
355 primOpHasSideEffects :: PrimOp -> Bool
356 #include "primop-has-side-effects.hs-incl"
357 \end{code}
358
359 Inline primitive operations that perform calls need wrappers to save
360 any live variables that are stored in caller-saves registers.
361
362 \begin{code}
363 primOpNeedsWrapper :: PrimOp -> Bool
364 #include "primop-needs-wrapper.hs-incl"
365 \end{code}
366
367 \begin{code}
368 primOpType :: PrimOp -> Type  -- you may want to use primOpSig instead
369 primOpType op
370   = case (primOpInfo op) of
371       Dyadic occ ty ->      dyadic_fun_ty ty
372       Monadic occ ty ->     monadic_fun_ty ty
373       Compare occ ty ->     compare_fun_ty ty
374
375       GenPrimOp occ tyvars arg_tys res_ty -> 
376         mkForAllTys tyvars (mkFunTys arg_tys res_ty)
377
378 primOpOcc :: PrimOp -> OccName
379 primOpOcc op = case (primOpInfo op) of
380                 Dyadic    occ _     -> occ
381                 Monadic   occ _     -> occ
382                 Compare   occ _     -> occ
383                 GenPrimOp occ _ _ _ -> occ
384
385 -- primOpSig is like primOpType but gives the result split apart:
386 -- (type variables, argument types, result type)
387 -- It also gives arity, strictness info
388
389 primOpSig :: PrimOp -> ([TyVar], [Type], Type, Arity, StrictSig)
390 primOpSig op
391   = (tyvars, arg_tys, res_ty, arity, primOpStrictness op arity)
392   where
393     arity = length arg_tys
394     (tyvars, arg_tys, res_ty)
395       = case (primOpInfo op) of
396           Monadic   occ ty -> ([],     [ty],    ty    )
397           Dyadic    occ ty -> ([],     [ty,ty], ty    )
398           Compare   occ ty -> ([],     [ty,ty], boolTy)
399           GenPrimOp occ tyvars arg_tys res_ty
400                            -> (tyvars, arg_tys, res_ty)
401 \end{code}
402
403 \begin{code}
404 data PrimOpResultInfo
405   = ReturnsPrim     PrimRep
406   | ReturnsAlg      TyCon
407
408 -- Some PrimOps need not return a manifest primitive or algebraic value
409 -- (i.e. they might return a polymorphic value).  These PrimOps *must*
410 -- be out of line, or the code generator won't work.
411
412 getPrimOpResultInfo :: PrimOp -> PrimOpResultInfo
413 getPrimOpResultInfo op
414   = case (primOpInfo op) of
415       Dyadic  _ ty                        -> ReturnsPrim (typePrimRep ty)
416       Monadic _ ty                        -> ReturnsPrim (typePrimRep ty)
417       Compare _ ty                        -> ReturnsAlg boolTyCon
418       GenPrimOp _ _ _ ty | isPrimTyCon tc -> ReturnsPrim (tyConPrimRep tc)
419                          | otherwise      -> ReturnsAlg tc
420                          where
421                            tc = tyConAppTyCon ty
422                         -- All primops return a tycon-app result
423                         -- The tycon can be an unboxed tuple, though, which
424                         -- gives rise to a ReturnAlg
425 \end{code}
426
427 The commutable ops are those for which we will try to move constants
428 to the right hand side for strength reduction.
429
430 \begin{code}
431 commutableOp :: PrimOp -> Bool
432 #include "primop-commutable.hs-incl"
433 \end{code}
434
435 Utils:
436 \begin{code}
437 dyadic_fun_ty  ty = mkFunTys [ty, ty] ty
438 monadic_fun_ty ty = mkFunTy  ty ty
439 compare_fun_ty ty = mkFunTys [ty, ty] boolTy
440 \end{code}
441
442 Output stuff:
443 \begin{code}
444 pprPrimOp  :: PrimOp -> SDoc
445 pprPrimOp other_op = pprOccName (primOpOcc other_op)
446 \end{code}
447