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(..)
27 #include "HsVersions.h"
34 import OccName ( OccName, pprOccName, mkVarOccFS )
35 import TyCon ( TyCon, isPrimTyCon, tyConPrimRep, PrimRep(..) )
36 import Type ( Type, mkForAllTys, mkFunTy, mkFunTys, tyConAppTyCon,
38 import BasicTypes ( Arity, Boxity(..) )
39 import Unique ( Unique, mkPrimOpIdUnique )
45 %************************************************************************
47 \subsection[PrimOp-datatype]{Datatype for @PrimOp@ (an enumeration)}
49 %************************************************************************
51 These are in \tr{state-interface.verb} order.
57 #include "primop-data-decl.hs-incl"
60 Used for the Ord instance
63 primOpTag :: PrimOp -> Int
64 primOpTag op = iBox (tagOf_PrimOp op)
67 -- tagOf_PrimOp :: PrimOp -> FastInt
68 #include "primop-tag.hs-incl"
71 instance Eq PrimOp where
72 op1 == op2 = tagOf_PrimOp op1 ==# tagOf_PrimOp op2
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
83 instance Outputable PrimOp where
86 instance Show PrimOp where
87 showsPrec p op = showsPrecSDoc p (pprPrimOp op)
90 An @Enum@-derived list would be better; meanwhile... (ToDo)
93 allThePrimOps :: [PrimOp]
95 #include "primop-list.hs-incl"
99 tagToEnumKey :: Unique
100 tagToEnumKey = mkPrimOpIdUnique (primOpTag TagToEnumOp)
105 %************************************************************************
107 \subsection[PrimOp-info]{The essential info about each @PrimOp@}
109 %************************************************************************
111 The @String@ in the @PrimOpInfos@ is the ``base name'' by which the user may
112 refer to the primitive operation. The conventional \tr{#}-for-
113 unboxed ops is added on later.
115 The reason for the funny characters in the names is so we do not
116 interfere with the programmer's Haskell name spaces.
118 We use @PrimKinds@ for the ``type'' information, because they're
119 (slightly) more convenient to use than @TyCons@.
122 = Dyadic OccName -- string :: T -> T -> T
124 | Monadic OccName -- string :: T -> T
126 | Compare OccName -- string :: T -> T -> Bool
129 | GenPrimOp OccName -- string :: \/a1..an . T1 -> .. -> Tk -> T
134 mkDyadic, mkMonadic, mkCompare :: FastString -> Type -> PrimOpInfo
135 mkDyadic str ty = Dyadic (mkVarOccFS str) ty
136 mkMonadic str ty = Monadic (mkVarOccFS str) ty
137 mkCompare str ty = Compare (mkVarOccFS str) ty
139 mkGenPrimOp :: FastString -> [TyVar] -> [Type] -> Type -> PrimOpInfo
140 mkGenPrimOp str tvs tys ty = GenPrimOp (mkVarOccFS str) tvs tys ty
143 %************************************************************************
145 \subsubsection{Strictness}
147 %************************************************************************
149 Not all primops are strict!
152 primOpStrictness :: PrimOp -> Arity -> StrictSig
153 -- See Demand.StrictnessInfo for discussion of what the results
154 -- The arity should be the arity of the primop; that's why
155 -- this function isn't exported.
156 #include "primop-strictness.hs-incl"
159 %************************************************************************
161 \subsubsection[PrimOp-comparison]{PrimOpInfo basic comparison ops}
163 %************************************************************************
165 @primOpInfo@ gives all essential information (from which everything
166 else, notably a type, can be constructed) for each @PrimOp@.
169 primOpInfo :: PrimOp -> PrimOpInfo
170 #include "primop-primop-info.hs-incl"
173 Here are a load of comments from the old primOp info:
175 A @Word#@ is an unsigned @Int#@.
177 @decodeFloat#@ is given w/ Integer-stuff (it's similar).
179 @decodeDouble#@ is given w/ Integer-stuff (it's similar).
181 Decoding of floating-point numbers is sorta Integer-related. Encoding
182 is done with plain ccalls now (see PrelNumExtra.lhs).
184 A @Weak@ Pointer is created by the @mkWeak#@ primitive:
186 mkWeak# :: k -> v -> f -> State# RealWorld
187 -> (# State# RealWorld, Weak# v #)
189 In practice, you'll use the higher-level
191 data Weak v = Weak# v
192 mkWeak :: k -> v -> IO () -> IO (Weak v)
194 The following operation dereferences a weak pointer. The weak pointer
195 may have been finalized, so the operation returns a result code which
196 must be inspected before looking at the dereferenced value.
198 deRefWeak# :: Weak# v -> State# RealWorld ->
199 (# State# RealWorld, v, Int# #)
201 Only look at v if the Int# returned is /= 0 !!
203 The higher-level op is
205 deRefWeak :: Weak v -> IO (Maybe v)
207 Weak pointers can be finalized early by using the finalize# operation:
209 finalizeWeak# :: Weak# v -> State# RealWorld ->
210 (# State# RealWorld, Int#, IO () #)
212 The Int# returned is either
214 0 if the weak pointer has already been finalized, or it has no
215 finalizer (the third component is then invalid).
217 1 if the weak pointer is still alive, with the finalizer returned
218 as the third component.
220 A {\em stable name/pointer} is an index into a table of stable name
221 entries. Since the garbage collector is told about stable pointers,
222 it is safe to pass a stable pointer to external systems such as C
226 makeStablePtr# :: a -> State# RealWorld -> (# State# RealWorld, StablePtr# a #)
227 freeStablePtr :: StablePtr# a -> State# RealWorld -> State# RealWorld
228 deRefStablePtr# :: StablePtr# a -> State# RealWorld -> (# State# RealWorld, a #)
229 eqStablePtr# :: StablePtr# a -> StablePtr# a -> Int#
232 It may seem a bit surprising that @makeStablePtr#@ is a @IO@
233 operation since it doesn't (directly) involve IO operations. The
234 reason is that if some optimisation pass decided to duplicate calls to
235 @makeStablePtr#@ and we only pass one of the stable pointers over, a
236 massive space leak can result. Putting it into the IO monad
237 prevents this. (Another reason for putting them in a monad is to
238 ensure correct sequencing wrt the side-effecting @freeStablePtr@
241 An important property of stable pointers is that if you call
242 makeStablePtr# twice on the same object you get the same stable
245 Note that we can implement @freeStablePtr#@ using @_ccall_@ (and,
246 besides, it's not likely to be used from Haskell) so it's not a
249 Question: Why @RealWorld@ - won't any instance of @_ST@ do the job? [ADR]
254 A stable name is like a stable pointer, but with three important differences:
256 (a) You can't deRef one to get back to the original object.
257 (b) You can convert one to an Int.
258 (c) You don't need to 'freeStableName'
260 The existence of a stable name doesn't guarantee to keep the object it
261 points to alive (unlike a stable pointer), hence (a).
265 (a) makeStableName always returns the same value for a given
266 object (same as stable pointers).
268 (b) if two stable names are equal, it implies that the objects
269 from which they were created were the same.
271 (c) stableNameToInt always returns the same Int for a given
275 -- HWL: The first 4 Int# in all par... annotations denote:
276 -- name, granularity info, size of result, degree of parallelism
277 -- Same structure as _seq_ i.e. returns Int#
278 -- KSW: v, the second arg in parAt# and parAtForNow#, is used only to determine
279 -- `the processor containing the expression v'; it is not evaluated
281 These primops are pretty wierd.
283 dataToTag# :: a -> Int (arg must be an evaluated data type)
284 tagToEnum# :: Int -> a (result type must be an enumerated type)
286 The constraints aren't currently checked by the front end, but the
287 code generator will fall over if they aren't satisfied.
289 %************************************************************************
291 \subsubsection[PrimOp-ool]{Which PrimOps are out-of-line}
293 %************************************************************************
295 Some PrimOps need to be called out-of-line because they either need to
296 perform a heap check or they block.
300 primOpOutOfLine :: PrimOp -> Bool
301 #include "primop-out-of-line.hs-incl"
305 primOpOkForSpeculation
306 ~~~~~~~~~~~~~~~~~~~~~~
307 Sometimes we may choose to execute a PrimOp even though it isn't
308 certain that its result will be required; ie execute them
309 ``speculatively''. The same thing as ``cheap eagerness.'' Usually
310 this is OK, because PrimOps are usually cheap, but it isn't OK for
311 (a)~expensive PrimOps and (b)~PrimOps which can fail.
313 PrimOps that have side effects also should not be executed speculatively.
315 Ok-for-speculation also means that it's ok *not* to execute the
319 Here the result is not used, so we can discard the primop. Anything
320 that has side effects mustn't be dicarded in this way, of course!
322 See also @primOpIsCheap@ (below).
326 primOpOkForSpeculation :: PrimOp -> Bool
327 -- See comments with CoreUtils.exprOkForSpeculation
328 primOpOkForSpeculation op
329 = not (primOpHasSideEffects op || primOpOutOfLine op || primOpCanFail op)
335 @primOpIsCheap@, as used in \tr{SimplUtils.lhs}. For now (HACK
336 WARNING), we just borrow some other predicates for a
337 what-should-be-good-enough test. "Cheap" means willing to call it more
338 than once, and/or push it inside a lambda. The latter could change the
339 behaviour of 'seq' for primops that can fail, so we don't treat them as cheap.
342 primOpIsCheap :: PrimOp -> Bool
343 primOpIsCheap op = primOpOkForSpeculation op
344 -- In March 2001, we changed this to
345 -- primOpIsCheap op = False
346 -- thereby making *no* primops seem cheap. But this killed eta
347 -- expansion on case (x ==# y) of True -> \s -> ...
348 -- which is bad. In particular a loop like
351 -- loop i | i == n = return ()
352 -- | otherwise = bar i >> loop (i+1)
353 -- allocated a closure every time round because it doesn't eta expand.
355 -- The problem that originally gave rise to the change was
356 -- let x = a +# b *# c in x +# x
357 -- were we don't want to inline x. But primopIsCheap doesn't control
358 -- that (it's exprIsDupable that does) so the problem doesn't occur
359 -- even if primOpIsCheap sometimes says 'True'.
364 primOpIsDupable means that the use of the primop is small enough to
365 duplicate into different case branches. See CoreUtils.exprIsDupable.
368 primOpIsDupable :: PrimOp -> Bool
369 -- See comments with CoreUtils.exprIsDupable
370 -- We say it's dupable it isn't implemented by a C call with a wrapper
371 primOpIsDupable op = not (primOpNeedsWrapper op)
376 primOpCanFail :: PrimOp -> Bool
377 #include "primop-can-fail.hs-incl"
380 And some primops have side-effects and so, for example, must not be
384 primOpHasSideEffects :: PrimOp -> Bool
385 #include "primop-has-side-effects.hs-incl"
388 Inline primitive operations that perform calls need wrappers to save
389 any live variables that are stored in caller-saves registers.
392 primOpNeedsWrapper :: PrimOp -> Bool
393 #include "primop-needs-wrapper.hs-incl"
397 primOpType :: PrimOp -> Type -- you may want to use primOpSig instead
399 = case primOpInfo op of
400 Dyadic _occ ty -> dyadic_fun_ty ty
401 Monadic _occ ty -> monadic_fun_ty ty
402 Compare _occ ty -> compare_fun_ty ty
404 GenPrimOp _occ tyvars arg_tys res_ty ->
405 mkForAllTys tyvars (mkFunTys arg_tys res_ty)
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, StrictSig)
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 -> (tyvars, arg_tys, res_ty)
432 data PrimOpResultInfo
433 = ReturnsPrim PrimRep
436 -- Some PrimOps need not return a manifest primitive or algebraic value
437 -- (i.e. they might return a polymorphic value). These PrimOps *must*
438 -- be out of line, or the code generator won't work.
440 getPrimOpResultInfo :: PrimOp -> PrimOpResultInfo
441 getPrimOpResultInfo op
442 = case (primOpInfo op) of
443 Dyadic _ ty -> ReturnsPrim (typePrimRep ty)
444 Monadic _ ty -> ReturnsPrim (typePrimRep ty)
445 Compare _ _ -> ReturnsAlg boolTyCon
446 GenPrimOp _ _ _ ty | isPrimTyCon tc -> ReturnsPrim (tyConPrimRep tc)
447 | otherwise -> ReturnsAlg tc
449 tc = tyConAppTyCon ty
450 -- All primops return a tycon-app result
451 -- The tycon can be an unboxed tuple, though, which
452 -- gives rise to a ReturnAlg
455 The commutable ops are those for which we will try to move constants
456 to the right hand side for strength reduction.
459 commutableOp :: PrimOp -> Bool
460 #include "primop-commutable.hs-incl"
465 dyadic_fun_ty, monadic_fun_ty, compare_fun_ty :: Type -> Type
466 dyadic_fun_ty ty = mkFunTys [ty, ty] ty
467 monadic_fun_ty ty = mkFunTy ty ty
468 compare_fun_ty ty = mkFunTys [ty, ty] boolTy
473 pprPrimOp :: PrimOp -> SDoc
474 pprPrimOp other_op = pprOccName (primOpOcc other_op)