c77b2579c3ba2336b1d74c7b2adc53ae953fb632
[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 SXHASH 18b
30 ;;;     does. (Under CMUCL 18b, SXHASH of any bit vector is 1..)
31 ;;;   * We'd like to scatter our hash values 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     (declare (type (unsigned-byte 32) xy))
67     (the (and fixnum unsigned-byte)
68          (logand most-positive-fixnum
69                  (logxor 441516657
70                          xy
71                          (the fixnum (ash xy -5)))))))
72 \f
73 ;;;; hashing strings
74 ;;;;
75 ;;;; Note that this operation is used in compiler symbol table lookups, so we'd
76 ;;;; like it to be fast.
77
78 #!-sb-fluid (declaim (inline %sxhash-substring))
79 (defun %sxhash-substring (string &optional (count (length string)))
80   ;; FIXME: As in MIX above, we wouldn't need (SAFETY 0) here if the
81   ;; cross-compiler were smarter about ASH, but we need it for sbcl-0.5.0m.
82   (declare (optimize (speed 3) (safety 0)))
83   (declare (type string string))
84   (declare (type index count))
85   (let ((result 408967240))
86     (declare (type fixnum result))
87     (dotimes (i count)
88       (declare (type index i))
89       (mixf result
90             (the fixnum
91                  (ash (char-code (aref string i)) 5))))
92     result))
93 ;;; test:
94 ;;;   (let ((ht (make-hash-table :test 'equal)))
95 ;;;     (do-all-symbols (symbol)
96 ;;;       (let* ((string (symbol-name symbol))
97 ;;;           (hash (%sxhash-substring string)))
98 ;;;      (if (gethash hash ht)
99 ;;;          (unless (string= (gethash hash ht) string)
100 ;;;            (format t "collision: ~S ~S~%" string (gethash hash ht)))
101 ;;;          (setf (gethash hash ht) string))))
102 ;;;     (format t "final count=~D~%" (hash-table-count ht)))
103
104 (defun %sxhash-simple-string (x)
105   (declare (optimize speed))
106   (declare (type simple-string x))
107   (%sxhash-substring x))
108
109 (defun %sxhash-simple-substring (x count)
110   (declare (optimize speed))
111   (declare (type simple-string x))
112   (declare (type index count))
113   (%sxhash-substring x count))
114 \f
115 ;;;; the SXHASH function
116
117 (defun sxhash (x)
118   (labels ((sxhash-number (x)
119              (etypecase x
120                (fixnum (sxhash x))      ; through DEFTRANSFORM
121                (integer (sb!bignum:sxhash-bignum x))
122                (single-float (sxhash x)) ; through DEFTRANSFORM
123                (double-float (sxhash x)) ; through DEFTRANSFORM
124                #!+long-float (long-float (error "stub: no LONG-FLOAT"))
125                (ratio (let ((result 127810327))
126                         (declare (type fixnum result))
127                         (mixf result (sxhash-number (numerator x)))
128                         (mixf result (sxhash-number (denominator x)))
129                         result))
130                (complex (let ((result 535698211))
131                           (declare (type fixnum result))
132                           (mixf result (sxhash-number (realpart x)))
133                           (mixf result (sxhash-number (imagpart x)))
134                           result))))
135            (sxhash-recurse (x &optional (depthoid +max-hash-depthoid+))
136              (declare (type index depthoid))
137              (typecase x
138                (list
139                 (if (plusp depthoid)
140                     (mix (sxhash-recurse (car x) (1- depthoid))
141                          (sxhash-recurse (cdr x) (1- depthoid)))
142                     261835505))
143                (instance
144                 (if (typep x 'structure-object)
145                     (logxor 422371266
146                             (sxhash ; through DEFTRANSFORM
147                              (class-name (layout-class (%instance-layout x)))))
148                     309518995))
149                (symbol (sxhash x)) ; through DEFTRANSFORM
150                (array
151                 (typecase x
152                   (simple-string (sxhash x)) ; through DEFTRANSFORM
153                   (string (%sxhash-substring x))
154                   (bit-vector (let ((result 410823708))
155                                 (declare (type fixnum result))
156                                 (dotimes (i (min depthoid (length x)))
157                                   (mixf result (aref x i)))
158                                 result))
159                   (t (logxor 191020317 (sxhash (array-rank x))))))
160                (character
161                 (logxor 72185131
162                         (sxhash (char-code x)))) ; through DEFTRANSFORM
163                ;; general, inefficient case of NUMBER
164                (number (sxhash-number x))
165                (t 42))))
166     (sxhash-recurse x)))
167 \f
168 ;;;; the PSXHASH function
169
170 ;;;; FIXME: This code does a lot of unnecessary full calls. It could be made
171 ;;;; more efficient (in both time and space) by rewriting it along the lines
172 ;;;; of the SXHASH code above.
173
174 ;;; like SXHASH, but for EQUALP hashing instead of EQUAL hashing
175 (defun psxhash (key &optional (depthoid +max-hash-depthoid+))
176   (declare (optimize speed))
177   (declare (type (integer 0 #.+max-hash-depthoid+) depthoid))
178   ;; Note: You might think it would be cleaner to use the ordering given in the
179   ;; table from Figure 5-13 in the EQUALP section of the ANSI specification
180   ;; here. So did I, but that is a snare for the unwary! Nothing in the ANSI
181   ;; spec says that HASH-TABLE can't be a STRUCTURE-OBJECT, and in fact our
182   ;; HASH-TABLEs *are* STRUCTURE-OBJECTs, so we need to pick off the special
183   ;; HASH-TABLE behavior before we fall through to the generic STRUCTURE-OBJECT
184   ;; comparison behavior.
185   (typecase key
186     (array (array-psxhash key depthoid))
187     (hash-table (hash-table-psxhash key))
188     (structure-object (structure-object-psxhash key depthoid))
189     (list (list-psxhash key depthoid))
190     (number (number-psxhash key))
191     (character (sxhash (char-upcase key)))
192     (t (sxhash key))))
193
194 (defun array-psxhash (key depthoid)
195   (declare (optimize speed))
196   (declare (type array key))
197   (declare (type (integer 0 #.+max-hash-depthoid+) depthoid))
198   (typecase key
199     ;; VECTORs have to be treated specially because ANSI specifies
200     ;; that we must respect fill pointers.
201     (vector
202      (macrolet ((frob ()
203                   '(let ((result 572539))
204                      (declare (type fixnum result))
205                      (mixf result (length key))
206                      (dotimes (i (min depthoid (length key)))
207                        (declare (type fixnum i))
208                        (mixf result
209                              (psxhash (aref key i)
210                                       (- depthoid 1 i))))
211                      result)))
212        ;; CMU can compile SIMPLE-ARRAY operations so much more efficiently
213        ;; than the general case that it's probably worth picking off the
214        ;; common special cases.
215        (typecase key
216          (simple-string
217           ;;(format t "~&SIMPLE-STRING special case~%")
218           (frob))
219          (simple-vector
220           ;;(format t "~&SIMPLE-VECTOR special case~%")
221           (frob))
222          (t (frob)))))
223     ;; Any other array can be hashed by working with its underlying
224     ;; one-dimensional physical representation.
225     (t
226      (let ((result 60828))
227        (declare (type fixnum result))
228        (dotimes (i (min depthoid (array-rank key)))
229          (mixf result (array-dimension key i)))
230        (dotimes (i (min depthoid (array-total-size key)))
231          (mixf result
232                (psxhash (row-major-aref key i)
233                         (- depthoid 1 i))))
234        result))))
235
236 (defun structure-object-psxhash (key depthoid)
237   (declare (optimize speed))
238   (declare (type structure-object key))
239   (declare (type (integer 0 #.+max-hash-depthoid+) depthoid))
240   (let* ((layout (%instance-layout key)) ; i.e. slot #0
241          (length (layout-length layout))
242          (class (layout-class layout))
243          (name (class-name class))
244          (result (mix (sxhash name) (the fixnum 79867))))
245     (declare (type fixnum result))
246     (dotimes (i (min depthoid (1- length)))
247       (declare (type fixnum i))
248       (let ((j (1+ i))) ; skipping slot #0, which is for LAYOUT
249         (declare (type fixnum j))
250         (mixf result
251               (psxhash (%instance-ref key j)
252                        (1- depthoid)))))
253     result))
254
255 (defun list-psxhash (key depthoid)
256   (declare (optimize speed))
257   (declare (type list key))
258   (declare (type (integer 0 #.+max-hash-depthoid+) depthoid))
259   (cond ((null key)
260          (the fixnum 480929))
261         ((zerop depthoid)
262          (the fixnum 779578))
263         (t
264          (mix (psxhash (car key) (1- depthoid))
265               (psxhash (cdr key) (1- depthoid))))))
266
267 (defun hash-table-psxhash (key)
268   (declare (optimize speed))
269   (declare (type hash-table key))
270   (let ((result 103924836))
271     (declare (type fixnum result))
272     (mixf result (hash-table-count key))
273     (mixf result (sxhash (hash-table-test key)))
274     result))
275
276 (defun number-psxhash (key)
277   (declare (optimize speed))
278   (declare (type number key))
279   (flet ((sxhash-double-float (val)
280            (declare (type double-float val))
281            ;; FIXME: Check to make sure that the DEFTRANSFORM kicks in and the
282            ;; resulting code works without consing. (In Debian cmucl 2.4.17,
283            ;; it didn't.)
284            (sxhash val)))
285     (etypecase key
286       (integer (sxhash key))
287       (float (macrolet ((frob (type)
288                           (let ((lo (coerce most-negative-fixnum type))
289                                 (hi (coerce most-positive-fixnum type)))
290                             `(cond (;; This clause allows FIXNUM-sized integer
291                                     ;; values to be handled without consing.
292                                     (<= ,lo key ,hi)
293                                     (multiple-value-bind (q r)
294                                         (floor (the (,type ,lo ,hi) key))
295                                       (if (zerop (the ,type r))
296                                           (sxhash q)
297                                           (sxhash-double-float
298                                            (coerce key 'double-float)))))
299                                    (t
300                                     (multiple-value-bind (q r) (floor key)
301                                       (if (zerop (the ,type r))
302                                           (sxhash q)
303                                           (sxhash-double-float
304                                            (coerce key 'double-float)))))))))
305                (etypecase key
306                  (single-float (frob single-float))
307                  (double-float (frob double-float))
308                  (short-float (frob short-float))
309                  (long-float (error "LONG-FLOAT not currently supported")))))
310       (rational (if (and (<= most-negative-double-float
311                              key
312                              most-positive-double-float)
313                          (= (coerce key 'double-float) key))
314                     (sxhash-double-float (coerce key 'double-float))
315                     (sxhash key)))
316       (complex (if (zerop (imagpart key))
317                    (number-psxhash (realpart key))
318                    (let ((result 330231))
319                      (declare (type fixnum result))
320                      (mixf result (number-psxhash (realpart key)))
321                      (mixf result (number-psxhash (imagpart key)))
322                      result))))))