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 -- HWL: The first 4 Int# in all par... annotations denote:
267 -- name, granularity info, size of result, degree of parallelism
268 -- Same structure as _seq_ i.e. returns Int#
269 -- KSW: v, the second arg in parAt# and parAtForNow#, is used only to determine
270 -- `the processor containing the expression v'; it is not evaluated
272 These primops are pretty wierd.
274 dataToTag# :: a -> Int (arg must be an evaluated data type)
275 tagToEnum# :: Int -> a (result type must be an enumerated type)
277 The constraints aren't currently checked by the front end, but the
278 code generator will fall over if they aren't satisfied.
282 primOpInfo op = pprPanic "primOpInfo:" (ppr op)
286 %************************************************************************
288 \subsubsection[PrimOp-ool]{Which PrimOps are out-of-line}
290 %************************************************************************
292 Some PrimOps need to be called out-of-line because they either need to
293 perform a heap check or they block.
297 primOpOutOfLine :: PrimOp -> Bool
298 #include "primop-out-of-line.hs-incl"
302 primOpOkForSpeculation
303 ~~~~~~~~~~~~~~~~~~~~~~
304 Sometimes we may choose to execute a PrimOp even though it isn't
305 certain that its result will be required; ie execute them
306 ``speculatively''. The same thing as ``cheap eagerness.'' Usually
307 this is OK, because PrimOps are usually cheap, but it isn't OK for
308 (a)~expensive PrimOps and (b)~PrimOps which can fail.
310 PrimOps that have side effects also should not be executed speculatively.
312 Ok-for-speculation also means that it's ok *not* to execute the
316 Here the result is not used, so we can discard the primop. Anything
317 that has side effects mustn't be dicarded in this way, of course!
319 See also @primOpIsCheap@ (below).
323 primOpOkForSpeculation :: PrimOp -> Bool
324 -- See comments with CoreUtils.exprOkForSpeculation
325 primOpOkForSpeculation op
326 = not (primOpHasSideEffects op || primOpOutOfLine op || primOpCanFail op)
332 @primOpIsCheap@, as used in \tr{SimplUtils.lhs}. For now (HACK
333 WARNING), we just borrow some other predicates for a
334 what-should-be-good-enough test. "Cheap" means willing to call it more
335 than once. Evaluation order is unaffected.
338 primOpIsCheap :: PrimOp -> Bool
339 primOpIsCheap op = False
340 -- March 2001: be less eager to inline PrimOps
341 -- Was: not (primOpHasSideEffects op || primOpOutOfLine op)
346 primOpIsDupable means that the use of the primop is small enough to
347 duplicate into different case branches. See CoreUtils.exprIsDupable.
350 primOpIsDupable :: PrimOp -> Bool
351 -- See comments with CoreUtils.exprIsDupable
352 -- We say it's dupable it isn't implemented by a C call with a wrapper
353 primOpIsDupable op = not (primOpNeedsWrapper op)
358 primOpCanFail :: PrimOp -> Bool
359 #include "primop-can-fail.hs-incl"
362 And some primops have side-effects and so, for example, must not be
366 primOpHasSideEffects :: PrimOp -> Bool
367 #include "primop-has-side-effects.hs-incl"
370 Inline primitive operations that perform calls need wrappers to save
371 any live variables that are stored in caller-saves registers.
374 primOpNeedsWrapper :: PrimOp -> Bool
375 #include "primop-needs-wrapper.hs-incl"
379 primOpArity :: PrimOp -> Arity
381 = case (primOpInfo op) of
385 GenPrimOp occ tyvars arg_tys res_ty -> length arg_tys
387 primOpType :: PrimOp -> Type -- you may want to use primOpSig instead
389 = case (primOpInfo op) of
390 Dyadic occ ty -> dyadic_fun_ty ty
391 Monadic occ ty -> monadic_fun_ty ty
392 Compare occ ty -> compare_fun_ty ty
394 GenPrimOp occ tyvars arg_tys res_ty ->
395 mkForAllTys tyvars (mkFunTys arg_tys res_ty)
397 mkPrimOpIdName :: PrimOp -> Name
398 -- Make the name for the PrimOp's Id
399 -- We have to pass in the Id itself because it's a WiredInId
400 -- and hence recursive
402 = mkWiredInName pREL_GHC (primOpOcc op) (mkPrimOpIdUnique (primOpTag op))
404 primOpRdrName :: PrimOp -> RdrName
405 primOpRdrName op = mkRdrOrig pREL_GHC_Name (primOpOcc op)
407 primOpOcc :: PrimOp -> OccName
408 primOpOcc op = case (primOpInfo op) of
412 GenPrimOp occ _ _ _ -> occ
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
418 primOpSig :: PrimOp -> ([TyVar], [Type], Type, Arity, StrictnessInfo)
420 = (tyvars, arg_tys, res_ty, arity, primOpStrictness op arity)
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
429 -> (tyvars, arg_tys, res_ty)
431 -- primOpUsg is like primOpSig but the types it yields are the
432 -- appropriate sigma (i.e., usage-annotated) types,
433 -- as required by the UsageSP inference.
435 primOpUsg :: PrimOp -> ([TyVar],[Type],Type)
436 #include "primop-usage.hs-incl"
438 -- Things with no Haskell pointers inside: in actuality, usages are
439 -- irrelevant here (hence it doesn't matter that some of these
440 -- apparently permit duplication; since such arguments are never
441 -- ENTERed anyway, the usage annotation they get is entirely irrelevant
442 -- except insofar as it propagates to infect other values that *are*
446 -- Helper bits & pieces for usage info.
448 mkZ = mkUTy usOnce -- pointed argument used zero
449 mkO = mkUTy usOnce -- pointed argument used once
450 mkM = mkUTy usMany -- pointed argument used multiply
451 mkP = mkUTy usOnce -- unpointed argument
452 mkR = mkUTy usMany -- unpointed result
455 = case primOpSig op of
456 (tyvars, arg_tys, res_ty, _, _)
457 -> (tyvars, map mkP arg_tys, mkR res_ty)
460 = case primOpSig op of
461 (tyvars, arg_tys, res_ty, _, _)
462 -> (tyvars, zipWithEqual "primOpUsg" ($) fs arg_tys, g res_ty)
465 = case splitFunTy_maybe ty of
466 Just (a,b) -> mkFunTy (f a) (g b)
467 Nothing -> pprPanic "primOpUsg:inFun" (ppr op <+> ppr ty)
470 = case splitTyConApp ty of
471 (tc,tys) -> ASSERT( tc == tupleTyCon Unboxed (length fs) )
472 mkTupleTy Unboxed (length fs) (zipWithEqual "primOpUsg" ($) fs tys)
476 data PrimOpResultInfo
477 = ReturnsPrim PrimRep
480 -- Some PrimOps need not return a manifest primitive or algebraic value
481 -- (i.e. they might return a polymorphic value). These PrimOps *must*
482 -- be out of line, or the code generator won't work.
484 getPrimOpResultInfo :: PrimOp -> PrimOpResultInfo
485 getPrimOpResultInfo op
486 = case (primOpInfo op) of
487 Dyadic _ ty -> ReturnsPrim (typePrimRep ty)
488 Monadic _ ty -> ReturnsPrim (typePrimRep ty)
489 Compare _ ty -> ReturnsAlg boolTyCon
490 GenPrimOp _ _ _ ty | isPrimTyCon tc -> ReturnsPrim (tyConPrimRep tc)
491 | otherwise -> ReturnsAlg tc
493 tc = tyConAppTyCon ty
494 -- All primops return a tycon-app result
495 -- The tycon can be an unboxed tuple, though, which
496 -- gives rise to a ReturnAlg
499 The commutable ops are those for which we will try to move constants
500 to the right hand side for strength reduction.
503 commutableOp :: PrimOp -> Bool
504 #include "primop-commutable.hs-incl"
509 dyadic_fun_ty ty = mkFunTys [ty, ty] ty
510 monadic_fun_ty ty = mkFunTy ty ty
511 compare_fun_ty ty = mkFunTys [ty, ty] boolTy
516 pprPrimOp :: PrimOp -> SDoc
518 = getPprStyle $ \ sty ->
519 if ifaceStyle sty then -- For interfaces Print it qualified with PrelGHC.
520 ptext SLIT("PrelGHC.") <> pprOccName occ
524 occ = primOpOcc other_op