1 ;;;; that part of the implementation of HASH-TABLE which lives solely
2 ;;;; on the target system, not on the cross-compilation host
4 ;;;; This software is part of the SBCL system. See the README file for
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.
13 (in-package "SB!IMPL")
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
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
))
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
)
47 (unless (and (null (hash-table-writing-thread
49 ,@(when (eq operation
:write
)
50 `((null (hash-table-reading-thread
53 (setf (,thread-slot-accessor
,hash-table
)
54 sb
!thread
::*current-thread
*)
56 (unless (and ,@(when (eq operation
:read
)
57 `((null (hash-table-writing-thread
59 ,@(when (eq operation
:write
)
60 ;; no readers are allowed while writing
61 `((null (hash-table-reading-thread
63 (eq (hash-table-writing-thread
65 sb
!thread
::*current-thread
*))))
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
)))
74 #!-sb-fluid
(declaim (inline eq-hash
))
76 (declare (values hash
(member t nil
)))
77 (values (pointer-hash key
)
78 (oddp (get-lisp-obj-address key
))))
80 #!-sb-fluid
(declaim (inline equal-hash
))
81 (defun equal-hash (key)
82 (declare (values hash
(member t nil
)))
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
94 #!-sb-fluid
(declaim (inline eql-hash
))
96 (declare (values hash
(member t nil
)))
101 (defun equalp-hash (key)
102 (declare (values hash
(member t nil
)))
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
))
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
120 (+ (logxor #b11100101010001011010100111
127 ;;;; user-defined hash table tests
129 (defvar *user-hash-table-tests
* nil
)
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."
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
*)))
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
))))
147 (push this
*user-hash-table-tests
*)))))
150 (defmacro define-hash-table-test
(name hash-function
)
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.
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.
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.
165 Note: The :HASH-FUNCTION keyword argument to MAKE-HASH-TABLE can be used to
166 override the specified default hash-function.
168 Attempting to define NAME in a locked package as hash-table test causes a
169 package lock violation.
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 -- which we don't want.
178 (defstruct foo (name nil :type (or null string)))
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)))
184 (define-hash-table-test foo-name= sxhash-foo-name)
186 ;; #'foo-name would work too.
187 (defun make-foo-table () (make-hash-table :test 'foo-name=))
191 (defun == (x y) (= x y))
193 (define-hash-table-test ==
195 ;; Hash codes must be consistent with test, so
196 ;; not (SXHASH X), since
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))))
203 ;; #'== would work too
204 (defun make-number-table () (make-hash-table :test '==))
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
))
214 (error "Malformed HASH-FUNCTION: ~S" hash-function
)))))
216 ;;;; construction and simple accessors
218 (defconstant +min-hash-table-size
+ 16)
219 (defconstant +min-hash-table-rehash-threshold
+ (float 1/16 1.0))
221 (defun make-hash-table (&key
223 (size +min-hash-table-size
+)
230 "Create and return a new hash table. The keywords are as follows:
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.
240 A hint as to how many elements will be put in this hash table.
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.
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.
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.
261 When :WEAKNESS is not NIL, garbage collection may remove entries from the
262 hash table. The value of :WEAKNESS specifies how the presence of a key or
263 value in the hash table preserves their entries from garbage collection.
267 :KEY means that the key of an entry must be live to guarantee that the
270 :VALUE means that the value of an entry must be live to guarantee that
271 the entry is preserved.
273 :KEY-AND-VALUE means that both the key and the value must be live to
274 guarantee that the entry is preserved.
276 :KEY-OR-VALUE means that either the key or the value must be live to
277 guarantee that the entry is preserved.
279 NIL (the default) means that entries are always preserved.
282 If NIL (the default), the hash-table may have multiple concurrent readers,
283 but results are undefined if a thread writes to the hash-table
284 concurrently with another reader or writer. If T, all concurrent accesses
285 are safe, but note that CLHS 3.6 (Traversal Rules and Side Effects)
286 remains in force. See also: SB-EXT:WITH-LOCKED-HASH-TABLE. This keyword
287 argument is experimental, and may change incompatibly or be removed in the
289 (declare (type (or function symbol
) test
))
290 (declare (type unsigned-byte size
))
291 (multiple-value-bind (test test-fun hash-fun
)
292 (cond ((or (eq test
#'eq
) (eq test
'eq
))
293 (values 'eq
#'eq
#'eq-hash
))
294 ((or (eq test
#'eql
) (eq test
'eql
))
295 (values 'eql
#'eql
#'eql-hash
))
296 ((or (eq test
#'equal
) (eq test
'equal
))
297 (values 'equal
#'equal
#'equal-hash
))
298 ((or (eq test
#'equalp
) (eq test
'equalp
))
299 (values 'equalp
#'equalp
#'equalp-hash
))
301 ;; FIXME: It would be nice to have a compiler-macro
302 ;; that resolved this at compile time: we could grab
303 ;; the alist cell in a LOAD-TIME-VALUE, etc.
304 (dolist (info *user-hash-table-tests
*
307 (values (%fun-name test
) test nil
)
308 (values test
(%coerce-callable-to-fun test
) nil
))
309 (error "Unknown :TEST for MAKE-HASH-TABLE: ~S"
311 (destructuring-bind (test-name test-fun hash-fun
) info
312 (when (or (eq test test-name
) (eq test test-fun
))
313 (return (values test-name test-fun hash-fun
)))))))
316 ;; Quickly check if the function has return return type which
317 ;; guarantees that the secondary return value is always NIL:
318 ;; (VALUES * &OPTIONAL), (VALUES * NULL ...) or (VALUES *
319 ;; &OPTIONAL NULL ...)
320 (let* ((actual (%coerce-callable-to-fun hash-function
))
321 (type-spec (%fun-type actual
))
322 (return-spec (when (consp type-spec
)
324 (extra-vals (when (consp return-spec
)
325 (cddr return-spec
))))
326 (if (and (consp extra-vals
)
327 (or (eq 'null
(car extra-vals
))
328 (and (eq '&optional
(car extra-vals
))
329 (or (not (cdr extra-vals
))
330 (eq 'null
(cadr extra-vals
))))))
332 ;; If there is a potential secondary value, make sure we
333 ;; don't accidentally claim EQ based hashing...
335 (declare (optimize (safety 0) (speed 3)))
336 (values (funcall actual object
) nil
))))))
337 (let* ((size (max +min-hash-table-size
+
339 ;; SIZE is just a hint, so if the user asks
340 ;; for a SIZE which'd be too big for us to
341 ;; easily implement, we bump it down.
342 (floor array-dimension-limit
1024))))
343 (rehash-size (if (integerp rehash-size
)
345 (float rehash-size
1.0)))
346 ;; FIXME: Original REHASH-THRESHOLD default should be 1.0,
347 ;; not 1, to make it easier for the compiler to avoid
349 (rehash-threshold (max +min-hash-table-rehash-threshold
+
350 (float rehash-threshold
1.0)))
351 (size+1 (1+ size
)) ; The first element is not usable.
352 ;; KLUDGE: The most natural way of expressing the below is
353 ;; (round (/ (float size+1) rehash-threshold)), and indeed
354 ;; it was expressed like that until 0.7.0. However,
355 ;; MAKE-HASH-TABLE is called very early in cold-init, and
356 ;; the SPARC has no primitive instructions for rounding,
357 ;; but only for truncating; therefore, we fudge this issue
358 ;; a little. The other uses of truncate, below, similarly
359 ;; used to be round. -- CSR, 2002-10-01
361 ;; Note that this has not yet been audited for
362 ;; correctness. It just seems to work. -- CSR, 2002-11-02
363 (scaled-size (truncate (/ (float size
+1) rehash-threshold
)))
364 (length (power-of-two-ceiling (max scaled-size
365 (1+ +min-hash-table-size
+))))
366 (index-vector (make-array length
368 '(unsigned-byte #.sb
!vm
:n-word-bits
)
370 ;; Needs to be the half the length of the KV vector to link
371 ;; KV entries - mapped to indeces at 2i and 2i+1 -
373 (next-vector (make-array size
+1
375 '(unsigned-byte #.sb
!vm
:n-word-bits
)))
376 (kv-vector (make-array (* 2 size
+1)
377 :initial-element
+empty-ht-slot
+))
378 (table (%make-hash-table
389 (unless (eq test
'eq
)
391 :element-type
'(unsigned-byte
393 :initial-element
+magic-hash-vector-value
+))
395 (declare (type index size
+1 scaled-size length
))
396 ;; Set up the free list, all free. These lists are 0 terminated.
399 (setf (aref next-vector i
) (1+ i
)))
400 (setf (aref next-vector size
) 0)
401 (setf (hash-table-next-free-kv table
) 1)
402 (setf (aref kv-vector
0) table
)
405 (defun hash-table-count (hash-table)
407 "Return the number of entries in the given HASH-TABLE."
408 (declare (type hash-table hash-table
)
410 (hash-table-number-entries hash-table
))
413 (setf (fdocumentation 'hash-table-rehash-size
'function
)
414 "Return the rehash-size HASH-TABLE was created with.")
417 (setf (fdocumentation 'hash-table-rehash-threshold
'function
)
418 "Return the rehash-threshold HASH-TABLE was created with.")
421 (setf (fdocumentation 'hash-table-synchronized-p
'function
)
422 "Returns T if HASH-TABLE is synchronized.")
424 (defun hash-table-size (hash-table)
426 "Return a size that can be used with MAKE-HASH-TABLE to create a hash
427 table that can hold however many entries HASH-TABLE can hold without
429 (hash-table-rehash-trigger hash-table
))
432 (setf (fdocumentation 'hash-table-test
'function
)
433 "Return the test HASH-TABLE was created with.")
436 (setf (fdocumentation 'hash-table-weakness
'function
)
437 "Return the WEAKNESS of HASH-TABLE which is one of NIL, :KEY,
438 :VALUE, :KEY-AND-VALUE, :KEY-OR-VALUE.")
440 ;;; Called when we detect circular chains in a hash-table.
441 (defun signal-corrupt-hash-table (hash-table)
442 (error "Corrupt NEXT-chain in ~A. This is probably caused by ~
443 multiple threads accessing the same hash-table without locking."
447 ;;;; accessing functions
449 ;;; Make new vectors for the table, extending the table based on the
451 (defun rehash (table)
452 (declare (type hash-table table
))
454 (let* ((old-kv-vector (hash-table-table table
))
455 (old-next-vector (hash-table-next-vector table
))
456 (old-hash-vector (hash-table-hash-vector table
))
457 (old-size (length old-next-vector
))
459 (power-of-two-ceiling
460 (let ((rehash-size (hash-table-rehash-size table
)))
461 (etypecase rehash-size
463 (+ rehash-size old-size
))
465 (the index
(truncate (* rehash-size old-size
))))))))
466 (new-kv-vector (make-array (* 2 new-size
)
467 :initial-element
+empty-ht-slot
+))
470 :element-type
'(unsigned-byte #.sb
!vm
:n-word-bits
)
473 (when old-hash-vector
475 :element-type
'(unsigned-byte #.sb
!vm
:n-word-bits
)
476 :initial-element
+magic-hash-vector-value
+)))
477 (new-length new-size
)
479 (make-array new-length
480 :element-type
'(unsigned-byte #.sb
!vm
:n-word-bits
)
481 :initial-element
0)))
482 (declare (type index new-size new-length old-size
))
484 ;; Disable GC tricks on the OLD-KV-VECTOR.
485 (set-header-data old-kv-vector sb
!vm
:vector-normal-subtype
)
487 ;; Non-empty weak hash tables always need GC support.
488 (when (and (hash-table-weakness table
) (plusp (hash-table-count table
)))
489 (set-header-data new-kv-vector sb
!vm
:vector-valid-hashing-subtype
))
491 ;; FIXME: here and in several other places in the hash table code,
492 ;; loops like this one are used when FILL or REPLACE would be
493 ;; appropriate. why are standard CL functions not used?
494 ;; Performance issues? General laziness? -- NJF, 2004-03-10
496 ;; Copy over the kv-vector. The element positions should not move
497 ;; in case there are active scans.
498 (dotimes (i (* old-size
2))
499 (declare (type index i
))
500 (setf (aref new-kv-vector i
) (aref old-kv-vector i
)))
502 ;; Copy over the hash-vector.
503 (when old-hash-vector
504 (dotimes (i old-size
)
505 (setf (aref new-hash-vector i
) (aref old-hash-vector i
))))
507 (setf (hash-table-next-free-kv table
) 0)
508 ;; Rehash all the entries; last to first so that after the pushes
509 ;; the chains are first to last.
510 (do ((i (1- new-size
) (1- i
)))
512 (declare (type index
/2 i
))
513 (let ((key (aref new-kv-vector
(* 2 i
)))
514 (value (aref new-kv-vector
(1+ (* 2 i
)))))
515 (cond ((and (eq key
+empty-ht-slot
+)
516 (eq value
+empty-ht-slot
+))
517 ;; Slot is empty, push it onto the free list.
518 (setf (aref new-next-vector i
)
519 (hash-table-next-free-kv table
))
520 (setf (hash-table-next-free-kv table
) i
))
521 ((and new-hash-vector
522 (not (= (aref new-hash-vector i
)
523 +magic-hash-vector-value
+)))
524 ;; Can use the existing hash value (not EQ based)
525 (let* ((hashing (aref new-hash-vector i
))
526 (index (index-for-hashing hashing new-length
))
527 (next (aref new-index-vector index
)))
528 (declare (type index index
)
530 ;; Push this slot into the next chain.
531 (setf (aref new-next-vector i
) next
)
532 (setf (aref new-index-vector index
) i
)))
536 (set-header-data new-kv-vector
537 sb
!vm
:vector-valid-hashing-subtype
)
538 (let* ((hashing (pointer-hash key
))
539 (index (index-for-hashing hashing new-length
))
540 (next (aref new-index-vector index
)))
541 (declare (type index index
)
543 ;; Push this slot onto the next chain.
544 (setf (aref new-next-vector i
) next
)
545 (setf (aref new-index-vector index
) i
))))))
546 (setf (hash-table-table table
) new-kv-vector
)
547 (setf (hash-table-index-vector table
) new-index-vector
)
548 (setf (hash-table-next-vector table
) new-next-vector
)
549 (setf (hash-table-hash-vector table
) new-hash-vector
)
550 ;; Fill the old kv-vector with 0 to help the conservative GC. Even
551 ;; if nothing else were zeroed, it's important to clear the
552 ;; special first cells in old-kv-vector.
553 (fill old-kv-vector
0)
554 (setf (hash-table-rehash-trigger table
) new-size
)
555 (setf (hash-table-needs-rehash-p table
) nil
))
558 ;;; Use the same size as before, re-using the vectors.
559 (defun rehash-without-growing (table)
560 (declare (type hash-table table
))
562 (let* ((kv-vector (hash-table-table table
))
563 (next-vector (hash-table-next-vector table
))
564 (hash-vector (hash-table-hash-vector table
))
565 (size (length next-vector
))
566 (index-vector (hash-table-index-vector table
))
567 (length (length index-vector
)))
568 (declare (type index size length
))
570 ;; Non-empty weak hash tables always need GC support.
571 (unless (and (hash-table-weakness table
) (plusp (hash-table-count table
)))
572 ;; Disable GC tricks, they will be re-enabled during the re-hash
574 (set-header-data kv-vector sb
!vm
:vector-normal-subtype
))
576 ;; Rehash all the entries.
577 (setf (hash-table-next-free-kv table
) 0)
579 (setf (aref next-vector i
) 0))
581 (setf (aref index-vector i
) 0))
582 (do ((i (1- size
) (1- i
)))
584 (declare (type index
/2 i
))
585 (let ((key (aref kv-vector
(* 2 i
)))
586 (value (aref kv-vector
(1+ (* 2 i
)))))
587 (cond ((and (eq key
+empty-ht-slot
+)
588 (eq value
+empty-ht-slot
+))
589 ;; Slot is empty, push it onto free list.
590 (setf (aref next-vector i
) (hash-table-next-free-kv table
))
591 (setf (hash-table-next-free-kv table
) i
))
592 ((and hash-vector
(not (= (aref hash-vector i
)
593 +magic-hash-vector-value
+)))
594 ;; Can use the existing hash value (not EQ based)
595 (let* ((hashing (aref hash-vector i
))
596 (index (index-for-hashing hashing length
))
597 (next (aref index-vector index
)))
598 (declare (type index index
))
599 ;; Push this slot into the next chain.
600 (setf (aref next-vector i
) next
)
601 (setf (aref index-vector index
) i
)))
605 (set-header-data kv-vector sb
!vm
:vector-valid-hashing-subtype
)
606 (let* ((hashing (pointer-hash key
))
607 (index (index-for-hashing hashing length
))
608 (next (aref index-vector index
)))
609 (declare (type index index
)
611 ;; Push this slot into the next chain.
612 (setf (aref next-vector i
) next
)
613 (setf (aref index-vector index
) i
)))))))
614 ;; Clear the rehash bit only at the very end, otherwise another thread
615 ;; might see a partially rehashed table as a normal one.
616 (setf (hash-table-needs-rehash-p table
) nil
)
619 (declaim (inline maybe-rehash
))
620 (defun maybe-rehash (hash-table ensure-free-slot-p
)
621 (when (hash-table-weakness hash-table
)
624 (and ensure-free-slot-p
625 (zerop (hash-table-next-free-kv hash-table
))))
626 (rehash-without-growing-p ()
627 (hash-table-needs-rehash-p hash-table
)))
628 (declare (inline rehash-p rehash-without-growing-p
))
630 ;; Use recursive locks since for weak tables the lock has
631 ;; already been acquired. GC must be inhibited to prevent
632 ;; the GC from seeing a rehash in progress.
633 (sb!thread
::with-recursive-system-lock
634 ((hash-table-lock hash-table
) :without-gcing t
)
635 ;; Repeat the condition inside the lock to ensure that if
636 ;; two reader threads enter MAYBE-REHASH at the same time
637 ;; only one rehash is performed.
639 (rehash hash-table
))))
640 ((rehash-without-growing-p)
641 (sb!thread
::with-recursive-system-lock
642 ((hash-table-lock hash-table
) :without-gcing t
)
643 (when (rehash-without-growing-p)
644 (rehash-without-growing hash-table
)))))))
646 (declaim (inline update-hash-table-cache
))
647 (defun update-hash-table-cache (hash-table index
)
648 (unless (hash-table-weakness hash-table
)
649 (setf (hash-table-cache hash-table
) index
)))
651 (defmacro with-hash-table-locks
((hash-table
652 &key
(operation :write
) inline pin
653 (synchronized `(hash-table-synchronized-p ,hash-table
)))
655 (declare (type (member :read
:write
) operation
))
656 (with-unique-names (body-fun)
657 `(flet ((,body-fun
()
658 (with-concurrent-access-check ,hash-table
,operation
659 (locally (declare (inline ,@inline
))
661 (if (hash-table-weakness ,hash-table
)
662 (sb!thread
::with-recursive-system-lock
663 ((hash-table-lock ,hash-table
) :without-gcing t
)
665 (with-pinned-objects ,pin
667 ;; We use a "system" lock here because it is very
668 ;; slightly faster, as it doesn't re-enable
670 (sb!thread
::with-recursive-system-lock
671 ((hash-table-lock ,hash-table
))
675 (defun gethash (key hash-table
&optional default
)
677 "Finds the entry in HASH-TABLE whose key is KEY and returns the
678 associated value and T as multiple values, or returns DEFAULT and NIL
679 if there is no such entry. Entries can be added using SETF."
680 (declare (type hash-table hash-table
)
681 (values t
(member t nil
)))
682 (gethash3 key hash-table default
))
684 (declaim (maybe-inline %gethash3
))
685 (defun %gethash3
(key hash-table default
)
686 (declare (type hash-table hash-table
)
688 (values t
(member t nil
)))
691 (let ((start-epoch sb
!kernel
::*gc-epoch
*))
692 (macrolet ((result (value foundp
)
693 ;; When the table has multiple concurrent readers,
694 ;; it's possible that there was a GC after this
695 ;; thread called MAYBE-REHASH from %GETHASH3, and
696 ;; some other thread then rehashed the table. If
697 ;; this happens, we might not find the key even if
698 ;; it's in the table. To protect against this,
699 ;; redo the lookup if the GC epoch counter has changed.
700 ;; -- JES, 2007-09-30
701 `(if (and (not ,foundp
)
702 (not (eq start-epoch sb
!kernel
::*gc-epoch
*)))
704 (return-from %gethash3
(values ,value
,foundp
))))
706 ;; The next-vector chain is circular. This is caused
707 ;; caused by thread-unsafe mutations of the table.
708 `(signal-corrupt-hash-table hash-table
)))
709 (maybe-rehash hash-table nil
)
710 ;; Note that it's OK for a GC + a REHASH-WITHOUT-GROWING to
711 ;; be triggered by another thread after this point, since the
712 ;; GC epoch check will catch it.
713 (let ((cache (hash-table-cache hash-table
))
714 (table (hash-table-table hash-table
)))
715 ;; First check the cache. Use EQ here for speed.
717 (< cache
(length table
))
718 (eq (aref table cache
) key
))
719 (let ((value (aref table
(1+ cache
))))
721 ;; Search for key in the hash table.
722 (multiple-value-bind (hashing eq-based
)
723 (funcall (hash-table-hash-fun hash-table
) key
)
724 (declare (type hash hashing
))
725 (let* ((index-vector (hash-table-index-vector hash-table
))
726 (length (length index-vector
))
727 (index (index-for-hashing hashing length
))
728 (next (aref index-vector index
))
729 (next-vector (hash-table-next-vector hash-table
))
730 (hash-vector (hash-table-hash-vector hash-table
))
731 (test-fun (hash-table-test-fun hash-table
)))
732 (declare (type index index
))
733 ;; Search next-vector chain for a matching key.
734 (if (or eq-based
(not hash-vector
))
735 (do ((next next
(aref next-vector next
))
737 ((zerop next
) (result default nil
))
738 (declare (type index
/2 next i
))
741 (when (eq key
(aref table
(* 2 next
)))
742 (update-hash-table-cache hash-table
(* 2 next
))
743 (let ((value (aref table
(1+ (* 2 next
)))))
745 (do ((next next
(aref next-vector next
))
747 ((zerop next
) (result default nil
))
748 (declare (type index
/2 next i
))
751 (when (and (= hashing
(aref hash-vector next
))
752 (funcall test-fun key
753 (aref table
(* 2 next
))))
755 (update-hash-table-cache hash-table
(* 2 next
))
756 (let ((value (aref table
(1+ (* 2 next
)))))
757 (result value t
)))))))))))))
758 ;;; Three argument version of GETHASH
759 (defun gethash3 (key hash-table default
)
760 (declare (type hash-table hash-table
))
761 (with-hash-table-locks (hash-table :operation
:read
:inline
(%gethash3
)
763 (%gethash3 key hash-table default
)))
765 ;;; so people can call #'(SETF GETHASH)
766 (defun (setf gethash
) (new-value key table
&optional default
)
767 (declare (ignore default
))
768 (%puthash key table new-value
))
770 (declaim (maybe-inline %%puthash
))
771 (defun %%puthash
(key hash-table value
)
772 (declare (optimize speed
))
773 ;; We need to rehash here so that a current key can be found if it
774 ;; exists. Check that there is room for one more entry. May not be
775 ;; needed if the key is already present.
776 (maybe-rehash hash-table t
)
777 ;; Search for key in the hash table.
778 (multiple-value-bind (hashing eq-based
)
779 (funcall (hash-table-hash-fun hash-table
) key
)
780 (declare (type hash hashing
))
781 (let* ((index-vector (hash-table-index-vector hash-table
))
782 (length (length index-vector
))
783 (index (index-for-hashing hashing length
))
784 (next (aref index-vector index
))
785 (kv-vector (hash-table-table hash-table
))
786 (next-vector (hash-table-next-vector hash-table
))
787 (hash-vector (hash-table-hash-vector hash-table
))
788 (test-fun (hash-table-test-fun hash-table
)))
789 (declare (type index index next
))
790 (when (hash-table-weakness hash-table
)
791 (set-header-data kv-vector sb
!vm
:vector-valid-hashing-subtype
))
792 (cond ((or eq-based
(not hash-vector
))
794 (set-header-data kv-vector
795 sb
!vm
:vector-valid-hashing-subtype
))
796 ;; Search next-vector chain for a matching key.
797 (do ((next next
(aref next-vector next
))
800 (declare (type index
/2 next i
))
802 (signal-corrupt-hash-table hash-table
))
803 (when (eq key
(aref kv-vector
(* 2 next
)))
804 ;; Found, just replace the value.
805 (update-hash-table-cache hash-table
(* 2 next
))
806 (setf (aref kv-vector
(1+ (* 2 next
))) value
)
807 (return-from %%puthash value
))))
809 ;; Search next-vector chain for a matching key.
810 (do ((next next
(aref next-vector next
))
813 (declare (type index
/2 next i
))
815 (signal-corrupt-hash-table hash-table
))
816 (when (and (= hashing
(aref hash-vector next
))
817 (funcall test-fun key
818 (aref kv-vector
(* 2 next
))))
819 ;; Found, just replace the value.
820 (update-hash-table-cache hash-table
(* 2 next
))
821 (setf (aref kv-vector
(1+ (* 2 next
))) value
)
822 (return-from %%puthash value
)))))
823 ;; Pop a KV slot off the free list
824 (let ((free-kv-slot (hash-table-next-free-kv hash-table
)))
825 (declare (type index
/2 free-kv-slot
))
826 ;; Double-check for overflow.
827 (aver (not (zerop free-kv-slot
)))
828 (setf (hash-table-next-free-kv hash-table
)
829 (aref next-vector free-kv-slot
))
830 (incf (hash-table-number-entries hash-table
))
831 (update-hash-table-cache hash-table
(* 2 free-kv-slot
))
832 (setf (aref kv-vector
(* 2 free-kv-slot
)) key
)
833 (setf (aref kv-vector
(1+ (* 2 free-kv-slot
))) value
)
834 ;; Setup the hash-vector if necessary.
837 (setf (aref hash-vector free-kv-slot
) hashing
)
838 (aver (= (aref hash-vector free-kv-slot
)
839 +magic-hash-vector-value
+))))
840 ;; Push this slot into the next chain.
841 (setf (aref next-vector free-kv-slot
) next
)
842 (setf (aref index-vector index
) free-kv-slot
)))
845 (defun %puthash
(key hash-table value
)
846 (declare (type hash-table hash-table
))
847 (aver (hash-table-index-vector hash-table
))
848 (macrolet ((put-it (lockedp)
849 `(let ((cache (hash-table-cache hash-table
))
850 (kv-vector (hash-table-table hash-table
)))
853 (< cache
(length kv-vector
))
854 (eq (aref kv-vector cache
) key
))
855 ;; If cached, just store here
856 (setf (aref kv-vector
(1+ cache
)) value
)
857 ;; Otherwise do things the hard way
859 '(%%puthash key hash-table value
)
860 '(with-hash-table-locks
861 (hash-table :inline
(%%puthash
) :pin
(key)
863 (%%puthash key hash-table value
)))))))
864 (if (hash-table-synchronized-p hash-table
)
865 (with-hash-table-locks (hash-table :pin
(key) :synchronized t
)
869 (declaim (maybe-inline %remhash
))
870 (defun %remhash
(key hash-table
)
871 ;; We need to rehash here so that a current key can be found if it
874 ;; Note that if a GC happens after MAYBE-REHASH returns and another
875 ;; thread the accesses the table (triggering a rehash), we might not
876 ;; find the key even if it is in the table. But that's ok, since the
877 ;; only concurrent case that we safely allow is multiple readers
879 (maybe-rehash hash-table nil
)
880 ;; Search for key in the hash table.
881 (multiple-value-bind (hashing eq-based
)
882 (funcall (hash-table-hash-fun hash-table
) key
)
883 (declare (type hash hashing
))
884 (let* ((index-vector (hash-table-index-vector hash-table
))
885 (length (length index-vector
))
886 (index (index-for-hashing hashing length
))
887 (next (aref index-vector index
))
888 (table (hash-table-table hash-table
))
889 (next-vector (hash-table-next-vector hash-table
))
890 (hash-vector (hash-table-hash-vector hash-table
))
891 (test-fun (hash-table-test-fun hash-table
)))
892 (declare (type index index
)
894 (flet ((clear-slot (chain-vector prior-slot-location slot-location
)
895 (declare (type index
/2 slot-location
))
896 ;; Mark slot as empty.
897 (setf (aref table
(* 2 slot-location
)) +empty-ht-slot
+
898 (aref table
(1+ (* 2 slot-location
))) +empty-ht-slot
+)
899 ;; Update the prior pointer in the chain to skip this.
900 (setf (aref chain-vector prior-slot-location
)
901 (aref next-vector slot-location
))
902 ;; Push KV slot onto free chain.
903 (setf (aref next-vector slot-location
)
904 (hash-table-next-free-kv hash-table
))
905 (setf (hash-table-next-free-kv hash-table
) slot-location
)
907 (setf (aref hash-vector slot-location
)
908 +magic-hash-vector-value
+))
909 ;; On parallel accesses this may turn out to be a
910 ;; type-error, so don't turn down the safety!
911 (decf (hash-table-number-entries hash-table
))
915 ((if (or eq-based
(not hash-vector
))
916 (eq key
(aref table
(* 2 next
)))
917 (and (= hashing
(aref hash-vector next
))
918 (funcall test-fun key
(aref table
(* 2 next
)))))
919 (clear-slot index-vector index next
))
920 ;; Search next-vector chain for a matching key.
921 ((or eq-based
(not hash-vector
))
923 (do ((prior next next
)
925 (next (aref next-vector next
) (aref next-vector next
)))
927 (declare (type index next
))
929 (signal-corrupt-hash-table hash-table
))
930 (when (eq key
(aref table
(* 2 next
)))
931 (return-from %remhash
(clear-slot next-vector prior next
)))))
934 (do ((prior next next
)
936 (next (aref next-vector next
) (aref next-vector next
)))
938 (declare (type index
/2 next
))
940 (signal-corrupt-hash-table hash-table
))
941 (when (and (= hashing
(aref hash-vector next
))
942 (funcall test-fun key
(aref table
(* 2 next
))))
943 (return-from %remhash
944 (clear-slot next-vector prior next
))))))))))
946 (defun remhash (key hash-table
)
948 "Remove the entry in HASH-TABLE associated with KEY. Return T if
949 there was such an entry, or NIL if not."
950 (declare (type hash-table hash-table
)
951 (values (member t nil
)))
952 (with-hash-table-locks (hash-table :inline
(%remhash
) :pin
(key))
953 ;; For now, just clear the cache
954 (setf (hash-table-cache hash-table
) nil
)
955 (%remhash key hash-table
)))
957 (defun clrhash (hash-table)
959 "This removes all the entries from HASH-TABLE and returns the hash
961 (when (plusp (hash-table-number-entries hash-table
))
962 (with-hash-table-locks (hash-table)
963 (let* ((kv-vector (hash-table-table hash-table
))
964 (next-vector (hash-table-next-vector hash-table
))
965 (hash-vector (hash-table-hash-vector hash-table
))
966 (size (length next-vector
))
967 (index-vector (hash-table-index-vector hash-table
)))
968 ;; Disable GC tricks.
969 (set-header-data kv-vector sb
!vm
:vector-normal-subtype
)
970 ;; Mark all slots as empty by setting all keys and values to magic
972 (aver (eq (aref kv-vector
0) hash-table
))
973 (fill kv-vector
+empty-ht-slot
+ :start
2)
974 ;; Set up the free list, all free.
977 (setf (aref next-vector i
) (1+ i
)))
978 (setf (aref next-vector
(1- size
)) 0)
979 (setf (hash-table-next-free-kv hash-table
) 1)
980 ;; Clear the index-vector.
981 (fill index-vector
0)
982 ;; Clear the hash-vector.
984 (fill hash-vector
+magic-hash-vector-value
+)))
985 (setf (hash-table-cache hash-table
) nil
)
986 (setf (hash-table-number-entries hash-table
) 0)))
992 ;;; FIXME: This should be made into a compiler transform for two reasons:
993 ;;; 1. It would then be available for compiling the entire system,
994 ;;; not only parts of the system which are defined after DEFUN MAPHASH.
995 ;;; 2. It could be conditional on compilation policy, so that
996 ;;; it could be compiled as a full call instead of an inline
997 ;;; expansion when SPACE>SPEED.
998 (declaim (inline maphash
))
999 (defun maphash (function-designator hash-table
)
1001 "For each entry in HASH-TABLE, call the designated two-argument function on
1002 the key and value of the entry. Return NIL.
1004 Consequences are undefined if HASH-TABLE is mutated during the call to
1005 MAPHASH, except for changing or removing elements corresponding to the
1006 current key. The applies to all threads, not just the current one --
1007 even for synchronized hash-tables. If the table may be mutated by
1008 another thread during iteration, use eg. SB-EXT:WITH-LOCKED-HASH-TABLE
1009 to protect the MAPHASH call."
1010 ;; This essentially duplicates WITH-HASH-TABLE-ITERATOR, so
1011 ;; any changes here should be reflected there as well.
1012 (let ((fun (%coerce-callable-to-fun function-designator
))
1013 (size (length (hash-table-next-vector hash-table
))))
1014 (declare (type function fun
))
1017 (declare (type index
/2 i
))
1018 (let* ((kv-vector (hash-table-table hash-table
))
1019 (key (aref kv-vector
(* 2 i
)))
1020 (value (aref kv-vector
(1+ (* 2 i
)))))
1021 ;; We are running without locking or WITHOUT-GCING. For a weak
1022 ;; :VALUE hash table it's possible that the GC hit after KEY
1023 ;; was read and now the entry is gone. So check if either the
1024 ;; key or the value is empty.
1025 (unless (or (eq key
+empty-ht-slot
+)
1026 (eq value
+empty-ht-slot
+))
1027 (funcall fun key value
))))))
1029 ;;;; methods on HASH-TABLE
1031 ;;; Return a list of keyword args and values to use for MAKE-HASH-TABLE
1032 ;;; when reconstructing HASH-TABLE.
1033 (defun %hash-table-ctor-args
(hash-table)
1034 `(:test
',(hash-table-test hash-table
)
1035 :size
',(hash-table-size hash-table
)
1036 :rehash-size
',(hash-table-rehash-size hash-table
)
1037 :rehash-threshold
',(hash-table-rehash-threshold hash-table
)
1038 :weakness
',(hash-table-weakness hash-table
)))
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
)
1046 (setf (gethash (car x
) hash-table
) (cdr x
)))
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
)
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
))))
1059 (write-string "#." stream
)
1060 (write `(%stuff-hash-table
(make-hash-table ,@(%hash-table-ctor-args
1062 ',(%hash-table-alist hash-table
))
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
))))