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