d6bba0039af63fddca08ac40db8b93899fa8c1a7
[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 (eval-when (:compile-toplevel :load-toplevel :execute)
21 (defconstant +max-hash-depthoid+ 4)
22 ) ; EVAL-WHEN
23 \f
24 ;;;; mixing hash values
25
26 ;;; a function for mixing hash values
27 ;;;
28 ;;; desiderata:
29 ;;;   * Non-commutativity keeps us from hashing e.g. #(1 5) to the
30 ;;;     same value as #(5 1), and ending up in real trouble in some
31 ;;;     special cases like bit vectors the way that CMUCL SXHASH 18b
32 ;;;     does. (Under CMUCL 18b, SXHASH of any bit vector is 1..)
33 ;;;   * We'd like to scatter our hash values the entire possible range
34 ;;;     of values instead of hashing small or common key values (like
35 ;;;     2 and NIL and #\a) to small FIXNUMs the way that the CMUCL 18b
36 ;;;     SXHASH function does, again helping to avoid pathologies like
37 ;;;     hashing all bit vectors to 1.
38 ;;;   * We'd like this to be simple and fast, too.
39 ;;;
40 ;;; FIXME: Should this be INLINE?
41 (declaim (ftype (function ((and fixnum unsigned-byte)
42                            (and fixnum unsigned-byte))
43                           (and fixnum unsigned-byte)) mix))
44 (defun mix (x y)
45   ;; FIXME: We wouldn't need the nasty (SAFETY 0) here if the compiler
46   ;; were smarter about optimizing ASH. (Without the THE FIXNUM below,
47   ;; and the (SAFETY 0) declaration here to get the compiler to trust
48   ;; it, the sbcl-0.5.0m cross-compiler running under Debian
49   ;; cmucl-2.4.17 turns the ASH into a full call, requiring the
50   ;; UNSIGNED-BYTE 32 argument to be coerced to a bignum, requiring
51   ;; consing, and thus generally obliterating performance.)
52   (declare (optimize (speed 3) (safety 0)))
53   (declare (type (and fixnum unsigned-byte) x y))
54   ;; the ideas here:
55   ;;   * Bits diffuse in both directions (shifted left by up to 2 places
56   ;;     in the calculation of XY, and shifted right by up to 5 places
57   ;;     by the ASH).
58   ;;   * The #'+ and #'LOGXOR operations don't commute with each other,
59   ;;     so different bit patterns are mixed together as they shift
60   ;;     past each other.
61   ;;   * The arbitrary constant in the #'LOGXOR expression is intended
62   ;;     to help break up any weird anomalies we might otherwise get
63   ;;     when hashing highly regular patterns.
64   ;; (These are vaguely like the ideas used in many cryptographic
65   ;; algorithms, but we're not pushing them hard enough here for them
66   ;; to be cryptographically strong.)
67   (let* ((xy (+ (* x 3) y)))
68     (declare (type (unsigned-byte 32) xy))
69     (the (and fixnum unsigned-byte)
70          (logand most-positive-fixnum
71                  (logxor 441516657
72                          xy
73                          (the fixnum (ash xy -5)))))))
74 \f
75 ;;;; hashing strings
76 ;;;;
77 ;;;; Note that this operation is used in compiler symbol table lookups, so we'd
78 ;;;; like it to be fast.
79
80 #!-sb-fluid (declaim (inline %sxhash-substring))
81 (defun %sxhash-substring (string &optional (count (length string)))
82   ;; FIXME: As in MIX above, we wouldn't need (SAFETY 0) here if the
83   ;; cross-compiler were smarter about ASH, but we need it for sbcl-0.5.0m.
84   (declare (optimize (speed 3) (safety 0)))
85   (declare (type string string))
86   (declare (type index count))
87   (let ((result 408967240))
88     (declare (type fixnum result))
89     (dotimes (i count)
90       (declare (type index i))
91       (mixf result
92             (the fixnum
93                  (ash (char-code (aref string i)) 5))))
94     result))
95 ;;; test:
96 ;;;   (let ((ht (make-hash-table :test 'equal)))
97 ;;;     (do-all-symbols (symbol)
98 ;;;       (let* ((string (symbol-name symbol))
99 ;;;           (hash (%sxhash-substring string)))
100 ;;;      (if (gethash hash ht)
101 ;;;          (unless (string= (gethash hash ht) string)
102 ;;;            (format t "collision: ~S ~S~%" string (gethash hash ht)))
103 ;;;          (setf (gethash hash ht) string))))
104 ;;;     (format t "final count=~D~%" (hash-table-count ht)))
105
106 (defun %sxhash-simple-string (x)
107   (declare (optimize speed))
108   (declare (type simple-string x))
109   (%sxhash-substring x))
110
111 (defun %sxhash-simple-substring (x count)
112   (declare (optimize speed))
113   (declare (type simple-string x))
114   (declare (type index count))
115   (%sxhash-substring x count))
116 \f
117 ;;;; the SXHASH function
118
119 (defun sxhash (x)
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                (list
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 (typep x 'structure-object)
147                     (logxor 422371266
148                             (sxhash ; through DEFTRANSFORM
149                              (class-name (layout-class (%instance-layout x)))))
150                     309518995))
151                (symbol (sxhash x)) ; through DEFTRANSFORM
152                (number (sxhash-number x))
153                (array
154                 (typecase x
155                   (simple-string (sxhash x)) ; through DEFTRANSFORM
156                   (string (%sxhash-substring x))
157                   (bit-vector (let ((result 410823708))
158                                 (declare (type fixnum result))
159                                 (dotimes (i (min depthoid (length x)))
160                                   (mixf result (aref x i)))
161                                 result))
162                   (t (logxor 191020317 (sxhash (array-rank x))))))
163                (character
164                 (logxor 72185131
165                         (sxhash (char-code x)))) ; through DEFTRANSFORM
166                (t 42))))
167     (sxhash-recurse x)))
168 \f
169 ;;;; the PSXHASH function
170
171 ;;;; FIXME: This code does a lot of unnecessary full calls. It could be made
172 ;;;; more efficient (in both time and space) by rewriting it along the lines
173 ;;;; of the SXHASH code above.
174
175 ;;; like SXHASH, but for EQUALP hashing instead of EQUAL hashing
176 (defun psxhash (key &optional (depthoid +max-hash-depthoid+))
177   (declare (optimize speed))
178   (declare (type (integer 0 #.+max-hash-depthoid+) depthoid))
179   ;; Note: You might think it would be cleaner to use the ordering given in the
180   ;; table from Figure 5-13 in the EQUALP section of the ANSI specification
181   ;; here. So did I, but that is a snare for the unwary! Nothing in the ANSI
182   ;; spec says that HASH-TABLE can't be a STRUCTURE-OBJECT, and in fact our
183   ;; HASH-TABLEs *are* STRUCTURE-OBJECTs, so we need to pick off the special
184   ;; HASH-TABLE behavior before we fall through to the generic STRUCTURE-OBJECT
185   ;; comparison behavior.
186   (typecase key
187     (array (array-psxhash key depthoid))
188     (hash-table (hash-table-psxhash key))
189     (structure-object (structure-object-psxhash key depthoid))
190     (list (list-psxhash key depthoid))
191     (number (number-psxhash key))
192     (character (sxhash (char-upcase key)))
193     (t (sxhash key))))
194
195 (defun array-psxhash (key depthoid)
196   (declare (optimize speed))
197   (declare (type array key))
198   (declare (type (integer 0 #.+max-hash-depthoid+) depthoid))
199   (typecase key
200     ;; VECTORs have to be treated specially because ANSI specifies
201     ;; that we must respect fill pointers.
202     (vector
203      (macrolet ((frob ()
204                   '(let ((result 572539))
205                      (declare (type fixnum result))
206                      (mixf result (length key))
207                      (dotimes (i (min depthoid (length key)))
208                        (declare (type fixnum i))
209                        (mixf result
210                              (psxhash (aref key i)
211                                       (- depthoid 1 i))))
212                      result)))
213        ;; CMU can compile SIMPLE-ARRAY operations so much more efficiently
214        ;; than the general case that it's probably worth picking off the
215        ;; common special cases.
216        (typecase key
217          (simple-string
218           ;;(format t "~&SIMPLE-STRING special case~%")
219           (frob))
220          (simple-vector
221           ;;(format t "~&SIMPLE-VECTOR special case~%")
222           (frob))
223          (t (frob)))))
224     ;; Any other array can be hashed by working with its underlying
225     ;; one-dimensional physical representation.
226     (t
227      (let ((result 60828))
228        (declare (type fixnum result))
229        (dotimes (i (min depthoid (array-rank key)))
230          (mixf result (array-dimension key i)))
231        (dotimes (i (min depthoid (array-total-size key)))
232          (mixf result
233                (psxhash (row-major-aref key i)
234                         (- depthoid 1 i))))
235        result))))
236
237 (defun structure-object-psxhash (key depthoid)
238   (declare (optimize speed))
239   (declare (type structure-object key))
240   (declare (type (integer 0 #.+max-hash-depthoid+) depthoid))
241   (let* ((layout (%instance-layout key)) ; i.e. slot #0
242          (length (layout-length layout))
243          (class (layout-class layout))
244          (name (class-name class))
245          (result (mix (sxhash name) (the fixnum 79867))))
246     (declare (type fixnum result))
247     (dotimes (i (min depthoid (1- length)))
248       (declare (type fixnum i))
249       (let ((j (1+ i))) ; skipping slot #0, which is for LAYOUT
250         (declare (type fixnum j))
251         (mixf result
252               (psxhash (%instance-ref key j)
253                        (1- depthoid)))))
254     result))
255
256 (defun list-psxhash (key depthoid)
257   (declare (optimize speed))
258   (declare (type list key))
259   (declare (type (integer 0 #.+max-hash-depthoid+) depthoid))
260   (cond ((null key)
261          (the fixnum 480929))
262         ((zerop depthoid)
263          (the fixnum 779578))
264         (t
265          (mix (psxhash (car key) (1- depthoid))
266               (psxhash (cdr key) (1- depthoid))))))
267
268 (defun hash-table-psxhash (key)
269   (declare (optimize speed))
270   (declare (type hash-table key))
271   (let ((result 103924836))
272     (declare (type fixnum result))
273     (mixf result (hash-table-count key))
274     (mixf result (sxhash (hash-table-test key)))
275     result))
276
277 (defun number-psxhash (key)
278   (declare (optimize speed))
279   (declare (type number key))
280   (flet ((sxhash-double-float (val)
281            (declare (type double-float val))
282            ;; FIXME: Check to make sure that the DEFTRANSFORM kicks in and the
283            ;; resulting code works without consing. (In Debian cmucl 2.4.17,
284            ;; it didn't.)
285            (sxhash val)))
286     (etypecase key
287       (integer (sxhash key))
288       (float (macrolet ((frob (type)
289                           (let ((lo (coerce most-negative-fixnum type))
290                                 (hi (coerce most-positive-fixnum type)))
291                             `(cond (;; This clause allows FIXNUM-sized integer
292                                     ;; values to be handled without consing.
293                                     (<= ,lo key ,hi)
294                                     (multiple-value-bind (q r)
295                                         (floor (the (,type ,lo ,hi) key))
296                                       (if (zerop (the ,type r))
297                                           (sxhash q)
298                                           (sxhash-double-float
299                                            (coerce key 'double-float)))))
300                                    (t
301                                     (multiple-value-bind (q r) (floor key)
302                                       (if (zerop (the ,type r))
303                                           (sxhash q)
304                                           (sxhash-double-float
305                                            (coerce key 'double-float)))))))))
306                (etypecase key
307                  (single-float (frob single-float))
308                  (double-float (frob double-float))
309                  (short-float (frob short-float))
310                  (long-float (error "LONG-FLOAT not currently supported")))))
311       (rational (if (and (<= most-negative-double-float
312                              key
313                              most-positive-double-float)
314                          (= (coerce key 'double-float) key))
315                     (sxhash-double-float (coerce key 'double-float))
316                     (sxhash key)))
317       (complex (if (zerop (imagpart key))
318                    (number-psxhash (realpart key))
319                    (let ((result 330231))
320                      (declare (type fixnum result))
321                      (mixf result (number-psxhash (realpart key)))
322                      (mixf result (number-psxhash (imagpart key)))
323                      result))))))
324
325 ;;; SXHASH and PSXHASH should distribute hash values well over the
326 ;;; space of possible values, so that collisions between the hash values
327 ;;; of unequal objects should be very uncommon.
328 ;;;
329 ;;; FIXME: These tests should be enabled once the rest of the system is
330 ;;; stable. (For now, I don't want to mess with things like making sure
331 ;;; that bignums are hashed uniquely.)
332 ;;;#!+sb-test
333 #+nil
334 (let* ((test-cases `((0 . 1)
335                      (0 . 1)
336                      (1 . 0)
337                      ((1 . 0) (0 . 0))
338                      ((0 . 1) (0 . 0))
339                      ((0 . 0) (1 . 0))
340                      ((0 . 0) (0 . 1))
341                      #((1 . 0) (0 . 0))
342                      #((0 . 1) (0 . 0))
343                      #((0 . 0) (1 . 0))
344                      #((0 . 0) (0 . 1))
345                      #((1 . 0) (0 . 0))
346                      #((0 1) (0 0))
347                      #((0 0) (1 0))
348                      #((0 0) (0 1))
349                      #(#(1 0) (0 0))
350                      #(#(0 1) (0 0))
351                      #(#(0 0) (1 0))
352                      #(#(0 0) (0 1))
353                      #(#*00 #*10)
354                      #(#(0 0) (0 1.0d0))
355                      #(#(-0.0d0 0) (1.0 0))
356                      ;; KLUDGE: Some multi-dimensional array test cases would
357                      ;; be good here too, but currently SBCL isn't smart enough
358                      ;; to dump them as literals, and I'm too lazy to make
359                      ;; code to create them at run time. -- WHN 20000111
360                      44 44.0 44.0d0
361                      44 44.0 44.0d0
362                      -44 -44.0 -44.0d0
363                      0 0.0 0.0d0
364                      -0 -0.0 -0.0d0
365                      -121 -121.0 -121.0d0
366                      3/4 0.75 0.75d0
367                      -3/4 -0.75 -0.75d0
368                      44.1 44.1d0
369                      45 45.0 45.0d0
370                      ,(expt 2 33) ,(expt 2.0 33) ,(expt 2.0d0 33)
371                      ,(- (expt 1/2 50)) ,(- (expt 0.5 50)) ,(- (expt 0.5d0 50))
372                      ,(- (expt 1/2 50)) ,(- (expt 0.5 50)) ,(- (expt 0.5d0 50))
373                      #c(1.0 2.0) #c(1 2.0) #c(1.5 -3/2) #c(3/2 -3/2) #c(0 1)
374                      #c(1.0 2.0) #c(1 2.0) #c(1.5 -3/2) #c(3/2 -3/2) #c(0 1)
375                      ,(make-hash-table)
376                      ,(make-hash-table :test 'equal)
377                      "abc" "ABC" "aBc" 'abc #(#\a #\b #\c) #(a b c) #("A" b c)
378                      "abcc"
379                      "" #* #() () (()) #(()) (#())
380                      "" #* #() () (()) #(()) (#())
381                      #\x #\X #\*
382                      #\x #\X #\*)))
383   (dolist (i test-cases)
384     (unless (typep (sxhash i) '(and fixnum unsigned-byte))
385       (error "bad SXHASH behavior for ~S" i))
386     (unless (typep (psxhash i) '(and fixnum unsigned-byte))
387       (error "bad PSXHASH behavior for ~S" i))
388     (dolist (j test-cases)
389       (flet ((t->boolean (x) (if x t nil)))
390         ;; Note: It's possible that a change to the hashing algorithm could
391         ;; leave it correct but still cause this test to bomb by causing an
392         ;; unlucky random collision. That's not very likely (since there are
393         ;; (EXPT 2 29) possible hash values and only on the order of 100 test
394         ;; cases, but it's probably worth checking if you are getting a
395         ;; mystifying error from this test.
396         (unless (eq (t->boolean (equal i j))
397                     (t->boolean (= (sxhash i) (sxhash j))))
398           (error "bad SXHASH behavior for ~S ~S" i j))
399         (unless (eq (t->boolean (equalp i j))
400                     (t->boolean (= (psxhash i) (psxhash j))))
401           (error "bad PSXHASH behavior for ~S ~S" i j))))))
402
403 ;;; FIXME: Test that the the hash functions can deal with common cases without
404 ;;; consing.
405 ;(defun consless-test ()
406 ;  (dotimes (j 100000)
407 ;    (dolist (i '("yo" #(1 2 3) #2A((1 2) (1 2)) (1 2 (3)) 1 1.0 1.0d0))
408 ;      (psxhash i))))