0.8.3.2:
[sbcl.git] / src / code / target-sxhash.lisp
1 ;;;; hashing functions
2
3 ;;;; This software is part of the SBCL system. See the README file for
4 ;;;; more information.
5 ;;;;
6 ;;;; This software is derived from the CMU CL system, which was
7 ;;;; written at Carnegie Mellon University and released into the
8 ;;;; public domain. The software is in the public domain and is
9 ;;;; provided with absolutely no warranty. See the COPYING and CREDITS
10 ;;;; files for more information.
11
12 (in-package "SB!IMPL")
13
14 ;;; the depthoid explored when calculating hash values
15 ;;;
16 ;;; "Depthoid" here is a sort of mixture of what Common Lisp ordinarily calls
17 ;;; depth and what Common Lisp ordinarily calls length; it's incremented either
18 ;;; when we descend into a compound object or when we step through elements of
19 ;;; a compound object.
20 (defconstant +max-hash-depthoid+ 4)
21 \f
22 ;;;; mixing hash values
23
24 ;;; a function for mixing hash values
25 ;;;
26 ;;; desiderata:
27 ;;;   * Non-commutativity keeps us from hashing e.g. #(1 5) to the
28 ;;;     same value as #(5 1), and ending up in real trouble in some
29 ;;;     special cases like bit vectors the way that CMUCL 18b SXHASH 
30 ;;;     does. (Under CMUCL 18b, SXHASH of any bit vector is 1..)
31 ;;;   * We'd like to scatter our hash values over the entire possible range
32 ;;;     of values instead of hashing small or common key values (like
33 ;;;     2 and NIL and #\a) to small FIXNUMs the way that the CMUCL 18b
34 ;;;     SXHASH function does, again helping to avoid pathologies like
35 ;;;     hashing all bit vectors to 1.
36 ;;;   * We'd like this to be simple and fast, too.
37 ;;;
38 ;;; FIXME: Should this be INLINE?
39 (declaim (ftype (function ((and fixnum unsigned-byte)
40                            (and fixnum unsigned-byte))
41                           (and fixnum unsigned-byte)) mix))
42 (defun mix (x y)
43   ;; FIXME: We wouldn't need the nasty (SAFETY 0) here if the compiler
44   ;; were smarter about optimizing ASH. (Without the THE FIXNUM below,
45   ;; and the (SAFETY 0) declaration here to get the compiler to trust
46   ;; it, the sbcl-0.5.0m cross-compiler running under Debian
47   ;; cmucl-2.4.17 turns the ASH into a full call, requiring the
48   ;; UNSIGNED-BYTE 32 argument to be coerced to a bignum, requiring
49   ;; consing, and thus generally obliterating performance.)
50   (declare (optimize (speed 3) (safety 0)))
51   (declare (type (and fixnum unsigned-byte) x y))
52   ;; the ideas here:
53   ;;   * Bits diffuse in both directions (shifted left by up to 2 places
54   ;;     in the calculation of XY, and shifted right by up to 5 places
55   ;;     by the ASH).
56   ;;   * The #'+ and #'LOGXOR operations don't commute with each other,
57   ;;     so different bit patterns are mixed together as they shift
58   ;;     past each other.
59   ;;   * The arbitrary constant in the #'LOGXOR expression is intended
60   ;;     to help break up any weird anomalies we might otherwise get
61   ;;     when hashing highly regular patterns.
62   ;; (These are vaguely like the ideas used in many cryptographic
63   ;; algorithms, but we're not pushing them hard enough here for them
64   ;; to be cryptographically strong.)
65   (let* ((xy (+ (* x 3) y)))
66     (logand most-positive-fixnum
67             (logxor 441516657
68                     xy
69                     (ash xy -5)))))
70 \f
71 ;;;; hashing strings
72 ;;;;
73 ;;;; Note that this operation is used in compiler symbol table lookups, so we'd
74 ;;;; like it to be fast.
75
76 #!-sb-fluid (declaim (inline %sxhash-substring))
77 (defun %sxhash-substring (string &optional (count (length string)))
78   ;; FIXME: As in MIX above, we wouldn't need (SAFETY 0) here if the
79   ;; cross-compiler were smarter about ASH, but we need it for sbcl-0.5.0m.
80   (declare (optimize (speed 3) (safety 0)))
81   (declare (type string string))
82   (declare (type index count))
83   (let ((result 408967240))
84     (declare (type fixnum result))
85     (unless (typep string '(vector nil))
86       (dotimes (i count)
87         (declare (type index i))
88         (mixf result
89               (the fixnum
90                 (ash (char-code (aref string i)) 5)))))
91     result))
92 ;;; test:
93 ;;;   (let ((ht (make-hash-table :test 'equal)))
94 ;;;     (do-all-symbols (symbol)
95 ;;;       (let* ((string (symbol-name symbol))
96 ;;;           (hash (%sxhash-substring string)))
97 ;;;      (if (gethash hash ht)
98 ;;;          (unless (string= (gethash hash ht) string)
99 ;;;            (format t "collision: ~S ~S~%" string (gethash hash ht)))
100 ;;;          (setf (gethash hash ht) string))))
101 ;;;     (format t "final count=~W~%" (hash-table-count ht)))
102
103 (defun %sxhash-simple-string (x)
104   (declare (optimize speed))
105   (declare (type simple-string x))
106   (%sxhash-substring x))
107
108 (defun %sxhash-simple-substring (x count)
109   (declare (optimize speed))
110   (declare (type simple-string x))
111   (declare (type index count))
112   (%sxhash-substring x count))
113 \f
114 ;;;; the SXHASH function
115
116 (defun sxhash (x)
117   ;; profiling SXHASH is hard, but we might as well try to make it go
118   ;; fast, in case it is the bottleneck somwhere.  -- CSR, 2003-03-14
119   (declare (optimize speed))
120   (labels ((sxhash-number (x)
121              (etypecase x
122                (fixnum (sxhash x))      ; through DEFTRANSFORM
123                (integer (sb!bignum:sxhash-bignum x))
124                (single-float (sxhash x)) ; through DEFTRANSFORM
125                (double-float (sxhash x)) ; through DEFTRANSFORM
126                #!+long-float (long-float (error "stub: no LONG-FLOAT"))
127                (ratio (let ((result 127810327))
128                         (declare (type fixnum result))
129                         (mixf result (sxhash-number (numerator x)))
130                         (mixf result (sxhash-number (denominator x)))
131                         result))
132                (complex (let ((result 535698211))
133                           (declare (type fixnum result))
134                           (mixf result (sxhash-number (realpart x)))
135                           (mixf result (sxhash-number (imagpart x)))
136                           result))))
137            (sxhash-recurse (x &optional (depthoid +max-hash-depthoid+))
138              (declare (type index depthoid))
139              (typecase x
140                (cons
141                 (if (plusp depthoid)
142                     (mix (sxhash-recurse (car x) (1- depthoid))
143                          (sxhash-recurse (cdr x) (1- depthoid)))
144                     261835505))
145                (instance
146                 (if (or (typep x 'structure-object) (typep x 'condition))
147                     (logxor 422371266
148                             (sxhash ; through DEFTRANSFORM
149                              (classoid-name
150                               (layout-classoid (%instance-layout x)))))
151                     (sxhash-instance x)))
152                (symbol (sxhash x)) ; through DEFTRANSFORM
153                (array
154                 (typecase x
155                   (simple-string (sxhash x)) ; through DEFTRANSFORM
156                   (string (%sxhash-substring x))
157                   (simple-bit-vector (sxhash x)) ; through DEFTRANSFORM
158                   (bit-vector
159                    ;; FIXME: It must surely be possible to do better
160                    ;; than this.  The problem is that a non-SIMPLE
161                    ;; BIT-VECTOR could be displaced to another, with a
162                    ;; non-zero offset -- so that significantly more
163                    ;; work needs to be done using the %RAW-BITS
164                    ;; approach.  This will probably do for now.
165                    (sxhash-recurse (copy-seq x) depthoid))
166                   (t (logxor 191020317 (sxhash (array-rank x))))))
167                (character
168                 (logxor 72185131
169                         (sxhash (char-code x)))) ; through DEFTRANSFORM
170                ;; general, inefficient case of NUMBER
171                (number (sxhash-number x))
172                (generic-function (sxhash-instance x))
173                (t 42))))
174     (sxhash-recurse x)))
175 \f
176 ;;;; the PSXHASH function
177
178 ;;;; FIXME: This code does a lot of unnecessary full calls. It could be made
179 ;;;; more efficient (in both time and space) by rewriting it along the lines
180 ;;;; of the SXHASH code above.
181
182 ;;; like SXHASH, but for EQUALP hashing instead of EQUAL hashing
183 (defun psxhash (key &optional (depthoid +max-hash-depthoid+))
184   (declare (optimize speed))
185   (declare (type (integer 0 #.+max-hash-depthoid+) depthoid))
186   ;; Note: You might think it would be cleaner to use the ordering given in the
187   ;; table from Figure 5-13 in the EQUALP section of the ANSI specification
188   ;; here. So did I, but that is a snare for the unwary! Nothing in the ANSI
189   ;; spec says that HASH-TABLE can't be a STRUCTURE-OBJECT, and in fact our
190   ;; HASH-TABLEs *are* STRUCTURE-OBJECTs, so we need to pick off the special
191   ;; HASH-TABLE behavior before we fall through to the generic STRUCTURE-OBJECT
192   ;; comparison behavior.
193   (typecase key
194     (array (array-psxhash key depthoid))
195     (hash-table (hash-table-psxhash key))
196     (structure-object (structure-object-psxhash key depthoid))
197     (cons (list-psxhash key depthoid))
198     (number (number-psxhash key))
199     (character (sxhash (char-upcase key)))
200     (t (sxhash key))))
201
202 (defun array-psxhash (key depthoid)
203   (declare (optimize speed))
204   (declare (type array key))
205   (declare (type (integer 0 #.+max-hash-depthoid+) depthoid))
206   (typecase key
207     ;; VECTORs have to be treated specially because ANSI specifies
208     ;; that we must respect fill pointers.
209     (vector
210      (macrolet ((frob ()
211                   '(let ((result 572539))
212                      (declare (type fixnum result))
213                      (mixf result (length key))
214                      (dotimes (i (min depthoid (length key)))
215                        (declare (type fixnum i))
216                        (mixf result
217                              (psxhash (aref key i)
218                                       (- depthoid 1 i))))
219                      result)))
220        ;; CMU can compile SIMPLE-ARRAY operations so much more efficiently
221        ;; than the general case that it's probably worth picking off the
222        ;; common special cases.
223        (typecase key
224          (simple-string
225           ;;(format t "~&SIMPLE-STRING special case~%")
226           (frob))
227          (simple-vector
228           ;;(format t "~&SIMPLE-VECTOR special case~%")
229           (frob))
230          (t (frob)))))
231     ;; Any other array can be hashed by working with its underlying
232     ;; one-dimensional physical representation.
233     (t
234      (let ((result 60828))
235        (declare (type fixnum result))
236        (dotimes (i (min depthoid (array-rank key)))
237          (mixf result (array-dimension key i)))
238        (dotimes (i (min depthoid (array-total-size key)))
239          (mixf result
240                (psxhash (row-major-aref key i)
241                         (- depthoid 1 i))))
242        result))))
243
244 (defun structure-object-psxhash (key depthoid)
245   (declare (optimize speed))
246   (declare (type structure-object key))
247   (declare (type (integer 0 #.+max-hash-depthoid+) depthoid))
248   (let* ((layout (%instance-layout key)) ; i.e. slot #0
249          (length (layout-length layout))
250          (classoid (layout-classoid layout))
251          (name (classoid-name classoid))
252          (result (mix (sxhash name) (the fixnum 79867))))
253     (declare (type fixnum result))
254     (dotimes (i (min depthoid (1- length)))
255       (declare (type fixnum i))
256       (let ((j (1+ i))) ; skipping slot #0, which is for LAYOUT
257         (declare (type fixnum j))
258         (mixf result
259               (psxhash (%instance-ref key j)
260                        (1- depthoid)))))
261     result))
262
263 (defun list-psxhash (key depthoid)
264   (declare (optimize speed))
265   (declare (type list key))
266   (declare (type (integer 0 #.+max-hash-depthoid+) depthoid))
267   (cond ((null key)
268          (the fixnum 480929))
269         ((zerop depthoid)
270          (the fixnum 779578))
271         (t
272          (mix (psxhash (car key) (1- depthoid))
273               (psxhash (cdr key) (1- depthoid))))))
274
275 (defun hash-table-psxhash (key)
276   (declare (optimize speed))
277   (declare (type hash-table key))
278   (let ((result 103924836))
279     (declare (type fixnum result))
280     (mixf result (hash-table-count key))
281     (mixf result (sxhash (hash-table-test key)))
282     result))
283
284 (defun number-psxhash (key)
285   (declare (optimize speed))
286   (declare (type number key))
287   (flet ((sxhash-double-float (val)
288            (declare (type double-float val))
289            ;; FIXME: Check to make sure that the DEFTRANSFORM kicks in and the
290            ;; resulting code works without consing. (In Debian cmucl 2.4.17,
291            ;; it didn't.)
292            (sxhash val)))
293     (etypecase key
294       (integer (sxhash key))
295       (float (macrolet ((frob (type)
296                           (let ((lo (coerce most-negative-fixnum type))
297                                 (hi (coerce most-positive-fixnum type)))
298                             `(cond (;; This clause allows FIXNUM-sized integer
299                                     ;; values to be handled without consing.
300                                     (<= ,lo key ,hi)
301                                     (multiple-value-bind (q r)
302                                         (floor (the (,type ,lo ,hi) key))
303                                       (if (zerop (the ,type r))
304                                           (sxhash q)
305                                           (sxhash-double-float
306                                            (coerce key 'double-float)))))
307                                    (t
308                                     (multiple-value-bind (q r) (floor key)
309                                       (if (zerop (the ,type r))
310                                           (sxhash q)
311                                           (sxhash-double-float
312                                            (coerce key 'double-float)))))))))
313                (etypecase key
314                  (single-float (frob single-float))
315                  (double-float (frob double-float))
316                  #!+long-float
317                  (long-float (error "LONG-FLOAT not currently supported")))))
318       (rational (if (and (<= most-negative-double-float
319                              key
320                              most-positive-double-float)
321                          (= (coerce key 'double-float) key))
322                     (sxhash-double-float (coerce key 'double-float))
323                     (sxhash key)))
324       (complex (if (zerop (imagpart key))
325                    (number-psxhash (realpart key))
326                    (let ((result 330231))
327                      (declare (type fixnum result))
328                      (mixf result (number-psxhash (realpart key)))
329                      (mixf result (number-psxhash (imagpart key)))
330                      result))))))