2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 \section[PrimOp]{Primitive operations (machine-level)}
7 {-# OPTIONS_GHC -H80m #-}
8 {-# OPTIONS -fno-warn-unused-binds #-}
9 -- The above warning supression flag is a temporary kludge.
10 -- While working on this module you are encouraged to remove it and fix
11 -- any warnings in the module. See
12 -- http://hackage.haskell.org/trac/ghc/wiki/Commentary/CodingStyle#Warnings
16 PrimOp(..), allThePrimOps,
17 primOpType, primOpSig,
18 primOpTag, maxPrimOpTag, primOpOcc,
22 primOpOutOfLine, primOpNeedsWrapper,
23 primOpOkForSpeculation, primOpIsCheap, primOpIsDupable,
25 getPrimOpResultInfo, PrimOpResultInfo(..)
28 #include "HsVersions.h"
35 import OccName ( OccName, pprOccName, mkVarOccFS )
36 import TyCon ( TyCon, isPrimTyCon, tyConPrimRep, PrimRep(..) )
37 import Type ( Type, mkForAllTys, mkFunTy, mkFunTys, tyConAppTyCon,
39 import BasicTypes ( Arity, Boxity(..) )
40 import Unique ( Unique, mkPrimOpIdUnique )
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"
72 instance Eq PrimOp where
73 op1 == op2 = tagOf_PrimOp op1 ==# tagOf_PrimOp op2
75 instance Ord PrimOp where
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 > op2 = tagOf_PrimOp op1 ># tagOf_PrimOp op2
80 op1 `compare` op2 | op1 < op2 = LT
84 instance Outputable PrimOp where
87 instance Show PrimOp where
88 showsPrec p op = showsPrecSDoc p (pprPrimOp op)
91 An @Enum@-derived list would be better; meanwhile... (ToDo)
94 allThePrimOps :: [PrimOp]
96 #include "primop-list.hs-incl"
100 tagToEnumKey :: Unique
101 tagToEnumKey = mkPrimOpIdUnique (primOpTag TagToEnumOp)
106 %************************************************************************
108 \subsection[PrimOp-info]{The essential info about each @PrimOp@}
110 %************************************************************************
112 The @String@ in the @PrimOpInfos@ is the ``base name'' by which the user may
113 refer to the primitive operation. The conventional \tr{#}-for-
114 unboxed ops is added on later.
116 The reason for the funny characters in the names is so we do not
117 interfere with the programmer's Haskell name spaces.
119 We use @PrimKinds@ for the ``type'' information, because they're
120 (slightly) more convenient to use than @TyCons@.
123 = Dyadic OccName -- string :: T -> T -> T
125 | Monadic OccName -- string :: T -> T
127 | Compare OccName -- string :: T -> T -> Bool
130 | GenPrimOp OccName -- string :: \/a1..an . T1 -> .. -> Tk -> T
135 mkDyadic, mkMonadic, mkCompare :: FastString -> Type -> PrimOpInfo
136 mkDyadic str ty = Dyadic (mkVarOccFS str) ty
137 mkMonadic str ty = Monadic (mkVarOccFS str) ty
138 mkCompare str ty = Compare (mkVarOccFS str) ty
140 mkGenPrimOp :: FastString -> [TyVar] -> [Type] -> Type -> PrimOpInfo
141 mkGenPrimOp str tvs tys ty = GenPrimOp (mkVarOccFS str) tvs tys ty
144 %************************************************************************
146 \subsubsection{Strictness}
148 %************************************************************************
150 Not all primops are strict!
153 primOpStrictness :: PrimOp -> Arity -> StrictSig
154 -- See Demand.StrictnessInfo for discussion of what the results
155 -- The arity should be the arity of the primop; that's why
156 -- this function isn't exported.
157 #include "primop-strictness.hs-incl"
160 %************************************************************************
162 \subsubsection[PrimOp-comparison]{PrimOpInfo basic comparison ops}
164 %************************************************************************
166 @primOpInfo@ gives all essential information (from which everything
167 else, notably a type, can be constructed) for each @PrimOp@.
170 primOpInfo :: PrimOp -> PrimOpInfo
171 #include "primop-primop-info.hs-incl"
174 Here are a load of comments from the old primOp info:
176 A @Word#@ is an unsigned @Int#@.
178 @decodeFloat#@ is given w/ Integer-stuff (it's similar).
180 @decodeDouble#@ is given w/ Integer-stuff (it's similar).
182 Decoding of floating-point numbers is sorta Integer-related. Encoding
183 is done with plain ccalls now (see PrelNumExtra.lhs).
185 A @Weak@ Pointer is created by the @mkWeak#@ primitive:
187 mkWeak# :: k -> v -> f -> State# RealWorld
188 -> (# State# RealWorld, Weak# v #)
190 In practice, you'll use the higher-level
192 data Weak v = Weak# v
193 mkWeak :: k -> v -> IO () -> IO (Weak v)
195 The following operation dereferences a weak pointer. The weak pointer
196 may have been finalized, so the operation returns a result code which
197 must be inspected before looking at the dereferenced value.
199 deRefWeak# :: Weak# v -> State# RealWorld ->
200 (# State# RealWorld, v, Int# #)
202 Only look at v if the Int# returned is /= 0 !!
204 The higher-level op is
206 deRefWeak :: Weak v -> IO (Maybe v)
208 Weak pointers can be finalized early by using the finalize# operation:
210 finalizeWeak# :: Weak# v -> State# RealWorld ->
211 (# State# RealWorld, Int#, IO () #)
213 The Int# returned is either
215 0 if the weak pointer has already been finalized, or it has no
216 finalizer (the third component is then invalid).
218 1 if the weak pointer is still alive, with the finalizer returned
219 as the third component.
221 A {\em stable name/pointer} is an index into a table of stable name
222 entries. Since the garbage collector is told about stable pointers,
223 it is safe to pass a stable pointer to external systems such as C
227 makeStablePtr# :: a -> State# RealWorld -> (# State# RealWorld, StablePtr# a #)
228 freeStablePtr :: StablePtr# a -> State# RealWorld -> State# RealWorld
229 deRefStablePtr# :: StablePtr# a -> State# RealWorld -> (# State# RealWorld, a #)
230 eqStablePtr# :: StablePtr# a -> StablePtr# a -> Int#
233 It may seem a bit surprising that @makeStablePtr#@ is a @IO@
234 operation since it doesn't (directly) involve IO operations. The
235 reason is that if some optimisation pass decided to duplicate calls to
236 @makeStablePtr#@ and we only pass one of the stable pointers over, a
237 massive space leak can result. Putting it into the IO monad
238 prevents this. (Another reason for putting them in a monad is to
239 ensure correct sequencing wrt the side-effecting @freeStablePtr@
242 An important property of stable pointers is that if you call
243 makeStablePtr# twice on the same object you get the same stable
246 Note that we can implement @freeStablePtr#@ using @_ccall_@ (and,
247 besides, it's not likely to be used from Haskell) so it's not a
250 Question: Why @RealWorld@ - won't any instance of @_ST@ do the job? [ADR]
255 A stable name is like a stable pointer, but with three important differences:
257 (a) You can't deRef one to get back to the original object.
258 (b) You can convert one to an Int.
259 (c) You don't need to 'freeStableName'
261 The existence of a stable name doesn't guarantee to keep the object it
262 points to alive (unlike a stable pointer), hence (a).
266 (a) makeStableName always returns the same value for a given
267 object (same as stable pointers).
269 (b) if two stable names are equal, it implies that the objects
270 from which they were created were the same.
272 (c) stableNameToInt always returns the same Int for a given
276 -- HWL: The first 4 Int# in all par... annotations denote:
277 -- name, granularity info, size of result, degree of parallelism
278 -- Same structure as _seq_ i.e. returns Int#
279 -- KSW: v, the second arg in parAt# and parAtForNow#, is used only to determine
280 -- `the processor containing the expression v'; it is not evaluated
282 These primops are pretty wierd.
284 dataToTag# :: a -> Int (arg must be an evaluated data type)
285 tagToEnum# :: Int -> a (result type must be an enumerated type)
287 The constraints aren't currently checked by the front end, but the
288 code generator will fall over if they aren't satisfied.
290 %************************************************************************
292 \subsubsection[PrimOp-ool]{Which PrimOps are out-of-line}
294 %************************************************************************
296 Some PrimOps need to be called out-of-line because they either need to
297 perform a heap check or they block.
301 primOpOutOfLine :: PrimOp -> Bool
302 #include "primop-out-of-line.hs-incl"
306 primOpOkForSpeculation
307 ~~~~~~~~~~~~~~~~~~~~~~
308 Sometimes we may choose to execute a PrimOp even though it isn't
309 certain that its result will be required; ie execute them
310 ``speculatively''. The same thing as ``cheap eagerness.'' Usually
311 this is OK, because PrimOps are usually cheap, but it isn't OK for
312 (a)~expensive PrimOps and (b)~PrimOps which can fail.
314 PrimOps that have side effects also should not be executed speculatively.
316 Ok-for-speculation also means that it's ok *not* to execute the
320 Here the result is not used, so we can discard the primop. Anything
321 that has side effects mustn't be dicarded in this way, of course!
323 See also @primOpIsCheap@ (below).
327 primOpOkForSpeculation :: PrimOp -> Bool
328 -- See comments with CoreUtils.exprOkForSpeculation
329 primOpOkForSpeculation op
330 = not (primOpHasSideEffects op || primOpOutOfLine op || primOpCanFail op)
336 @primOpIsCheap@, as used in \tr{SimplUtils.lhs}. For now (HACK
337 WARNING), we just borrow some other predicates for a
338 what-should-be-good-enough test. "Cheap" means willing to call it more
339 than once, and/or push it inside a lambda. The latter could change the
340 behaviour of 'seq' for primops that can fail, so we don't treat them as cheap.
343 primOpIsCheap :: PrimOp -> Bool
344 primOpIsCheap op = primOpOkForSpeculation op
345 -- In March 2001, we changed this to
346 -- primOpIsCheap op = False
347 -- thereby making *no* primops seem cheap. But this killed eta
348 -- expansion on case (x ==# y) of True -> \s -> ...
349 -- which is bad. In particular a loop like
352 -- loop i | i == n = return ()
353 -- | otherwise = bar i >> loop (i+1)
354 -- allocated a closure every time round because it doesn't eta expand.
356 -- The problem that originally gave rise to the change was
357 -- let x = a +# b *# c in x +# x
358 -- were we don't want to inline x. But primopIsCheap doesn't control
359 -- that (it's exprIsDupable that does) so the problem doesn't occur
360 -- even if primOpIsCheap sometimes says 'True'.
365 primOpIsDupable means that the use of the primop is small enough to
366 duplicate into different case branches. See CoreUtils.exprIsDupable.
369 primOpIsDupable :: PrimOp -> Bool
370 -- See comments with CoreUtils.exprIsDupable
371 -- We say it's dupable it isn't implemented by a C call with a wrapper
372 primOpIsDupable op = not (primOpNeedsWrapper op)
377 primOpCanFail :: PrimOp -> Bool
378 #include "primop-can-fail.hs-incl"
381 And some primops have side-effects and so, for example, must not be
385 primOpHasSideEffects :: PrimOp -> Bool
386 #include "primop-has-side-effects.hs-incl"
389 Inline primitive operations that perform calls need wrappers to save
390 any live variables that are stored in caller-saves registers.
393 primOpNeedsWrapper :: PrimOp -> Bool
394 #include "primop-needs-wrapper.hs-incl"
398 primOpType :: PrimOp -> Type -- you may want to use primOpSig instead
400 = case primOpInfo op of
401 Dyadic _occ ty -> dyadic_fun_ty ty
402 Monadic _occ ty -> monadic_fun_ty ty
403 Compare _occ ty -> compare_fun_ty ty
405 GenPrimOp _occ tyvars arg_tys res_ty ->
406 mkForAllTys tyvars (mkFunTys arg_tys res_ty)
408 primOpOcc :: PrimOp -> OccName
409 primOpOcc op = case primOpInfo op of
413 GenPrimOp occ _ _ _ -> occ
415 -- primOpSig is like primOpType but gives the result split apart:
416 -- (type variables, argument types, result type)
417 -- It also gives arity, strictness info
419 primOpSig :: PrimOp -> ([TyVar], [Type], Type, Arity, StrictSig)
421 = (tyvars, arg_tys, res_ty, arity, primOpStrictness op arity)
423 arity = length arg_tys
424 (tyvars, arg_tys, res_ty)
425 = case (primOpInfo op) of
426 Monadic _occ ty -> ([], [ty], ty )
427 Dyadic _occ ty -> ([], [ty,ty], ty )
428 Compare _occ ty -> ([], [ty,ty], boolTy)
429 GenPrimOp _occ tyvars arg_tys res_ty -> (tyvars, arg_tys, res_ty)
433 data PrimOpResultInfo
434 = ReturnsPrim PrimRep
437 -- Some PrimOps need not return a manifest primitive or algebraic value
438 -- (i.e. they might return a polymorphic value). These PrimOps *must*
439 -- be out of line, or the code generator won't work.
441 getPrimOpResultInfo :: PrimOp -> PrimOpResultInfo
442 getPrimOpResultInfo op
443 = case (primOpInfo op) of
444 Dyadic _ ty -> ReturnsPrim (typePrimRep ty)
445 Monadic _ ty -> ReturnsPrim (typePrimRep ty)
446 Compare _ _ -> ReturnsAlg boolTyCon
447 GenPrimOp _ _ _ ty | isPrimTyCon tc -> ReturnsPrim (tyConPrimRep tc)
448 | otherwise -> ReturnsAlg tc
450 tc = tyConAppTyCon ty
451 -- All primops return a tycon-app result
452 -- The tycon can be an unboxed tuple, though, which
453 -- gives rise to a ReturnAlg
456 The commutable ops are those for which we will try to move constants
457 to the right hand side for strength reduction.
460 commutableOp :: PrimOp -> Bool
461 #include "primop-commutable.hs-incl"
466 dyadic_fun_ty, monadic_fun_ty, compare_fun_ty :: Type -> Type
467 dyadic_fun_ty ty = mkFunTys [ty, ty] ty
468 monadic_fun_ty ty = mkFunTy ty ty
469 compare_fun_ty ty = mkFunTys [ty, ty] boolTy
474 pprPrimOp :: PrimOp -> SDoc
475 pprPrimOp other_op = pprOccName (primOpOcc other_op)