1.0.28.63: SB-EXT:DEFINE-HASH-TABLE-TEST
[sbcl.git] / src / code / target-hash-table.lisp
1 ;;;; that part of the implementation of HASH-TABLE which lives solely
2 ;;;; on the target system, not on the cross-compilation host
3
4 ;;;; This software is part of the SBCL system. See the README file for
5 ;;;; more information.
6 ;;;;
7 ;;;; This software is derived from the CMU CL system, which was
8 ;;;; written at Carnegie Mellon University and released into the
9 ;;;; public domain. The software is in the public domain and is
10 ;;;; provided with absolutely no warranty. See the COPYING and CREDITS
11 ;;;; files for more information.
12
13 (in-package "SB!IMPL")
14 \f
15 ;;;; utilities
16
17 ;;; Code for detecting concurrent accesses to the same table from
18 ;;; multiple threads. Only compiled in when the :SB-HASH-TABLE-DEBUG
19 ;;; feature is enabled. The main reason for the existence of this code
20 ;;; is to detect thread-unsafe uses of hash-tables in sbcl itself,
21 ;;; where debugging anythign can be impossible after an important
22 ;;; internal hash-table has been corrupted. It's plausible that this
23 ;;; could be useful for some user code too, but the runtime cost is
24 ;;; really too high to enable it by default.
25 (defmacro with-concurrent-access-check (hash-table operation &body body)
26   (declare (ignorable hash-table operation)
27            (type (member :read :write) operation))
28   #!-sb-hash-table-debug
29   `(progn ,@body)
30   #!+sb-hash-table-debug
31   (let ((thread-slot-accessor (if (eq operation :read)
32                                   'hash-table-reading-thread
33                                   'hash-table-writing-thread)))
34     (once-only ((hash-table hash-table))
35       `(progn
36          (flet ((body-fun ()
37                   ,@body)
38                 (error-fun ()
39                   ;; Don't signal more errors for this table.
40                   (setf (hash-table-signal-concurrent-access ,hash-table) nil)
41                   (cerror "Ignore the concurrent access"
42                           "Concurrent access to ~A" ,hash-table)))
43            (declare (inline body-fun))
44            (if (hash-table-signal-concurrent-access ,hash-table)
45                (unwind-protect
46                     (progn
47                       (unless (and (null (hash-table-writing-thread
48                                           ,hash-table))
49                                    ,@(when (eq operation :write)
50                                            `((null (hash-table-reading-thread
51                                                     ,hash-table)))))
52                         (error-fun))
53                       (setf (,thread-slot-accessor ,hash-table)
54                             sb!thread::*current-thread*)
55                       (body-fun))
56                  (unless (and ,@(when (eq operation :read)
57                                   `((null (hash-table-writing-thread
58                                            ,hash-table))))
59                               ,@(when (eq operation :write)
60                                   ;; no readers are allowed while writing
61                                   `((null (hash-table-reading-thread
62                                            ,hash-table))
63                                     (eq (hash-table-writing-thread
64                                          ,hash-table)
65                                         sb!thread::*current-thread*))))
66                    (error-fun))
67                  (when (eq (,thread-slot-accessor ,hash-table)
68                            sb!thread::*current-thread*)
69                    ;; this is not 100% correct here and may hide
70                    ;; concurrent access in rare circumstances.
71                    (setf (,thread-slot-accessor ,hash-table) nil)))
72                (body-fun)))))))
73
74 #!-sb-fluid (declaim (inline eq-hash))
75 (defun eq-hash (key)
76   (declare (values hash (member t nil)))
77   (values (pointer-hash key)
78           (oddp (get-lisp-obj-address key))))
79
80 #!-sb-fluid (declaim (inline equal-hash))
81 (defun equal-hash (key)
82   (declare (values hash (member t nil)))
83   (typecase key
84     ;; For some types the definition of EQUAL implies a special hash
85     ((or string cons number bit-vector pathname)
86      (values (sxhash key) nil))
87     ;; Otherwise use an EQ hash, rather than SXHASH, since the values
88     ;; of SXHASH will be extremely badly distributed due to the
89     ;; requirements of the spec fitting badly with our implementation
90     ;; strategy.
91     (t
92      (eq-hash key))))
93
94 #!-sb-fluid (declaim (inline eql-hash))
95 (defun eql-hash (key)
96   (declare (values hash (member t nil)))
97   (if (numberp key)
98       (equal-hash key)
99       (eq-hash key)))
100
101 (defun equalp-hash (key)
102   (declare (values hash (member t nil)))
103   (typecase key
104     ;; Types requiring special treatment. Note that PATHNAME and
105     ;; HASH-TABLE are caught by the STRUCTURE-OBJECT test.
106     ((or array cons number character structure-object)
107      (values (psxhash key) nil))
108     (t
109      (eq-hash key))))
110
111 (declaim (inline index-for-hashing))
112 (defun index-for-hashing (hash length)
113   (declare (type hash hash length))
114   ;; We're using power of two tables which obviously are very
115   ;; sensitive to the exact values of the low bits in the hash
116   ;; value. Do a little shuffling of the value to mix the high bits in
117   ;; there too.
118   (truly-the index
119              (logand (1- length)
120                      (+ (logxor #b11100101010001011010100111
121                                 hash)
122                         (ash hash -3)
123                         (ash hash -12)
124                         (ash hash -20)))))
125
126 \f
127 ;;;; user-defined hash table tests
128
129 (defvar *user-hash-table-tests* nil)
130
131 (defun register-hash-table-test (name hash-fun)
132   (declare (symbol name) (function hash-fun))
133   (unless (fboundp name)
134     (error "Cannot register ~S has a hash table test: undefined function."
135            name))
136   (with-single-package-locked-error
137       (:symbol name "defining ~S as a hash table test")
138     (let* ((test-fun (fdefinition name))
139            (this (list name test-fun hash-fun))
140            (spec (assoc name *user-hash-table-tests*)))
141       (cond (spec
142              (unless (and (eq (second spec) test-fun)
143                           (eq (third spec) hash-fun))
144                (style-warn "Redefining hash table test ~S." name)
145                (setf (cdr spec) (cdr this))))
146             (t
147              (push this *user-hash-table-tests*)))))
148   name)
149
150 (defmacro define-hash-table-test (name hash-function)
151   #!+sb-doc
152   "Defines NAME as a new kind of hash table test for use with the :TEST
153 argument to MAKE-HASH-TABLE, and associates a default HASH-FUNCTION with it.
154
155 NAME must be a symbol naming a global two argument equivalence predicate.
156 Afterwards both 'NAME and #'NAME can be used with :TEST argument. In both
157 cases HASH-TABLE-TEST will return the symbol NAME.
158
159 HASH-FUNCTION must be a symbol naming a global hash function consistent with
160 the predicate, or be a LAMBDA form implementing one in the current lexical
161 environment. The hash function must compute the same hash code for any two
162 objects for which NAME returns true, and subsequent calls with already hashed
163 objects must always return the same hash code.
164
165 Note: The :HASH-FUNCTION keyword argument to MAKE-HASH-TABLE can be used to
166 override the specified default hash-function.
167
168 Attempting to define NAME in a locked package as hash-table test causes a
169 package lock violation.
170
171 Examples:
172
173   ;;; 1.
174
175   ;; We want to use objects of type FOO as keys (by their
176   ;; names.) EQUALP would work, but would make the names
177   ;; case-insensitive -- wich we don't want.
178   (defstruct foo (name nil :type (or null string)))
179
180   ;; Define an equivalence test function and a hash function.
181   (defun foo-name= (f1 f2) (equal (foo-name f1) (foo-name f2)))
182   (defun sxhash-foo-name (f) (sxhash (foo-name f)))
183
184   (define-hash-table-test foo-name= sxhash-foo-name)
185
186   ;; #'foo-name would work too.
187   (defun make-foo-table () (make-hash-table :test 'foo-name=))
188
189   ;;; 2.
190
191   (defun == (x y) (= x y))
192
193   (define-hash-table-test ==
194     (lambda (x)
195       ;; Hash codes must be consistent with test, so
196       ;; not (SXHASH X), since
197       ;;   (= 1 1.0)                   => T
198       ;;   (= (SXHASH 1) (SXHASH 1.0)) => NIL
199       ;; Note: this doesn't deal with complex numbers or
200       ;; bignums too large to represent as double floats.
201       (sxhash (coerce x 'double-float))))
202
203   ;; #'== would work too
204   (defun make-number-table () (make-hash-table :test '==))
205 "
206   (check-type name symbol)
207   (if (member name '(eq eql equal equalp))
208       (error "Cannot redefine standard hash table test ~S." name)
209       (cond ((symbolp hash-function)
210              `(register-hash-table-test ',name (symbol-function ',hash-function)))
211             ((and (consp hash-function) (eq 'lambda (car hash-function)))
212              `(register-hash-table-test ',name #',hash-function))
213             (t
214              (error "Malformed HASH-FUNCTION: ~S" hash-function)))))
215 \f
216 ;;;; construction and simple accessors
217
218 (defconstant +min-hash-table-size+ 16)
219 (defconstant +min-hash-table-rehash-threshold+ (float 1/16 1.0))
220
221 (defun make-hash-table (&key
222                         (test 'eql)
223                         (size +min-hash-table-size+)
224                         (rehash-size 1.5)
225                         (rehash-threshold 1)
226                         (hash-function nil)
227                         (weakness nil)
228                         (synchronized))
229   #!+sb-doc
230   "Create and return a new hash table. The keywords are as follows:
231
232   :TEST
233     Determines how keys are compared. Must a designator for one of the
234     standard hash table tests, or a hash table test defined using
235     SB-EXT:DEFINE-HASH-TABLE-TEST. Additionally, when an explicit
236     HASH-FUNCTION is provided (see below), any two argument equivalence
237     predicate can be used as the TEST.
238
239   :SIZE
240     A hint as to how many elements will be put in this hash table.
241
242   :REHASH-SIZE
243     Indicates how to expand the table when it fills up. If an integer, add
244     space for that many elements. If a floating point number (which must be
245     greater than 1.0), multiply the size by that amount.
246
247   :REHASH-THRESHOLD
248     Indicates how dense the table can become before forcing a rehash. Can be
249     any positive number <=1, with density approaching zero as the threshold
250     approaches 0. Density 1 means an average of one entry per bucket.
251
252   :HASH-FUNCTION
253     If NIL (the default), a hash function based on the TEST argument is used,
254     which then must be one of the standardized hash table test functions, or
255     one for which a default hash function has been defined using
256     SB-EXT:DEFINE-HASH-TABLE-TEST. If HASH-FUNCTION is specified, the TEST
257     argument can be any two argument predicate consistent with it. The
258     HASH-FUNCTION is expected to return a non-negative fixnum hash code.
259
260   :WEAKNESS
261     If NIL (the default) it is a normal non-weak hash table. If one
262     of :KEY, :VALUE, :KEY-AND-VALUE, :KEY-OR-VALUE it is a weak hash table.
263     Depending on the type of weakness the lack of references to the key and
264     the value may allow for removal of the entry. If WEAKNESS is :KEY and the
265     key would otherwise be garbage the entry is eligible for removal from the
266     hash table. Similarly, if WEAKNESS is :VALUE the life of an entry depends
267     on its value's references. If WEAKNESS is :KEY-AND-VALUE and either the
268     key or the value would otherwise be garbage the entry can be removed. If
269     WEAKNESS is :KEY-OR-VALUE and both the key and the value would otherwise
270     be garbage the entry can be removed.
271
272   :SYNCHRONIZED
273     If NIL (the default), the hash-table may have multiple concurrent readers,
274     but results are undefined if a thread writes to the hash-table
275     concurrently with another reader or writer. If T, all concurrent accesses
276     are safe, but note that CLHS 3.6 (Traversal Rules and Side Effects)
277     remains in force. See also: SB-EXT:WITH-LOCKED-HASH-TABLE. This keyword
278     argument is experimental, and may change incompatibly or be removed in the
279     future."
280   (declare (type (or function symbol) test))
281   (declare (type unsigned-byte size))
282   (multiple-value-bind (test test-fun hash-fun)
283       (cond ((or (eq test #'eq) (eq test 'eq))
284              (values 'eq #'eq #'eq-hash))
285             ((or (eq test #'eql) (eq test 'eql))
286              (values 'eql #'eql #'eql-hash))
287             ((or (eq test #'equal) (eq test 'equal))
288              (values 'equal #'equal #'equal-hash))
289             ((or (eq test #'equalp) (eq test 'equalp))
290              (values 'equalp #'equalp #'equalp-hash))
291             (t
292              ;; FIXME: It would be nice to have a compiler-macro
293              ;; that resolved this at compile time: we could grab
294              ;; the alist cell in a LOAD-TIME-VALUE, etc.
295              (dolist (info *user-hash-table-tests*
296                       (if hash-function
297                           (if (functionp test)
298                               (values (%fun-name test) test nil)
299                               (values test (%coerce-callable-to-fun test) nil))
300                        (error "Unknown :TEST for MAKE-HASH-TABLE: ~S"
301                               test)))
302                (destructuring-bind (test-name test-fun hash-fun) info
303                  (when (or (eq test test-name) (eq test test-fun))
304                    (return (values test-name test-fun hash-fun)))))))
305     (when hash-function
306       (setf hash-fun
307             ;; Quickly check if the function has return return type which
308             ;; guarantees that the secondary return value is always NIL:
309             ;; (VALUES * &OPTIONAL), (VALUES * NULL ...) or (VALUES *
310             ;; &OPTIONAL NULL ...)
311             (let* ((actual (%coerce-callable-to-fun hash-function))
312                    (type-spec (%fun-type actual))
313                    (return-spec (when (consp type-spec)
314                                   (caddr type-spec)))
315                    (extra-vals (when (consp return-spec)
316                                  (cddr return-spec))))
317               (if (and (consp extra-vals)
318                        (or (eq 'null (car extra-vals))
319                            (and (eq '&optional (car extra-vals))
320                                 (or (not (cdr extra-vals))
321                                     (eq 'null (cadr extra-vals))))))
322                   actual
323                   ;; If there is a potential secondary value, make sure we
324                   ;; don't accidentally claim EQ based hashing...
325                   (lambda (object)
326                     (declare (optimize (safety 0) (speed 3)))
327                     (values (funcall actual object) nil))))))
328     (let* ((size (max +min-hash-table-size+
329                       (min size
330                            ;; SIZE is just a hint, so if the user asks
331                            ;; for a SIZE which'd be too big for us to
332                            ;; easily implement, we bump it down.
333                            (floor array-dimension-limit 1024))))
334            (rehash-size (if (integerp rehash-size)
335                             rehash-size
336                             (float rehash-size 1.0)))
337            ;; FIXME: Original REHASH-THRESHOLD default should be 1.0,
338            ;; not 1, to make it easier for the compiler to avoid
339            ;; boxing.
340            (rehash-threshold (max +min-hash-table-rehash-threshold+
341                                   (float rehash-threshold 1.0)))
342            (size+1 (1+ size))       ; The first element is not usable.
343            ;; KLUDGE: The most natural way of expressing the below is
344            ;; (round (/ (float size+1) rehash-threshold)), and indeed
345            ;; it was expressed like that until 0.7.0. However,
346            ;; MAKE-HASH-TABLE is called very early in cold-init, and
347            ;; the SPARC has no primitive instructions for rounding,
348            ;; but only for truncating; therefore, we fudge this issue
349            ;; a little. The other uses of truncate, below, similarly
350            ;; used to be round. -- CSR, 2002-10-01
351            ;;
352            ;; Note that this has not yet been audited for
353            ;; correctness. It just seems to work. -- CSR, 2002-11-02
354            (scaled-size (truncate (/ (float size+1) rehash-threshold)))
355            (length (power-of-two-ceiling (max scaled-size
356                                               (1+ +min-hash-table-size+))))
357            (index-vector (make-array length
358                                      :element-type
359                                      '(unsigned-byte #.sb!vm:n-word-bits)
360                                      :initial-element 0))
361            ;; Needs to be the half the length of the KV vector to link
362            ;; KV entries - mapped to indeces at 2i and 2i+1 -
363            ;; together.
364            (next-vector (make-array size+1
365                                     :element-type
366                                     '(unsigned-byte #.sb!vm:n-word-bits)))
367            (kv-vector (make-array (* 2 size+1)
368                                   :initial-element +empty-ht-slot+))
369            (table (%make-hash-table
370                    :test test
371                    :test-fun test-fun
372                    :hash-fun hash-fun
373                    :rehash-size rehash-size
374                    :rehash-threshold rehash-threshold
375                    :rehash-trigger size
376                    :table kv-vector
377                    :weakness weakness
378                    :index-vector index-vector
379                    :next-vector next-vector
380                    :hash-vector
381                    (unless (eq test 'eq)
382                      (make-array size+1
383                                  :element-type '(unsigned-byte
384                                                  #.sb!vm:n-word-bits)
385                                  :initial-element +magic-hash-vector-value+))
386                    :synchronized-p synchronized)))
387       (declare (type index size+1 scaled-size length))
388       ;; Set up the free list, all free. These lists are 0 terminated.
389       (do ((i 1 (1+ i)))
390           ((>= i size))
391         (setf (aref next-vector i) (1+ i)))
392       (setf (aref next-vector size) 0)
393       (setf (hash-table-next-free-kv table) 1)
394       (setf (aref kv-vector 0) table)
395       table)))
396
397 (defun hash-table-count (hash-table)
398   #!+sb-doc
399   "Return the number of entries in the given HASH-TABLE."
400   (declare (type hash-table hash-table)
401            (values index))
402   (hash-table-number-entries hash-table))
403
404 #!+sb-doc
405 (setf (fdocumentation 'hash-table-rehash-size 'function)
406       "Return the rehash-size HASH-TABLE was created with.")
407
408 #!+sb-doc
409 (setf (fdocumentation 'hash-table-rehash-threshold 'function)
410       "Return the rehash-threshold HASH-TABLE was created with.")
411
412 #!+sb-doc
413 (setf (fdocumentation 'hash-table-synchronized-p 'function)
414       "Returns T if HASH-TABLE is synchronized.")
415
416 (defun hash-table-size (hash-table)
417   #!+sb-doc
418   "Return a size that can be used with MAKE-HASH-TABLE to create a hash
419    table that can hold however many entries HASH-TABLE can hold without
420    having to be grown."
421   (hash-table-rehash-trigger hash-table))
422
423 #!+sb-doc
424 (setf (fdocumentation 'hash-table-test 'function)
425       "Return the test HASH-TABLE was created with.")
426
427 #!+sb-doc
428 (setf (fdocumentation 'hash-table-weakness 'function)
429       "Return the WEAKNESS of HASH-TABLE which is one of NIL, :KEY,
430 :VALUE, :KEY-AND-VALUE, :KEY-OR-VALUE.")
431
432 ;;; Called when we detect circular chains in a hash-table.
433 (defun signal-corrupt-hash-table (hash-table)
434   (error "Corrupt NEXT-chain in ~A. This is probably caused by ~
435 multiple threads accessing the same hash-table without locking."
436          hash-table))
437
438 \f
439 ;;;; accessing functions
440
441 ;;; Make new vectors for the table, extending the table based on the
442 ;;; rehash-size.
443 (defun rehash (table)
444   (declare (type hash-table table))
445   (aver *gc-inhibit*)
446   (let* ((old-kv-vector (hash-table-table table))
447          (old-next-vector (hash-table-next-vector table))
448          (old-hash-vector (hash-table-hash-vector table))
449          (old-size (length old-next-vector))
450          (new-size
451           (power-of-two-ceiling
452            (let ((rehash-size (hash-table-rehash-size table)))
453              (etypecase rehash-size
454                (fixnum
455                 (+ rehash-size old-size))
456                (float
457                 (the index (truncate (* rehash-size old-size))))))))
458          (new-kv-vector (make-array (* 2 new-size)
459                                     :initial-element +empty-ht-slot+))
460          (new-next-vector
461           (make-array new-size
462                       :element-type '(unsigned-byte #.sb!vm:n-word-bits)
463                       :initial-element 0))
464          (new-hash-vector
465           (when old-hash-vector
466             (make-array new-size
467                         :element-type '(unsigned-byte #.sb!vm:n-word-bits)
468                         :initial-element +magic-hash-vector-value+)))
469          (new-length new-size)
470          (new-index-vector
471           (make-array new-length
472                       :element-type '(unsigned-byte #.sb!vm:n-word-bits)
473                       :initial-element 0)))
474     (declare (type index new-size new-length old-size))
475
476     ;; Disable GC tricks on the OLD-KV-VECTOR.
477     (set-header-data old-kv-vector sb!vm:vector-normal-subtype)
478
479     ;; Non-empty weak hash tables always need GC support.
480     (when (and (hash-table-weakness table) (plusp (hash-table-count table)))
481       (set-header-data new-kv-vector sb!vm:vector-valid-hashing-subtype))
482
483     ;; FIXME: here and in several other places in the hash table code,
484     ;; loops like this one are used when FILL or REPLACE would be
485     ;; appropriate.  why are standard CL functions not used?
486     ;; Performance issues?  General laziness?  -- NJF, 2004-03-10
487
488     ;; Copy over the kv-vector. The element positions should not move
489     ;; in case there are active scans.
490     (dotimes (i (* old-size 2))
491       (declare (type index i))
492       (setf (aref new-kv-vector i) (aref old-kv-vector i)))
493
494     ;; Copy over the hash-vector.
495     (when old-hash-vector
496       (dotimes (i old-size)
497         (setf (aref new-hash-vector i) (aref old-hash-vector i))))
498
499     (setf (hash-table-next-free-kv table) 0)
500     ;; Rehash all the entries; last to first so that after the pushes
501     ;; the chains are first to last.
502     (do ((i (1- new-size) (1- i)))
503         ((zerop i))
504       (declare (type index/2 i))
505       (let ((key (aref new-kv-vector (* 2 i)))
506             (value (aref new-kv-vector (1+ (* 2 i)))))
507         (cond ((and (eq key +empty-ht-slot+)
508                     (eq value +empty-ht-slot+))
509                ;; Slot is empty, push it onto the free list.
510                (setf (aref new-next-vector i)
511                      (hash-table-next-free-kv table))
512                (setf (hash-table-next-free-kv table) i))
513               ((and new-hash-vector
514                     (not (= (aref new-hash-vector i)
515                             +magic-hash-vector-value+)))
516                ;; Can use the existing hash value (not EQ based)
517                (let* ((hashing (aref new-hash-vector i))
518                       (index (index-for-hashing hashing new-length))
519                       (next (aref new-index-vector index)))
520                  (declare (type index index)
521                           (type hash hashing))
522                  ;; Push this slot into the next chain.
523                  (setf (aref new-next-vector i) next)
524                  (setf (aref new-index-vector index) i)))
525               (t
526                ;; EQ base hash.
527                ;; Enable GC tricks.
528                (set-header-data new-kv-vector
529                                 sb!vm:vector-valid-hashing-subtype)
530                (let* ((hashing (pointer-hash key))
531                       (index (index-for-hashing hashing new-length))
532                       (next (aref new-index-vector index)))
533                  (declare (type index index)
534                           (type hash hashing))
535                  ;; Push this slot onto the next chain.
536                  (setf (aref new-next-vector i) next)
537                  (setf (aref new-index-vector index) i))))))
538     (setf (hash-table-table table) new-kv-vector)
539     (setf (hash-table-index-vector table) new-index-vector)
540     (setf (hash-table-next-vector table) new-next-vector)
541     (setf (hash-table-hash-vector table) new-hash-vector)
542     ;; Fill the old kv-vector with 0 to help the conservative GC. Even
543     ;; if nothing else were zeroed, it's important to clear the
544     ;; special first cells in old-kv-vector.
545     (fill old-kv-vector 0)
546     (setf (hash-table-rehash-trigger table) new-size)
547     (setf (hash-table-needs-rehash-p table) nil))
548   (values))
549
550 ;;; Use the same size as before, re-using the vectors.
551 (defun rehash-without-growing (table)
552   (declare (type hash-table table))
553   (aver *gc-inhibit*)
554   (let* ((kv-vector (hash-table-table table))
555          (next-vector (hash-table-next-vector table))
556          (hash-vector (hash-table-hash-vector table))
557          (size (length next-vector))
558          (index-vector (hash-table-index-vector table))
559          (length (length index-vector)))
560     (declare (type index size length))
561
562     ;; Non-empty weak hash tables always need GC support.
563     (unless (and (hash-table-weakness table) (plusp (hash-table-count table)))
564       ;; Disable GC tricks, they will be re-enabled during the re-hash
565       ;; if necessary.
566       (set-header-data kv-vector sb!vm:vector-normal-subtype))
567
568     ;; Rehash all the entries.
569     (setf (hash-table-next-free-kv table) 0)
570     (dotimes (i size)
571       (setf (aref next-vector i) 0))
572     (dotimes (i length)
573       (setf (aref index-vector i) 0))
574     (do ((i (1- size) (1- i)))
575         ((zerop i))
576       (declare (type index/2 i))
577       (let ((key (aref kv-vector (* 2 i)))
578             (value (aref kv-vector (1+ (* 2 i)))))
579         (cond ((and (eq key +empty-ht-slot+)
580                     (eq value +empty-ht-slot+))
581                ;; Slot is empty, push it onto free list.
582                (setf (aref next-vector i) (hash-table-next-free-kv table))
583                (setf (hash-table-next-free-kv table) i))
584               ((and hash-vector (not (= (aref hash-vector i)
585                                         +magic-hash-vector-value+)))
586                ;; Can use the existing hash value (not EQ based)
587                (let* ((hashing (aref hash-vector i))
588                       (index (index-for-hashing hashing length))
589                       (next (aref index-vector index)))
590                  (declare (type index index))
591                  ;; Push this slot into the next chain.
592                  (setf (aref next-vector i) next)
593                  (setf (aref index-vector index) i)))
594               (t
595                ;; EQ base hash.
596                ;; Enable GC tricks.
597                (set-header-data kv-vector sb!vm:vector-valid-hashing-subtype)
598                (let* ((hashing (pointer-hash key))
599                       (index (index-for-hashing hashing length))
600                       (next (aref index-vector index)))
601                  (declare (type index index)
602                           (type hash hashing))
603                  ;; Push this slot into the next chain.
604                  (setf (aref next-vector i) next)
605                  (setf (aref index-vector index) i)))))))
606   ;; Clear the rehash bit only at the very end, otherwise another thread
607   ;; might see a partially rehashed table as a normal one.
608   (setf (hash-table-needs-rehash-p table) nil)
609   (values))
610
611 (declaim (inline maybe-rehash))
612 (defun maybe-rehash (hash-table ensure-free-slot-p)
613   (when (hash-table-weakness hash-table)
614     (aver *gc-inhibit*))
615   (flet ((rehash-p ()
616            (and ensure-free-slot-p
617                 (zerop (hash-table-next-free-kv hash-table))))
618          (rehash-without-growing-p ()
619            (hash-table-needs-rehash-p hash-table)))
620     (declare (inline rehash-p rehash-without-growing-p))
621     (cond ((rehash-p)
622            ;; Use recursive spinlocks since for weak tables the
623            ;; spinlock has already been acquired. GC must be inhibited
624            ;; to prevent the GC from seeing a rehash in progress.
625            (sb!thread::with-recursive-system-spinlock
626                ((hash-table-spinlock hash-table) :without-gcing t)
627              ;; Repeat the condition inside the lock to ensure that if
628              ;; two reader threads enter MAYBE-REHASH at the same time
629              ;; only one rehash is performed.
630              (when (rehash-p)
631                (rehash hash-table))))
632           ((rehash-without-growing-p)
633            (sb!thread::with-recursive-system-spinlock
634                ((hash-table-spinlock hash-table) :without-gcing t)
635              (when (rehash-without-growing-p)
636                (rehash-without-growing hash-table)))))))
637
638 (declaim (inline update-hash-table-cache))
639 (defun update-hash-table-cache (hash-table index)
640   (unless (hash-table-weakness hash-table)
641     (setf (hash-table-cache hash-table) index)))
642
643 (defmacro with-hash-table-locks ((hash-table
644                                   &key (operation :write) inline pin
645                                   (synchronized `(hash-table-synchronized-p ,hash-table)))
646                                  &body body)
647   (declare (type (member :read :write) operation))
648   (with-unique-names (body-fun)
649     `(flet ((,body-fun ()
650               (with-concurrent-access-check ,hash-table ,operation
651                 (locally (declare (inline ,@inline))
652                   ,@body))))
653        (if (hash-table-weakness ,hash-table)
654            (sb!thread::with-recursive-system-spinlock
655                ((hash-table-spinlock ,hash-table) :without-gcing t)
656              (,body-fun))
657            (with-pinned-objects ,pin
658              (if ,synchronized
659                  ;; We use a "system" spinlock here because it is very
660                  ;; slightly faster, as it doesn't re-enable interrupts.
661                  (sb!thread::with-recursive-system-spinlock
662                      ((hash-table-spinlock ,hash-table))
663                    (,body-fun))
664                  (,body-fun)))))))
665
666 (defun gethash (key hash-table &optional default)
667   #!+sb-doc
668   "Finds the entry in HASH-TABLE whose key is KEY and returns the
669 associated value and T as multiple values, or returns DEFAULT and NIL
670 if there is no such entry. Entries can be added using SETF."
671   (declare (type hash-table hash-table)
672            (values t (member t nil)))
673   (gethash3 key hash-table default))
674
675 (declaim (maybe-inline %gethash3))
676 (defun %gethash3 (key hash-table default)
677   (declare (type hash-table hash-table)
678            (optimize speed)
679            (values t (member t nil)))
680   (tagbody
681    start
682      (let ((start-epoch sb!kernel::*gc-epoch*))
683        (macrolet ((result (value foundp)
684                     ;; When the table has multiple concurrent readers,
685                     ;; it's possible that there was a GC after this
686                     ;; thread called MAYBE-REHASH from %GETHASH3, and
687                     ;; some other thread then rehashed the table. If
688                     ;; this happens, we might not find the key even if
689                     ;; it's in the table. To protect against this,
690                     ;; redo the lookup if the GC epoch counter has changed.
691                     ;; -- JES,  2007-09-30
692                     `(if (and (not ,foundp)
693                               (not (eq start-epoch sb!kernel::*gc-epoch*)))
694                          (go start)
695                          (return-from %gethash3 (values ,value ,foundp))))
696                   (overflow ()
697                     ;; The next-vector chain is circular. This is caused
698                     ;; caused by thread-unsafe mutations of the table.
699                     `(signal-corrupt-hash-table hash-table)))
700          (maybe-rehash hash-table nil)
701          ;; Note that it's OK for a GC + a REHASH-WITHOUT-GROWING to
702          ;; be triggered by another thread after this point, since the
703          ;; GC epoch check will catch it.
704          (let ((cache (hash-table-cache hash-table))
705                (table (hash-table-table hash-table)))
706            ;; First check the cache.  Use EQ here for speed.
707            (if (and cache
708                     (< cache (length table))
709                     (eq (aref table cache) key))
710                (let ((value (aref table (1+ cache))))
711                  (result value t))
712                ;; Search for key in the hash table.
713                (multiple-value-bind (hashing eq-based)
714                    (funcall (hash-table-hash-fun hash-table) key)
715                  (declare (type hash hashing))
716                  (let* ((index-vector (hash-table-index-vector hash-table))
717                         (length (length index-vector))
718                         (index (index-for-hashing hashing length))
719                         (next (aref index-vector index))
720                         (next-vector (hash-table-next-vector hash-table))
721                         (hash-vector (hash-table-hash-vector hash-table))
722                         (test-fun (hash-table-test-fun hash-table)))
723                    (declare (type index index))
724                    ;; Search next-vector chain for a matching key.
725                    (if (or eq-based (not hash-vector))
726                        (do ((next next (aref next-vector next))
727                             (i 0 (1+ i)))
728                            ((zerop next) (result default nil))
729                          (declare (type index/2 next i))
730                          (when (> i length)
731                            (overflow))
732                          (when (eq key (aref table (* 2 next)))
733                            (update-hash-table-cache hash-table (* 2 next))
734                            (let ((value (aref table (1+ (* 2 next)))))
735                              (result value t))))
736                        (do ((next next (aref next-vector next))
737                             (i 0 (1+ i)))
738                            ((zerop next) (result default nil))
739                          (declare (type index/2 next i))
740                          (when (> i length)
741                            (overflow))
742                          (when (and (= hashing (aref hash-vector next))
743                                     (funcall test-fun key
744                                              (aref table (* 2 next))))
745                            ;; Found.
746                            (update-hash-table-cache hash-table (* 2 next))
747                            (let ((value (aref table (1+ (* 2 next)))))
748                              (result value t)))))))))))))
749
750 (defun gethash3 (key hash-table default)
751   "Three argument version of GETHASH"
752   (declare (type hash-table hash-table))
753   (with-hash-table-locks (hash-table :operation :read :inline (%gethash3)
754                                      :pin (key))
755     (%gethash3 key hash-table default)))
756
757 ;;; so people can call #'(SETF GETHASH)
758 (defun (setf gethash) (new-value key table &optional default)
759   (declare (ignore default))
760   (%puthash key table new-value))
761
762 (declaim (maybe-inline %%puthash))
763 (defun %%puthash (key hash-table value)
764   (declare (optimize speed))
765   ;; We need to rehash here so that a current key can be found if it
766   ;; exists. Check that there is room for one more entry. May not be
767   ;; needed if the key is already present.
768   (maybe-rehash hash-table t)
769   ;; Search for key in the hash table.
770   (multiple-value-bind (hashing eq-based)
771       (funcall (hash-table-hash-fun hash-table) key)
772     (declare (type hash hashing))
773     (let* ((index-vector (hash-table-index-vector hash-table))
774            (length (length index-vector))
775            (index (index-for-hashing hashing length))
776            (next (aref index-vector index))
777            (kv-vector (hash-table-table hash-table))
778            (next-vector (hash-table-next-vector hash-table))
779            (hash-vector (hash-table-hash-vector hash-table))
780            (test-fun (hash-table-test-fun hash-table)))
781       (declare (type index index next))
782       (when (hash-table-weakness hash-table)
783         (set-header-data kv-vector sb!vm:vector-valid-hashing-subtype))
784       (cond ((or eq-based (not hash-vector))
785              (when eq-based
786                (set-header-data kv-vector
787                                 sb!vm:vector-valid-hashing-subtype))
788              ;; Search next-vector chain for a matching key.
789              (do ((next next (aref next-vector next))
790                   (i 0 (1+ i)))
791                  ((zerop next))
792                (declare (type index/2 next i))
793                (when (> i length)
794                  (signal-corrupt-hash-table hash-table))
795                (when (eq key (aref kv-vector (* 2 next)))
796                  ;; Found, just replace the value.
797                  (update-hash-table-cache hash-table (* 2 next))
798                  (setf (aref kv-vector (1+ (* 2 next))) value)
799                  (return-from %%puthash value))))
800             (t
801              ;; Search next-vector chain for a matching key.
802              (do ((next next (aref next-vector next))
803                   (i 0 (1+ i)))
804                  ((zerop next))
805                (declare (type index/2 next i))
806                (when (> i length)
807                  (signal-corrupt-hash-table hash-table))
808                (when (and (= hashing (aref hash-vector next))
809                           (funcall test-fun key
810                                    (aref kv-vector (* 2 next))))
811                  ;; Found, just replace the value.
812                  (update-hash-table-cache hash-table (* 2 next))
813                  (setf (aref kv-vector (1+ (* 2 next))) value)
814                  (return-from %%puthash value)))))
815       ;; Pop a KV slot off the free list
816       (let ((free-kv-slot (hash-table-next-free-kv hash-table)))
817         (declare (type index/2 free-kv-slot))
818         ;; Double-check for overflow.
819         (aver (not (zerop free-kv-slot)))
820         (setf (hash-table-next-free-kv hash-table)
821               (aref next-vector free-kv-slot))
822         (incf (hash-table-number-entries hash-table))
823         (update-hash-table-cache hash-table (* 2 free-kv-slot))
824         (setf (aref kv-vector (* 2 free-kv-slot)) key)
825         (setf (aref kv-vector (1+ (* 2 free-kv-slot))) value)
826         ;; Setup the hash-vector if necessary.
827         (when hash-vector
828           (if (not eq-based)
829               (setf (aref hash-vector free-kv-slot) hashing)
830               (aver (= (aref hash-vector free-kv-slot)
831                        +magic-hash-vector-value+))))
832         ;; Push this slot into the next chain.
833         (setf (aref next-vector free-kv-slot) next)
834         (setf (aref index-vector index) free-kv-slot)))
835     value))
836
837 (defun %puthash (key hash-table value)
838   (declare (type hash-table hash-table))
839   (aver (hash-table-index-vector hash-table))
840   (macrolet ((put-it (lockedp)
841                `(let ((cache (hash-table-cache hash-table))
842                       (kv-vector (hash-table-table hash-table)))
843                   ;; Check the cache
844                   (if (and cache
845                            (< cache (length kv-vector))
846                            (eq (aref kv-vector cache) key))
847                       ;; If cached, just store here
848                       (setf (aref kv-vector (1+ cache)) value)
849                       ;; Otherwise do things the hard way
850                       ,(if lockedp
851                            '(%%puthash key hash-table value)
852                            '(with-hash-table-locks
853                              (hash-table :inline (%%puthash) :pin (key)
854                               :synchronized nil)
855                              (%%puthash key hash-table value)))))))
856     (if (hash-table-synchronized-p hash-table)
857         (with-hash-table-locks (hash-table :pin (key) :synchronized t)
858           (put-it t))
859         (put-it nil))))
860
861 (declaim (maybe-inline %remhash))
862 (defun %remhash (key hash-table)
863   ;; We need to rehash here so that a current key can be found if it
864   ;; exists.
865   ;;
866   ;; Note that if a GC happens after MAYBE-REHASH returns and another
867   ;; thread the accesses the table (triggering a rehash), we might not
868   ;; find the key even if it is in the table. But that's ok, since the
869   ;; only concurrent case that we safely allow is multiple readers
870   ;; with no writers.
871   (maybe-rehash hash-table nil)
872   ;; Search for key in the hash table.
873   (multiple-value-bind (hashing eq-based)
874       (funcall (hash-table-hash-fun hash-table) key)
875     (declare (type hash hashing))
876     (let* ((index-vector (hash-table-index-vector hash-table))
877            (length (length index-vector))
878            (index (index-for-hashing hashing length))
879            (next (aref index-vector index))
880            (table (hash-table-table hash-table))
881            (next-vector (hash-table-next-vector hash-table))
882            (hash-vector (hash-table-hash-vector hash-table))
883            (test-fun (hash-table-test-fun hash-table)))
884       (declare (type index index)
885                (type index/2 next))
886       (flet ((clear-slot (chain-vector prior-slot-location slot-location)
887                (declare (type index/2 slot-location))
888                ;; Mark slot as empty.
889                (setf (aref table (* 2 slot-location)) +empty-ht-slot+
890                      (aref table (1+ (* 2 slot-location))) +empty-ht-slot+)
891                ;; Update the prior pointer in the chain to skip this.
892                (setf (aref chain-vector prior-slot-location)
893                      (aref next-vector slot-location))
894                ;; Push KV slot onto free chain.
895                (setf (aref next-vector slot-location)
896                      (hash-table-next-free-kv hash-table))
897                (setf (hash-table-next-free-kv hash-table) slot-location)
898                (when hash-vector
899                  (setf (aref hash-vector slot-location)
900                        +magic-hash-vector-value+))
901                ;; On parallel accesses this may turn out to be a
902                ;; type-error, so don't turn down the safety!
903                (decf (hash-table-number-entries hash-table))
904                t))
905         (cond ((zerop next)
906                nil)
907               ((if (or eq-based (not hash-vector))
908                    (eq key (aref table (* 2 next)))
909                    (and (= hashing (aref hash-vector next))
910                         (funcall test-fun key (aref table (* 2 next)))))
911                (clear-slot index-vector index next))
912               ;; Search next-vector chain for a matching key.
913               ((or eq-based (not hash-vector))
914                ;; EQ based
915                (do ((prior next next)
916                     (i 0 (1+ i))
917                     (next (aref next-vector next) (aref next-vector next)))
918                    ((zerop next) nil)
919                  (declare (type index next))
920                  (when (> i length)
921                    (signal-corrupt-hash-table hash-table))
922                  (when (eq key (aref table (* 2 next)))
923                    (return-from %remhash (clear-slot next-vector prior next)))))
924               (t
925                ;; not EQ based
926                (do ((prior next next)
927                     (i 0 (1+ i))
928                     (next (aref next-vector next) (aref next-vector next)))
929                    ((zerop next) nil)
930                  (declare (type index/2 next))
931                  (when (> i length)
932                    (signal-corrupt-hash-table hash-table))
933                  (when (and (= hashing (aref hash-vector next))
934                             (funcall test-fun key (aref table (* 2 next))))
935                    (return-from %remhash
936                      (clear-slot next-vector prior next))))))))))
937
938 (defun remhash (key hash-table)
939   #!+sb-doc
940   "Remove the entry in HASH-TABLE associated with KEY. Return T if
941 there was such an entry, or NIL if not."
942   (declare (type hash-table hash-table)
943            (values (member t nil)))
944   (with-hash-table-locks (hash-table :inline (%remhash) :pin (key))
945     ;; For now, just clear the cache
946     (setf (hash-table-cache hash-table) nil)
947     (%remhash key hash-table)))
948
949 (defun clrhash (hash-table)
950   #!+sb-doc
951   "This removes all the entries from HASH-TABLE and returns the hash
952 table itself."
953   (when (plusp (hash-table-number-entries hash-table))
954     (with-hash-table-locks (hash-table)
955       (let* ((kv-vector (hash-table-table hash-table))
956              (next-vector (hash-table-next-vector hash-table))
957              (hash-vector (hash-table-hash-vector hash-table))
958              (size (length next-vector))
959              (index-vector (hash-table-index-vector hash-table)))
960         ;; Disable GC tricks.
961         (set-header-data kv-vector sb!vm:vector-normal-subtype)
962         ;; Mark all slots as empty by setting all keys and values to magic
963         ;; tag.
964         (aver (eq (aref kv-vector 0) hash-table))
965         (fill kv-vector +empty-ht-slot+ :start 2)
966         ;; Set up the free list, all free.
967         (do ((i 1 (1+ i)))
968             ((>= i (1- size)))
969           (setf (aref next-vector i) (1+ i)))
970         (setf (aref next-vector (1- size)) 0)
971         (setf (hash-table-next-free-kv hash-table) 1)
972         ;; Clear the index-vector.
973         (fill index-vector 0)
974         ;; Clear the hash-vector.
975         (when hash-vector
976           (fill hash-vector +magic-hash-vector-value+)))
977       (setf (hash-table-cache hash-table) nil)
978       (setf (hash-table-number-entries hash-table) 0)))
979   hash-table)
980
981 \f
982 ;;;; MAPHASH
983
984 ;;; FIXME: This should be made into a compiler transform for two reasons:
985 ;;;   1. It would then be available for compiling the entire system,
986 ;;;      not only parts of the system which are defined after DEFUN MAPHASH.
987 ;;;   2. It could be conditional on compilation policy, so that
988 ;;;      it could be compiled as a full call instead of an inline
989 ;;;      expansion when SPACE>SPEED.
990 (declaim (inline maphash))
991 (defun maphash (function-designator hash-table)
992   #!+sb-doc
993   "For each entry in HASH-TABLE, call the designated two-argument function on
994 the key and value of the entry. Return NIL.
995
996 Consequences are undefined if HASH-TABLE is mutated during the call to
997 MAPHASH, except for changing or removing elements corresponding to the
998 current key. The applies to all threads, not just the current one --
999 even for synchronized hash-tables. If the table may be mutated by
1000 another thread during iteration, use eg. SB-EXT:WITH-LOCKED-HASH-TABLE
1001 to protect the MAPHASH call."
1002   ;; This essentially duplicates WITH-HASH-TABLE-ITERATOR, so
1003   ;; any changes here should be reflected there as well.
1004   (let ((fun (%coerce-callable-to-fun function-designator))
1005         (size (length (hash-table-next-vector hash-table))))
1006     (declare (type function fun))
1007     (do ((i 1 (1+ i)))
1008         ((>= i size))
1009       (declare (type index/2 i))
1010       (let* ((kv-vector (hash-table-table hash-table))
1011              (key (aref kv-vector (* 2 i)))
1012              (value (aref kv-vector (1+ (* 2 i)))))
1013         ;; We are running without locking or WITHOUT-GCING. For a weak
1014         ;; :VALUE hash table it's possible that the GC hit after KEY
1015         ;; was read and now the entry is gone. So check if either the
1016         ;; key or the value is empty.
1017         (unless (or (eq key +empty-ht-slot+)
1018                     (eq value +empty-ht-slot+))
1019           (funcall fun key value))))))
1020 \f
1021 ;;;; methods on HASH-TABLE
1022
1023 ;;; Return a list of keyword args and values to use for MAKE-HASH-TABLE
1024 ;;; when reconstructing HASH-TABLE.
1025 (defun %hash-table-ctor-args (hash-table)
1026   `(:test             ',(hash-table-test             hash-table)
1027     :size             ',(hash-table-size             hash-table)
1028     :rehash-size      ',(hash-table-rehash-size      hash-table)
1029     :rehash-threshold ',(hash-table-rehash-threshold hash-table)
1030     :weakness         ',(hash-table-weakness         hash-table)))
1031
1032 ;;; Return an association list representing the same data as HASH-TABLE.
1033 (defun %hash-table-alist (hash-table)
1034   (let ((result nil))
1035     (maphash (lambda (key value)
1036                (push (cons key value) result))
1037              hash-table)
1038     result))
1039
1040 ;;; Stuff an association list into HASH-TABLE. Return the hash table,
1041 ;;; so that we can use this for the *PRINT-READABLY* case in
1042 ;;; PRINT-OBJECT (HASH-TABLE T) without having to worry about LET
1043 ;;; forms and readable gensyms and stuff.
1044 (defun %stuff-hash-table (hash-table alist)
1045   (dolist (x alist)
1046     (setf (gethash (car x) hash-table) (cdr x)))
1047   hash-table)
1048
1049 (def!method print-object ((hash-table hash-table) stream)
1050   (declare (type stream stream))
1051   (cond ((or (not *print-readably*) (not *read-eval*))
1052          (print-unreadable-object (hash-table stream :type t :identity t)
1053            (format stream
1054                    ":TEST ~S :COUNT ~S~@[ :WEAKNESS ~S~]"
1055                    (hash-table-test hash-table)
1056                    (hash-table-count hash-table)
1057                    (hash-table-weakness hash-table))))
1058         (t
1059          (write-string "#." stream)
1060          (write `(%stuff-hash-table (make-hash-table ,@(%hash-table-ctor-args
1061                                                           hash-table))
1062                                      ',(%hash-table-alist hash-table))
1063                 :stream stream))))
1064
1065 (def!method make-load-form ((hash-table hash-table) &optional environment)
1066   (declare (ignore environment))
1067   (values `(make-hash-table ,@(%hash-table-ctor-args hash-table))
1068           `(%stuff-hash-table ,hash-table ',(%hash-table-alist hash-table))))
1069
1070 \f