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(..),
20 CCall(..), CCallTarget(..), ccallMayGC, ccallIsCasm, pprCCallOp,
21 isDynamicTarget, dynamicTarget, setCCallUnique
24 #include "HsVersions.h"
26 import PrimRep -- most of it
30 import Demand ( wwLazy, wwPrim, wwStrict, StrictnessInfo(..) )
32 import CallConv ( CallConv, pprCallConv )
33 import Name ( Name, mkWiredInName )
34 import RdrName ( RdrName, mkRdrOrig )
35 import OccName ( OccName, pprOccName, mkVarOcc )
36 import TyCon ( TyCon, tyConArity )
37 import Type ( Type, mkForAllTys, mkFunTy, mkFunTys, mkTyVarTys,
38 mkTyConApp, typePrimRep,
39 splitFunTy_maybe, splitAlgTyConApp_maybe, splitTyConApp,
42 import Unique ( Unique, mkPrimOpIdUnique )
43 import BasicTypes ( Arity, Boxity(..) )
44 import CStrings ( CLabelString, pprCLabelString )
45 import PrelNames ( pREL_GHC, pREL_GHC_Name )
47 import Util ( zipWithEqual )
51 %************************************************************************
53 \subsection[PrimOp-datatype]{Datatype for @PrimOp@ (an enumeration)}
55 %************************************************************************
57 These are in \tr{state-interface.verb} order.
63 #include "primop-data-decl.hs-incl"
64 | CCallOp CCall -- and don't forget to add CCall
67 Used for the Ord instance
70 primOpTag :: PrimOp -> Int
71 primOpTag op = iBox (tagOf_PrimOp op)
74 -- tagOf_PrimOp :: PrimOp -> FastInt
75 #include "primop-tag.hs-incl"
76 tagOf_PrimOp op = pprPanic# "tagOf_PrimOp: pattern-match" (ppr op)
79 instance Eq PrimOp where
80 op1 == op2 = tagOf_PrimOp op1 ==# tagOf_PrimOp op2
82 instance Ord PrimOp where
83 op1 < op2 = tagOf_PrimOp op1 <# tagOf_PrimOp op2
84 op1 <= op2 = tagOf_PrimOp op1 <=# tagOf_PrimOp op2
85 op1 >= op2 = tagOf_PrimOp op1 >=# tagOf_PrimOp op2
86 op1 > op2 = tagOf_PrimOp op1 ># tagOf_PrimOp op2
87 op1 `compare` op2 | op1 < op2 = LT
91 instance Outputable PrimOp where
94 instance Show PrimOp where
95 showsPrec p op = showsPrecSDoc p (pprPrimOp op)
98 An @Enum@-derived list would be better; meanwhile... (ToDo)
100 allThePrimOps :: [PrimOp]
102 #include "primop-list.hs-incl"
103 -- Doesn't include CCall, which is really a family of primops
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 str ty = Dyadic (mkVarOcc str) ty
136 mkMonadic str ty = Monadic (mkVarOcc str) ty
137 mkCompare str ty = Compare (mkVarOcc str) ty
138 mkGenPrimOp str tvs tys ty = GenPrimOp (mkVarOcc str) tvs tys ty
141 %************************************************************************
143 \subsubsection{Strictness}
145 %************************************************************************
147 Not all primops are strict!
150 primOpStrictness :: PrimOp -> Arity -> StrictnessInfo
151 -- See Demand.StrictnessInfo for discussion of what the results
152 -- The arity should be the arity of the primop; that's why
153 -- this function isn't exported.
154 #include "primop-strictness.hs-incl"
157 %************************************************************************
159 \subsubsection[PrimOp-comparison]{PrimOpInfo basic comparison ops}
161 %************************************************************************
163 @primOpInfo@ gives all essential information (from which everything
164 else, notably a type, can be constructed) for each @PrimOp@.
167 primOpInfo :: PrimOp -> PrimOpInfo
168 #include "primop-primop-info.hs-incl"
171 Here are a load of comments from the old primOp info:
173 A @Word#@ is an unsigned @Int#@.
175 @decodeFloat#@ is given w/ Integer-stuff (it's similar).
177 @decodeDouble#@ is given w/ Integer-stuff (it's similar).
179 Decoding of floating-point numbers is sorta Integer-related. Encoding
180 is done with plain ccalls now (see PrelNumExtra.lhs).
182 A @Weak@ Pointer is created by the @mkWeak#@ primitive:
184 mkWeak# :: k -> v -> f -> State# RealWorld
185 -> (# State# RealWorld, Weak# v #)
187 In practice, you'll use the higher-level
189 data Weak v = Weak# v
190 mkWeak :: k -> v -> IO () -> IO (Weak v)
192 The following operation dereferences a weak pointer. The weak pointer
193 may have been finalized, so the operation returns a result code which
194 must be inspected before looking at the dereferenced value.
196 deRefWeak# :: Weak# v -> State# RealWorld ->
197 (# State# RealWorld, v, Int# #)
199 Only look at v if the Int# returned is /= 0 !!
201 The higher-level op is
203 deRefWeak :: Weak v -> IO (Maybe v)
205 Weak pointers can be finalized early by using the finalize# operation:
207 finalizeWeak# :: Weak# v -> State# RealWorld ->
208 (# State# RealWorld, Int#, IO () #)
210 The Int# returned is either
212 0 if the weak pointer has already been finalized, or it has no
213 finalizer (the third component is then invalid).
215 1 if the weak pointer is still alive, with the finalizer returned
216 as the third component.
218 A {\em stable name/pointer} is an index into a table of stable name
219 entries. Since the garbage collector is told about stable pointers,
220 it is safe to pass a stable pointer to external systems such as C
224 makeStablePtr# :: a -> State# RealWorld -> (# State# RealWorld, StablePtr# a #)
225 freeStablePtr :: StablePtr# a -> State# RealWorld -> State# RealWorld
226 deRefStablePtr# :: StablePtr# a -> State# RealWorld -> (# State# RealWorld, a #)
227 eqStablePtr# :: StablePtr# a -> StablePtr# a -> Int#
230 It may seem a bit surprising that @makeStablePtr#@ is a @IO@
231 operation since it doesn't (directly) involve IO operations. The
232 reason is that if some optimisation pass decided to duplicate calls to
233 @makeStablePtr#@ and we only pass one of the stable pointers over, a
234 massive space leak can result. Putting it into the IO monad
235 prevents this. (Another reason for putting them in a monad is to
236 ensure correct sequencing wrt the side-effecting @freeStablePtr@
239 An important property of stable pointers is that if you call
240 makeStablePtr# twice on the same object you get the same stable
243 Note that we can implement @freeStablePtr#@ using @_ccall_@ (and,
244 besides, it's not likely to be used from Haskell) so it's not a
247 Question: Why @RealWorld@ - won't any instance of @_ST@ do the job? [ADR]
252 A stable name is like a stable pointer, but with three important differences:
254 (a) You can't deRef one to get back to the original object.
255 (b) You can convert one to an Int.
256 (c) You don't need to 'freeStableName'
258 The existence of a stable name doesn't guarantee to keep the object it
259 points to alive (unlike a stable pointer), hence (a).
263 (a) makeStableName always returns the same value for a given
264 object (same as stable pointers).
266 (b) if two stable names are equal, it implies that the objects
267 from which they were created were the same.
269 (c) stableNameToInt always returns the same Int for a given
273 [Alastair Reid is to blame for this!]
275 These days, (Glasgow) Haskell seems to have a bit of everything from
276 other languages: strict operations, mutable variables, sequencing,
277 pointers, etc. About the only thing left is LISP's ability to test
278 for pointer equality. So, let's add it in!
281 reallyUnsafePtrEquality :: a -> a -> Int#
284 which tests any two closures (of the same type) to see if they're the
285 same. (Returns $0$ for @False@, $\neq 0$ for @True@ - to avoid
286 difficulties of trying to box up the result.)
288 NB This is {\em really unsafe\/} because even something as trivial as
289 a garbage collection might change the answer by removing indirections.
290 Still, no-one's forcing you to use it. If you're worried about little
291 things like loss of referential transparency, you might like to wrap
292 it all up in a monad-like thing as John O'Donnell and John Hughes did
293 for non-determinism (1989 (Fraserburgh) Glasgow FP Workshop
296 I'm thinking of using it to speed up a critical equality test in some
297 graphics stuff in a context where the possibility of saying that
298 denotationally equal things aren't isn't a problem (as long as it
299 doesn't happen too often.) ADR
301 To Will: Jim said this was already in, but I can't see it so I'm
302 adding it. Up to you whether you add it. (Note that this could have
303 been readily implemented using a @veryDangerousCCall@ before they were
307 -- HWL: The first 4 Int# in all par... annotations denote:
308 -- name, granularity info, size of result, degree of parallelism
309 -- Same structure as _seq_ i.e. returns Int#
310 -- KSW: v, the second arg in parAt# and parAtForNow#, is used only to determine
311 -- `the processor containing the expression v'; it is not evaluated
313 These primops are pretty wierd.
315 dataToTag# :: a -> Int (arg must be an evaluated data type)
316 tagToEnum# :: Int -> a (result type must be an enumerated type)
318 The constraints aren't currently checked by the front end, but the
319 code generator will fall over if they aren't satisfied.
323 primOpInfo op = pprPanic "primOpInfo:" (ppr op)
327 %************************************************************************
329 \subsubsection[PrimOp-ool]{Which PrimOps are out-of-line}
331 %************************************************************************
333 Some PrimOps need to be called out-of-line because they either need to
334 perform a heap check or they block.
337 primOpOutOfLine (CCallOp c_call) = ccallMayGC c_call
338 #include "primop-out-of-line.hs-incl"
342 primOpOkForSpeculation
343 ~~~~~~~~~~~~~~~~~~~~~~
344 Sometimes we may choose to execute a PrimOp even though it isn't
345 certain that its result will be required; ie execute them
346 ``speculatively''. The same thing as ``cheap eagerness.'' Usually
347 this is OK, because PrimOps are usually cheap, but it isn't OK for
348 (a)~expensive PrimOps and (b)~PrimOps which can fail.
350 PrimOps that have side effects also should not be executed speculatively.
352 Ok-for-speculation also means that it's ok *not* to execute the
356 Here the result is not used, so we can discard the primop. Anything
357 that has side effects mustn't be dicarded in this way, of course!
359 See also @primOpIsCheap@ (below).
363 primOpOkForSpeculation :: PrimOp -> Bool
364 -- See comments with CoreUtils.exprOkForSpeculation
365 primOpOkForSpeculation op
366 = not (primOpHasSideEffects op || primOpOutOfLine op || primOpCanFail op)
372 @primOpIsCheap@, as used in \tr{SimplUtils.lhs}. For now (HACK
373 WARNING), we just borrow some other predicates for a
374 what-should-be-good-enough test. "Cheap" means willing to call it more
375 than once. Evaluation order is unaffected.
378 primOpIsCheap :: PrimOp -> Bool
379 primOpIsCheap op = False
380 -- March 2001: be less eager to inline PrimOps
381 -- Was: not (primOpHasSideEffects op || primOpOutOfLine op)
386 primOpIsDupable means that the use of the primop is small enough to
387 duplicate into different case branches. See CoreUtils.exprIsDupable.
390 primOpIsDupable :: PrimOp -> Bool
391 -- See comments with CoreUtils.exprIsDupable
392 -- We say it's dupable it isn't implemented by a C call with a wrapper
393 primOpIsDupable op = not (primOpNeedsWrapper op)
398 primOpCanFail :: PrimOp -> Bool
399 #include "primop-can-fail.hs-incl"
402 And some primops have side-effects and so, for example, must not be
406 primOpHasSideEffects :: PrimOp -> Bool
407 primOpHasSideEffects (CCallOp _) = True
408 #include "primop-has-side-effects.hs-incl"
411 Inline primitive operations that perform calls need wrappers to save
412 any live variables that are stored in caller-saves registers.
415 primOpNeedsWrapper :: PrimOp -> Bool
416 primOpNeedsWrapper (CCallOp _) = True
417 #include "primop-needs-wrapper.hs-incl"
421 primOpArity :: PrimOp -> Arity
423 = case (primOpInfo op) of
427 GenPrimOp occ tyvars arg_tys res_ty -> length arg_tys
429 primOpType :: PrimOp -> Type -- you may want to use primOpSig instead
431 = case (primOpInfo op) of
432 Dyadic occ ty -> dyadic_fun_ty ty
433 Monadic occ ty -> monadic_fun_ty ty
434 Compare occ ty -> compare_fun_ty ty
436 GenPrimOp occ tyvars arg_tys res_ty ->
437 mkForAllTys tyvars (mkFunTys arg_tys res_ty)
439 mkPrimOpIdName :: PrimOp -> Name
440 -- Make the name for the PrimOp's Id
441 -- We have to pass in the Id itself because it's a WiredInId
442 -- and hence recursive
444 = mkWiredInName pREL_GHC (primOpOcc op) (mkPrimOpIdUnique (primOpTag op))
446 primOpRdrName :: PrimOp -> RdrName
447 primOpRdrName op = mkRdrOrig pREL_GHC_Name (primOpOcc op)
449 primOpOcc :: PrimOp -> OccName
450 primOpOcc op = case (primOpInfo op) of
454 GenPrimOp occ _ _ _ -> occ
456 -- primOpSig is like primOpType but gives the result split apart:
457 -- (type variables, argument types, result type)
458 -- It also gives arity, strictness info
460 primOpSig :: PrimOp -> ([TyVar], [Type], Type, Arity, StrictnessInfo)
462 = (tyvars, arg_tys, res_ty, arity, primOpStrictness op arity)
464 arity = length arg_tys
465 (tyvars, arg_tys, res_ty)
466 = case (primOpInfo op) of
467 Monadic occ ty -> ([], [ty], ty )
468 Dyadic occ ty -> ([], [ty,ty], ty )
469 Compare occ ty -> ([], [ty,ty], boolTy)
470 GenPrimOp occ tyvars arg_tys res_ty
471 -> (tyvars, arg_tys, res_ty)
473 -- primOpUsg is like primOpSig but the types it yields are the
474 -- appropriate sigma (i.e., usage-annotated) types,
475 -- as required by the UsageSP inference.
477 primOpUsg :: PrimOp -> ([TyVar],[Type],Type)
478 primOpUsg p@(CCallOp _) = mangle p [] mkM
479 #include "primop-usage.hs-incl"
481 -- Things with no Haskell pointers inside: in actuality, usages are
482 -- irrelevant here (hence it doesn't matter that some of these
483 -- apparently permit duplication; since such arguments are never
484 -- ENTERed anyway, the usage annotation they get is entirely irrelevant
485 -- except insofar as it propagates to infect other values that *are*
489 -- Helper bits & pieces for usage info.
491 mkZ = mkUTy usOnce -- pointed argument used zero
492 mkO = mkUTy usOnce -- pointed argument used once
493 mkM = mkUTy usMany -- pointed argument used multiply
494 mkP = mkUTy usOnce -- unpointed argument
495 mkR = mkUTy usMany -- unpointed result
498 = case primOpSig op of
499 (tyvars, arg_tys, res_ty, _, _)
500 -> (tyvars, map mkP arg_tys, mkR res_ty)
503 = case primOpSig op of
504 (tyvars, arg_tys, res_ty, _, _)
505 -> (tyvars, zipWithEqual "primOpUsg" ($) fs arg_tys, g res_ty)
508 = case splitFunTy_maybe ty of
509 Just (a,b) -> mkFunTy (f a) (g b)
510 Nothing -> pprPanic "primOpUsg:inFun" (ppr op <+> ppr ty)
513 = case splitTyConApp ty of
514 (tc,tys) -> ASSERT( tc == tupleTyCon Unboxed (length fs) )
515 mkTupleTy Unboxed (length fs) (zipWithEqual "primOpUsg" ($) fs tys)
519 data PrimOpResultInfo
520 = ReturnsPrim PrimRep
523 -- Some PrimOps need not return a manifest primitive or algebraic value
524 -- (i.e. they might return a polymorphic value). These PrimOps *must*
525 -- be out of line, or the code generator won't work.
527 getPrimOpResultInfo :: PrimOp -> PrimOpResultInfo
528 getPrimOpResultInfo (CCallOp _)
529 = ReturnsAlg unboxedPairTyCon
530 getPrimOpResultInfo op
531 = case (primOpInfo op) of
532 Dyadic _ ty -> ReturnsPrim (typePrimRep ty)
533 Monadic _ ty -> ReturnsPrim (typePrimRep ty)
534 Compare _ ty -> ReturnsAlg boolTyCon
535 GenPrimOp _ _ _ ty ->
536 let rep = typePrimRep ty in
538 PtrRep -> case splitAlgTyConApp_maybe ty of
539 Nothing -> pprPanic "getPrimOpResultInfo"
541 Just (tc,_,_) -> ReturnsAlg tc
542 other -> ReturnsPrim other
545 The commutable ops are those for which we will try to move constants
546 to the right hand side for strength reduction.
549 commutableOp :: PrimOp -> Bool
550 #include "primop-commutable.hs-incl"
555 mkPrimTyApp :: [TyVar] -> PrimRep -> ([TyVar], Type)
556 -- CharRep --> ([], Char#)
557 -- StablePtrRep --> ([a], StablePtr# a)
559 = (forall_tvs, mkTyConApp tycon (mkTyVarTys forall_tvs))
561 tycon = primRepTyCon kind
562 forall_tvs = take (tyConArity tycon) tvs
564 dyadic_fun_ty ty = mkFunTys [ty, ty] ty
565 monadic_fun_ty ty = mkFunTy ty ty
566 compare_fun_ty ty = mkFunTys [ty, ty] boolTy
571 pprPrimOp :: PrimOp -> SDoc
573 pprPrimOp (CCallOp c_call) = pprCCallOp c_call
575 = getPprStyle $ \ sty ->
576 if ifaceStyle sty then -- For interfaces Print it qualified with PrelGHC.
577 ptext SLIT("PrelGHC.") <> pprOccName occ
581 occ = primOpOcc other_op
585 %************************************************************************
587 \subsubsection{CCalls}
589 %************************************************************************
591 A special ``trap-door'' to use in making calls direct to C functions:
595 Bool -- True <=> really a "casm"
596 Bool -- True <=> might invoke Haskell GC
597 CallConv -- calling convention to use.
601 = StaticTarget CLabelString -- An "unboxed" ccall# to `fn'.
602 | DynamicTarget Unique -- First argument (an Addr#) is the function pointer
603 -- (unique is used to generate a 'typedef' to cast
604 -- the function pointer if compiling the ccall# down to
605 -- .hc code - can't do this inline for tedious reasons.)
607 instance Eq CCallTarget where
608 (StaticTarget l1) == (StaticTarget l2) = l1 == l2
609 (DynamicTarget _) == (DynamicTarget _) = True
610 -- Ignore the arbitrary unique; this is important when comparing
611 -- a dynamic ccall read from an interface file A.hi with the
612 -- one constructed from A.hs, when deciding whether the interface
616 ccallMayGC :: CCall -> Bool
617 ccallMayGC (CCall _ _ may_gc _) = may_gc
619 ccallIsCasm :: CCall -> Bool
620 ccallIsCasm (CCall _ c_asm _ _) = c_asm
622 isDynamicTarget (DynamicTarget _) = True
623 isDynamicTarget (StaticTarget _) = False
625 dynamicTarget :: CCallTarget
626 dynamicTarget = DynamicTarget (panic "Unique in DynamicTarget not yet set")
627 -- The unique is really only to do with code generation, so it
628 -- is only set in CoreToStg; before then it's just an error message
630 setCCallUnique :: CCall -> Unique -> CCall
631 setCCallUnique (CCall (DynamicTarget _) is_asm may_gc cconv) uniq
632 = CCall (DynamicTarget uniq) is_asm may_gc cconv
633 setCCallUnique ccall uniq = ccall
637 pprCCallOp (CCall fun is_casm may_gc cconv)
638 = hcat [ ifPprDebug callconv
640 , text before , ppr_fun , after]
642 callconv = text "{-" <> pprCallConv cconv <> text "-}"
645 | is_casm && may_gc = "casm_GC ``"
646 | is_casm = "casm ``"
647 | may_gc = "ccall_GC "
648 | otherwise = "ccall "
651 | is_casm = text "''"
654 ppr_dyn = case fun of
655 DynamicTarget _ -> text "dyn_"
658 ppr_fun = case fun of
659 DynamicTarget _ -> text "\"\""
660 StaticTarget fn -> pprCLabelString fn