1.0.4.30: make WITH-SPINLOCK-AND-WITHOUT-GCING inhibit interrupts as well
[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 ;; This stuff is performance critical and unwind-protect is too
18 ;; slow. And without the locking the next vector can get cyclic
19 ;; causing looping in a WITHOUT-GCING form, SHRINK-VECTOR can corrupt
20 ;; memory and who knows what else.
21 (defmacro with-spinlock-and-without-gcing ((spinlock) &body body)
22   #!-sb-thread
23   (declare (ignore spinlock))
24   (with-unique-names (old-gc-inhibit old-interrupts-enabled)
25     `(let ((,old-gc-inhibit *gc-inhibit*)
26            (,old-interrupts-enabled *interrupts-enabled*)
27            (*interrupts-enabled* nil)
28            (*gc-inhibit* t))
29        (unwind-protect
30             (progn
31               #!+sb-thread
32               (sb!thread::get-spinlock ,spinlock)
33               ,@body)
34          #!+sb-thread
35          (sb!thread::release-spinlock ,spinlock)
36          (let ((*interrupts-enabled* ,old-interrupts-enabled)
37                (*gc-inhibit* ,old-gc-inhibit))
38            ;; the test is racy, but it can err only on the overeager
39            ;; side
40            (sb!kernel::maybe-handle-pending-gc))))))
41
42 (eval-when (:compile-toplevel :load-toplevel :execute)
43   (defconstant max-hash sb!xc:most-positive-fixnum))
44
45 (deftype hash ()
46   `(integer 0 ,max-hash))
47
48 ;;; FIXME: Does this always make a nonnegative FIXNUM? If so, then
49 ;;; explain why. If not (or if the reason it always makes a
50 ;;; nonnegative FIXNUM is only the accident that pointers in supported
51 ;;; architectures happen to be in the lower half of the address
52 ;;; space), then fix it.
53 #!-sb-fluid (declaim (inline pointer-hash))
54 (defun pointer-hash (key)
55   (declare (values hash))
56   (truly-the hash (%primitive sb!c:make-fixnum key)))
57
58 #!-sb-fluid (declaim (inline eq-hash))
59 (defun eq-hash (key)
60   (declare (values hash (member t nil)))
61   (values (pointer-hash key)
62           (oddp (get-lisp-obj-address key))))
63
64 #!-sb-fluid (declaim (inline equal-hash))
65 (defun equal-hash (key)
66   (declare (values hash (member t nil)))
67   (values (sxhash key) nil))
68
69 #!-sb-fluid (declaim (inline eql-hash))
70 (defun eql-hash (key)
71   (declare (values hash (member t nil)))
72   (if (numberp key)
73       (equal-hash key)
74       (eq-hash key)))
75
76 (defun equalp-hash (key)
77   (declare (values hash (member t nil)))
78   (values (psxhash key) nil))
79
80 (defun almost-primify (num)
81   (declare (type index num))
82   #!+sb-doc
83   "Return an almost prime number greater than or equal to NUM."
84   (if (= (rem num 2) 0)
85       (setq num (+ 1 num)))
86   (if (= (rem num 3) 0)
87       (setq num (+ 2 num)))
88   (if (= (rem num 7) 0)
89       (setq num (+ 4 num)))
90   num)
91 \f
92 ;;;; user-defined hash table tests
93
94 (defvar *hash-table-tests* nil)
95
96 (defun define-hash-table-test (name test-fun hash-fun)
97   #!+sb-doc
98   "Define a new kind of hash table test."
99   (declare (type symbol name)
100            (type function test-fun hash-fun))
101   (setf *hash-table-tests*
102         (cons (list name test-fun hash-fun)
103               (remove name *hash-table-tests* :test #'eq :key #'car)))
104   name)
105 \f
106 ;;;; construction and simple accessors
107
108 (defconstant +min-hash-table-size+ 16)
109 (defconstant +min-hash-table-rehash-threshold+ (float 1/16 1.0))
110
111 (defun make-hash-table (&key (test 'eql)
112                         (size +min-hash-table-size+)
113                         (rehash-size 1.5)
114                         (rehash-threshold 1)
115                         (weakness nil))
116   #!+sb-doc
117   "Create and return a new hash table. The keywords are as follows:
118      :TEST -- Indicates what kind of test to use.
119      :SIZE -- A hint as to how many elements will be put in this hash
120        table.
121      :REHASH-SIZE -- Indicates how to expand the table when it fills up.
122        If an integer, add space for that many elements. If a floating
123        point number (which must be greater than 1.0), multiply the size
124        by that amount.
125      :REHASH-THRESHOLD -- Indicates how dense the table can become before
126        forcing a rehash. Can be any positive number <=1, with density
127        approaching zero as the threshold approaches 0. Density 1 means an
128        average of one entry per bucket.
129      :WEAKNESS -- IF NIL (the default) it is a normal non-weak hash table.
130        If one of :KEY, :VALUE, :KEY-AND-VALUE, :KEY-OR-VALUE it is a weak
131        hash table.
132        Depending on the type of weakness the lack of references to the
133        key and the value may allow for removal of the entry. If WEAKNESS
134        is :KEY and the key would otherwise be garbage the entry is eligible
135        for removal from the hash table. Similarly, if WEAKNESS is :VALUE
136        the life of an entry depends on its value's references. If WEAKNESS
137        is :KEY-AND-VALUE and either the key or the value would otherwise be
138        garbage the entry can be removed. If WEAKNESS is :KEY-OR-VALUE and
139        both the key and the value would otherwise be garbage the entry can
140        be removed."
141   (declare (type (or function symbol) test))
142   (declare (type unsigned-byte size))
143   (multiple-value-bind (test test-fun hash-fun)
144       (cond ((or (eq test #'eq) (eq test 'eq))
145              (values 'eq #'eq #'eq-hash))
146             ((or (eq test #'eql) (eq test 'eql))
147              (values 'eql #'eql #'eql-hash))
148             ((or (eq test #'equal) (eq test 'equal))
149              (values 'equal #'equal #'equal-hash))
150             ((or (eq test #'equalp) (eq test 'equalp))
151              (values 'equalp #'equalp #'equalp-hash))
152             (t
153              ;; FIXME: I'd like to remove *HASH-TABLE-TESTS* stuff.
154              ;; Failing that, I'd like to rename it to
155              ;; *USER-HASH-TABLE-TESTS*.
156              (dolist (info *hash-table-tests*
157                       (error "unknown :TEST for MAKE-HASH-TABLE: ~S"
158                              test))
159                (destructuring-bind (test-name test-fun hash-fun) info
160                  (when (or (eq test test-name) (eq test test-fun))
161                    (return (values test-name test-fun hash-fun)))))))
162     (let* ((size (max +min-hash-table-size+
163                       (min size
164                            ;; SIZE is just a hint, so if the user asks
165                            ;; for a SIZE which'd be too big for us to
166                            ;; easily implement, we bump it down.
167                            (floor array-dimension-limit 1024))))
168            (rehash-size (if (integerp rehash-size)
169                             rehash-size
170                             (float rehash-size 1.0)))
171            ;; FIXME: Original REHASH-THRESHOLD default should be 1.0,
172            ;; not 1, to make it easier for the compiler to avoid
173            ;; boxing.
174            (rehash-threshold (max +min-hash-table-rehash-threshold+
175                                   (float rehash-threshold 1.0)))
176            (size+1 (1+ size))       ; The first element is not usable.
177            ;; KLUDGE: The most natural way of expressing the below is
178            ;; (round (/ (float size+1) rehash-threshold)), and indeed
179            ;; it was expressed like that until 0.7.0. However,
180            ;; MAKE-HASH-TABLE is called very early in cold-init, and
181            ;; the SPARC has no primitive instructions for rounding,
182            ;; but only for truncating; therefore, we fudge this issue
183            ;; a little. The other uses of truncate, below, similarly
184            ;; used to be round. -- CSR, 2002-10-01
185            ;;
186            ;; Note that this has not yet been audited for
187            ;; correctness. It just seems to work. -- CSR, 2002-11-02
188            (scaled-size (truncate (/ (float size+1) rehash-threshold)))
189            (length (almost-primify (max scaled-size
190                                         (1+ +min-hash-table-size+))))
191            (index-vector (make-array length
192                                      :element-type
193                                      '(unsigned-byte #.sb!vm:n-word-bits)
194                                      :initial-element 0))
195            ;; Needs to be the half the length of the KV vector to link
196            ;; KV entries - mapped to indeces at 2i and 2i+1 -
197            ;; together.
198            (next-vector (make-array size+1
199                                     :element-type
200                                     '(unsigned-byte #.sb!vm:n-word-bits)))
201            (kv-vector (make-array (* 2 size+1)
202                                   :initial-element +empty-ht-slot+))
203            (table (%make-hash-table
204                    :test test
205                    :test-fun test-fun
206                    :hash-fun hash-fun
207                    :rehash-size rehash-size
208                    :rehash-threshold rehash-threshold
209                    :rehash-trigger size
210                    :table kv-vector
211                    :weakness weakness
212                    :index-vector index-vector
213                    :next-vector next-vector
214                    :hash-vector
215                    (unless (eq test 'eq)
216                      (make-array size+1
217                                  :element-type '(unsigned-byte
218                                                  #.sb!vm:n-word-bits)
219                                  :initial-element +magic-hash-vector-value+))
220                    :spinlock (sb!thread::make-spinlock))))
221       (declare (type index size+1 scaled-size length))
222       ;; Set up the free list, all free. These lists are 0 terminated.
223       (do ((i 1 (1+ i)))
224           ((>= i size))
225         (setf (aref next-vector i) (1+ i)))
226       (setf (aref next-vector size) 0)
227       (setf (hash-table-next-free-kv table) 1)
228       (setf (hash-table-needing-rehash table) 0)
229       (setf (aref kv-vector 0) table)
230       table)))
231
232 (defun hash-table-count (hash-table)
233   #!+sb-doc
234   "Return the number of entries in the given HASH-TABLE."
235   (declare (type hash-table hash-table)
236            (values index))
237   (hash-table-number-entries hash-table))
238
239 #!+sb-doc
240 (setf (fdocumentation 'hash-table-rehash-size 'function)
241       "Return the rehash-size HASH-TABLE was created with.")
242
243 #!+sb-doc
244 (setf (fdocumentation 'hash-table-rehash-threshold 'function)
245       "Return the rehash-threshold HASH-TABLE was created with.")
246
247 (defun hash-table-size (hash-table)
248   #!+sb-doc
249   "Return a size that can be used with MAKE-HASH-TABLE to create a hash
250    table that can hold however many entries HASH-TABLE can hold without
251    having to be grown."
252   (hash-table-rehash-trigger hash-table))
253
254 #!+sb-doc
255 (setf (fdocumentation 'hash-table-test 'function)
256       "Return the test HASH-TABLE was created with.")
257
258 #!+sb-doc
259 (setf (fdocumentation 'hash-table-weakness 'function)
260       "Return the WEAKNESS of HASH-TABLE which is one of NIL, :KEY,
261 :VALUE, :KEY-AND-VALUE, :KEY-OR-VALUE.")
262 \f
263 ;;;; accessing functions
264
265 ;;; Make new vectors for the table, extending the table based on the
266 ;;; rehash-size.
267 (defun rehash (table)
268   (declare (type hash-table table))
269   (let* ((old-kv-vector (hash-table-table table))
270          (old-next-vector (hash-table-next-vector table))
271          (old-hash-vector (hash-table-hash-vector table))
272          (old-size (length old-next-vector))
273          (new-size
274           (let ((rehash-size (hash-table-rehash-size table)))
275             (etypecase rehash-size
276               (fixnum
277                (+ rehash-size old-size))
278               (float
279                (the index (truncate (* rehash-size old-size)))))))
280          (new-kv-vector (make-array (* 2 new-size)
281                                     :initial-element +empty-ht-slot+))
282          (new-next-vector
283           (make-array new-size
284                       :element-type '(unsigned-byte #.sb!vm:n-word-bits)
285                       :initial-element 0))
286          (new-hash-vector
287           (when old-hash-vector
288             (make-array new-size
289                         :element-type '(unsigned-byte #.sb!vm:n-word-bits)
290                         :initial-element +magic-hash-vector-value+)))
291          (old-index-vector (hash-table-index-vector table))
292          (new-length (almost-primify
293                       (truncate (/ (float new-size)
294                                    (hash-table-rehash-threshold table)))))
295          (new-index-vector
296           (make-array new-length
297                       :element-type '(unsigned-byte #.sb!vm:n-word-bits)
298                       :initial-element 0)))
299     (declare (type index new-size new-length old-size))
300
301     ;; Disable GC tricks on the OLD-KV-VECTOR.
302     (set-header-data old-kv-vector sb!vm:vector-normal-subtype)
303
304     ;; Non-empty weak hash tables always need GC support.
305     (when (and (hash-table-weakness table) (plusp (hash-table-count table)))
306       (set-header-data new-kv-vector sb!vm:vector-valid-hashing-subtype))
307
308     ;; FIXME: here and in several other places in the hash table code,
309     ;; loops like this one are used when FILL or REPLACE would be
310     ;; appropriate.  why are standard CL functions not used?
311     ;; Performance issues?  General laziness?  -- NJF, 2004-03-10
312
313     ;; Copy over the kv-vector. The element positions should not move
314     ;; in case there are active scans.
315     (dotimes (i (* old-size 2))
316       (declare (type index i))
317       (setf (aref new-kv-vector i) (aref old-kv-vector i)))
318
319     ;; Copy over the hash-vector.
320     (when old-hash-vector
321       (dotimes (i old-size)
322         (setf (aref new-hash-vector i) (aref old-hash-vector i))))
323
324     (setf (hash-table-next-free-kv table) 0)
325     (setf (hash-table-needing-rehash table) 0)
326     ;; Rehash all the entries; last to first so that after the pushes
327     ;; the chains are first to last.
328     (do ((i (1- new-size) (1- i)))
329         ((zerop i))
330       (declare (type index/2 i))
331       (let ((key (aref new-kv-vector (* 2 i)))
332             (value (aref new-kv-vector (1+ (* 2 i)))))
333         (cond ((and (eq key +empty-ht-slot+)
334                     (eq value +empty-ht-slot+))
335                ;; Slot is empty, push it onto the free list.
336                (setf (aref new-next-vector i)
337                      (hash-table-next-free-kv table))
338                (setf (hash-table-next-free-kv table) i))
339               ((and new-hash-vector
340                     (not (= (aref new-hash-vector i)
341                             +magic-hash-vector-value+)))
342                ;; Can use the existing hash value (not EQ based)
343                (let* ((hashing (aref new-hash-vector i))
344                       (index (rem hashing new-length))
345                       (next (aref new-index-vector index)))
346                  (declare (type index index)
347                           (type hash hashing))
348                  ;; Push this slot into the next chain.
349                  (setf (aref new-next-vector i) next)
350                  (setf (aref new-index-vector index) i)))
351               (t
352                ;; EQ base hash.
353                ;; Enable GC tricks.
354                (set-header-data new-kv-vector
355                                 sb!vm:vector-valid-hashing-subtype)
356                (let* ((hashing (pointer-hash key))
357                       (index (rem hashing new-length))
358                       (next (aref new-index-vector index)))
359                  (declare (type index index)
360                           (type hash hashing))
361                  ;; Push this slot onto the next chain.
362                  (setf (aref new-next-vector i) next)
363                  (setf (aref new-index-vector index) i))))))
364     (setf (hash-table-table table) new-kv-vector)
365     (setf (hash-table-index-vector table) new-index-vector)
366     (setf (hash-table-next-vector table) new-next-vector)
367     (setf (hash-table-hash-vector table) new-hash-vector)
368     ;; Shrink the old vectors to 0 size to help the conservative GC.
369     (%shrink-vector old-kv-vector 0)
370     (%shrink-vector old-index-vector 0)
371     (%shrink-vector old-next-vector 0)
372     (when old-hash-vector
373       (%shrink-vector old-hash-vector 0))
374     (setf (hash-table-rehash-trigger table) new-size))
375   (values))
376
377 ;;; Use the same size as before, re-using the vectors.
378 (defun rehash-without-growing (table)
379   (declare (type hash-table table))
380   (let* ((kv-vector (hash-table-table table))
381          (next-vector (hash-table-next-vector table))
382          (hash-vector (hash-table-hash-vector table))
383          (size (length next-vector))
384          (index-vector (hash-table-index-vector table))
385          (length (length index-vector)))
386     (declare (type index size length))
387
388     ;; Non-empty weak hash tables always need GC support.
389     (unless (and (hash-table-weakness table) (plusp (hash-table-count table)))
390       ;; Disable GC tricks, they will be re-enabled during the re-hash
391       ;; if necessary.
392       (set-header-data kv-vector sb!vm:vector-normal-subtype))
393
394     ;; Rehash all the entries.
395     (setf (hash-table-next-free-kv table) 0)
396     (setf (hash-table-needing-rehash table) 0)
397     (dotimes (i size)
398       (setf (aref next-vector i) 0))
399     (dotimes (i length)
400       (setf (aref index-vector i) 0))
401     (do ((i (1- size) (1- i)))
402         ((zerop i))
403       (declare (type index/2 i))
404       (let ((key (aref kv-vector (* 2 i)))
405             (value (aref kv-vector (1+ (* 2 i)))))
406         (cond ((and (eq key +empty-ht-slot+)
407                     (eq value +empty-ht-slot+))
408                ;; Slot is empty, push it onto free list.
409                (setf (aref next-vector i) (hash-table-next-free-kv table))
410                (setf (hash-table-next-free-kv table) i))
411               ((and hash-vector (not (= (aref hash-vector i)
412                                         +magic-hash-vector-value+)))
413                ;; Can use the existing hash value (not EQ based)
414                (let* ((hashing (aref hash-vector i))
415                       (index (rem hashing length))
416                       (next (aref index-vector index)))
417                  (declare (type index index))
418                  ;; Push this slot into the next chain.
419                  (setf (aref next-vector i) next)
420                  (setf (aref index-vector index) i)))
421               (t
422                ;; EQ base hash.
423                ;; Enable GC tricks.
424                (set-header-data kv-vector sb!vm:vector-valid-hashing-subtype)
425                (let* ((hashing (pointer-hash key))
426                       (index (rem hashing length))
427                       (next (aref index-vector index)))
428                  (declare (type index index)
429                           (type hash hashing))
430                  ;; Push this slot into the next chain.
431                  (setf (aref next-vector i) next)
432                  (setf (aref index-vector index) i)))))))
433   (values))
434
435 (defun flush-needing-rehash (table)
436   (let* ((kv-vector (hash-table-table table))
437          (index-vector (hash-table-index-vector table))
438          (next-vector (hash-table-next-vector table))
439          (length (length index-vector)))
440     (do ((next (hash-table-needing-rehash table)))
441         ((zerop next))
442       (declare (type index/2 next))
443       (let* ((key (aref kv-vector (* 2 next)))
444              (hashing (pointer-hash key))
445              (index (rem hashing length))
446              (temp (aref next-vector next)))
447         (setf (aref next-vector next) (aref index-vector index))
448         (setf (aref index-vector index) next)
449         (setf next temp))))
450   (setf (hash-table-needing-rehash table) 0)
451   (values))
452
453 (defun gethash (key hash-table &optional default)
454   #!+sb-doc
455   "Finds the entry in HASH-TABLE whose key is KEY and returns the associated
456    value and T as multiple values, or returns DEFAULT and NIL if there is no
457    such entry. Entries can be added using SETF."
458   (declare (type hash-table hash-table)
459            (values t (member t nil)))
460   (gethash3 key hash-table default))
461
462 (defun gethash2 (key hash-table)
463   #!+sb-doc
464   "Two argument version of GETHASH"
465   (declare (type hash-table hash-table)
466            (values t (member t nil)))
467   (gethash3 key hash-table nil))
468
469 (defun gethash3 (key hash-table default)
470   #!+sb-doc
471   "Three argument version of GETHASH"
472   (declare (type hash-table hash-table)
473            (values t (member t nil)))
474   (with-spinlock-and-without-gcing ((hash-table-spinlock hash-table))
475    (cond ((= (get-header-data (hash-table-table hash-table))
476              sb!vm:vector-must-rehash-subtype)
477           (rehash-without-growing hash-table))
478          ((not (zerop (hash-table-needing-rehash hash-table)))
479           (flush-needing-rehash hash-table)))
480
481    ;; First check the cache.  Use EQ here for speed.
482    (let ((cache (hash-table-cache hash-table))
483          (table (hash-table-table hash-table)))
484
485      (if (and cache (< cache (length table)) (eq (aref table cache) key))
486          (values (aref table (1+ cache)) t)
487
488        ;; Search for key in the hash table.
489        (multiple-value-bind (hashing eq-based)
490            (funcall (hash-table-hash-fun hash-table) key)
491          (declare (type hash hashing))
492          (let* ((index-vector (hash-table-index-vector hash-table))
493                 (length (length index-vector))
494                 (index (rem hashing length))
495                 (next (aref index-vector index))
496                 (next-vector (hash-table-next-vector hash-table))
497                 (hash-vector (hash-table-hash-vector hash-table))
498                 (test-fun (hash-table-test-fun hash-table)))
499            (declare (type index index))
500            ;; Search next-vector chain for a matching key.
501            (if (or eq-based (not hash-vector))
502                (do ((next next (aref next-vector next)))
503                    ((zerop next) (values default nil))
504                  (declare (type index/2 next))
505                  (when (eq key (aref table (* 2 next)))
506                    (setf (hash-table-cache hash-table) (* 2 next))
507                    (return (values (aref table (1+ (* 2 next))) t))))
508              (do ((next next (aref next-vector next)))
509                  ((zerop next) (values default nil))
510                (declare (type index/2 next))
511                (when (and (= hashing (aref hash-vector next))
512                           (funcall test-fun key (aref table (* 2 next))))
513                  ;; Found.
514                  (setf (hash-table-cache hash-table) (* 2 next))
515                  (return (values (aref table (1+ (* 2 next))) t)))))))))))
516
517 ;;; so people can call #'(SETF GETHASH)
518 (defun (setf gethash) (new-value key table &optional default)
519   (declare (ignore default))
520   (%puthash key table new-value))
521
522 (defun %puthash (key hash-table value)
523   (declare (type hash-table hash-table))
524   (aver (hash-table-index-vector hash-table))
525   (with-spinlock-and-without-gcing ((hash-table-spinlock hash-table))
526    ;; We need to rehash here so that a current key can be found if it
527    ;; exists. Check that there is room for one more entry. May not be
528    ;; needed if the key is already present.
529    (cond ((zerop (hash-table-next-free-kv hash-table))
530           (rehash hash-table))
531          ((= (get-header-data (hash-table-table hash-table))
532              sb!vm:vector-must-rehash-subtype)
533           (rehash-without-growing hash-table))
534          ((not (zerop (hash-table-needing-rehash hash-table)))
535           (flush-needing-rehash hash-table)))
536
537    (let ((cache (hash-table-cache hash-table))
538          (kv-vector (hash-table-table hash-table)))
539
540      ;; Check the cache
541      (if (and cache (< cache (length kv-vector))
542               (eq (aref kv-vector cache) key))
543          ;; If cached, just store here
544          (setf (aref kv-vector (1+ cache)) value)
545
546        ;; Search for key in the hash table.
547        (multiple-value-bind (hashing eq-based)
548            (funcall (hash-table-hash-fun hash-table) key)
549          (declare (type hash hashing))
550          (let* ((index-vector (hash-table-index-vector hash-table))
551                 (length (length index-vector))
552                 (index (rem hashing length))
553                 (next (aref index-vector index))
554                 (kv-vector (hash-table-table hash-table))
555                 (next-vector (hash-table-next-vector hash-table))
556                 (hash-vector (hash-table-hash-vector hash-table))
557                 (test-fun (hash-table-test-fun hash-table)))
558            (declare (type index index next))
559            (when (hash-table-weakness hash-table)
560              (set-header-data kv-vector sb!vm:vector-valid-hashing-subtype))
561            (cond ((or eq-based (not hash-vector))
562                   (when eq-based
563                     (set-header-data kv-vector
564                                      sb!vm:vector-valid-hashing-subtype))
565
566                   ;; Search next-vector chain for a matching key.
567                   (do ((next next (aref next-vector next)))
568                       ((zerop next))
569                     (declare (type index/2 next))
570                     (when (eq key (aref kv-vector (* 2 next)))
571                       ;; Found, just replace the value.
572                       (setf (hash-table-cache hash-table) (* 2 next))
573                       (setf (aref kv-vector (1+ (* 2 next))) value)
574                       (return-from %puthash value))))
575                  (t
576                   ;; Search next-vector chain for a matching key.
577                   (do ((next next (aref next-vector next)))
578                       ((zerop next))
579                     (declare (type index/2 next))
580                     (when (and (= hashing (aref hash-vector next))
581                                (funcall test-fun key
582                                         (aref kv-vector (* 2 next))))
583                       ;; Found, just replace the value.
584                       (setf (hash-table-cache hash-table) (* 2 next))
585                       (setf (aref kv-vector (1+ (* 2 next))) value)
586                       (return-from %puthash value)))))
587
588            ;; Pop a KV slot off the free list
589            (let ((free-kv-slot (hash-table-next-free-kv hash-table)))
590              (declare (type index/2 free-kv-slot))
591              ;; Double-check for overflow.
592              (aver (not (zerop free-kv-slot)))
593              (setf (hash-table-next-free-kv hash-table)
594                    (aref next-vector free-kv-slot))
595              (incf (hash-table-number-entries hash-table))
596
597              (setf (hash-table-cache hash-table) (* 2 free-kv-slot))
598              (setf (aref kv-vector (* 2 free-kv-slot)) key)
599              (setf (aref kv-vector (1+ (* 2 free-kv-slot))) value)
600
601              ;; Setup the hash-vector if necessary.
602              (when hash-vector
603                (if (not eq-based)
604                    (setf (aref hash-vector free-kv-slot) hashing)
605                    (aver (= (aref hash-vector free-kv-slot)
606                             +magic-hash-vector-value+))))
607
608              ;; Push this slot into the next chain.
609              (setf (aref next-vector free-kv-slot) next)
610              (setf (aref index-vector index) free-kv-slot)))))))
611   value)
612
613 (defun remhash (key hash-table)
614   #!+sb-doc
615   "Remove the entry in HASH-TABLE associated with KEY. Return T if there
616    was such an entry, or NIL if not."
617   (declare (type hash-table hash-table)
618            (values (member t nil)))
619   (with-spinlock-and-without-gcing ((hash-table-spinlock hash-table))
620    ;; We need to rehash here so that a current key can be found if it
621    ;; exists.
622    (cond ((= (get-header-data (hash-table-table hash-table))
623              sb!vm:vector-must-rehash-subtype)
624           (rehash-without-growing hash-table))
625          ((not (zerop (hash-table-needing-rehash hash-table)))
626           (flush-needing-rehash hash-table)))
627
628    ;; For now, just clear the cache
629    (setf (hash-table-cache hash-table) nil)
630
631    ;; Search for key in the hash table.
632    (multiple-value-bind (hashing eq-based)
633        (funcall (hash-table-hash-fun hash-table) key)
634      (declare (type hash hashing))
635      (let* ((index-vector (hash-table-index-vector hash-table))
636             (length (length index-vector))
637             (index (rem hashing length))
638             (next (aref index-vector index))
639             (table (hash-table-table hash-table))
640             (next-vector (hash-table-next-vector hash-table))
641             (hash-vector (hash-table-hash-vector hash-table))
642             (test-fun (hash-table-test-fun hash-table)))
643        (declare (type index index)
644                 (type index/2 next))
645        (flet ((clear-slot (chain-vector prior-slot-location slot-location)
646                 (declare (type index/2 slot-location))
647                 ;; Mark slot as empty.
648                 (setf (aref table (* 2 slot-location)) +empty-ht-slot+
649                       (aref table (1+ (* 2 slot-location))) +empty-ht-slot+)
650                 ;; Update the prior pointer in the chain to skip this.
651                 (setf (aref chain-vector prior-slot-location)
652                       (aref next-vector slot-location))
653                 ;; Push KV slot onto free chain.
654                 (setf (aref next-vector slot-location)
655                       (hash-table-next-free-kv hash-table))
656                 (setf (hash-table-next-free-kv hash-table) slot-location)
657                 (when hash-vector
658                   (setf (aref hash-vector slot-location)
659                         +magic-hash-vector-value+))
660                 (decf (hash-table-number-entries hash-table))
661                 t))
662          (cond ((zerop next)
663                 nil)
664                ((if (or eq-based (not hash-vector))
665                     (eq key (aref table (* 2 next)))
666                     (and (= hashing (aref hash-vector next))
667                          (funcall test-fun key (aref table (* 2 next)))))
668                 (clear-slot index-vector index next))
669                ;; Search next-vector chain for a matching key.
670                ((or eq-based (not hash-vector))
671                 ;; EQ based
672                 (do ((prior next next)
673                      (next (aref next-vector next) (aref next-vector next)))
674                     ((zerop next) nil)
675                   (declare (type index next))
676                   (when (eq key (aref table (* 2 next)))
677                     (return-from remhash (clear-slot next-vector prior next)))))
678                (t
679                 ;; not EQ based
680                 (do ((prior next next)
681                      (next (aref next-vector next) (aref next-vector next)))
682                     ((zerop next) nil)
683                   (declare (type index/2 next))
684                   (when (and (= hashing (aref hash-vector next))
685                              (funcall test-fun key (aref table (* 2 next))))
686                     (return-from remhash
687                       (clear-slot next-vector prior next)))))))))))
688
689 (defun clrhash (hash-table)
690   #!+sb-doc
691   "This removes all the entries from HASH-TABLE and returns the hash table
692    itself."
693   (declare (optimize speed))
694   (with-spinlock-and-without-gcing ((hash-table-spinlock hash-table))
695     (let* ((kv-vector (hash-table-table hash-table))
696            (next-vector (hash-table-next-vector hash-table))
697            (hash-vector (hash-table-hash-vector hash-table))
698            (size (length next-vector))
699            (index-vector (hash-table-index-vector hash-table)))
700       ;; Disable GC tricks.
701       (set-header-data kv-vector sb!vm:vector-normal-subtype)
702       ;; Mark all slots as empty by setting all keys and values to magic
703       ;; tag.
704       (aver (eq (aref kv-vector 0) hash-table))
705       (fill kv-vector +empty-ht-slot+ :start 2)
706       ;; Set up the free list, all free.
707       (do ((i 1 (1+ i)))
708           ((>= i (1- size)))
709         (setf (aref next-vector i) (1+ i)))
710       (setf (aref next-vector (1- size)) 0)
711       (setf (hash-table-next-free-kv hash-table) 1)
712       (setf (hash-table-needing-rehash hash-table) 0)
713       ;; Clear the index-vector.
714       (fill index-vector 0)
715       ;; Clear the hash-vector.
716       (when hash-vector
717         (fill hash-vector +magic-hash-vector-value+)))
718     (setf (hash-table-cache hash-table) nil)
719     (setf (hash-table-number-entries hash-table) 0))
720   hash-table)
721 \f
722 ;;;; MAPHASH
723
724 ;;; FIXME: This should be made into a compiler transform for two reasons:
725 ;;;   1. It would then be available for compiling the entire system,
726 ;;;      not only parts of the system which are defined after DEFUN MAPHASH.
727 ;;;   2. It could be conditional on compilation policy, so that
728 ;;;      it could be compiled as a full call instead of an inline
729 ;;;      expansion when SPACE>SPEED.
730 (declaim (inline maphash))
731 (defun maphash (function-designator hash-table)
732   #!+sb-doc
733   "For each entry in HASH-TABLE, call the designated two-argument function on
734 the key and value of the entry. Return NIL."
735   ;; This essentially duplicates WITH-HASH-TABLE-ITERATOR, so
736   ;; any changes here should be reflected there as well.
737   (let ((fun (%coerce-callable-to-fun function-designator))
738         (size (length (hash-table-next-vector hash-table))))
739     (declare (type function fun))
740     (do ((i 1 (1+ i)))
741         ((>= i size))
742       (declare (type index/2 i))
743       (let* ((kv-vector (hash-table-table hash-table))
744              (key (aref kv-vector (* 2 i)))
745              (value (aref kv-vector (1+ (* 2 i)))))
746         ;; We are running without locking or WITHOUT-GCING. For a weak
747         ;; :VALUE hash table it's possible that the GC hit after KEY
748         ;; was read and now the entry is gone. So check if either the
749         ;; key or the value is empty.
750         (unless (or (eq key +empty-ht-slot+)
751                     (eq value +empty-ht-slot+))
752           (funcall fun key value))))))
753 \f
754 ;;;; methods on HASH-TABLE
755
756 ;;; Return a list of keyword args and values to use for MAKE-HASH-TABLE
757 ;;; when reconstructing HASH-TABLE.
758 (defun %hash-table-ctor-args (hash-table)
759   `(:test             ',(hash-table-test             hash-table)
760     :size             ',(hash-table-size             hash-table)
761     :rehash-size      ',(hash-table-rehash-size      hash-table)
762     :rehash-threshold ',(hash-table-rehash-threshold hash-table)
763     :weakness         ',(hash-table-weakness         hash-table)))
764
765 ;;; Return an association list representing the same data as HASH-TABLE.
766 (defun %hash-table-alist (hash-table)
767   (let ((result nil))
768     (maphash (lambda (key value)
769                (push (cons key value) result))
770              hash-table)
771     result))
772
773 ;;; Stuff an association list into HASH-TABLE. Return the hash table,
774 ;;; so that we can use this for the *PRINT-READABLY* case in
775 ;;; PRINT-OBJECT (HASH-TABLE T) without having to worry about LET
776 ;;; forms and readable gensyms and stuff.
777 (defun %stuff-hash-table (hash-table alist)
778   (dolist (x alist)
779     (setf (gethash (car x) hash-table) (cdr x)))
780   hash-table)
781
782 (def!method print-object ((hash-table hash-table) stream)
783   (declare (type stream stream))
784   (cond ((or (not *print-readably*) (not *read-eval*))
785          (print-unreadable-object (hash-table stream :type t :identity t)
786            (format stream
787                    ":TEST ~S :COUNT ~S"
788                    (hash-table-test hash-table)
789                    (hash-table-count hash-table))))
790         (t
791          (with-standard-io-syntax
792           (format stream
793                   "#.~W"
794                   `(%stuff-hash-table (make-hash-table ,@(%hash-table-ctor-args
795                                                           hash-table))
796                                      ',(%hash-table-alist hash-table)))))))
797
798 (def!method make-load-form ((hash-table hash-table) &optional environment)
799   (declare (ignore environment))
800   (values `(make-hash-table ,@(%hash-table-ctor-args hash-table))
801           `(%stuff-hash-table ,hash-table ',(%hash-table-alist hash-table))))