[project @ 2002-02-12 15:17:13 by simonmar]
[ghc-hetmet.git] / ghc / compiler / basicTypes / Unique.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
3 %
4
5 @Uniques@ are used to distinguish entities in the compiler (@Ids@,
6 @Classes@, etc.) from each other.  Thus, @Uniques@ are the basic
7 comparison key in the compiler.
8
9 If there is any single operation that needs to be fast, it is @Unique@
10 comparison.  Unsurprisingly, there is quite a bit of huff-and-puff
11 directed to that end.
12
13 Some of the other hair in this code is to be able to use a
14 ``splittable @UniqueSupply@'' if requested/possible (not standard
15 Haskell).
16
17 \begin{code}
18 module Unique (
19         Unique, Uniquable(..), hasKey,
20         u2i,                            -- hack: used in UniqFM
21
22         pprUnique, pprUnique10,
23
24         mkUnique,                       -- Used in UniqSupply
25         mkUniqueGrimily,                -- Used in UniqSupply only!
26         getKey,                         -- Used in Var only!
27
28         incrUnique,                     -- Used for renumbering
29         deriveUnique,                   -- Ditto
30         newTagUnique,                   -- Used in CgCase
31         initTyVarUnique,
32         initTidyUniques,
33
34         isTupleKey, 
35
36         -- now all the built-in Uniques (and functions to make them)
37         -- [the Oh-So-Wonderful Haskell module system wins again...]
38         mkAlphaTyVarUnique,
39         mkPrimOpIdUnique,
40         mkTupleTyConUnique, mkTupleDataConUnique,
41         mkPreludeMiscIdUnique, mkPreludeDataConUnique,
42         mkPreludeTyConUnique, mkPreludeClassUnique,
43         mkPArrDataConUnique,
44
45         mkBuiltinUnique,
46         mkPseudoUnique1, mkPseudoUnique2, mkPseudoUnique3
47     ) where
48
49 #include "HsVersions.h"
50
51 import BasicTypes       ( Boxity(..) )
52 import FastString       ( FastString, uniqueOfFS )
53 import GlaExts
54 import ST
55 import Char             ( chr, ord )
56 import FastTypes
57
58 import Outputable
59 \end{code}
60
61 %************************************************************************
62 %*                                                                      *
63 \subsection[Unique-type]{@Unique@ type and operations}
64 %*                                                                      *
65 %************************************************************************
66
67 The @Chars@ are ``tag letters'' that identify the @UniqueSupply@.
68 Fast comparison is everything on @Uniques@:
69
70 \begin{code}
71 data Unique = MkUnique Int#
72 \end{code}
73
74 \begin{code}
75 u2i :: Unique -> FastInt
76 u2i (MkUnique i) = i
77 \end{code}
78
79 Now come the functions which construct uniques from their pieces, and vice versa.
80 The stuff about unique *supplies* is handled further down this module.
81
82 \begin{code}
83 mkUnique        :: Char -> Int -> Unique        -- Builds a unique from pieces
84 unpkUnique      :: Unique -> (Char, Int)        -- The reverse
85
86 mkUniqueGrimily :: Int# -> Unique               -- A trap-door for UniqSupply
87
88 getKey          :: Unique -> Int#               -- for Var
89
90 incrUnique      :: Unique -> Unique
91 deriveUnique    :: Unique -> Int -> Unique
92 newTagUnique    :: Unique -> Char -> Unique
93
94 isTupleKey      :: Unique -> Bool
95 \end{code}
96
97
98 \begin{code}
99 mkUniqueGrimily x = MkUnique x
100
101 {-# INLINE getKey #-}
102 getKey (MkUnique x) = x
103
104 incrUnique (MkUnique i) = MkUnique (i +# 1#)
105
106 -- deriveUnique uses an 'X' tag so that it won't clash with
107 -- any of the uniques produced any other way
108 deriveUnique (MkUnique i) delta = mkUnique 'X' (I# i + delta)
109
110 -- newTagUnique changes the "domain" of a unique to a different char
111 newTagUnique u c = mkUnique c i where (_,i) = unpkUnique u
112
113 -- pop the Char in the top 8 bits of the Unique(Supply)
114
115 -- No 64-bit bugs here, as long as we have at least 32 bits. --JSM
116
117 w2i x = word2Int# x
118 i2w x = int2Word# x
119 i2w_s x = (x::Int#)
120
121 mkUnique (C# c) (I# i)
122   = MkUnique (w2i (tag `or#` bits))
123   where
124 #if __GLASGOW_HASKELL__ >= 503
125     tag  = i2w (ord# c) `uncheckedShiftL#` i2w_s 24#
126 #else
127     tag  = i2w (ord# c) `shiftL#` i2w_s 24#
128 #endif
129     bits = i2w i `and#` (i2w 16777215#){-``0x00ffffff''-}
130
131 unpkUnique (MkUnique u)
132   = let
133         tag = C# (chr# (w2i ((i2w u) `shiftr` (i2w_s 24#))))
134         i   = I# (w2i ((i2w u) `and#` (i2w 16777215#){-``0x00ffffff''-}))
135     in
136     (tag, i)
137   where
138 #if __GLASGOW_HASKELL__ >= 503
139     shiftr x y = uncheckedShiftRL# x y
140 #else
141     shiftr x y = shiftRL# x y
142 #endif
143 \end{code}
144
145
146
147 %************************************************************************
148 %*                                                                      *
149 \subsection[Uniquable-class]{The @Uniquable@ class}
150 %*                                                                      *
151 %************************************************************************
152
153 \begin{code}
154 class Uniquable a where
155     getUnique :: a -> Unique
156
157 hasKey          :: Uniquable a => a -> Unique -> Bool
158 x `hasKey` k    = getUnique x == k
159
160 instance Uniquable FastString where
161  getUnique fs = mkUniqueGrimily (uniqueOfFS fs)
162
163 instance Uniquable Int where
164  getUnique (I# i#) = mkUniqueGrimily i#
165 \end{code}
166
167
168 %************************************************************************
169 %*                                                                      *
170 \subsection[Unique-instances]{Instance declarations for @Unique@}
171 %*                                                                      *
172 %************************************************************************
173
174 And the whole point (besides uniqueness) is fast equality.  We don't
175 use `deriving' because we want {\em precise} control of ordering
176 (equality on @Uniques@ is v common).
177
178 \begin{code}
179 eqUnique (MkUnique u1) (MkUnique u2) = u1 ==# u2
180 ltUnique (MkUnique u1) (MkUnique u2) = u1 <#  u2
181 leUnique (MkUnique u1) (MkUnique u2) = u1 <=# u2
182
183 cmpUnique (MkUnique u1) (MkUnique u2)
184   = if u1 ==# u2 then EQ else if u1 <# u2 then LT else GT
185
186 instance Eq Unique where
187     a == b = eqUnique a b
188     a /= b = not (eqUnique a b)
189
190 instance Ord Unique where
191     a  < b = ltUnique a b
192     a <= b = leUnique a b
193     a  > b = not (leUnique a b)
194     a >= b = not (ltUnique a b)
195     compare a b = cmpUnique a b
196
197 -----------------
198 instance Uniquable Unique where
199     getUnique u = u
200 \end{code}
201
202 We do sometimes make strings with @Uniques@ in them:
203 \begin{code}
204 pprUnique, pprUnique10 :: Unique -> SDoc
205
206 pprUnique uniq
207   = case unpkUnique uniq of
208       (tag, u) -> finish_ppr tag u (iToBase62 u)
209
210 pprUnique10 uniq        -- in base-10, dudes
211   = case unpkUnique uniq of
212       (tag, u) -> finish_ppr tag u (int u)
213
214 finish_ppr 't' u pp_u | u < 26
215   =     -- Special case to make v common tyvars, t1, t2, ...
216         -- come out as a, b, ... (shorter, easier to read)
217     char (chr (ord 'a' + u))
218 finish_ppr tag u pp_u = char tag <> pp_u
219
220 instance Outputable Unique where
221     ppr u = pprUnique u
222
223 instance Show Unique where
224     showsPrec p uniq = showsPrecSDoc p (pprUnique uniq)
225 \end{code}
226
227 %************************************************************************
228 %*                                                                      *
229 \subsection[Utils-base62]{Base-62 numbers}
230 %*                                                                      *
231 %************************************************************************
232
233 A character-stingy way to read/write numbers (notably Uniques).
234 The ``62-its'' are \tr{[0-9a-zA-Z]}.  We don't handle negative Ints.
235 Code stolen from Lennart.
236 \begin{code}
237 # define BYTE_ARRAY GlaExts.ByteArray
238 # define RUN_ST     ST.runST
239 # define AND_THEN   >>=
240 # define AND_THEN_  >>
241 # define RETURN     return
242
243 iToBase62 :: Int -> SDoc
244
245 iToBase62 n@(I# n#)
246   = ASSERT(n >= 0)
247     let
248 #if __GLASGOW_HASKELL__ < 405
249         bytes = case chars62 of { BYTE_ARRAY bounds_who_needs_'em bytes -> bytes }
250 #else
251         bytes = case chars62 of { BYTE_ARRAY _ _ bytes -> bytes }
252 #endif
253     in
254     if n# <# 62# then
255         case (indexCharArray# bytes n#) of { c ->
256         char (C# c) }
257     else
258         case (quotRem n 62)             of { (q, I# r#) ->
259         case (indexCharArray# bytes r#) of { c  ->
260         (<>) (iToBase62 q) (char (C# c)) }}
261
262 -- keep this at top level! (bug on 94/10/24 WDP)
263 chars62 :: BYTE_ARRAY Int
264 chars62
265   = RUN_ST (
266         newCharArray (0, 61)    AND_THEN \ ch_array ->
267         fill_in ch_array 0 62 "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
268                                 AND_THEN_
269         unsafeFreezeByteArray ch_array
270     )
271   where
272     fill_in ch_array i lim str
273       | i == lim
274       = RETURN ()
275       | otherwise
276       = writeCharArray ch_array i (str !! i)    AND_THEN_
277         fill_in ch_array (i+1) lim str
278 \end{code}
279
280 %************************************************************************
281 %*                                                                      *
282 \subsection[Uniques-prelude]{@Uniques@ for wired-in Prelude things}
283 %*                                                                      *
284 %************************************************************************
285
286 Allocation of unique supply characters:
287         v,t,u : for renumbering value-, type- and usage- vars.
288         other a-z: lower case chars for unique supplies (see Main.lhs)
289         B:   builtin
290         C-E: pseudo uniques     (used in native-code generator)
291         X:   uniques derived by deriveUnique
292         _:   unifiable tyvars   (above)
293         0-9: prelude things below
294
295 \begin{code}
296 mkAlphaTyVarUnique i            = mkUnique '1' i
297
298 mkPreludeClassUnique i          = mkUnique '2' i
299
300 -- Prelude type constructors occupy *three* slots.
301 -- The first is for the tycon itself; the latter two
302 -- are for the generic to/from Ids.  See TysWiredIn.mk_tc_gen_info.
303
304 mkPreludeTyConUnique i          = mkUnique '3' (3*i)
305 mkTupleTyConUnique Boxed   a    = mkUnique '4' (3*a)
306 mkTupleTyConUnique Unboxed a    = mkUnique '5' (3*a)
307
308 -- Data constructor keys occupy *two* slots.  The first is used for the
309 -- data constructor itself and its wrapper function (the function that
310 -- evaluates arguments as necessary and calls the worker). The second is
311 -- used for the worker function (the function that builds the constructor
312 -- representation).
313
314 mkPreludeDataConUnique i        = mkUnique '6' (2*i)    -- Must be alphabetic
315 mkTupleDataConUnique Boxed a    = mkUnique '7' (2*a)    -- ditto (*may* be used in C labels)
316 mkTupleDataConUnique Unboxed a  = mkUnique '8' (2*a)
317
318 -- This one is used for a tiresome reason
319 -- to improve a consistency-checking error check in the renamer
320 isTupleKey u = case unpkUnique u of
321                 (tag,_) -> tag == '4' || tag == '5' || tag == '7' || tag == '8'
322
323 mkPrimOpIdUnique op             = mkUnique '9' op
324 mkPreludeMiscIdUnique i         = mkUnique '0' i
325
326 -- No numbers left anymore, so I pick something different for the character
327 -- tag 
328 mkPArrDataConUnique a           = mkUnique ':' (2*a)
329
330 -- The "tyvar uniques" print specially nicely: a, b, c, etc.
331 -- See pprUnique for details
332
333 initTyVarUnique :: Unique
334 initTyVarUnique = mkUnique 't' 0
335
336 initTidyUniques :: (Unique, Unique)     -- Global and local
337 initTidyUniques = (mkUnique 'g' 0, mkUnique 'x' 0)
338
339 mkPseudoUnique1, mkPseudoUnique2, mkPseudoUnique3, 
340    mkBuiltinUnique :: Int -> Unique
341
342 mkBuiltinUnique i = mkUnique 'B' i
343 mkPseudoUnique1 i = mkUnique 'C' i -- used for getUnique on Regs
344 mkPseudoUnique2 i = mkUnique 'D' i -- used in NCG for getUnique on RealRegs
345 mkPseudoUnique3 i = mkUnique 'E' i -- used in NCG spiller to create spill VirtualRegs
346 \end{code}
347