[project @ 2001-10-17 11:26:04 by simonpj]
[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, primOpUsg, primOpArity,
10         mkPrimOpIdName, primOpRdrName, primOpTag, primOpOcc,
11
12         commutableOp,
13
14         primOpOutOfLine, primOpNeedsWrapper, 
15         primOpOkForSpeculation, primOpIsCheap, primOpIsDupable,
16         primOpHasSideEffects,
17
18         getPrimOpResultInfo,  PrimOpResultInfo(..)
19     ) where
20
21 #include "HsVersions.h"
22
23 import PrimRep          -- most of it
24 import TysPrim
25 import TysWiredIn
26
27 import Demand           ( wwLazy, wwPrim, wwStrict, StrictnessInfo(..) )
28 import Var              ( TyVar )
29 import Name             ( Name, mkWiredInName )
30 import RdrName          ( RdrName, mkRdrOrig )
31 import OccName          ( OccName, pprOccName, mkVarOcc )
32 import TyCon            ( TyCon, isPrimTyCon, tyConPrimRep )
33 import Type             ( Type, mkForAllTys, mkFunTy, mkFunTys, typePrimRep,
34                           splitFunTy_maybe, tyConAppTyCon, splitTyConApp,
35                           mkUTy, usOnce, usMany
36                         )
37 import PprType          () -- get at Outputable Type instance.
38 import Unique           ( mkPrimOpIdUnique )
39 import BasicTypes       ( Arity, Boxity(..) )
40 import PrelNames        ( pREL_GHC, pREL_GHC_Name )
41 import Outputable
42 import Util             ( zipWithEqual )
43 import FastTypes
44 \end{code}
45
46 %************************************************************************
47 %*                                                                      *
48 \subsection[PrimOp-datatype]{Datatype for @PrimOp@ (an enumeration)}
49 %*                                                                      *
50 %************************************************************************
51
52 These are in \tr{state-interface.verb} order.
53
54 \begin{code}
55
56 -- supplies: 
57 -- data PrimOp = ...
58 #include "primop-data-decl.hs-incl"
59 \end{code}
60
61 Used for the Ord instance
62
63 \begin{code}
64 primOpTag :: PrimOp -> Int
65 primOpTag op = iBox (tagOf_PrimOp op)
66
67 -- supplies   
68 -- tagOf_PrimOp :: PrimOp -> FastInt
69 #include "primop-tag.hs-incl"
70 tagOf_PrimOp op = pprPanic# "tagOf_PrimOp: pattern-match" (ppr op)
71
72
73 instance Eq PrimOp where
74     op1 == op2 = tagOf_PrimOp op1 ==# tagOf_PrimOp op2
75
76 instance Ord PrimOp where
77     op1 <  op2 =  tagOf_PrimOp op1 <# tagOf_PrimOp op2
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 `compare` op2 | op1 < op2  = LT
82                       | op1 == op2 = EQ
83                       | otherwise  = GT
84
85 instance Outputable PrimOp where
86     ppr op = pprPrimOp op
87
88 instance Show PrimOp where
89     showsPrec p op = showsPrecSDoc p (pprPrimOp op)
90 \end{code}
91
92 An @Enum@-derived list would be better; meanwhile... (ToDo)
93 \begin{code}
94 allThePrimOps :: [PrimOp]
95 allThePrimOps =
96 #include "primop-list.hs-incl"
97 \end{code}
98
99 %************************************************************************
100 %*                                                                      *
101 \subsection[PrimOp-info]{The essential info about each @PrimOp@}
102 %*                                                                      *
103 %************************************************************************
104
105 The @String@ in the @PrimOpInfos@ is the ``base name'' by which the user may
106 refer to the primitive operation.  The conventional \tr{#}-for-
107 unboxed ops is added on later.
108
109 The reason for the funny characters in the names is so we do not
110 interfere with the programmer's Haskell name spaces.
111
112 We use @PrimKinds@ for the ``type'' information, because they're
113 (slightly) more convenient to use than @TyCons@.
114 \begin{code}
115 data PrimOpInfo
116   = Dyadic      OccName         -- string :: T -> T -> T
117                 Type
118   | Monadic     OccName         -- string :: T -> T
119                 Type
120   | Compare     OccName         -- string :: T -> T -> Bool
121                 Type
122
123   | GenPrimOp   OccName         -- string :: \/a1..an . T1 -> .. -> Tk -> T
124                 [TyVar] 
125                 [Type] 
126                 Type 
127
128 mkDyadic str  ty = Dyadic  (mkVarOcc str) ty
129 mkMonadic str ty = Monadic (mkVarOcc str) ty
130 mkCompare str ty = Compare (mkVarOcc str) ty
131 mkGenPrimOp str tvs tys ty = GenPrimOp (mkVarOcc str) tvs tys ty
132 \end{code}
133
134 %************************************************************************
135 %*                                                                      *
136 \subsubsection{Strictness}
137 %*                                                                      *
138 %************************************************************************
139
140 Not all primops are strict!
141
142 \begin{code}
143 primOpStrictness :: PrimOp -> Arity -> StrictnessInfo
144         -- See Demand.StrictnessInfo for discussion of what the results
145         -- The arity should be the arity of the primop; that's why
146         -- this function isn't exported.
147 #include "primop-strictness.hs-incl"
148 \end{code}
149
150 %************************************************************************
151 %*                                                                      *
152 \subsubsection[PrimOp-comparison]{PrimOpInfo basic comparison ops}
153 %*                                                                      *
154 %************************************************************************
155
156 @primOpInfo@ gives all essential information (from which everything
157 else, notably a type, can be constructed) for each @PrimOp@.
158
159 \begin{code}
160 primOpInfo :: PrimOp -> PrimOpInfo
161 #include "primop-primop-info.hs-incl"
162 \end{code}
163
164 Here are a load of comments from the old primOp info:
165
166 A @Word#@ is an unsigned @Int#@.
167
168 @decodeFloat#@ is given w/ Integer-stuff (it's similar).
169
170 @decodeDouble#@ is given w/ Integer-stuff (it's similar).
171
172 Decoding of floating-point numbers is sorta Integer-related.  Encoding
173 is done with plain ccalls now (see PrelNumExtra.lhs).
174
175 A @Weak@ Pointer is created by the @mkWeak#@ primitive:
176
177         mkWeak# :: k -> v -> f -> State# RealWorld 
178                         -> (# State# RealWorld, Weak# v #)
179
180 In practice, you'll use the higher-level
181
182         data Weak v = Weak# v
183         mkWeak :: k -> v -> IO () -> IO (Weak v)
184
185 The following operation dereferences a weak pointer.  The weak pointer
186 may have been finalized, so the operation returns a result code which
187 must be inspected before looking at the dereferenced value.
188
189         deRefWeak# :: Weak# v -> State# RealWorld ->
190                         (# State# RealWorld, v, Int# #)
191
192 Only look at v if the Int# returned is /= 0 !!
193
194 The higher-level op is
195
196         deRefWeak :: Weak v -> IO (Maybe v)
197
198 Weak pointers can be finalized early by using the finalize# operation:
199         
200         finalizeWeak# :: Weak# v -> State# RealWorld -> 
201                            (# State# RealWorld, Int#, IO () #)
202
203 The Int# returned is either
204
205         0 if the weak pointer has already been finalized, or it has no
206           finalizer (the third component is then invalid).
207
208         1 if the weak pointer is still alive, with the finalizer returned
209           as the third component.
210
211 A {\em stable name/pointer} is an index into a table of stable name
212 entries.  Since the garbage collector is told about stable pointers,
213 it is safe to pass a stable pointer to external systems such as C
214 routines.
215
216 \begin{verbatim}
217 makeStablePtr#  :: a -> State# RealWorld -> (# State# RealWorld, StablePtr# a #)
218 freeStablePtr   :: StablePtr# a -> State# RealWorld -> State# RealWorld
219 deRefStablePtr# :: StablePtr# a -> State# RealWorld -> (# State# RealWorld, a #)
220 eqStablePtr#    :: StablePtr# a -> StablePtr# a -> Int#
221 \end{verbatim}
222
223 It may seem a bit surprising that @makeStablePtr#@ is a @IO@
224 operation since it doesn't (directly) involve IO operations.  The
225 reason is that if some optimisation pass decided to duplicate calls to
226 @makeStablePtr#@ and we only pass one of the stable pointers over, a
227 massive space leak can result.  Putting it into the IO monad
228 prevents this.  (Another reason for putting them in a monad is to
229 ensure correct sequencing wrt the side-effecting @freeStablePtr@
230 operation.)
231
232 An important property of stable pointers is that if you call
233 makeStablePtr# twice on the same object you get the same stable
234 pointer back.
235
236 Note that we can implement @freeStablePtr#@ using @_ccall_@ (and,
237 besides, it's not likely to be used from Haskell) so it's not a
238 primop.
239
240 Question: Why @RealWorld@ - won't any instance of @_ST@ do the job? [ADR]
241
242 Stable Names
243 ~~~~~~~~~~~~
244
245 A stable name is like a stable pointer, but with three important differences:
246
247         (a) You can't deRef one to get back to the original object.
248         (b) You can convert one to an Int.
249         (c) You don't need to 'freeStableName'
250
251 The existence of a stable name doesn't guarantee to keep the object it
252 points to alive (unlike a stable pointer), hence (a).
253
254 Invariants:
255         
256         (a) makeStableName always returns the same value for a given
257             object (same as stable pointers).
258
259         (b) if two stable names are equal, it implies that the objects
260             from which they were created were the same.
261
262         (c) stableNameToInt always returns the same Int for a given
263             stable name.
264
265
266 [Alastair Reid is to blame for this!]
267
268 These days, (Glasgow) Haskell seems to have a bit of everything from
269 other languages: strict operations, mutable variables, sequencing,
270 pointers, etc.  About the only thing left is LISP's ability to test
271 for pointer equality.  So, let's add it in!
272
273 \begin{verbatim}
274 reallyUnsafePtrEquality :: a -> a -> Int#
275 \end{verbatim}
276
277 which tests any two closures (of the same type) to see if they're the
278 same.  (Returns $0$ for @False@, $\neq 0$ for @True@ - to avoid
279 difficulties of trying to box up the result.)
280
281 NB This is {\em really unsafe\/} because even something as trivial as
282 a garbage collection might change the answer by removing indirections.
283 Still, no-one's forcing you to use it.  If you're worried about little
284 things like loss of referential transparency, you might like to wrap
285 it all up in a monad-like thing as John O'Donnell and John Hughes did
286 for non-determinism (1989 (Fraserburgh) Glasgow FP Workshop
287 Proceedings?)
288
289 I'm thinking of using it to speed up a critical equality test in some
290 graphics stuff in a context where the possibility of saying that
291 denotationally equal things aren't isn't a problem (as long as it
292 doesn't happen too often.)  ADR
293
294 To Will: Jim said this was already in, but I can't see it so I'm
295 adding it.  Up to you whether you add it.  (Note that this could have
296 been readily implemented using a @veryDangerousCCall@ before they were
297 removed...)
298
299
300 -- HWL: The first 4 Int# in all par... annotations denote:
301 --   name, granularity info, size of result, degree of parallelism
302 --      Same  structure as _seq_ i.e. returns Int#
303 -- KSW: v, the second arg in parAt# and parAtForNow#, is used only to determine
304 --   `the processor containing the expression v'; it is not evaluated
305
306 These primops are pretty wierd.
307
308         dataToTag# :: a -> Int    (arg must be an evaluated data type)
309         tagToEnum# :: Int -> a    (result type must be an enumerated type)
310
311 The constraints aren't currently checked by the front end, but the
312 code generator will fall over if they aren't satisfied.
313
314 \begin{code}
315 #ifdef DEBUG
316 primOpInfo op = pprPanic "primOpInfo:" (ppr op)
317 #endif
318 \end{code}
319
320 %************************************************************************
321 %*                                                                      *
322 \subsubsection[PrimOp-ool]{Which PrimOps are out-of-line}
323 %*                                                                      *
324 %************************************************************************
325
326 Some PrimOps need to be called out-of-line because they either need to
327 perform a heap check or they block.
328
329
330 \begin{code}
331 primOpOutOfLine :: PrimOp -> Bool
332 #include "primop-out-of-line.hs-incl"
333 \end{code}
334
335
336 primOpOkForSpeculation
337 ~~~~~~~~~~~~~~~~~~~~~~
338 Sometimes we may choose to execute a PrimOp even though it isn't
339 certain that its result will be required; ie execute them
340 ``speculatively''.  The same thing as ``cheap eagerness.'' Usually
341 this is OK, because PrimOps are usually cheap, but it isn't OK for
342 (a)~expensive PrimOps and (b)~PrimOps which can fail.
343
344 PrimOps that have side effects also should not be executed speculatively.
345
346 Ok-for-speculation also means that it's ok *not* to execute the
347 primop. For example
348         case op a b of
349           r -> 3
350 Here the result is not used, so we can discard the primop.  Anything
351 that has side effects mustn't be dicarded in this way, of course!
352
353 See also @primOpIsCheap@ (below).
354
355
356 \begin{code}
357 primOpOkForSpeculation :: PrimOp -> Bool
358         -- See comments with CoreUtils.exprOkForSpeculation
359 primOpOkForSpeculation op 
360   = not (primOpHasSideEffects op || primOpOutOfLine op || primOpCanFail op)
361 \end{code}
362
363
364 primOpIsCheap
365 ~~~~~~~~~~~~~
366 @primOpIsCheap@, as used in \tr{SimplUtils.lhs}.  For now (HACK
367 WARNING), we just borrow some other predicates for a
368 what-should-be-good-enough test.  "Cheap" means willing to call it more
369 than once.  Evaluation order is unaffected.
370
371 \begin{code}
372 primOpIsCheap :: PrimOp -> Bool
373 primOpIsCheap op = False
374         -- March 2001: be less eager to inline PrimOps
375         -- Was: not (primOpHasSideEffects op || primOpOutOfLine op)
376 \end{code}
377
378 primOpIsDupable
379 ~~~~~~~~~~~~~~~
380 primOpIsDupable means that the use of the primop is small enough to
381 duplicate into different case branches.  See CoreUtils.exprIsDupable.
382
383 \begin{code}
384 primOpIsDupable :: PrimOp -> Bool
385         -- See comments with CoreUtils.exprIsDupable
386         -- We say it's dupable it isn't implemented by a C call with a wrapper
387 primOpIsDupable op = not (primOpNeedsWrapper op)
388 \end{code}
389
390
391 \begin{code}
392 primOpCanFail :: PrimOp -> Bool
393 #include "primop-can-fail.hs-incl"
394 \end{code}
395
396 And some primops have side-effects and so, for example, must not be
397 duplicated.
398
399 \begin{code}
400 primOpHasSideEffects :: PrimOp -> Bool
401 #include "primop-has-side-effects.hs-incl"
402 \end{code}
403
404 Inline primitive operations that perform calls need wrappers to save
405 any live variables that are stored in caller-saves registers.
406
407 \begin{code}
408 primOpNeedsWrapper :: PrimOp -> Bool
409 #include "primop-needs-wrapper.hs-incl"
410 \end{code}
411
412 \begin{code}
413 primOpArity :: PrimOp -> Arity
414 primOpArity op 
415   = case (primOpInfo op) of
416       Monadic occ ty                      -> 1
417       Dyadic occ ty                       -> 2
418       Compare occ ty                      -> 2
419       GenPrimOp occ tyvars arg_tys res_ty -> length arg_tys
420                 
421 primOpType :: PrimOp -> Type  -- you may want to use primOpSig instead
422 primOpType op
423   = case (primOpInfo op) of
424       Dyadic occ ty ->      dyadic_fun_ty ty
425       Monadic occ ty ->     monadic_fun_ty ty
426       Compare occ ty ->     compare_fun_ty ty
427
428       GenPrimOp occ tyvars arg_tys res_ty -> 
429         mkForAllTys tyvars (mkFunTys arg_tys res_ty)
430
431 mkPrimOpIdName :: PrimOp -> Name
432         -- Make the name for the PrimOp's Id
433         -- We have to pass in the Id itself because it's a WiredInId
434         -- and hence recursive
435 mkPrimOpIdName op
436   = mkWiredInName pREL_GHC (primOpOcc op) (mkPrimOpIdUnique (primOpTag op))
437
438 primOpRdrName :: PrimOp -> RdrName 
439 primOpRdrName op = mkRdrOrig pREL_GHC_Name (primOpOcc op)
440
441 primOpOcc :: PrimOp -> OccName
442 primOpOcc op = case (primOpInfo op) of
443                               Dyadic    occ _     -> occ
444                               Monadic   occ _     -> occ
445                               Compare   occ _     -> occ
446                               GenPrimOp occ _ _ _ -> occ
447
448 -- primOpSig is like primOpType but gives the result split apart:
449 -- (type variables, argument types, result type)
450 -- It also gives arity, strictness info
451
452 primOpSig :: PrimOp -> ([TyVar], [Type], Type, Arity, StrictnessInfo)
453 primOpSig op
454   = (tyvars, arg_tys, res_ty, arity, primOpStrictness op arity)
455   where
456     arity = length arg_tys
457     (tyvars, arg_tys, res_ty)
458       = case (primOpInfo op) of
459           Monadic   occ ty -> ([],     [ty],    ty    )
460           Dyadic    occ ty -> ([],     [ty,ty], ty    )
461           Compare   occ ty -> ([],     [ty,ty], boolTy)
462           GenPrimOp occ tyvars arg_tys res_ty
463                            -> (tyvars, arg_tys, res_ty)
464
465 -- primOpUsg is like primOpSig but the types it yields are the
466 -- appropriate sigma (i.e., usage-annotated) types,
467 -- as required by the UsageSP inference.
468
469 primOpUsg :: PrimOp -> ([TyVar],[Type],Type)
470 #include "primop-usage.hs-incl"
471
472 -- Things with no Haskell pointers inside: in actuality, usages are
473 -- irrelevant here (hence it doesn't matter that some of these
474 -- apparently permit duplication; since such arguments are never 
475 -- ENTERed anyway, the usage annotation they get is entirely irrelevant
476 -- except insofar as it propagates to infect other values that *are*
477 -- pointed.
478
479
480 -- Helper bits & pieces for usage info.
481                                     
482 mkZ          = mkUTy usOnce  -- pointed argument used zero
483 mkO          = mkUTy usOnce  -- pointed argument used once
484 mkM          = mkUTy usMany  -- pointed argument used multiply
485 mkP          = mkUTy usOnce  -- unpointed argument
486 mkR          = mkUTy usMany  -- unpointed result
487
488 nomangle op
489    = case primOpSig op of
490         (tyvars, arg_tys, res_ty, _, _)
491            -> (tyvars, map mkP arg_tys, mkR res_ty)
492
493 mangle op fs g  
494    = case primOpSig op of
495         (tyvars, arg_tys, res_ty, _, _)
496            -> (tyvars, zipWithEqual "primOpUsg" ($) fs arg_tys, g res_ty)
497
498 inFun op f g ty 
499    = case splitFunTy_maybe ty of
500         Just (a,b) -> mkFunTy (f a) (g b)
501         Nothing    -> pprPanic "primOpUsg:inFun" (ppr op <+> ppr ty)
502
503 inUB op fs ty
504    = case splitTyConApp ty of
505         (tc,tys) -> ASSERT( tc == tupleTyCon Unboxed (length fs) )
506                     mkTupleTy Unboxed (length fs) (zipWithEqual "primOpUsg" ($) fs tys)
507 \end{code}
508
509 \begin{code}
510 data PrimOpResultInfo
511   = ReturnsPrim     PrimRep
512   | ReturnsAlg      TyCon
513
514 -- Some PrimOps need not return a manifest primitive or algebraic value
515 -- (i.e. they might return a polymorphic value).  These PrimOps *must*
516 -- be out of line, or the code generator won't work.
517
518 getPrimOpResultInfo :: PrimOp -> PrimOpResultInfo
519 getPrimOpResultInfo op
520   = case (primOpInfo op) of
521       Dyadic  _ ty                        -> ReturnsPrim (typePrimRep ty)
522       Monadic _ ty                        -> ReturnsPrim (typePrimRep ty)
523       Compare _ ty                        -> ReturnsAlg boolTyCon
524       GenPrimOp _ _ _ ty | isPrimTyCon tc -> ReturnsPrim (tyConPrimRep tc)
525                          | otherwise      -> ReturnsAlg tc
526                          where
527                            tc = tyConAppTyCon ty
528                         -- All primops return a tycon-app result
529                         -- The tycon can be an unboxed tuple, though, which
530                         -- gives rise to a ReturnAlg
531 \end{code}
532
533 The commutable ops are those for which we will try to move constants
534 to the right hand side for strength reduction.
535
536 \begin{code}
537 commutableOp :: PrimOp -> Bool
538 #include "primop-commutable.hs-incl"
539 \end{code}
540
541 Utils:
542 \begin{code}
543 dyadic_fun_ty  ty = mkFunTys [ty, ty] ty
544 monadic_fun_ty ty = mkFunTy  ty ty
545 compare_fun_ty ty = mkFunTys [ty, ty] boolTy
546 \end{code}
547
548 Output stuff:
549 \begin{code}
550 pprPrimOp  :: PrimOp -> SDoc
551 pprPrimOp other_op
552   = getPprStyle $ \ sty ->
553     if ifaceStyle sty then      -- For interfaces Print it qualified with PrelGHC.
554         ptext SLIT("PrelGHC.") <> pprOccName occ
555     else
556         pprOccName occ
557   where
558     occ = primOpOcc other_op
559 \end{code}
560
561