[project @ 1999-06-23 15:30:59 by simonmar]
[ghc-hetmet.git] / ghc / compiler / basicTypes / Const.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1998
3 %
4 \section[Literal]{@Literal@: Machine literals (unboxed, of course)}
5
6 \begin{code}
7 module Const (
8         Con(..),
9         conType, conPrimRep,
10         conOkForApp, conOkForAlt, isWHNFCon, isDataCon,
11         conIsTrivial, conIsCheap, conIsDupable, conStrictness, 
12         conOkForSpeculation, hashCon,
13
14         DataCon, PrimOp,        -- For completeness
15
16         -- Defined here
17         Literal(..),            -- Exported to ParseIface
18         mkMachInt, mkMachWord,
19         mkMachInt_safe, mkMachInt64, mkMachWord64,
20         mkStrLit,                       -- ToDo: rm (not used anywhere)
21         isNoRepLit, isLitLitLit,
22         literalType, literalPrimRep
23     ) where
24
25 #include "HsVersions.h"
26
27 import TysPrim          ( charPrimTy, addrPrimTy, floatPrimTy, doublePrimTy,
28                           intPrimTy, wordPrimTy, int64PrimTy, word64PrimTy
29                         )
30 import Name             ( hashName )
31 import PrimOp           ( PrimOp, primOpType, primOpIsDupable, primOpTag,
32                           primOpIsCheap, primOpStrictness, primOpOkForSpeculation )
33 import PrimRep          ( PrimRep(..) )
34 import DataCon          ( DataCon, dataConName, dataConType, dataConTyCon, isNullaryDataCon, dataConRepStrictness )
35 import TyCon            ( isNewTyCon )
36 import Type             ( Type, typePrimRep )
37 import PprType          ( pprParendType )
38 import Demand           ( Demand )
39 import CStrings         ( stringToC, charToC, charToEasyHaskell )
40
41 import Outputable
42 import Util             ( thenCmp )
43
44 import Ratio            ( numerator, denominator )
45 import FastString       ( uniqueOfFS )
46 import Char             ( ord )
47 \end{code}
48
49
50 %************************************************************************
51 %*                                                                      *
52 \subsection{The main data type}
53 %*                                                                      *
54 %************************************************************************
55
56 \begin{code}
57 data Con
58   = DataCon  DataCon
59   | Literal  Literal
60   | PrimOp   PrimOp
61   | DEFAULT                     -- Used in case clauses
62   deriving (Eq, Ord)
63
64 -- The Ord is needed for the FiniteMap used in the lookForConstructor
65 -- in SimplEnv.  If you declared that lookForConstructor *ignores*
66 -- constructor-applications with LitArg args, then you could get
67 -- rid of this Ord.
68
69 instance Outputable Con where
70   ppr (DataCon dc)  = ppr dc
71   ppr (Literal lit) = ppr lit
72   ppr (PrimOp op)   = ppr op
73   ppr DEFAULT       = ptext SLIT("__DEFAULT")
74
75 instance Show Con where
76   showsPrec p con = showsPrecSDoc p (ppr con)
77
78 conType :: Con -> Type
79 conType (DataCon dc)  = dataConType dc
80 conType (Literal lit) = literalType lit
81 conType (PrimOp op)   = primOpType op
82
83 conStrictness :: Con -> ([Demand], Bool)
84 conStrictness (DataCon dc)  = (dataConRepStrictness dc, False)
85 conStrictness (PrimOp op)   = primOpStrictness op
86 conStrictness (Literal lit) = ([], False)
87
88 conPrimRep :: Con -> PrimRep    -- Only data valued constants
89 conPrimRep (DataCon dc)  = ASSERT( isNullaryDataCon dc) PtrRep
90 conPrimRep (Literal lit) = literalPrimRep lit
91
92 conOkForApp, conOkForAlt :: Con -> Bool
93
94 -- OK for appliation site
95 conOkForApp (DataCon dc) = not (isNewTyCon (dataConTyCon dc))
96 conOkForApp (Literal _)  = True
97 conOkForApp (PrimOp op)  = True
98 conOkForApp DEFAULT      = False
99
100 -- OK for case alternative pattern
101 conOkForAlt (DataCon dc)  = not (isNewTyCon (dataConTyCon dc))
102 conOkForAlt (Literal lit) = not (isNoRepLit lit)
103 conOkForAlt (PrimOp _)    = False
104 conOkForAlt DEFAULT       = True
105
106         -- isWHNFCon is false for PrimOps, which contain work
107         -- Ditto for newtype constructors, which can occur in the output
108         -- of the desugarer, but which will be inlined right away thereafter
109 isWHNFCon (DataCon dc) = not (isNewTyCon (dataConTyCon dc))
110 isWHNFCon (Literal _)  = True
111 isWHNFCon (PrimOp _)   = False
112
113 isDataCon (DataCon dc) = True
114 isDataCon other        = False
115
116 -- conIsTrivial is true for constants we are unconditionally happy to duplicate
117 -- cf CoreUtils.exprIsTrivial
118 conIsTrivial (Literal lit) = not (isNoRepLit lit)
119 conIsTrivial (PrimOp _)    = False
120 conIsTrivial con           = True
121
122 -- conIsCheap is true for constants whose applications we are willing
123 -- to duplicate in exchange for some modest gain.  cf CoreUtils.exprIsCheap
124 conIsCheap (Literal lit) = not (isNoRepLit lit)
125 conIsCheap (DataCon con) = True
126 conIsCheap (PrimOp op)   = primOpIsCheap op
127
128 -- conIsDupable is true for constants whose applications we are willing
129 -- to duplicate in different case branches; i.e no issue about loss of
130 -- work, just space
131 conIsDupable (Literal lit) = not (isNoRepLit lit)
132 conIsDupable (DataCon con) = True
133 conIsDupable (PrimOp op)   = primOpIsDupable op
134
135 -- Similarly conOkForSpeculation
136 conOkForSpeculation (Literal lit) = True
137 conOkForSpeculation (DataCon con) = True
138 conOkForSpeculation (PrimOp op)   = primOpOkForSpeculation op
139 \end{code}
140
141
142 %************************************************************************
143 %*                                                                      *
144 \subsection{Literals}
145 %*                                                                      *
146 %************************************************************************
147
148 So-called @Literals@ are {\em either}:
149 \begin{itemize}
150 \item
151 An unboxed (``machine'') literal (type: @IntPrim@, @FloatPrim@, etc.),
152 which is presumed to be surrounded by appropriate constructors
153 (@mKINT@, etc.), so that the overall thing makes sense.
154 \item
155 An Integer, Rational, or String literal whose representation we are
156 {\em uncommitted} about; i.e., the surrounding with constructors,
157 function applications, etc., etc., has not yet been done.
158 \end{itemize}
159
160 \begin{code}
161 data Literal
162   =     ------------------
163         -- First the primitive guys
164     MachChar    Char
165   | MachStr     FAST_STRING
166
167   | MachAddr    Integer -- Whatever this machine thinks is a "pointer"
168
169   | MachInt     Integer -- For the numeric types, these are
170                 Bool    -- True <=> signed (Int#); False <=> unsigned (Word#)
171
172   | MachInt64   Integer -- guaranteed 64-bit versions of the above.
173                 Bool    -- True <=> signed (Int#); False <=> unsigned (Word#)
174
175
176   | MachFloat   Rational
177   | MachDouble  Rational
178
179   | MachLitLit  FAST_STRING Type        -- Type might be Add# or Int# etc
180
181         ------------------
182         -- The no-rep guys
183   | NoRepStr        FAST_STRING Type    -- This Type is always String
184   | NoRepInteger    Integer     Type    -- This Type is always Integer
185   | NoRepRational   Rational    Type    -- This Type is always Rational
186                         -- We keep these Types in the literal because Rational isn't
187                         -- (currently) wired in, so we can't conjure up its type out of
188                         -- thin air.    Integer is, so the type here is really redundant.
189 \end{code}
190
191 \begin{code}
192 instance Outputable Literal where
193     ppr lit = pprLit lit
194
195 instance Show Literal where
196     showsPrec p lit = showsPrecSDoc p (ppr lit)
197
198 instance Eq Literal where
199     a == b = case (a `compare` b) of { EQ -> True;   _ -> False }
200     a /= b = case (a `compare` b) of { EQ -> False;  _ -> True  }
201
202 instance Ord Literal where
203     a <= b = case (a `compare` b) of { LT -> True;  EQ -> True;  GT -> False }
204     a <  b = case (a `compare` b) of { LT -> True;  EQ -> False; GT -> False }
205     a >= b = case (a `compare` b) of { LT -> False; EQ -> True;  GT -> True  }
206     a >  b = case (a `compare` b) of { LT -> False; EQ -> False; GT -> True  }
207     compare a b = cmpLit a b
208 \end{code}
209
210
211         Construction
212         ~~~~~~~~~~~~
213 \begin{code}
214 mkMachInt, mkMachWord :: Integer -> Literal
215
216 mkMachInt  x = MachInt x True{-signed-}
217 mkMachWord x = MachInt x False{-unsigned-}
218
219 -- check if the int is within range
220 mkMachInt_safe :: Integer -> Literal
221 mkMachInt_safe i
222  | out_of_range = 
223    pprPanic "mkMachInt_safe" 
224             (hsep [text "ERROR: Int ", text (show i), text "out of range",
225                    brackets (int minInt <+> text ".." <+> int maxInt)])
226  | otherwise = MachInt i True{-signed-}
227  where
228   out_of_range =
229 --    i < fromInt minBound ||
230     i > fromInt maxInt
231
232 mkMachInt64  x = MachInt64 x True{-signed-}
233 mkMachWord64 x = MachInt64 x False{-unsigned-}
234
235 mkStrLit :: String -> Type -> Literal
236 mkStrLit s ty = NoRepStr (_PK_ s) ty
237 \end{code}
238
239
240         Predicates
241         ~~~~~~~~~~
242 \begin{code}
243 isNoRepLit (NoRepStr _ _)       = True -- these are not primitive typed!
244 isNoRepLit (NoRepInteger  _ _)  = True
245 isNoRepLit (NoRepRational _ _)  = True
246 isNoRepLit _                    = False
247
248 isLitLitLit (MachLitLit _ _) = True
249 isLitLitLit _                = False
250 \end{code}
251
252         Types
253         ~~~~~
254 \begin{code}
255 literalType :: Literal -> Type
256 literalType (MachChar _)          = charPrimTy
257 literalType (MachStr  _)          = addrPrimTy
258 literalType (MachAddr _)          = addrPrimTy
259 literalType (MachInt  _ signed)   = if signed then intPrimTy else wordPrimTy
260 literalType (MachInt64  _ signed) = if signed then int64PrimTy else word64PrimTy
261 literalType (MachFloat _)         = floatPrimTy
262 literalType (MachDouble _)        = doublePrimTy
263 literalType (MachLitLit _ ty)     = ty
264 literalType (NoRepInteger  _ ty)  = ty
265 literalType (NoRepRational _ ty)  = ty
266 literalType (NoRepStr _ ty)       = ty
267 \end{code}
268
269 \begin{code}
270 literalPrimRep :: Literal -> PrimRep
271
272 literalPrimRep (MachChar _)       = CharRep
273 literalPrimRep (MachStr _)        = AddrRep  -- specifically: "char *"
274 literalPrimRep (MachAddr  _)      = AddrRep
275 literalPrimRep (MachInt _ signed) = if signed then IntRep else WordRep
276 literalPrimRep (MachInt64 _ signed) = if signed then Int64Rep else Word64Rep
277 literalPrimRep (MachFloat _)      = FloatRep
278 literalPrimRep (MachDouble _)     = DoubleRep
279 literalPrimRep (MachLitLit _ ty)  = typePrimRep ty
280 #ifdef DEBUG
281 literalPrimRep (NoRepInteger  _ _) = panic "literalPrimRep:NoRepInteger"
282 literalPrimRep (NoRepRational _ _) = panic "literalPrimRep:NoRepRational"
283 literalPrimRep (NoRepStr _ _)      = panic "literalPrimRep:NoRepString"
284 #endif
285 \end{code}
286
287
288         Comparison
289         ~~~~~~~~~~
290 \begin{code}
291 cmpLit (MachChar      a)   (MachChar       b)   = a `compare` b
292 cmpLit (MachStr       a)   (MachStr        b)   = a `compare` b
293 cmpLit (MachAddr      a)   (MachAddr       b)   = a `compare` b
294 cmpLit (MachInt       a b) (MachInt        c d) = (a `compare` c) `thenCmp` (b `compare` d)
295 cmpLit (MachFloat     a)   (MachFloat      b)   = a `compare` b
296 cmpLit (MachDouble    a)   (MachDouble     b)   = a `compare` b
297 cmpLit (MachLitLit    a b) (MachLitLit    c d)  = (a `compare` c) `thenCmp` (b `compare` d)
298 cmpLit (NoRepStr      a _) (NoRepStr      b _)  = a `compare` b
299 cmpLit (NoRepInteger  a _) (NoRepInteger  b _)  = a `compare` b
300 cmpLit (NoRepRational a _) (NoRepRational b _)  = a `compare` b
301 cmpLit lit1                lit2                 | litTag lit1 _LT_ litTag lit2 = LT
302                                                 | otherwise                    = GT
303
304 litTag (MachChar      _)   = ILIT(1)
305 litTag (MachStr       _)   = ILIT(2)
306 litTag (MachAddr      _)   = ILIT(3)
307 litTag (MachInt       _ _) = ILIT(4)
308 litTag (MachFloat     _)   = ILIT(5)
309 litTag (MachDouble    _)   = ILIT(6)
310 litTag (MachLitLit    _ _) = ILIT(7)
311 litTag (NoRepStr      _ _) = ILIT(8)
312 litTag (NoRepInteger  _ _) = ILIT(9)
313 litTag (NoRepRational _ _) = ILIT(10)
314 \end{code}
315
316         Printing
317         ~~~~~~~~
318 * MachX (i.e. unboxed) things are printed unadornded (e.g. 3, 'a', "foo")
319   exceptions: MachFloat and MachAddr get an initial keyword prefix
320
321 * NoRep things get an initial keyword prefix (e.g. _integer_ 3)
322
323 \begin{code}
324 pprLit lit
325   = getPprStyle $ \ sty ->
326     let
327       code_style = codeStyle sty
328     in
329     case lit of
330       MachChar ch | code_style     -> hcat [ptext SLIT("(C_)"), char '\'', 
331                                             text (charToC ch), char '\'']
332                   | ifaceStyle sty -> char '\'' <> text (charToEasyHaskell ch) <> char '\''
333                   | otherwise      -> text ['\'', ch, '\'']
334
335       MachStr s | code_style -> doubleQuotes (text (stringToC (_UNPK_ s)))
336                 | otherwise  -> pprFSAsString s
337
338
339       NoRepStr s ty | code_style -> pprPanic "NoRep in code style" (ppr lit)
340                     | otherwise  -> ptext SLIT("__string") <+> pprFSAsString s
341
342       MachInt i signed | code_style && out_of_range 
343                        -> pprPanic "" (hsep [text "ERROR: Int ", text (show i), 
344                                              text "out of range",
345                                              brackets (ppr range_min <+> text ".." 
346                                                         <+> ppr range_max)])
347                         -- in interface files, parenthesize raw negative ints.
348                         -- this avoids problems like {-1} being interpreted
349                         -- as a comment starter. -}
350                        | ifaceStyle sty && i < 0 -> parens (integer i)
351                         -- avoid a problem whereby gcc interprets the constant
352                         -- minInt as unsigned.
353                        | code_style && i == (toInteger (minBound :: Int))
354                                 -> parens (hcat [integer (i+1), text "-1"])
355                        | otherwise -> integer i
356
357                        where
358                         range_min = if signed then minInt else 0
359                         range_max = maxInt
360                         out_of_range = not (i >= toInteger range_min && i <= toInteger range_max)
361
362       MachFloat f | code_style -> ptext SLIT("(StgFloat)") <> rational f
363                   | otherwise  -> ptext SLIT("__float") <+> rational f
364
365       MachDouble d | ifaceStyle sty && d < 0 -> parens (rational d)
366                    | otherwise -> rational d
367
368       MachAddr p | code_style -> ptext SLIT("(void*)") <> integer p
369                  | otherwise  -> ptext SLIT("__addr") <+> integer p
370
371       NoRepInteger i _ | code_style -> pprPanic "NoRep in code style" (ppr lit)
372                        | otherwise  -> ptext SLIT("__integer") <+> integer i
373
374       NoRepRational r _ | code_style -> pprPanic "NoRep in code style" (ppr lit)
375                         | otherwise  -> hsep [ptext SLIT("__rational"), integer (numerator r), 
376                                                                         integer (denominator r)]
377
378       MachLitLit s ty | code_style -> ptext s
379                       | otherwise  -> parens (hsep [ptext SLIT("__litlit"), 
380                                                     pprFSAsString s,
381                                                     pprParendType ty])
382 \end{code}
383
384
385 %************************************************************************
386 %*                                                                      *
387 \subsection{Hashing
388 %*                                                                      *
389 %************************************************************************
390
391 Hash values should be zero or a positive integer.  No negatives please.
392 (They mess up the UniqFM for some reason.)
393
394 \begin{code}
395 hashCon :: Con -> Int
396 hashCon (DataCon dc)  = hashName (dataConName dc)
397 hashCon (PrimOp op)   = primOpTag op + 500      -- Keep it out of range of common ints
398 hashCon (Literal lit) = hashLiteral lit
399 hashCon other         = pprTrace "hashCon" (ppr other) 0
400
401 hashLiteral :: Literal -> Int
402 hashLiteral (MachChar c)        = ord c + 1000  -- Keep it out of range of common ints
403 hashLiteral (MachStr s)         = hashFS s
404 hashLiteral (MachAddr i)        = hashInteger i
405 hashLiteral (MachInt i _)       = hashInteger i
406 hashLiteral (MachInt64 i _)     = hashInteger i
407 hashLiteral (MachFloat r)       = hashRational r
408 hashLiteral (MachDouble r)      = hashRational r
409 hashLiteral (MachLitLit s _)    = hashFS s
410 hashLiteral (NoRepStr s _)      = hashFS s
411 hashLiteral (NoRepInteger i _)  = hashInteger i
412 hashLiteral (NoRepRational r _) = hashRational r
413
414 hashRational :: Rational -> Int
415 hashRational r = hashInteger (numerator r)
416
417 hashInteger :: Integer -> Int
418 hashInteger i = abs (fromInteger (i `rem` 10000))
419
420 hashFS :: FAST_STRING -> Int
421 hashFS s = IBOX( uniqueOfFS s )
422 \end{code}
423