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