2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 \section[PrimOp]{Primitive operations (machine-level)}
7 {-# OPTIONS -fno-warn-unused-binds #-}
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/Commentary/CodingStyle#Warnings
15 PrimOp(..), allThePrimOps,
16 primOpType, primOpSig,
17 primOpTag, maxPrimOpTag, primOpOcc,
21 primOpOutOfLine, primOpNeedsWrapper,
22 primOpOkForSpeculation, primOpIsCheap, primOpIsDupable,
24 getPrimOpResultInfo, PrimOpResultInfo(..),
29 #include "HsVersions.h"
36 import OccName ( OccName, pprOccName, mkVarOccFS )
37 import TyCon ( TyCon, isPrimTyCon, tyConPrimRep, PrimRep(..) )
38 import Type ( Type, mkForAllTys, mkFunTy, mkFunTys, tyConAppTyCon,
40 import BasicTypes ( Arity, Boxity(..) )
41 import ForeignCall ( CLabelString )
42 import Unique ( Unique, mkPrimOpIdUnique )
48 %************************************************************************
50 \subsection[PrimOp-datatype]{Datatype for @PrimOp@ (an enumeration)}
52 %************************************************************************
54 These are in \tr{state-interface.verb} order.
60 #include "primop-data-decl.hs-incl"
63 Used for the Ord instance
66 primOpTag :: PrimOp -> Int
67 primOpTag op = iBox (tagOf_PrimOp op)
70 -- tagOf_PrimOp :: PrimOp -> FastInt
71 #include "primop-tag.hs-incl"
74 instance Eq PrimOp where
75 op1 == op2 = tagOf_PrimOp op1 ==# tagOf_PrimOp op2
77 instance Ord PrimOp where
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 > op2 = tagOf_PrimOp op1 ># tagOf_PrimOp op2
82 op1 `compare` op2 | op1 < op2 = LT
86 instance Outputable PrimOp where
89 instance Show PrimOp where
90 showsPrec p op = showsPrecSDoc p (pprPrimOp op)
93 An @Enum@-derived list would be better; meanwhile... (ToDo)
96 allThePrimOps :: [PrimOp]
98 #include "primop-list.hs-incl"
102 tagToEnumKey :: Unique
103 tagToEnumKey = mkPrimOpIdUnique (primOpTag TagToEnumOp)
108 %************************************************************************
110 \subsection[PrimOp-info]{The essential info about each @PrimOp@}
112 %************************************************************************
114 The @String@ in the @PrimOpInfos@ is the ``base name'' by which the user may
115 refer to the primitive operation. The conventional \tr{#}-for-
116 unboxed ops is added on later.
118 The reason for the funny characters in the names is so we do not
119 interfere with the programmer's Haskell name spaces.
121 We use @PrimKinds@ for the ``type'' information, because they're
122 (slightly) more convenient to use than @TyCons@.
125 = Dyadic OccName -- string :: T -> T -> T
127 | Monadic OccName -- string :: T -> T
129 | Compare OccName -- string :: T -> T -> Bool
132 | GenPrimOp OccName -- string :: \/a1..an . T1 -> .. -> Tk -> T
137 mkDyadic, mkMonadic, mkCompare :: FastString -> Type -> PrimOpInfo
138 mkDyadic str ty = Dyadic (mkVarOccFS str) ty
139 mkMonadic str ty = Monadic (mkVarOccFS str) ty
140 mkCompare str ty = Compare (mkVarOccFS str) ty
142 mkGenPrimOp :: FastString -> [TyVar] -> [Type] -> Type -> PrimOpInfo
143 mkGenPrimOp str tvs tys ty = GenPrimOp (mkVarOccFS str) tvs tys ty
146 %************************************************************************
148 \subsubsection{Strictness}
150 %************************************************************************
152 Not all primops are strict!
155 primOpStrictness :: PrimOp -> Arity -> StrictSig
156 -- See Demand.StrictnessInfo for discussion of what the results
157 -- The arity should be the arity of the primop; that's why
158 -- this function isn't exported.
159 #include "primop-strictness.hs-incl"
162 %************************************************************************
164 \subsubsection[PrimOp-comparison]{PrimOpInfo basic comparison ops}
166 %************************************************************************
168 @primOpInfo@ gives all essential information (from which everything
169 else, notably a type, can be constructed) for each @PrimOp@.
172 primOpInfo :: PrimOp -> PrimOpInfo
173 #include "primop-primop-info.hs-incl"
176 Here are a load of comments from the old primOp info:
178 A @Word#@ is an unsigned @Int#@.
180 @decodeFloat#@ is given w/ Integer-stuff (it's similar).
182 @decodeDouble#@ is given w/ Integer-stuff (it's similar).
184 Decoding of floating-point numbers is sorta Integer-related. Encoding
185 is done with plain ccalls now (see PrelNumExtra.lhs).
187 A @Weak@ Pointer is created by the @mkWeak#@ primitive:
189 mkWeak# :: k -> v -> f -> State# RealWorld
190 -> (# State# RealWorld, Weak# v #)
192 In practice, you'll use the higher-level
194 data Weak v = Weak# v
195 mkWeak :: k -> v -> IO () -> IO (Weak v)
197 The following operation dereferences a weak pointer. The weak pointer
198 may have been finalized, so the operation returns a result code which
199 must be inspected before looking at the dereferenced value.
201 deRefWeak# :: Weak# v -> State# RealWorld ->
202 (# State# RealWorld, v, Int# #)
204 Only look at v if the Int# returned is /= 0 !!
206 The higher-level op is
208 deRefWeak :: Weak v -> IO (Maybe v)
210 Weak pointers can be finalized early by using the finalize# operation:
212 finalizeWeak# :: Weak# v -> State# RealWorld ->
213 (# State# RealWorld, Int#, IO () #)
215 The Int# returned is either
217 0 if the weak pointer has already been finalized, or it has no
218 finalizer (the third component is then invalid).
220 1 if the weak pointer is still alive, with the finalizer returned
221 as the third component.
223 A {\em stable name/pointer} is an index into a table of stable name
224 entries. Since the garbage collector is told about stable pointers,
225 it is safe to pass a stable pointer to external systems such as C
229 makeStablePtr# :: a -> State# RealWorld -> (# State# RealWorld, StablePtr# a #)
230 freeStablePtr :: StablePtr# a -> State# RealWorld -> State# RealWorld
231 deRefStablePtr# :: StablePtr# a -> State# RealWorld -> (# State# RealWorld, a #)
232 eqStablePtr# :: StablePtr# a -> StablePtr# a -> Int#
235 It may seem a bit surprising that @makeStablePtr#@ is a @IO@
236 operation since it doesn't (directly) involve IO operations. The
237 reason is that if some optimisation pass decided to duplicate calls to
238 @makeStablePtr#@ and we only pass one of the stable pointers over, a
239 massive space leak can result. Putting it into the IO monad
240 prevents this. (Another reason for putting them in a monad is to
241 ensure correct sequencing wrt the side-effecting @freeStablePtr@
244 An important property of stable pointers is that if you call
245 makeStablePtr# twice on the same object you get the same stable
248 Note that we can implement @freeStablePtr#@ using @_ccall_@ (and,
249 besides, it's not likely to be used from Haskell) so it's not a
252 Question: Why @RealWorld@ - won't any instance of @_ST@ do the job? [ADR]
257 A stable name is like a stable pointer, but with three important differences:
259 (a) You can't deRef one to get back to the original object.
260 (b) You can convert one to an Int.
261 (c) You don't need to 'freeStableName'
263 The existence of a stable name doesn't guarantee to keep the object it
264 points to alive (unlike a stable pointer), hence (a).
268 (a) makeStableName always returns the same value for a given
269 object (same as stable pointers).
271 (b) if two stable names are equal, it implies that the objects
272 from which they were created were the same.
274 (c) stableNameToInt always returns the same Int for a given
278 -- HWL: The first 4 Int# in all par... annotations denote:
279 -- name, granularity info, size of result, degree of parallelism
280 -- Same structure as _seq_ i.e. returns Int#
281 -- KSW: v, the second arg in parAt# and parAtForNow#, is used only to determine
282 -- `the processor containing the expression v'; it is not evaluated
284 These primops are pretty wierd.
286 dataToTag# :: a -> Int (arg must be an evaluated data type)
287 tagToEnum# :: Int -> a (result type must be an enumerated type)
289 The constraints aren't currently checked by the front end, but the
290 code generator will fall over if they aren't satisfied.
292 %************************************************************************
294 \subsubsection[PrimOp-ool]{Which PrimOps are out-of-line}
296 %************************************************************************
298 Some PrimOps need to be called out-of-line because they either need to
299 perform a heap check or they block.
303 primOpOutOfLine :: PrimOp -> Bool
304 #include "primop-out-of-line.hs-incl"
308 primOpOkForSpeculation
309 ~~~~~~~~~~~~~~~~~~~~~~
310 Sometimes we may choose to execute a PrimOp even though it isn't
311 certain that its result will be required; ie execute them
312 ``speculatively''. The same thing as ``cheap eagerness.'' Usually
313 this is OK, because PrimOps are usually cheap, but it isn't OK for
314 (a)~expensive PrimOps and (b)~PrimOps which can fail.
316 PrimOps that have side effects also should not be executed speculatively.
318 Ok-for-speculation also means that it's ok *not* to execute the
322 Here the result is not used, so we can discard the primop. Anything
323 that has side effects mustn't be dicarded in this way, of course!
325 See also @primOpIsCheap@ (below).
329 primOpOkForSpeculation :: PrimOp -> Bool
330 -- See comments with CoreUtils.exprOkForSpeculation
331 primOpOkForSpeculation op
332 = not (primOpHasSideEffects op || primOpOutOfLine op || primOpCanFail op)
338 @primOpIsCheap@, as used in \tr{SimplUtils.lhs}. For now (HACK
339 WARNING), we just borrow some other predicates for a
340 what-should-be-good-enough test. "Cheap" means willing to call it more
341 than once, and/or push it inside a lambda. The latter could change the
342 behaviour of 'seq' for primops that can fail, so we don't treat them as cheap.
345 primOpIsCheap :: PrimOp -> Bool
346 primOpIsCheap op = primOpOkForSpeculation op
347 -- In March 2001, we changed this to
348 -- primOpIsCheap op = False
349 -- thereby making *no* primops seem cheap. But this killed eta
350 -- expansion on case (x ==# y) of True -> \s -> ...
351 -- which is bad. In particular a loop like
354 -- loop i | i == n = return ()
355 -- | otherwise = bar i >> loop (i+1)
356 -- allocated a closure every time round because it doesn't eta expand.
358 -- The problem that originally gave rise to the change was
359 -- let x = a +# b *# c in x +# x
360 -- were we don't want to inline x. But primopIsCheap doesn't control
361 -- that (it's exprIsDupable that does) so the problem doesn't occur
362 -- even if primOpIsCheap sometimes says 'True'.
367 primOpIsDupable means that the use of the primop is small enough to
368 duplicate into different case branches. See CoreUtils.exprIsDupable.
371 primOpIsDupable :: PrimOp -> Bool
372 -- See comments with CoreUtils.exprIsDupable
373 -- We say it's dupable it isn't implemented by a C call with a wrapper
374 primOpIsDupable op = not (primOpNeedsWrapper op)
379 primOpCanFail :: PrimOp -> Bool
380 #include "primop-can-fail.hs-incl"
383 And some primops have side-effects and so, for example, must not be
386 This predicate means a little more than just "modifies the state of
387 the world". What it really means is "it cosumes the state on its
388 input". To see what this means, consider
391 t = case readMutVar# v s0 of (# s1, x #) -> (S# s1, x)
392 y = case t of (s,x) -> x
396 Now, this is part of an ST or IO thread, so we are guaranteed by
397 construction that the program uses the state in a single-threaded way.
398 Whenever the state resulting from the readMutVar# is demanded, the
399 readMutVar# will be performed, and it will be ordered correctly with
400 respect to other operations in the monad.
402 But there's another way this could go wrong: GHC can inline t into y,
403 and inline y. Then although the original readMutVar# will still be
404 correctly ordered with respect to the other operations, there will be
405 one or more extra readMutVar#s performed later, possibly out-of-order.
406 This really happened; see #3207.
408 The property we need to capture about readMutVar# is that it consumes
409 the State# value on its input. We must retain the linearity of the
412 Our fix for this is to declare any primop that must be used linearly
413 as having side-effects. When primOpHasSideEffects is True,
414 primOpOkForSpeculation will be False, and hence primOpIsCheap will
415 also be False, and applications of the primop will never be
419 primOpHasSideEffects :: PrimOp -> Bool
420 #include "primop-has-side-effects.hs-incl"
423 Inline primitive operations that perform calls need wrappers to save
424 any live variables that are stored in caller-saves registers.
427 primOpNeedsWrapper :: PrimOp -> Bool
428 #include "primop-needs-wrapper.hs-incl"
432 primOpType :: PrimOp -> Type -- you may want to use primOpSig instead
434 = case primOpInfo op of
435 Dyadic _occ ty -> dyadic_fun_ty ty
436 Monadic _occ ty -> monadic_fun_ty ty
437 Compare _occ ty -> compare_fun_ty ty
439 GenPrimOp _occ tyvars arg_tys res_ty ->
440 mkForAllTys tyvars (mkFunTys arg_tys res_ty)
442 primOpOcc :: PrimOp -> OccName
443 primOpOcc op = case primOpInfo op of
447 GenPrimOp occ _ _ _ -> occ
449 -- primOpSig is like primOpType but gives the result split apart:
450 -- (type variables, argument types, result type)
451 -- It also gives arity, strictness info
453 primOpSig :: PrimOp -> ([TyVar], [Type], Type, Arity, StrictSig)
455 = (tyvars, arg_tys, res_ty, arity, primOpStrictness op arity)
457 arity = length arg_tys
458 (tyvars, arg_tys, res_ty)
459 = case (primOpInfo op) of
460 Monadic _occ ty -> ([], [ty], ty )
461 Dyadic _occ ty -> ([], [ty,ty], ty )
462 Compare _occ ty -> ([], [ty,ty], boolTy)
463 GenPrimOp _occ tyvars arg_tys res_ty -> (tyvars, arg_tys, res_ty)
467 data PrimOpResultInfo
468 = ReturnsPrim PrimRep
471 -- Some PrimOps need not return a manifest primitive or algebraic value
472 -- (i.e. they might return a polymorphic value). These PrimOps *must*
473 -- be out of line, or the code generator won't work.
475 getPrimOpResultInfo :: PrimOp -> PrimOpResultInfo
476 getPrimOpResultInfo op
477 = case (primOpInfo op) of
478 Dyadic _ ty -> ReturnsPrim (typePrimRep ty)
479 Monadic _ ty -> ReturnsPrim (typePrimRep ty)
480 Compare _ _ -> ReturnsAlg boolTyCon
481 GenPrimOp _ _ _ ty | isPrimTyCon tc -> ReturnsPrim (tyConPrimRep tc)
482 | otherwise -> ReturnsAlg tc
484 tc = tyConAppTyCon ty
485 -- All primops return a tycon-app result
486 -- The tycon can be an unboxed tuple, though, which
487 -- gives rise to a ReturnAlg
490 The commutable ops are those for which we will try to move constants
491 to the right hand side for strength reduction.
494 commutableOp :: PrimOp -> Bool
495 #include "primop-commutable.hs-incl"
500 dyadic_fun_ty, monadic_fun_ty, compare_fun_ty :: Type -> Type
501 dyadic_fun_ty ty = mkFunTys [ty, ty] ty
502 monadic_fun_ty ty = mkFunTy ty ty
503 compare_fun_ty ty = mkFunTys [ty, ty] boolTy
508 pprPrimOp :: PrimOp -> SDoc
509 pprPrimOp other_op = pprOccName (primOpOcc other_op)
513 %************************************************************************
515 \subsubsection[PrimCall]{User-imported primitive calls}
517 %************************************************************************
520 newtype PrimCall = PrimCall CLabelString
522 instance Outputable PrimCall where
523 ppr (PrimCall lbl) = ppr lbl