[project @ 2001-12-10 14:07:30 by simonmar]
[ghc-hetmet.git] / ghc / compiler / prelude / PrimOp.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
3 %
4 \section[PrimOp]{Primitive operations (machine-level)}
5
6 \begin{code}
7 module PrimOp (
8         PrimOp(..), allThePrimOps,
9         primOpType, primOpSig, primOpUsg, primOpArity,
10         mkPrimOpIdName, primOpRdrName, primOpTag, primOpOcc,
11
12         commutableOp,
13
14         primOpOutOfLine, primOpNeedsWrapper, 
15         primOpOkForSpeculation, primOpIsCheap, primOpIsDupable,
16         primOpHasSideEffects,
17
18         getPrimOpResultInfo,  PrimOpResultInfo(..)
19     ) where
20
21 #include "HsVersions.h"
22
23 import PrimRep          -- most of it
24 import TysPrim
25 import TysWiredIn
26
27 import NewDemand
28 import Var              ( TyVar )
29 import Name             ( Name, mkWiredInName )
30 import RdrName          ( RdrName, mkRdrOrig )
31 import OccName          ( OccName, pprOccName, mkVarOcc )
32 import TyCon            ( TyCon, isPrimTyCon, tyConPrimRep )
33 import Type             ( Type, mkForAllTys, mkFunTy, mkFunTys, typePrimRep,
34                           splitFunTy_maybe, tyConAppTyCon, splitTyConApp,
35                           mkUTy, usOnce, usMany
36                         )
37 import PprType          () -- get at Outputable Type instance.
38 import Unique           ( mkPrimOpIdUnique )
39 import BasicTypes       ( Arity, Boxity(..) )
40 import PrelNames        ( pREL_GHC, pREL_GHC_Name )
41 import Outputable
42 import Util             ( zipWithEqual )
43 import FastTypes
44 \end{code}
45
46 %************************************************************************
47 %*                                                                      *
48 \subsection[PrimOp-datatype]{Datatype for @PrimOp@ (an enumeration)}
49 %*                                                                      *
50 %************************************************************************
51
52 These are in \tr{state-interface.verb} order.
53
54 \begin{code}
55
56 -- supplies: 
57 -- data PrimOp = ...
58 #include "primop-data-decl.hs-incl"
59 \end{code}
60
61 Used for the Ord instance
62
63 \begin{code}
64 primOpTag :: PrimOp -> Int
65 primOpTag op = iBox (tagOf_PrimOp op)
66
67 -- supplies   
68 -- tagOf_PrimOp :: PrimOp -> FastInt
69 #include "primop-tag.hs-incl"
70 tagOf_PrimOp op = pprPanic# "tagOf_PrimOp: pattern-match" (ppr op)
71
72
73 instance Eq PrimOp where
74     op1 == op2 = tagOf_PrimOp op1 ==# tagOf_PrimOp op2
75
76 instance Ord PrimOp where
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 >  op2 =  tagOf_PrimOp op1 ># tagOf_PrimOp op2
81     op1 `compare` op2 | op1 < op2  = LT
82                       | op1 == op2 = EQ
83                       | otherwise  = GT
84
85 instance Outputable PrimOp where
86     ppr op = pprPrimOp op
87
88 instance Show PrimOp where
89     showsPrec p op = showsPrecSDoc p (pprPrimOp op)
90 \end{code}
91
92 An @Enum@-derived list would be better; meanwhile... (ToDo)
93 \begin{code}
94 allThePrimOps :: [PrimOp]
95 allThePrimOps =
96 #include "primop-list.hs-incl"
97 \end{code}
98
99 %************************************************************************
100 %*                                                                      *
101 \subsection[PrimOp-info]{The essential info about each @PrimOp@}
102 %*                                                                      *
103 %************************************************************************
104
105 The @String@ in the @PrimOpInfos@ is the ``base name'' by which the user may
106 refer to the primitive operation.  The conventional \tr{#}-for-
107 unboxed ops is added on later.
108
109 The reason for the funny characters in the names is so we do not
110 interfere with the programmer's Haskell name spaces.
111
112 We use @PrimKinds@ for the ``type'' information, because they're
113 (slightly) more convenient to use than @TyCons@.
114 \begin{code}
115 data PrimOpInfo
116   = Dyadic      OccName         -- string :: T -> T -> T
117                 Type
118   | Monadic     OccName         -- string :: T -> T
119                 Type
120   | Compare     OccName         -- string :: T -> T -> Bool
121                 Type
122
123   | GenPrimOp   OccName         -- string :: \/a1..an . T1 -> .. -> Tk -> T
124                 [TyVar] 
125                 [Type] 
126                 Type 
127
128 mkDyadic str  ty = Dyadic  (mkVarOcc str) ty
129 mkMonadic str ty = Monadic (mkVarOcc str) ty
130 mkCompare str ty = Compare (mkVarOcc str) ty
131 mkGenPrimOp str tvs tys ty = GenPrimOp (mkVarOcc str) tvs tys ty
132 \end{code}
133
134 %************************************************************************
135 %*                                                                      *
136 \subsubsection{Strictness}
137 %*                                                                      *
138 %************************************************************************
139
140 Not all primops are strict!
141
142 \begin{code}
143 primOpStrictness :: PrimOp -> Arity -> StrictSig
144         -- See Demand.StrictnessInfo for discussion of what the results
145         -- The arity should be the arity of the primop; that's why
146         -- this function isn't exported.
147 #include "primop-strictness.hs-incl"
148 \end{code}
149
150 %************************************************************************
151 %*                                                                      *
152 \subsubsection[PrimOp-comparison]{PrimOpInfo basic comparison ops}
153 %*                                                                      *
154 %************************************************************************
155
156 @primOpInfo@ gives all essential information (from which everything
157 else, notably a type, can be constructed) for each @PrimOp@.
158
159 \begin{code}
160 primOpInfo :: PrimOp -> PrimOpInfo
161 #include "primop-primop-info.hs-incl"
162 \end{code}
163
164 Here are a load of comments from the old primOp info:
165
166 A @Word#@ is an unsigned @Int#@.
167
168 @decodeFloat#@ is given w/ Integer-stuff (it's similar).
169
170 @decodeDouble#@ is given w/ Integer-stuff (it's similar).
171
172 Decoding of floating-point numbers is sorta Integer-related.  Encoding
173 is done with plain ccalls now (see PrelNumExtra.lhs).
174
175 A @Weak@ Pointer is created by the @mkWeak#@ primitive:
176
177         mkWeak# :: k -> v -> f -> State# RealWorld 
178                         -> (# State# RealWorld, Weak# v #)
179
180 In practice, you'll use the higher-level
181
182         data Weak v = Weak# v
183         mkWeak :: k -> v -> IO () -> IO (Weak v)
184
185 The following operation dereferences a weak pointer.  The weak pointer
186 may have been finalized, so the operation returns a result code which
187 must be inspected before looking at the dereferenced value.
188
189         deRefWeak# :: Weak# v -> State# RealWorld ->
190                         (# State# RealWorld, v, Int# #)
191
192 Only look at v if the Int# returned is /= 0 !!
193
194 The higher-level op is
195
196         deRefWeak :: Weak v -> IO (Maybe v)
197
198 Weak pointers can be finalized early by using the finalize# operation:
199         
200         finalizeWeak# :: Weak# v -> State# RealWorld -> 
201                            (# State# RealWorld, Int#, IO () #)
202
203 The Int# returned is either
204
205         0 if the weak pointer has already been finalized, or it has no
206           finalizer (the third component is then invalid).
207
208         1 if the weak pointer is still alive, with the finalizer returned
209           as the third component.
210
211 A {\em stable name/pointer} is an index into a table of stable name
212 entries.  Since the garbage collector is told about stable pointers,
213 it is safe to pass a stable pointer to external systems such as C
214 routines.
215
216 \begin{verbatim}
217 makeStablePtr#  :: a -> State# RealWorld -> (# State# RealWorld, StablePtr# a #)
218 freeStablePtr   :: StablePtr# a -> State# RealWorld -> State# RealWorld
219 deRefStablePtr# :: StablePtr# a -> State# RealWorld -> (# State# RealWorld, a #)
220 eqStablePtr#    :: StablePtr# a -> StablePtr# a -> Int#
221 \end{verbatim}
222
223 It may seem a bit surprising that @makeStablePtr#@ is a @IO@
224 operation since it doesn't (directly) involve IO operations.  The
225 reason is that if some optimisation pass decided to duplicate calls to
226 @makeStablePtr#@ and we only pass one of the stable pointers over, a
227 massive space leak can result.  Putting it into the IO monad
228 prevents this.  (Another reason for putting them in a monad is to
229 ensure correct sequencing wrt the side-effecting @freeStablePtr@
230 operation.)
231
232 An important property of stable pointers is that if you call
233 makeStablePtr# twice on the same object you get the same stable
234 pointer back.
235
236 Note that we can implement @freeStablePtr#@ using @_ccall_@ (and,
237 besides, it's not likely to be used from Haskell) so it's not a
238 primop.
239
240 Question: Why @RealWorld@ - won't any instance of @_ST@ do the job? [ADR]
241
242 Stable Names
243 ~~~~~~~~~~~~
244
245 A stable name is like a stable pointer, but with three important differences:
246
247         (a) You can't deRef one to get back to the original object.
248         (b) You can convert one to an Int.
249         (c) You don't need to 'freeStableName'
250
251 The existence of a stable name doesn't guarantee to keep the object it
252 points to alive (unlike a stable pointer), hence (a).
253
254 Invariants:
255         
256         (a) makeStableName always returns the same value for a given
257             object (same as stable pointers).
258
259         (b) if two stable names are equal, it implies that the objects
260             from which they were created were the same.
261
262         (c) stableNameToInt always returns the same Int for a given
263             stable name.
264
265
266 -- HWL: The first 4 Int# in all par... annotations denote:
267 --   name, granularity info, size of result, degree of parallelism
268 --      Same  structure as _seq_ i.e. returns Int#
269 -- KSW: v, the second arg in parAt# and parAtForNow#, is used only to determine
270 --   `the processor containing the expression v'; it is not evaluated
271
272 These primops are pretty wierd.
273
274         dataToTag# :: a -> Int    (arg must be an evaluated data type)
275         tagToEnum# :: Int -> a    (result type must be an enumerated type)
276
277 The constraints aren't currently checked by the front end, but the
278 code generator will fall over if they aren't satisfied.
279
280 \begin{code}
281 #ifdef DEBUG
282 primOpInfo op = pprPanic "primOpInfo:" (ppr op)
283 #endif
284 \end{code}
285
286 %************************************************************************
287 %*                                                                      *
288 \subsubsection[PrimOp-ool]{Which PrimOps are out-of-line}
289 %*                                                                      *
290 %************************************************************************
291
292 Some PrimOps need to be called out-of-line because they either need to
293 perform a heap check or they block.
294
295
296 \begin{code}
297 primOpOutOfLine :: PrimOp -> Bool
298 #include "primop-out-of-line.hs-incl"
299 \end{code}
300
301
302 primOpOkForSpeculation
303 ~~~~~~~~~~~~~~~~~~~~~~
304 Sometimes we may choose to execute a PrimOp even though it isn't
305 certain that its result will be required; ie execute them
306 ``speculatively''.  The same thing as ``cheap eagerness.'' Usually
307 this is OK, because PrimOps are usually cheap, but it isn't OK for
308 (a)~expensive PrimOps and (b)~PrimOps which can fail.
309
310 PrimOps that have side effects also should not be executed speculatively.
311
312 Ok-for-speculation also means that it's ok *not* to execute the
313 primop. For example
314         case op a b of
315           r -> 3
316 Here the result is not used, so we can discard the primop.  Anything
317 that has side effects mustn't be dicarded in this way, of course!
318
319 See also @primOpIsCheap@ (below).
320
321
322 \begin{code}
323 primOpOkForSpeculation :: PrimOp -> Bool
324         -- See comments with CoreUtils.exprOkForSpeculation
325 primOpOkForSpeculation op 
326   = not (primOpHasSideEffects op || primOpOutOfLine op || primOpCanFail op)
327 \end{code}
328
329
330 primOpIsCheap
331 ~~~~~~~~~~~~~
332 @primOpIsCheap@, as used in \tr{SimplUtils.lhs}.  For now (HACK
333 WARNING), we just borrow some other predicates for a
334 what-should-be-good-enough test.  "Cheap" means willing to call it more
335 than once.  Evaluation order is unaffected.
336
337 \begin{code}
338 primOpIsCheap :: PrimOp -> Bool
339 primOpIsCheap op = False
340         -- March 2001: be less eager to inline PrimOps
341         -- Was: not (primOpHasSideEffects op || primOpOutOfLine op)
342 \end{code}
343
344 primOpIsDupable
345 ~~~~~~~~~~~~~~~
346 primOpIsDupable means that the use of the primop is small enough to
347 duplicate into different case branches.  See CoreUtils.exprIsDupable.
348
349 \begin{code}
350 primOpIsDupable :: PrimOp -> Bool
351         -- See comments with CoreUtils.exprIsDupable
352         -- We say it's dupable it isn't implemented by a C call with a wrapper
353 primOpIsDupable op = not (primOpNeedsWrapper op)
354 \end{code}
355
356
357 \begin{code}
358 primOpCanFail :: PrimOp -> Bool
359 #include "primop-can-fail.hs-incl"
360 \end{code}
361
362 And some primops have side-effects and so, for example, must not be
363 duplicated.
364
365 \begin{code}
366 primOpHasSideEffects :: PrimOp -> Bool
367 #include "primop-has-side-effects.hs-incl"
368 \end{code}
369
370 Inline primitive operations that perform calls need wrappers to save
371 any live variables that are stored in caller-saves registers.
372
373 \begin{code}
374 primOpNeedsWrapper :: PrimOp -> Bool
375 #include "primop-needs-wrapper.hs-incl"
376 \end{code}
377
378 \begin{code}
379 primOpArity :: PrimOp -> Arity
380 primOpArity op 
381   = case (primOpInfo op) of
382       Monadic occ ty                      -> 1
383       Dyadic occ ty                       -> 2
384       Compare occ ty                      -> 2
385       GenPrimOp occ tyvars arg_tys res_ty -> length arg_tys
386                 
387 primOpType :: PrimOp -> Type  -- you may want to use primOpSig instead
388 primOpType op
389   = case (primOpInfo op) of
390       Dyadic occ ty ->      dyadic_fun_ty ty
391       Monadic occ ty ->     monadic_fun_ty ty
392       Compare occ ty ->     compare_fun_ty ty
393
394       GenPrimOp occ tyvars arg_tys res_ty -> 
395         mkForAllTys tyvars (mkFunTys arg_tys res_ty)
396
397 mkPrimOpIdName :: PrimOp -> Name
398         -- Make the name for the PrimOp's Id
399         -- We have to pass in the Id itself because it's a WiredInId
400         -- and hence recursive
401 mkPrimOpIdName op
402   = mkWiredInName pREL_GHC (primOpOcc op) (mkPrimOpIdUnique (primOpTag op))
403
404 primOpRdrName :: PrimOp -> RdrName 
405 primOpRdrName op = mkRdrOrig pREL_GHC_Name (primOpOcc op)
406
407 primOpOcc :: PrimOp -> OccName
408 primOpOcc op = case (primOpInfo op) of
409                               Dyadic    occ _     -> occ
410                               Monadic   occ _     -> occ
411                               Compare   occ _     -> occ
412                               GenPrimOp occ _ _ _ -> occ
413
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
417
418 primOpSig :: PrimOp -> ([TyVar], [Type], Type, Arity, StrictSig)
419 primOpSig op
420   = (tyvars, arg_tys, res_ty, arity, primOpStrictness op arity)
421   where
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
429                            -> (tyvars, arg_tys, res_ty)
430
431 -- primOpUsg is like primOpSig but the types it yields are the
432 -- appropriate sigma (i.e., usage-annotated) types,
433 -- as required by the UsageSP inference.
434
435 primOpUsg :: PrimOp -> ([TyVar],[Type],Type)
436 #include "primop-usage.hs-incl"
437
438 -- Things with no Haskell pointers inside: in actuality, usages are
439 -- irrelevant here (hence it doesn't matter that some of these
440 -- apparently permit duplication; since such arguments are never 
441 -- ENTERed anyway, the usage annotation they get is entirely irrelevant
442 -- except insofar as it propagates to infect other values that *are*
443 -- pointed.
444
445
446 -- Helper bits & pieces for usage info.
447                                     
448 mkZ          = mkUTy usOnce  -- pointed argument used zero
449 mkO          = mkUTy usOnce  -- pointed argument used once
450 mkM          = mkUTy usMany  -- pointed argument used multiply
451 mkP          = mkUTy usOnce  -- unpointed argument
452 mkR          = mkUTy usMany  -- unpointed result
453
454 nomangle op
455    = case primOpSig op of
456         (tyvars, arg_tys, res_ty, _, _)
457            -> (tyvars, map mkP arg_tys, mkR res_ty)
458
459 mangle op fs g  
460    = case primOpSig op of
461         (tyvars, arg_tys, res_ty, _, _)
462            -> (tyvars, zipWithEqual "primOpUsg" ($) fs arg_tys, g res_ty)
463
464 inFun op f g ty 
465    = case splitFunTy_maybe ty of
466         Just (a,b) -> mkFunTy (f a) (g b)
467         Nothing    -> pprPanic "primOpUsg:inFun" (ppr op <+> ppr ty)
468
469 inUB op fs ty
470    = case splitTyConApp ty of
471         (tc,tys) -> ASSERT( tc == tupleTyCon Unboxed (length fs) )
472                     mkTupleTy Unboxed (length fs) (zipWithEqual "primOpUsg" ($) fs tys)
473 \end{code}
474
475 \begin{code}
476 data PrimOpResultInfo
477   = ReturnsPrim     PrimRep
478   | ReturnsAlg      TyCon
479
480 -- Some PrimOps need not return a manifest primitive or algebraic value
481 -- (i.e. they might return a polymorphic value).  These PrimOps *must*
482 -- be out of line, or the code generator won't work.
483
484 getPrimOpResultInfo :: PrimOp -> PrimOpResultInfo
485 getPrimOpResultInfo op
486   = case (primOpInfo op) of
487       Dyadic  _ ty                        -> ReturnsPrim (typePrimRep ty)
488       Monadic _ ty                        -> ReturnsPrim (typePrimRep ty)
489       Compare _ ty                        -> ReturnsAlg boolTyCon
490       GenPrimOp _ _ _ ty | isPrimTyCon tc -> ReturnsPrim (tyConPrimRep tc)
491                          | otherwise      -> ReturnsAlg tc
492                          where
493                            tc = tyConAppTyCon ty
494                         -- All primops return a tycon-app result
495                         -- The tycon can be an unboxed tuple, though, which
496                         -- gives rise to a ReturnAlg
497 \end{code}
498
499 The commutable ops are those for which we will try to move constants
500 to the right hand side for strength reduction.
501
502 \begin{code}
503 commutableOp :: PrimOp -> Bool
504 #include "primop-commutable.hs-incl"
505 \end{code}
506
507 Utils:
508 \begin{code}
509 dyadic_fun_ty  ty = mkFunTys [ty, ty] ty
510 monadic_fun_ty ty = mkFunTy  ty ty
511 compare_fun_ty ty = mkFunTys [ty, ty] boolTy
512 \end{code}
513
514 Output stuff:
515 \begin{code}
516 pprPrimOp  :: PrimOp -> SDoc
517 pprPrimOp other_op
518   = getPprStyle $ \ sty ->
519     if ifaceStyle sty then      -- For interfaces Print it qualified with PrelGHC.
520         ptext SLIT("PrelGHC.") <> pprOccName occ
521     else
522         pprOccName occ
523   where
524     occ = primOpOcc other_op
525 \end{code}
526
527