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 = primOpIsCheap op && not (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 -- See comments with CoreUtils.exprOkForSpeculation
380 primOpIsCheap op = not (primOpHasSideEffects op || primOpOutOfLine op)
385 primOpIsDupable means that the use of the primop is small enough to
386 duplicate into different case branches. See CoreUtils.exprIsDupable.
389 primOpIsDupable :: PrimOp -> Bool
390 -- See comments with CoreUtils.exprIsDupable
391 -- We say it's dupable it isn't implemented by a C call with a wrapper
392 primOpIsDupable op = not (primOpNeedsWrapper op)
397 primOpCanFail :: PrimOp -> Bool
398 #include "primop-can-fail.hs-incl"
401 And some primops have side-effects and so, for example, must not be
405 primOpHasSideEffects :: PrimOp -> Bool
406 primOpHasSideEffects (CCallOp _) = True
407 #include "primop-has-side-effects.hs-incl"
410 Inline primitive operations that perform calls need wrappers to save
411 any live variables that are stored in caller-saves registers.
414 primOpNeedsWrapper :: PrimOp -> Bool
415 primOpNeedsWrapper (CCallOp _) = True
416 #include "primop-needs-wrapper.hs-incl"
420 primOpArity :: PrimOp -> Arity
422 = case (primOpInfo op) of
426 GenPrimOp occ tyvars arg_tys res_ty -> length arg_tys
428 primOpType :: PrimOp -> Type -- you may want to use primOpSig instead
430 = case (primOpInfo op) of
431 Dyadic occ ty -> dyadic_fun_ty ty
432 Monadic occ ty -> monadic_fun_ty ty
433 Compare occ ty -> compare_fun_ty ty
435 GenPrimOp occ tyvars arg_tys res_ty ->
436 mkForAllTys tyvars (mkFunTys arg_tys res_ty)
438 mkPrimOpIdName :: PrimOp -> Name
439 -- Make the name for the PrimOp's Id
440 -- We have to pass in the Id itself because it's a WiredInId
441 -- and hence recursive
443 = mkWiredInName pREL_GHC (primOpOcc op) (mkPrimOpIdUnique (primOpTag op))
445 primOpRdrName :: PrimOp -> RdrName
446 primOpRdrName op = mkRdrOrig pREL_GHC_Name (primOpOcc op)
448 primOpOcc :: PrimOp -> OccName
449 primOpOcc op = case (primOpInfo op) of
453 GenPrimOp occ _ _ _ -> occ
455 -- primOpSig is like primOpType but gives the result split apart:
456 -- (type variables, argument types, result type)
457 -- It also gives arity, strictness info
459 primOpSig :: PrimOp -> ([TyVar], [Type], Type, Arity, StrictnessInfo)
461 = (tyvars, arg_tys, res_ty, arity, primOpStrictness op arity)
463 arity = length arg_tys
464 (tyvars, arg_tys, res_ty)
465 = case (primOpInfo op) of
466 Monadic occ ty -> ([], [ty], ty )
467 Dyadic occ ty -> ([], [ty,ty], ty )
468 Compare occ ty -> ([], [ty,ty], boolTy)
469 GenPrimOp occ tyvars arg_tys res_ty
470 -> (tyvars, arg_tys, res_ty)
472 -- primOpUsg is like primOpSig but the types it yields are the
473 -- appropriate sigma (i.e., usage-annotated) types,
474 -- as required by the UsageSP inference.
476 primOpUsg :: PrimOp -> ([TyVar],[Type],Type)
477 primOpUsg p@(CCallOp _) = mangle p [] mkM
478 #include "primop-usage.hs-incl"
480 -- Things with no Haskell pointers inside: in actuality, usages are
481 -- irrelevant here (hence it doesn't matter that some of these
482 -- apparently permit duplication; since such arguments are never
483 -- ENTERed anyway, the usage annotation they get is entirely irrelevant
484 -- except insofar as it propagates to infect other values that *are*
488 -- Helper bits & pieces for usage info.
490 mkZ = mkUTy usOnce -- pointed argument used zero
491 mkO = mkUTy usOnce -- pointed argument used once
492 mkM = mkUTy usMany -- pointed argument used multiply
493 mkP = mkUTy usOnce -- unpointed argument
494 mkR = mkUTy usMany -- unpointed result
497 = case primOpSig op of
498 (tyvars, arg_tys, res_ty, _, _)
499 -> (tyvars, map mkP arg_tys, mkR res_ty)
502 = case primOpSig op of
503 (tyvars, arg_tys, res_ty, _, _)
504 -> (tyvars, zipWithEqual "primOpUsg" ($) fs arg_tys, g res_ty)
507 = case splitFunTy_maybe ty of
508 Just (a,b) -> mkFunTy (f a) (g b)
509 Nothing -> pprPanic "primOpUsg:inFun" (ppr op <+> ppr ty)
512 = case splitTyConApp ty of
513 (tc,tys) -> ASSERT( tc == tupleTyCon Unboxed (length fs) )
514 mkTupleTy Unboxed (length fs) (zipWithEqual "primOpUsg" ($) fs tys)
518 data PrimOpResultInfo
519 = ReturnsPrim PrimRep
522 -- Some PrimOps need not return a manifest primitive or algebraic value
523 -- (i.e. they might return a polymorphic value). These PrimOps *must*
524 -- be out of line, or the code generator won't work.
526 getPrimOpResultInfo :: PrimOp -> PrimOpResultInfo
527 getPrimOpResultInfo (CCallOp _)
528 = ReturnsAlg unboxedPairTyCon
529 getPrimOpResultInfo op
530 = case (primOpInfo op) of
531 Dyadic _ ty -> ReturnsPrim (typePrimRep ty)
532 Monadic _ ty -> ReturnsPrim (typePrimRep ty)
533 Compare _ ty -> ReturnsAlg boolTyCon
534 GenPrimOp _ _ _ ty ->
535 let rep = typePrimRep ty in
537 PtrRep -> case splitAlgTyConApp_maybe ty of
538 Nothing -> pprPanic "getPrimOpResultInfo"
540 Just (tc,_,_) -> ReturnsAlg tc
541 other -> ReturnsPrim other
544 The commutable ops are those for which we will try to move constants
545 to the right hand side for strength reduction.
548 commutableOp :: PrimOp -> Bool
549 #include "primop-commutable.hs-incl"
554 mkPrimTyApp :: [TyVar] -> PrimRep -> ([TyVar], Type)
555 -- CharRep --> ([], Char#)
556 -- StablePtrRep --> ([a], StablePtr# a)
558 = (forall_tvs, mkTyConApp tycon (mkTyVarTys forall_tvs))
560 tycon = primRepTyCon kind
561 forall_tvs = take (tyConArity tycon) tvs
563 dyadic_fun_ty ty = mkFunTys [ty, ty] ty
564 monadic_fun_ty ty = mkFunTy ty ty
565 compare_fun_ty ty = mkFunTys [ty, ty] boolTy
570 pprPrimOp :: PrimOp -> SDoc
572 pprPrimOp (CCallOp c_call) = pprCCallOp c_call
574 = getPprStyle $ \ sty ->
575 if ifaceStyle sty then -- For interfaces Print it qualified with PrelGHC.
576 ptext SLIT("PrelGHC.") <> pprOccName occ
580 occ = primOpOcc other_op
584 %************************************************************************
586 \subsubsection{CCalls}
588 %************************************************************************
590 A special ``trap-door'' to use in making calls direct to C functions:
594 Bool -- True <=> really a "casm"
595 Bool -- True <=> might invoke Haskell GC
596 CallConv -- calling convention to use.
600 = StaticTarget CLabelString -- An "unboxed" ccall# to `fn'.
601 | DynamicTarget Unique -- First argument (an Addr#) is the function pointer
602 -- (unique is used to generate a 'typedef' to cast
603 -- the function pointer if compiling the ccall# down to
604 -- .hc code - can't do this inline for tedious reasons.)
606 instance Eq CCallTarget where
607 (StaticTarget l1) == (StaticTarget l2) = l1 == l2
608 (DynamicTarget _) == (DynamicTarget _) = True
609 -- Ignore the arbitrary unique; this is important when comparing
610 -- a dynamic ccall read from an interface file A.hi with the
611 -- one constructed from A.hs, when deciding whether the interface
615 ccallMayGC :: CCall -> Bool
616 ccallMayGC (CCall _ _ may_gc _) = may_gc
618 ccallIsCasm :: CCall -> Bool
619 ccallIsCasm (CCall _ c_asm _ _) = c_asm
621 isDynamicTarget (DynamicTarget _) = True
622 isDynamicTarget (StaticTarget _) = False
624 dynamicTarget :: CCallTarget
625 dynamicTarget = DynamicTarget (panic "Unique in DynamicTarget not yet set")
626 -- The unique is really only to do with code generation, so it
627 -- is only set in CoreToStg; before then it's just an error message
629 setCCallUnique :: CCall -> Unique -> CCall
630 setCCallUnique (CCall (DynamicTarget _) is_asm may_gc cconv) uniq
631 = CCall (DynamicTarget uniq) is_asm may_gc cconv
632 setCCallUnique ccall uniq = ccall
636 pprCCallOp (CCall fun is_casm may_gc cconv)
637 = hcat [ ifPprDebug callconv
639 , text before , ppr_fun , after]
641 callconv = text "{-" <> pprCallConv cconv <> text "-}"
644 | is_casm && may_gc = "casm_GC ``"
645 | is_casm = "casm ``"
646 | may_gc = "ccall_GC "
647 | otherwise = "ccall "
650 | is_casm = text "''"
653 ppr_dyn = case fun of
654 DynamicTarget _ -> text "dyn_"
657 ppr_fun = case fun of
658 DynamicTarget _ -> text "\"\""
659 StaticTarget fn -> pprCLabelString fn