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