[project @ 2002-03-18 09:44:46 by simonmar]
[ghc-hetmet.git] / ghc / compiler / basicTypes / Literal.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 Literal
8         ( Literal(..)           -- Exported to ParseIface
9         , mkMachInt, mkMachWord
10         , mkMachInt64, mkMachWord64
11         , isLitLitLit, maybeLitLit, litSize, litIsDupable,
12         , literalType, literalPrimRep
13         , hashLiteral
14
15         , inIntRange, inWordRange, tARGET_MAX_INT, inCharRange
16         , isZeroLit,
17
18         , word2IntLit, int2WordLit
19         , narrow8IntLit, narrow16IntLit, narrow32IntLit
20         , narrow8WordLit, narrow16WordLit, narrow32WordLit
21         , char2IntLit, int2CharLit
22         , float2IntLit, int2FloatLit, double2IntLit, int2DoubleLit
23         , nullAddrLit, float2DoubleLit, double2FloatLit
24         ) where
25
26 #include "HsVersions.h"
27
28 import TysPrim          ( charPrimTy, addrPrimTy, floatPrimTy, doublePrimTy,
29                           intPrimTy, wordPrimTy, int64PrimTy, word64PrimTy
30                         )
31 import PrimRep          ( PrimRep(..) )
32 import TcType           ( Type, tcCmpType )
33 import Type             ( typePrimRep )
34 import PprType          ( pprParendType )
35 import CStrings         ( pprFSInCStyle )
36
37 import Outputable
38 import FastTypes
39 import Binary
40 import Util             ( thenCmp )
41
42 import Ratio            ( numerator )
43 import FastString       ( uniqueOfFS, lengthFS )
44 import Int              ( Int8,  Int16,  Int32 )
45 import Word             ( Word8, Word16, Word32 )
46 import Char             ( ord, chr )
47 \end{code}
48
49
50
51 %************************************************************************
52 %*                                                                      *
53 \subsection{Sizes}
54 %*                                                                      *
55 %************************************************************************
56
57 If we're compiling with GHC (and we're not cross-compiling), then we
58 know that minBound and maxBound :: Int are the right values for the
59 target architecture.  Otherwise, we assume -2^31 and 2^31-1
60 respectively (which will be wrong on a 64-bit machine).
61
62 \begin{code}
63 tARGET_MIN_INT, tARGET_MAX_INT, tARGET_MAX_WORD :: Integer
64 #if __GLASGOW_HASKELL__
65 tARGET_MIN_INT  = toInteger (minBound :: Int)
66 tARGET_MAX_INT  = toInteger (maxBound :: Int)
67 #else
68 tARGET_MIN_INT = -2147483648
69 tARGET_MAX_INT =  2147483647
70 #endif
71 tARGET_MAX_WORD = (tARGET_MAX_INT * 2) + 1
72
73 tARGET_MAX_CHAR :: Int
74 tARGET_MAX_CHAR = 0x10ffff
75 \end{code}
76  
77
78 %************************************************************************
79 %*                                                                      *
80 \subsection{Literals}
81 %*                                                                      *
82 %************************************************************************
83
84 So-called @Literals@ are {\em either}:
85 \begin{itemize}
86 \item
87 An unboxed (``machine'') literal (type: @IntPrim@, @FloatPrim@, etc.),
88 which is presumed to be surrounded by appropriate constructors
89 (@mKINT@, etc.), so that the overall thing makes sense.
90 \item
91 An Integer, Rational, or String literal whose representation we are
92 {\em uncommitted} about; i.e., the surrounding with constructors,
93 function applications, etc., etc., has not yet been done.
94 \end{itemize}
95
96 \begin{code}
97 data Literal
98   =     ------------------
99         -- First the primitive guys
100     MachChar    Int             -- Char#        At least 31 bits
101   | MachStr     FAST_STRING
102
103   | MachAddr    Integer -- Whatever this machine thinks is a "pointer"
104
105   | MachInt     Integer         -- Int#         At least WORD_SIZE_IN_BITS bits
106   | MachInt64   Integer         -- Int64#       At least 64 bits
107   | MachWord    Integer         -- Word#        At least WORD_SIZE_IN_BITS bits
108   | MachWord64  Integer         -- Word64#      At least 64 bits
109
110   | MachFloat   Rational
111   | MachDouble  Rational
112
113         -- MachLabel is used (only) for the literal derived from a 
114         -- "foreign label" declaration.
115         -- string argument is the name of a symbol.  This literal
116         -- refers to the *address* of the label.
117   | MachLabel   FAST_STRING             -- always an Addr#
118
119         -- lit-lits only work for via-C compilation, hence they
120         -- are deprecated.  The string is emitted verbatim into
121         -- the C file, and can therefore be any C expression,
122         -- macro call, #defined constant etc.
123   | MachLitLit  FAST_STRING Type        -- Type might be Addr# or Int# etc
124 \end{code}
125
126 Binary instance: must do this manually, because we don't want the type
127 arg of MachLitLit involved.
128
129 \begin{code}
130 instance Binary Literal where
131     put_ bh (MachChar aa)     = do putByte bh 0; put_ bh aa
132     put_ bh (MachStr ab)      = do putByte bh 1; put_ bh ab
133     put_ bh (MachAddr ac)     = do putByte bh 2; put_ bh ac
134     put_ bh (MachInt ad)      = do putByte bh 3; put_ bh ad
135     put_ bh (MachInt64 ae)    = do putByte bh 4; put_ bh ae
136     put_ bh (MachWord af)     = do putByte bh 5; put_ bh af
137     put_ bh (MachWord64 ag)   = do putByte bh 6; put_ bh ag
138     put_ bh (MachFloat ah)    = do putByte bh 7; put_ bh ah
139     put_ bh (MachDouble ai)   = do putByte bh 8; put_ bh ai
140     put_ bh (MachLabel aj)    = do putByte bh 9; put_ bh aj
141     put_ bh (MachLitLit ak _) = do putByte bh 10; put_ bh ak
142     get bh = do
143             h <- getByte bh
144             case h of
145               0 -> do
146                     aa <- get bh
147                     return (MachChar aa)
148               1 -> do
149                     ab <- get bh
150                     return (MachStr ab)
151               2 -> do
152                     ac <- get bh
153                     return (MachAddr ac)
154               3 -> do
155                     ad <- get bh
156                     return (MachInt ad)
157               4 -> do
158                     ae <- get bh
159                     return (MachInt64 ae)
160               5 -> do
161                     af <- get bh
162                     return (MachWord af)
163               6 -> do
164                     ag <- get bh
165                     return (MachWord64 ag)
166               7 -> do
167                     ah <- get bh
168                     return (MachFloat ah)
169               8 -> do
170                     ai <- get bh
171                     return (MachDouble ai)
172               9 -> do
173                     aj <- get bh
174                     return (MachLabel aj)
175               10 -> do
176                     ak <- get bh
177                     return (MachLitLit ak (error "MachLitLit: no type"))
178 \end{code}
179
180 \begin{code}
181 instance Outputable Literal where
182     ppr lit = pprLit lit
183
184 instance Show Literal where
185     showsPrec p lit = showsPrecSDoc p (ppr lit)
186
187 instance Eq Literal where
188     a == b = case (a `compare` b) of { EQ -> True;   _ -> False }
189     a /= b = case (a `compare` b) of { EQ -> False;  _ -> True  }
190
191 instance Ord Literal where
192     a <= b = case (a `compare` b) of { LT -> True;  EQ -> True;  GT -> False }
193     a <  b = case (a `compare` b) of { LT -> True;  EQ -> False; GT -> False }
194     a >= b = case (a `compare` b) of { LT -> False; EQ -> True;  GT -> True  }
195     a >  b = case (a `compare` b) of { LT -> False; EQ -> False; GT -> True  }
196     compare a b = cmpLit a b
197 \end{code}
198
199
200         Construction
201         ~~~~~~~~~~~~
202 \begin{code}
203 mkMachInt, mkMachWord, mkMachInt64, mkMachWord64 :: Integer -> Literal
204
205 mkMachInt  x   = -- ASSERT2( inIntRange x,  integer x ) 
206                  -- Not true: you can write out of range Int# literals
207                  -- For example, one can write (intToWord# 0xffff0000) to
208                  -- get a particular Word bit-pattern, and there's no other
209                  -- convenient way to write such literals, which is why we allow it.
210                  MachInt x
211 mkMachWord x   = -- ASSERT2( inWordRange x, integer x ) 
212                  MachWord x
213 mkMachInt64  x = MachInt64 x
214 mkMachWord64 x = MachWord64 x
215
216 inIntRange, inWordRange :: Integer -> Bool
217 inIntRange  x = x >= tARGET_MIN_INT && x <= tARGET_MAX_INT
218 inWordRange x = x >= 0              && x <= tARGET_MAX_WORD
219
220 inCharRange :: Int -> Bool
221 inCharRange c =  c >= 0 && c <= tARGET_MAX_CHAR
222
223 isZeroLit :: Literal -> Bool
224 isZeroLit (MachInt    0) = True
225 isZeroLit (MachInt64  0) = True
226 isZeroLit (MachWord   0) = True
227 isZeroLit (MachWord64 0) = True
228 isZeroLit (MachFloat  0) = True
229 isZeroLit (MachDouble 0) = True
230 isZeroLit other          = False
231 \end{code}
232
233         Coercions
234         ~~~~~~~~~
235 \begin{code}
236 word2IntLit, int2WordLit,
237   narrow8IntLit, narrow16IntLit, narrow32IntLit,
238   narrow8WordLit, narrow16WordLit, narrow32WordLit,
239   char2IntLit, int2CharLit,
240   float2IntLit, int2FloatLit, double2IntLit, int2DoubleLit,
241   float2DoubleLit, double2FloatLit
242   :: Literal -> Literal
243
244 word2IntLit (MachWord w) 
245   | w > tARGET_MAX_INT = MachInt (w - tARGET_MAX_WORD - 1)
246   | otherwise          = MachInt w
247
248 int2WordLit (MachInt i)
249   | i < 0     = MachWord (1 + tARGET_MAX_WORD + i)      -- (-1)  --->  tARGET_MAX_WORD
250   | otherwise = MachWord i
251
252 narrow8IntLit    (MachInt  i) = MachInt  (toInteger (fromInteger i :: Int8))
253 narrow16IntLit   (MachInt  i) = MachInt  (toInteger (fromInteger i :: Int16))
254 narrow32IntLit   (MachInt  i) = MachInt  (toInteger (fromInteger i :: Int32))
255 narrow8WordLit   (MachWord w) = MachWord (toInteger (fromInteger w :: Word8))
256 narrow16WordLit  (MachWord w) = MachWord (toInteger (fromInteger w :: Word16))
257 narrow32WordLit  (MachWord w) = MachWord (toInteger (fromInteger w :: Word32))
258
259 char2IntLit (MachChar c) = MachInt  (toInteger c)
260 int2CharLit (MachInt  i) = MachChar (fromInteger i)
261
262 float2IntLit (MachFloat f) = MachInt   (truncate    f)
263 int2FloatLit (MachInt   i) = MachFloat (fromInteger i)
264
265 double2IntLit (MachDouble f) = MachInt    (truncate    f)
266 int2DoubleLit (MachInt   i) = MachDouble (fromInteger i)
267
268 float2DoubleLit (MachFloat  f) = MachDouble f
269 double2FloatLit (MachDouble d) = MachFloat  d
270
271 nullAddrLit :: Literal
272 nullAddrLit = MachAddr 0
273 \end{code}
274
275         Predicates
276         ~~~~~~~~~~
277 \begin{code}
278 isLitLitLit (MachLitLit _ _) = True
279 isLitLitLit _                = False
280
281 maybeLitLit (MachLitLit s t) = Just (s,t)
282 maybeLitLit _                = Nothing
283
284 litIsDupable :: Literal -> Bool
285         -- True if code space does not go bad if we duplicate this literal
286         -- False principally of strings
287 litIsDupable (MachStr _) = False
288 litIsDupable other       = True
289
290 litSize :: Literal -> Int
291         -- used by CoreUnfold.sizeExpr
292 litSize (MachStr str) = lengthFS str `div` 4
293 litSize _other        = 1
294 \end{code}
295
296         Types
297         ~~~~~
298 \begin{code}
299 literalType :: Literal -> Type
300 literalType (MachChar _)          = charPrimTy
301 literalType (MachStr  _)          = addrPrimTy
302 literalType (MachAddr _)          = addrPrimTy
303 literalType (MachInt  _)          = intPrimTy
304 literalType (MachWord  _)         = wordPrimTy
305 literalType (MachInt64  _)        = int64PrimTy
306 literalType (MachWord64  _)       = word64PrimTy
307 literalType (MachFloat _)         = floatPrimTy
308 literalType (MachDouble _)        = doublePrimTy
309 literalType (MachLabel _)         = addrPrimTy
310 literalType (MachLitLit _ ty)     = ty
311 \end{code}
312
313 \begin{code}
314 literalPrimRep :: Literal -> PrimRep
315
316 literalPrimRep (MachChar _)       = CharRep
317 literalPrimRep (MachStr _)        = AddrRep  -- specifically: "char *"
318 literalPrimRep (MachAddr  _)      = AddrRep
319 literalPrimRep (MachInt _)        = IntRep
320 literalPrimRep (MachWord _)       = WordRep
321 literalPrimRep (MachInt64 _)      = Int64Rep
322 literalPrimRep (MachWord64 _)     = Word64Rep
323 literalPrimRep (MachFloat _)      = FloatRep
324 literalPrimRep (MachDouble _)     = DoubleRep
325 literalPrimRep (MachLabel _)      = AddrRep
326 literalPrimRep (MachLitLit _ ty)  = typePrimRep ty
327 \end{code}
328
329
330         Comparison
331         ~~~~~~~~~~
332 \begin{code}
333 cmpLit (MachChar      a)   (MachChar       b)   = a `compare` b
334 cmpLit (MachStr       a)   (MachStr        b)   = a `compare` b
335 cmpLit (MachAddr      a)   (MachAddr       b)   = a `compare` b
336 cmpLit (MachInt       a)   (MachInt        b)   = a `compare` b
337 cmpLit (MachWord      a)   (MachWord       b)   = a `compare` b
338 cmpLit (MachInt64     a)   (MachInt64      b)   = a `compare` b
339 cmpLit (MachWord64    a)   (MachWord64     b)   = a `compare` b
340 cmpLit (MachFloat     a)   (MachFloat      b)   = a `compare` b
341 cmpLit (MachDouble    a)   (MachDouble     b)   = a `compare` b
342 cmpLit (MachLabel     a)   (MachLabel      b)   = a `compare` b
343 cmpLit (MachLitLit    a b) (MachLitLit    c d)  = (a `compare` c) `thenCmp` (b `tcCmpType` d)
344 cmpLit lit1                lit2                 | litTag lit1 <# litTag lit2 = LT
345                                                 | otherwise                    = GT
346
347 litTag (MachChar      _)   = _ILIT(1)
348 litTag (MachStr       _)   = _ILIT(2)
349 litTag (MachAddr      _)   = _ILIT(3)
350 litTag (MachInt       _)   = _ILIT(4)
351 litTag (MachWord      _)   = _ILIT(5)
352 litTag (MachInt64     _)   = _ILIT(6)
353 litTag (MachWord64    _)   = _ILIT(7)
354 litTag (MachFloat     _)   = _ILIT(8)
355 litTag (MachDouble    _)   = _ILIT(9)
356 litTag (MachLabel     _)   = _ILIT(10)
357 litTag (MachLitLit    _ _) = _ILIT(11)
358 \end{code}
359
360         Printing
361         ~~~~~~~~
362 * MachX (i.e. unboxed) things are printed unadornded (e.g. 3, 'a', "foo")
363   exceptions: MachFloat and MachAddr get an initial keyword prefix
364
365 \begin{code}
366 pprLit lit
367   = getPprStyle $ \ sty ->
368     let
369       code_style  = codeStyle  sty
370     in
371     case lit of
372       MachChar ch | code_style -> hcat [ptext SLIT("(C_)"), text (show ch)]
373                   | otherwise  -> pprHsChar ch
374
375       MachStr s | code_style -> pprFSInCStyle s
376                 | otherwise  -> pprHsString s
377       -- Warning: printing MachStr in code_style assumes it contains
378       -- only characters '\0'..'\xFF'!
379
380       MachInt i | code_style && i == tARGET_MIN_INT -> parens (integer (i+1) <> text "-1")
381                                 -- Avoid a problem whereby gcc interprets
382                                 -- the constant minInt as unsigned.
383                 | otherwise -> pprIntVal i
384
385       MachInt64 i | code_style -> pprIntVal i           -- Same problem with gcc???
386                   | otherwise -> ptext SLIT("__int64") <+> integer i
387
388       MachWord w | code_style -> pprHexVal w
389                  | otherwise  -> ptext SLIT("__word") <+> integer w
390
391       MachWord64 w | code_style -> pprHexVal w
392                    | otherwise  -> ptext SLIT("__word64") <+> integer w
393
394       MachFloat f | code_style -> ptext SLIT("(StgFloat)") <> rational f
395                   | otherwise  -> ptext SLIT("__float") <+> rational f
396
397       MachDouble d -> rational d
398
399       MachAddr p | code_style -> ptext SLIT("(void*)") <> integer p
400                  | otherwise  -> ptext SLIT("__addr") <+> integer p
401
402       MachLabel l | code_style -> ptext SLIT("(&") <> ptext l <> char ')'
403                   | otherwise  -> ptext SLIT("__label") <+> pprHsString l
404
405       MachLitLit s ty | code_style  -> ptext s
406                       | otherwise   -> parens (hsep [ptext SLIT("__litlit"), 
407                                                      pprHsString s,
408                                                      pprParendType ty])
409
410 pprIntVal :: Integer -> SDoc
411 -- Print negative integers with parens to be sure it's unambiguous
412 pprIntVal i | i < 0     = parens (integer i)
413             | otherwise = integer i
414                 
415 pprHexVal :: Integer -> SDoc
416 -- Print in C hex format: 0x13fa 
417 pprHexVal 0 = ptext SLIT("0x0")
418 pprHexVal w = ptext SLIT("0x") <> go w
419             where
420               go 0 = empty
421               go w = go quot <> dig
422                    where
423                      (quot,rem) = w `quotRem` 16
424                      dig | rem < 10  = char (chr (fromInteger rem + ord '0'))
425                          | otherwise = char (chr (fromInteger rem - 10 + ord 'a'))
426 \end{code}
427
428
429 %************************************************************************
430 %*                                                                      *
431 \subsection{Hashing}
432 %*                                                                      *
433 %************************************************************************
434
435 Hash values should be zero or a positive integer.  No negatives please.
436 (They mess up the UniqFM for some reason.)
437
438 \begin{code}
439 hashLiteral :: Literal -> Int
440 hashLiteral (MachChar c)        = c + 1000      -- Keep it out of range of common ints
441 hashLiteral (MachStr s)         = hashFS s
442 hashLiteral (MachAddr i)        = hashInteger i
443 hashLiteral (MachInt i)         = hashInteger i
444 hashLiteral (MachInt64 i)       = hashInteger i
445 hashLiteral (MachWord i)        = hashInteger i
446 hashLiteral (MachWord64 i)      = hashInteger i
447 hashLiteral (MachFloat r)       = hashRational r
448 hashLiteral (MachDouble r)      = hashRational r
449 hashLiteral (MachLabel s)       = hashFS s
450 hashLiteral (MachLitLit s _)    = hashFS s
451
452 hashRational :: Rational -> Int
453 hashRational r = hashInteger (numerator r)
454
455 hashInteger :: Integer -> Int
456 hashInteger i = 1 + abs (fromInteger (i `rem` 10000))
457                 -- The 1+ is to avoid zero, which is a Bad Number
458                 -- since we use * to combine hash values
459
460 hashFS :: FAST_STRING -> Int
461 hashFS s = iBox (uniqueOfFS s)
462 \end{code}