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