[project @ 2004-08-13 13:04:50 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 TysPrim
21 import TysWiredIn
22
23 import NewDemand
24 import Var              ( TyVar )
25 import OccName          ( OccName, pprOccName, mkVarOcc )
26 import TyCon            ( TyCon, isPrimTyCon, tyConPrimRep, PrimRep(..) )
27 import Type             ( Type, mkForAllTys, mkFunTy, mkFunTys, tyConAppTyCon,
28                           typePrimRep )
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, and/or push it inside a lambda.  The latter could change the
325 behaviour of 'seq' for primops that can fail, so we don't treat them as cheap.
326
327 \begin{code}
328 primOpIsCheap :: PrimOp -> Bool
329 primOpIsCheap op = primOpOkForSpeculation op
330 -- In March 2001, we changed this to 
331 --      primOpIsCheap op = False
332 -- thereby making *no* primops seem cheap.  But this killed eta
333 -- expansion on case (x ==# y) of True -> \s -> ... 
334 -- which is bad.  In particular a loop like
335 --      doLoop n = loop 0
336 --     where
337 --         loop i | i == n    = return ()
338 --                | otherwise = bar i >> loop (i+1)
339 -- allocated a closure every time round because it doesn't eta expand.
340 -- 
341 -- The problem that originally gave rise to the change was
342 --      let x = a +# b *# c in x +# x
343 -- were we don't want to inline x. But primopIsCheap doesn't control
344 -- that (it's exprIsDupable that does) so the problem doesn't occur
345 -- even if primOpIsCheap sometimes says 'True'.
346 \end{code}
347
348 primOpIsDupable
349 ~~~~~~~~~~~~~~~
350 primOpIsDupable means that the use of the primop is small enough to
351 duplicate into different case branches.  See CoreUtils.exprIsDupable.
352
353 \begin{code}
354 primOpIsDupable :: PrimOp -> Bool
355         -- See comments with CoreUtils.exprIsDupable
356         -- We say it's dupable it isn't implemented by a C call with a wrapper
357 primOpIsDupable op = not (primOpNeedsWrapper op)
358 \end{code}
359
360
361 \begin{code}
362 primOpCanFail :: PrimOp -> Bool
363 #include "primop-can-fail.hs-incl"
364 \end{code}
365
366 And some primops have side-effects and so, for example, must not be
367 duplicated.
368
369 \begin{code}
370 primOpHasSideEffects :: PrimOp -> Bool
371 #include "primop-has-side-effects.hs-incl"
372 \end{code}
373
374 Inline primitive operations that perform calls need wrappers to save
375 any live variables that are stored in caller-saves registers.
376
377 \begin{code}
378 primOpNeedsWrapper :: PrimOp -> Bool
379 #include "primop-needs-wrapper.hs-incl"
380 \end{code}
381
382 \begin{code}
383 primOpType :: PrimOp -> Type  -- you may want to use primOpSig instead
384 primOpType op
385   = case (primOpInfo op) of
386       Dyadic occ ty ->      dyadic_fun_ty ty
387       Monadic occ ty ->     monadic_fun_ty ty
388       Compare occ ty ->     compare_fun_ty ty
389
390       GenPrimOp occ tyvars arg_tys res_ty -> 
391         mkForAllTys tyvars (mkFunTys arg_tys res_ty)
392
393 primOpOcc :: PrimOp -> OccName
394 primOpOcc op = case (primOpInfo op) of
395                 Dyadic    occ _     -> occ
396                 Monadic   occ _     -> occ
397                 Compare   occ _     -> occ
398                 GenPrimOp occ _ _ _ -> occ
399
400 -- primOpSig is like primOpType but gives the result split apart:
401 -- (type variables, argument types, result type)
402 -- It also gives arity, strictness info
403
404 primOpSig :: PrimOp -> ([TyVar], [Type], Type, Arity, StrictSig)
405 primOpSig op
406   = (tyvars, arg_tys, res_ty, arity, primOpStrictness op arity)
407   where
408     arity = length arg_tys
409     (tyvars, arg_tys, res_ty)
410       = case (primOpInfo op) of
411           Monadic   occ ty -> ([],     [ty],    ty    )
412           Dyadic    occ ty -> ([],     [ty,ty], ty    )
413           Compare   occ ty -> ([],     [ty,ty], boolTy)
414           GenPrimOp occ tyvars arg_tys res_ty
415                            -> (tyvars, arg_tys, res_ty)
416 \end{code}
417
418 \begin{code}
419 data PrimOpResultInfo
420   = ReturnsPrim     PrimRep
421   | ReturnsAlg      TyCon
422
423 -- Some PrimOps need not return a manifest primitive or algebraic value
424 -- (i.e. they might return a polymorphic value).  These PrimOps *must*
425 -- be out of line, or the code generator won't work.
426
427 getPrimOpResultInfo :: PrimOp -> PrimOpResultInfo
428 getPrimOpResultInfo op
429   = case (primOpInfo op) of
430       Dyadic  _ ty                        -> ReturnsPrim (typePrimRep ty)
431       Monadic _ ty                        -> ReturnsPrim (typePrimRep ty)
432       Compare _ ty                        -> ReturnsAlg boolTyCon
433       GenPrimOp _ _ _ ty | isPrimTyCon tc -> ReturnsPrim (tyConPrimRep tc)
434                          | otherwise      -> ReturnsAlg tc
435                          where
436                            tc = tyConAppTyCon ty
437                         -- All primops return a tycon-app result
438                         -- The tycon can be an unboxed tuple, though, which
439                         -- gives rise to a ReturnAlg
440 \end{code}
441
442 The commutable ops are those for which we will try to move constants
443 to the right hand side for strength reduction.
444
445 \begin{code}
446 commutableOp :: PrimOp -> Bool
447 #include "primop-commutable.hs-incl"
448 \end{code}
449
450 Utils:
451 \begin{code}
452 dyadic_fun_ty  ty = mkFunTys [ty, ty] ty
453 monadic_fun_ty ty = mkFunTy  ty ty
454 compare_fun_ty ty = mkFunTys [ty, ty] boolTy
455 \end{code}
456
457 Output stuff:
458 \begin{code}
459 pprPrimOp  :: PrimOp -> SDoc
460 pprPrimOp other_op = pprOccName (primOpOcc other_op)
461 \end{code}
462