2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 \section[PrimOp]{Primitive operations (machine-level)}
8 PrimOp(..), allThePrimOps,
9 primOpType, primOpSig, primOpUsg, primOpArity,
10 mkPrimOpIdName, primOpRdrName, primOpTag, primOpOcc,
14 primOpOutOfLine, primOpNeedsWrapper,
15 primOpOkForSpeculation, primOpIsCheap, primOpIsDupable,
18 getPrimOpResultInfo, PrimOpResultInfo(..)
21 #include "HsVersions.h"
23 import PrimRep -- most of it
27 import Demand ( wwLazy, wwPrim, wwStrict, StrictnessInfo(..) )
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,
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 )
42 import Util ( zipWithEqual )
46 %************************************************************************
48 \subsection[PrimOp-datatype]{Datatype for @PrimOp@ (an enumeration)}
50 %************************************************************************
52 These are in \tr{state-interface.verb} order.
58 #include "primop-data-decl.hs-incl"
61 Used for the Ord instance
64 primOpTag :: PrimOp -> Int
65 primOpTag op = iBox (tagOf_PrimOp op)
68 -- tagOf_PrimOp :: PrimOp -> FastInt
69 #include "primop-tag.hs-incl"
70 tagOf_PrimOp op = pprPanic# "tagOf_PrimOp: pattern-match" (ppr op)
73 instance Eq PrimOp where
74 op1 == op2 = tagOf_PrimOp op1 ==# tagOf_PrimOp op2
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
85 instance Outputable PrimOp where
88 instance Show PrimOp where
89 showsPrec p op = showsPrecSDoc p (pprPrimOp op)
92 An @Enum@-derived list would be better; meanwhile... (ToDo)
94 allThePrimOps :: [PrimOp]
96 #include "primop-list.hs-incl"
99 %************************************************************************
101 \subsection[PrimOp-info]{The essential info about each @PrimOp@}
103 %************************************************************************
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.
109 The reason for the funny characters in the names is so we do not
110 interfere with the programmer's Haskell name spaces.
112 We use @PrimKinds@ for the ``type'' information, because they're
113 (slightly) more convenient to use than @TyCons@.
116 = Dyadic OccName -- string :: T -> T -> T
118 | Monadic OccName -- string :: T -> T
120 | Compare OccName -- string :: T -> T -> Bool
123 | GenPrimOp OccName -- string :: \/a1..an . T1 -> .. -> Tk -> T
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
134 %************************************************************************
136 \subsubsection{Strictness}
138 %************************************************************************
140 Not all primops are strict!
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"
150 %************************************************************************
152 \subsubsection[PrimOp-comparison]{PrimOpInfo basic comparison ops}
154 %************************************************************************
156 @primOpInfo@ gives all essential information (from which everything
157 else, notably a type, can be constructed) for each @PrimOp@.
160 primOpInfo :: PrimOp -> PrimOpInfo
161 #include "primop-primop-info.hs-incl"
164 Here are a load of comments from the old primOp info:
166 A @Word#@ is an unsigned @Int#@.
168 @decodeFloat#@ is given w/ Integer-stuff (it's similar).
170 @decodeDouble#@ is given w/ Integer-stuff (it's similar).
172 Decoding of floating-point numbers is sorta Integer-related. Encoding
173 is done with plain ccalls now (see PrelNumExtra.lhs).
175 A @Weak@ Pointer is created by the @mkWeak#@ primitive:
177 mkWeak# :: k -> v -> f -> State# RealWorld
178 -> (# State# RealWorld, Weak# v #)
180 In practice, you'll use the higher-level
182 data Weak v = Weak# v
183 mkWeak :: k -> v -> IO () -> IO (Weak v)
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.
189 deRefWeak# :: Weak# v -> State# RealWorld ->
190 (# State# RealWorld, v, Int# #)
192 Only look at v if the Int# returned is /= 0 !!
194 The higher-level op is
196 deRefWeak :: Weak v -> IO (Maybe v)
198 Weak pointers can be finalized early by using the finalize# operation:
200 finalizeWeak# :: Weak# v -> State# RealWorld ->
201 (# State# RealWorld, Int#, IO () #)
203 The Int# returned is either
205 0 if the weak pointer has already been finalized, or it has no
206 finalizer (the third component is then invalid).
208 1 if the weak pointer is still alive, with the finalizer returned
209 as the third component.
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
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#
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@
232 An important property of stable pointers is that if you call
233 makeStablePtr# twice on the same object you get the same stable
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
240 Question: Why @RealWorld@ - won't any instance of @_ST@ do the job? [ADR]
245 A stable name is like a stable pointer, but with three important differences:
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'
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).
256 (a) makeStableName always returns the same value for a given
257 object (same as stable pointers).
259 (b) if two stable names are equal, it implies that the objects
260 from which they were created were the same.
262 (c) stableNameToInt always returns the same Int for a given
266 [Alastair Reid is to blame for this!]
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!
274 reallyUnsafePtrEquality :: a -> a -> Int#
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.)
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
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
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
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
306 These primops are pretty wierd.
308 dataToTag# :: a -> Int (arg must be an evaluated data type)
309 tagToEnum# :: Int -> a (result type must be an enumerated type)
311 The constraints aren't currently checked by the front end, but the
312 code generator will fall over if they aren't satisfied.
316 primOpInfo op = pprPanic "primOpInfo:" (ppr op)
320 %************************************************************************
322 \subsubsection[PrimOp-ool]{Which PrimOps are out-of-line}
324 %************************************************************************
326 Some PrimOps need to be called out-of-line because they either need to
327 perform a heap check or they block.
331 primOpOutOfLine :: PrimOp -> Bool
332 #include "primop-out-of-line.hs-incl"
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.
344 PrimOps that have side effects also should not be executed speculatively.
346 Ok-for-speculation also means that it's ok *not* to execute the
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!
353 See also @primOpIsCheap@ (below).
357 primOpOkForSpeculation :: PrimOp -> Bool
358 -- See comments with CoreUtils.exprOkForSpeculation
359 primOpOkForSpeculation op
360 = not (primOpHasSideEffects op || primOpOutOfLine op || primOpCanFail op)
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.
372 primOpIsCheap :: PrimOp -> Bool
373 primOpIsCheap op = False
374 -- March 2001: be less eager to inline PrimOps
375 -- Was: not (primOpHasSideEffects op || primOpOutOfLine op)
380 primOpIsDupable means that the use of the primop is small enough to
381 duplicate into different case branches. See CoreUtils.exprIsDupable.
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)
392 primOpCanFail :: PrimOp -> Bool
393 #include "primop-can-fail.hs-incl"
396 And some primops have side-effects and so, for example, must not be
400 primOpHasSideEffects :: PrimOp -> Bool
401 #include "primop-has-side-effects.hs-incl"
404 Inline primitive operations that perform calls need wrappers to save
405 any live variables that are stored in caller-saves registers.
408 primOpNeedsWrapper :: PrimOp -> Bool
409 #include "primop-needs-wrapper.hs-incl"
413 primOpArity :: PrimOp -> Arity
415 = case (primOpInfo op) of
419 GenPrimOp occ tyvars arg_tys res_ty -> length arg_tys
421 primOpType :: PrimOp -> Type -- you may want to use primOpSig instead
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
428 GenPrimOp occ tyvars arg_tys res_ty ->
429 mkForAllTys tyvars (mkFunTys arg_tys res_ty)
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
436 = mkWiredInName pREL_GHC (primOpOcc op) (mkPrimOpIdUnique (primOpTag op))
438 primOpRdrName :: PrimOp -> RdrName
439 primOpRdrName op = mkRdrOrig pREL_GHC_Name (primOpOcc op)
441 primOpOcc :: PrimOp -> OccName
442 primOpOcc op = case (primOpInfo op) of
446 GenPrimOp occ _ _ _ -> occ
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
452 primOpSig :: PrimOp -> ([TyVar], [Type], Type, Arity, StrictnessInfo)
454 = (tyvars, arg_tys, res_ty, arity, primOpStrictness op arity)
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)
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.
469 primOpUsg :: PrimOp -> ([TyVar],[Type],Type)
470 #include "primop-usage.hs-incl"
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*
480 -- Helper bits & pieces for usage info.
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
489 = case primOpSig op of
490 (tyvars, arg_tys, res_ty, _, _)
491 -> (tyvars, map mkP arg_tys, mkR res_ty)
494 = case primOpSig op of
495 (tyvars, arg_tys, res_ty, _, _)
496 -> (tyvars, zipWithEqual "primOpUsg" ($) fs arg_tys, g res_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)
504 = case splitTyConApp ty of
505 (tc,tys) -> ASSERT( tc == tupleTyCon Unboxed (length fs) )
506 mkTupleTy Unboxed (length fs) (zipWithEqual "primOpUsg" ($) fs tys)
510 data PrimOpResultInfo
511 = ReturnsPrim PrimRep
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.
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
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
533 The commutable ops are those for which we will try to move constants
534 to the right hand side for strength reduction.
537 commutableOp :: PrimOp -> Bool
538 #include "primop-commutable.hs-incl"
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
550 pprPrimOp :: PrimOp -> SDoc
552 = getPprStyle $ \ sty ->
553 if ifaceStyle sty then -- For interfaces Print it qualified with PrelGHC.
554 ptext SLIT("PrelGHC.") <> pprOccName occ
558 occ = primOpOcc other_op