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