-H80m isn't allowed in an options pragma. Just remove it for now.
[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 \begin{code}
384 primOpHasSideEffects :: PrimOp -> Bool
385 #include "primop-has-side-effects.hs-incl"
386 \end{code}
387
388 Inline primitive operations that perform calls need wrappers to save
389 any live variables that are stored in caller-saves registers.
390
391 \begin{code}
392 primOpNeedsWrapper :: PrimOp -> Bool
393 #include "primop-needs-wrapper.hs-incl"
394 \end{code}
395
396 \begin{code}
397 primOpType :: PrimOp -> Type  -- you may want to use primOpSig instead
398 primOpType op
399   = case primOpInfo op of
400     Dyadic  _occ ty -> dyadic_fun_ty ty
401     Monadic _occ ty -> monadic_fun_ty ty
402     Compare _occ ty -> compare_fun_ty ty
403
404     GenPrimOp _occ tyvars arg_tys res_ty -> 
405         mkForAllTys tyvars (mkFunTys arg_tys res_ty)
406
407 primOpOcc :: PrimOp -> OccName
408 primOpOcc op = case primOpInfo op of
409                Dyadic    occ _     -> occ
410                Monadic   occ _     -> occ
411                Compare   occ _     -> occ
412                GenPrimOp occ _ _ _ -> occ
413
414 -- primOpSig is like primOpType but gives the result split apart:
415 -- (type variables, argument types, result type)
416 -- It also gives arity, strictness info
417
418 primOpSig :: PrimOp -> ([TyVar], [Type], Type, Arity, StrictSig)
419 primOpSig op
420   = (tyvars, arg_tys, res_ty, arity, primOpStrictness op arity)
421   where
422     arity = length arg_tys
423     (tyvars, arg_tys, res_ty)
424       = case (primOpInfo op) of
425         Monadic   _occ ty                    -> ([],     [ty],    ty    )
426         Dyadic    _occ ty                    -> ([],     [ty,ty], ty    )
427         Compare   _occ ty                    -> ([],     [ty,ty], boolTy)
428         GenPrimOp _occ tyvars arg_tys res_ty -> (tyvars, arg_tys, res_ty)
429 \end{code}
430
431 \begin{code}
432 data PrimOpResultInfo
433   = ReturnsPrim     PrimRep
434   | ReturnsAlg      TyCon
435
436 -- Some PrimOps need not return a manifest primitive or algebraic value
437 -- (i.e. they might return a polymorphic value).  These PrimOps *must*
438 -- be out of line, or the code generator won't work.
439
440 getPrimOpResultInfo :: PrimOp -> PrimOpResultInfo
441 getPrimOpResultInfo op
442   = case (primOpInfo op) of
443       Dyadic  _ ty                        -> ReturnsPrim (typePrimRep ty)
444       Monadic _ ty                        -> ReturnsPrim (typePrimRep ty)
445       Compare _ _                         -> ReturnsAlg boolTyCon
446       GenPrimOp _ _ _ ty | isPrimTyCon tc -> ReturnsPrim (tyConPrimRep tc)
447                          | otherwise      -> ReturnsAlg tc
448                          where
449                            tc = tyConAppTyCon ty
450                         -- All primops return a tycon-app result
451                         -- The tycon can be an unboxed tuple, though, which
452                         -- gives rise to a ReturnAlg
453 \end{code}
454
455 The commutable ops are those for which we will try to move constants
456 to the right hand side for strength reduction.
457
458 \begin{code}
459 commutableOp :: PrimOp -> Bool
460 #include "primop-commutable.hs-incl"
461 \end{code}
462
463 Utils:
464 \begin{code}
465 dyadic_fun_ty, monadic_fun_ty, compare_fun_ty :: Type -> Type
466 dyadic_fun_ty  ty = mkFunTys [ty, ty] ty
467 monadic_fun_ty ty = mkFunTy  ty ty
468 compare_fun_ty ty = mkFunTys [ty, ty] boolTy
469 \end{code}
470
471 Output stuff:
472 \begin{code}
473 pprPrimOp  :: PrimOp -> SDoc
474 pprPrimOp other_op = pprOccName (primOpOcc other_op)
475 \end{code}
476