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