-
Notifications
You must be signed in to change notification settings - Fork 313
/
target-hash-table.lisp
2272 lines (2124 loc) · 121 KB
/
target-hash-table.lisp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
;;;; that part of the implementation of HASH-TABLE which lives solely
;;;; on the target system, not on the cross-compilation host
;;;; This software is part of the SBCL system. See the README file for
;;;; more information.
;;;;
;;;; This software is derived from the CMU CL system, which was
;;;; written at Carnegie Mellon University and released into the
;;;; public domain. The software is in the public domain and is
;;;; provided with absolutely no warranty. See the COPYING and CREDITS
;;;; files for more information.
(in-package "SB-IMPL")
;;;; utilities
;;;; TODOs:
;;;; - change recursive locks to nonrecursive.
;;;; This will, I fear, be impossible because we've exposed and documented
;;;; an API that pretty much tells users that it's ok to create a synchronized
;;;; table while *also* wrapping any random operation in the table lock.
;;;; Hence recursion on the lock. (commit b9a1b17b079d315c)
;;;; - place the 3 or 4 vectors in a separate structure that can be atomically
;;;; swapped out for a new instance with new vectors. Remove array bounds
;;;; checking since all the arrays will be tied together.
;;; T if and only if table has non-null weakness kind.
(declaim (inline hash-table-weak-p))
(defun hash-table-weak-p (ht)
(logtest (hash-table-flags ht) hash-table-weak-flag))
;;; Value of :synchronized constructor argument.
(declaim (inline hash-table-synchronized-p))
(defun hash-table-synchronized-p (ht)
(logtest (hash-table-flags ht) hash-table-synchronized-flag))
;;; Keep in sync with weak_ht_alivep_funs[] in gc-common
(declaim (inline decode-hash-table-weakness))
(defun decode-hash-table-weakness (x)
;; The bits of 'weakness' are interpreted as follows:
;; bit 0 : live key forces value to be live
;; bit 1 : live value forces key to be live
;; both : either forces the other to be live
;; :KEY-AND-VALUE has two zero bits, as neither object livens the other
(aref #(:key-and-value :key :value :key-or-value) x))
;;; Non-NIL if this is some kind of weak hash table. For details see
;;; the docstring of MAKE-HASH-TABLE.
(defun hash-table-weakness (ht)
"Return the WEAKNESS of HASH-TABLE which is one of NIL, :KEY,
:VALUE, :KEY-AND-VALUE, :KEY-OR-VALUE."
(and (hash-table-weak-p ht)
(decode-hash-table-weakness (ht-flags-weakness (hash-table-flags ht)))))
;;; Hash table hash functions can return any FIXNUM, because POINTER-HASH can.
;;; This is less restrictive than SXHASH which says it has to be positive.
(declaim (ftype (sfunction (t) (values fixnum boolean))
eq-hash eql-hash equal-hash equalp-hash))
(declaim (inline eq-hash))
(defun eq-hash (key)
(declare (values fixnum boolean))
;; I think it would be ok to pick off SYMBOL here and use its hash slot
;; as far as semantics are concerned, but EQ-hash is supposed to be
;; the lightest-weight in terms of speed, so I'm letting everything use
;; address-based hashing, unlike the other standard hash-table hash functions
;; which try use the hash slot of certain objects.
;; Note also that as we add logic into the EQ-HASH function to decide whether
;; the hash is address-based, we either have to replicate that logic into
;; rehashing, or else actually call EQ-HASH to decide for us.
(values (pointer-hash key)
(sb-vm:is-lisp-pointer (get-lisp-obj-address key))))
;;; Note: We could somewhat easily add SAP-WIDETAG into the list of types
;;; that get a stable hash for EQL tables (via SAP-HASH), however:
;;; - we don't compare SAPs with SAP= when the table's test is EQL,
;;; so there is no real advantage (nor requirement) to have a hash
;;; derived from the object's contents.
;;; - I don't imagine that users often store SAPs in hash-tables.
(declaim (inline eql-hash))
(defun eql-hash (key)
(declare (values fixnum boolean))
(if (%other-pointer-subtype-p
key
;; SYMBOL is listed here so that we can hash symbols address-insensitively.
;; We have to pick off a bunch of OTHER-POINTER objects anyway, so there
;; no overhead to extending the widetag range by 1 widetag.
'#.(list sb-vm:bignum-widetag sb-vm:ratio-widetag sb-vm:double-float-widetag
sb-vm:single-float-widetag
sb-vm:complex-rational-widetag sb-vm:complex-single-float-widetag
sb-vm:complex-double-float-widetag
sb-vm:symbol-widetag))
;; NON-NULL-SYMBOL-P skips a test for NIL which is sensible, and we're
;; excluding NIL anyway because it's not an OTHER-POINTER.
;; To produce the best code for NON-NULL-SYMBOL-P (omitting a lowtag test)
;; we need to force the compiler to see that KEY is definitely an
;; OTHER-POINTER (cf OTHER-POINTER-TN-REF-P) because %OTHER-POINTER-SUBTYPE-P
;; doesn't suffice, though it would be nice if it did.
(values (if (non-null-symbol-p
(truly-the (or (and number (not fixnum) #+64-bit (not single-float))
(and symbol (not null)))
key))
(symbol-hash (truly-the symbol key))
(number-sxhash (truly-the number key)))
nil)
;; Consider picking off %INSTANCEP too before using EQ-HASH ?
(eq-hash key)))
;;; Decide if WIDETAG (an OTHER-POINTER) should use SXHASH in EQUAL-HASH
(defmacro equal-hash-sxhash-widetag-p (widetag)
(let ((list `(,sb-vm:simple-base-string-widetag
#+sb-unicode ,sb-vm:simple-character-string-widetag
,sb-vm:complex-base-string-widetag
#+sb-unicode ,sb-vm:complex-character-string-widetag
,sb-vm:bignum-widetag
,sb-vm:ratio-widetag
,sb-vm:double-float-widetag
,sb-vm:complex-rational-widetag
,sb-vm:complex-single-float-widetag
,sb-vm:complex-double-float-widetag
,sb-vm:simple-bit-vector-widetag
,sb-vm:complex-bit-vector-widetag)))
(let ((mask 0))
(dolist (i list mask)
(setf mask (logior mask (ash 1 (ash i -2)))))
#+64-bit `(logbitp (ash ,widetag -2) ,mask)
#-64-bit `(let ((bit (ash ,widetag -2)))
(if (<= bit 31)
(logbitp bit ,(ldb (byte 32 0) mask))
(logbitp (- bit 32) ,(ash mask -32)))))))
;;; As a consequence of change 3bdd4d28ed, the compiler started to emit multiple
;;; definitions of certain INLINE global functions.
;;; Genesis is so fraught with other pitfalls and traps that I want no chance
;;; of seeing duplicate definitions. So no INLINE here. Tail wagging the dog?
;;; Perhaps, but that was an dangerous thing to sneakily allow.
;; (declaim (inline equal-hash))
(defun equal-hash (key)
(declare (values fixnum boolean))
;; Ultimately we just need to choose between SXHASH or EQ-HASH. As to using
;; INSTANCE-SXHASH, it doesn't matter, and in fact it's quicker to use EQ-HASH.
;; If the outermost object passed as a key is LIST, then it descends using SXASH,
;; you will in fact get stable hashes for nested objects.
(if (case (lowtag-of key)
(#.sb-vm:list-pointer-lowtag t)
;; pathnames require SXHASH, all other instances are indifferent.
(#.sb-vm:instance-pointer-lowtag (pathnamep (truly-the instance key)))
(#.sb-vm:other-pointer-lowtag
(if (= (%other-pointer-widetag key) sb-vm:symbol-widetag)
(return-from equal-hash
(values (symbol-hash (truly-the symbol key)) nil))
(equal-hash-sxhash-widetag-p (%other-pointer-widetag key)))))
(values (sxhash key) nil)
(eq-hash key)))
(defun equalp-hash (key)
(declare (values fixnum boolean))
(typecase key
;; Types requiring special treatment. Note that PATHNAME and
;; HASH-TABLE are caught by the STRUCTURE-OBJECT test.
((or array cons number character structure-object)
(values (psxhash key) nil))
(symbol (values (symbol-hash key) nil))
;; INSTANCE at this point means STANDARD-OBJECT and CONDITION,
;; since STRUCTURE-OBJECT is recursed into by PSXHASH.
(instance (values (instance-sxhash key) nil))
(t
(eq-hash key))))
(declaim (inline prefuzz-hash))
(export 'prefuzz-hash) ; for regression tests
(defun prefuzz-hash (hash)
;; We're using power of two tables which obviously are very
;; sensitive to the exact values of the low bits in the hash
;; value. Do a little shuffling of the value to mix the high bits in
;; there too. On 32-bit machines, the result is is a positive fixnum,
;; but on 64-bit, we use 2 more bits though must avoid conflict with
;; the unique value that that denotes an address-based hash.
(ldb (byte #-64-bit 29 #+64-bit 31 0)
(+ (logxor #b11100101010001011010100111 hash)
(ash hash -3)
(ash hash -12)
(ash hash -20))))
(declaim (inline mask-hash))
(defun mask-hash (hash mask)
(truly-the index (logand mask hash)))
(declaim (inline pointer-hash->bucket))
(defun pointer-hash->bucket (hash mask)
(declare (fixnum hash) (hash-code mask))
(truly-the index (logand mask (prefuzz-hash hash))))
;;;; user-defined hash table tests
(define-load-time-global *user-hash-table-tests* nil)
(defun register-hash-table-test (name hash-fun)
(declare (symbol name) (function hash-fun))
(unless (fboundp name)
(error "Cannot register ~S has a hash table test: undefined function."
name))
(with-single-package-locked-error
(:symbol name "defining ~S as a hash table test")
(let* ((test-fun (fdefinition name))
(this (list name test-fun hash-fun))
(spec (assoc name *user-hash-table-tests*)))
(cond (spec
(unless (and (eq (second spec) test-fun)
(eq (third spec) hash-fun))
(style-warn "Redefining hash table test ~S." name)
(setf (cdr spec) (cdr this))))
(t
(push this *user-hash-table-tests*)))))
name)
(defmacro define-hash-table-test (name hash-function)
"Defines NAME as a new kind of hash table test for use with the :TEST
argument to MAKE-HASH-TABLE, and associates a default HASH-FUNCTION with it.
NAME must be a symbol naming a global two argument equivalence predicate.
Afterwards both 'NAME and #'NAME can be used with :TEST argument. In both
cases HASH-TABLE-TEST will return the symbol NAME.
HASH-FUNCTION must be a symbol naming a global hash function consistent with
the predicate, or be a LAMBDA form implementing one in the current lexical
environment. The hash function must compute the same hash code for any two
objects for which NAME returns true, and subsequent calls with already hashed
objects must always return the same hash code.
Note: The :HASH-FUNCTION keyword argument to MAKE-HASH-TABLE can be used to
override the specified default hash-function.
Attempting to define NAME in a locked package as hash-table test causes a
package lock violation.
Examples:
;;; 1.
;; We want to use objects of type FOO as keys (by their
;; names.) EQUALP would work, but would make the names
;; case-insensitive -- which we don't want.
(defstruct foo (name nil :type (or null string)))
;; Define an equivalence test function and a hash function.
(defun foo-name= (f1 f2) (equal (foo-name f1) (foo-name f2)))
(defun sxhash-foo-name (f) (sxhash (foo-name f)))
(define-hash-table-test foo-name= sxhash-foo-name)
;; #'foo-name would work too.
(defun make-foo-table () (make-hash-table :test 'foo-name=))
;;; 2.
(defun == (x y) (= x y))
(define-hash-table-test ==
(lambda (x)
;; Hash codes must be consistent with test, so
;; not (SXHASH X), since
;; (= 1 1.0) => T
;; (= (SXHASH 1) (SXHASH 1.0)) => NIL
;; Note: this doesn't deal with complex numbers or
;; bignums too large to represent as double floats.
(sxhash (coerce x 'double-float))))
;; #'== would work too
(defun make-number-table () (make-hash-table :test '==))
"
(check-type name symbol)
(if (member name '(eq eql equal equalp))
(error "Cannot redefine standard hash table test ~S." name)
(cond ((symbolp hash-function)
`(register-hash-table-test ',name (symbol-function ',hash-function)))
((and (consp hash-function) (eq 'lambda (car hash-function)))
`(register-hash-table-test ',name #',hash-function))
(t
(error "Malformed HASH-FUNCTION: ~S" hash-function)))))
;;;; construction and simple accessors
;;; The smallest table holds 14 items distributed among 16 buckets.
;;; So we allocate 14 k/v pairs = 28 cells + 3 overhead = 31 cells,
;;; and at maximum load the table will have a load factor of 87.5%
(defconstant kv-pairs-overhead-slots 3)
(defconstant bad-next-value #xfefefefe)
;;; This constant is referenced via its name in cold load, so it needs to
;;; be evaluable in the host.
(defconstant +min-hash-table-rehash-threshold+ #.(sb-xc:float 1/16 1.0))
;; The GC will set this to 1 if it moves an address-sensitive key. This used
;; to be signaled by a bit in the header of the kv vector, but that
;; implementation caused some concurrency issues when we stopped
;; inhibiting GC during hash-table lookup.
;;
;; This indicator properly belongs to the k/v vector for at least 2 reasons:
;; - if the vector is on an already-written page but the table is not,
;; it avoids a write fault when setting to true. This a boon to gencgc
;; - if there were lock-free tables - which presumably operate by atomically
;; changing out the vector for a new one - whether the vector is bucketized
;; correctly after GC is an aspect of the vector, not the table
;;
;; We could do it with a single bit by implementing vops for atomic
;; read/modify/write on the header. In C there's sync_or_and_fetch, etc.
(defconstant rehash-stamp-elt 1)
(defmacro kv-vector-rehash-stamp (vector) `(truly-the fixnum (svref ,vector 1)))
(defconstant kv-vector-rehashing 2)
;;; The 'supplement' points to the hash-table if the table is weak,
;;; or to the hash vector if the table is not weak.
;;; Other possible values are NIL for an EQ table, or T for an EQL table.
;;; For a concurrent GC, this element will not require a read barrier because
;;; it must be treated as a strong reference even if the vector is weak.
(defmacro kv-vector-supplement (pairs)
`(svref ,pairs (1- (length ,pairs))))
(declaim (inline set-kv-hwm)) ; can't setf data-vector-ref
(defun set-kv-hwm (vector hwm) (setf (svref vector 0) hwm))
(defsetf kv-vector-high-water-mark set-kv-hwm)
;;; Make a new key/value vector. Weak tables do not mark the vector as weak
;;; initially, because the vector can't hold a backpointer to the table
;;; since the table hasn't been made yet. (GC asserts that every weak hash-table
;;; storage vector has a table pointer - no exceptions)
;;; Also we can't set the HASHING bit in the header until the vector is prepared,
;;; but if GC occurs meanwhile, it must not move this to a purely boxed page.
;;; But we can set the ALLOC-MIXED bit. That's what it's there for.
(defmacro %alloc-kv-pairs (size)
`(let* ((nwords
(truly-the index (+ (* 2 (truly-the index/2 ,size))
,kv-pairs-overhead-slots)))
(v (truly-the simple-vector
(allocate-vector (logior sb-vm::+vector-alloc-mixed-region-bit+
sb-vm:simple-vector-widetag)
nwords nwords))))
(declare (optimize (sb-c:insert-array-bounds-checks 0)))
(fill v (make-unbound-marker))
(setf (kv-vector-high-water-mark v) 0)
(setf (kv-vector-rehash-stamp v) 0)
;; If GC observes VECTOR-HASHING-FLAG, it needs to see a valid value
;; in the 'supplement' slot. Neither 0 nor +empty-ht-slot+ is valid.
;; And if we ever get non-prezeroed-memory to work, this will be even more
;; important to do things in the right order.
(setf (kv-vector-supplement v) nil)
(logior-array-flags v sb-vm:vector-hashing-flag)
v))
(defun install-hash-table-lock (table)
(declare (inline sb-thread:make-mutex))
(let* ((lock (sb-thread:make-mutex :name "hash-table lock"))
(oldval (cas (hash-table-%lock (truly-the hash-table table)) nil lock)))
(if (eq oldval nil) lock oldval)))
(defconstant hash-table-kind-eq 0)
(defconstant hash-table-kind-eql 1)
(defconstant hash-table-kind-equal 2)
(defconstant hash-table-kind-equalp 3)
;;; I don't want to change peoples' assumptions about what operations are threadsafe
;;; on a weak table that was not created as expressly synchronized, so we continue to
;;; create nearly all weak tables as synchronized. With such tables, lock acquisition
;;; might be recursive, because we also told users that they can use
;;; SB-EXT:WITH-LOCKED-HASH-TABLE even with tables that are self-locking.
;;; This results in a really strange design in which it is exceptionally difficult
;;; to plug in standard POSIX mutexes which do not default to being recursive.
;;; To slightly mitigate the problem of assuming all mutexes should be recursive,
;;; some of the system weak hash-table are frobbed to turn off SYNCHRONIZED.
;;; Maybe I can figure out how to make concurrent weak GETHASH threadsafe,
;;; but I've spent a bit of time on it and it is quite difficult.
(defun make-hash-table (&key (test 'eql)
(size #.+min-hash-table-size+)
(rehash-size #.default-rehash-size)
(rehash-threshold 1)
(hash-function nil user-hashfun-p)
(weakness nil)
(synchronized))
"Create and return a new hash table. The keywords are as follows:
:TEST
Determines how keys are compared. Must a designator for one of the
standard hash table tests, or a hash table test defined using
SB-EXT:DEFINE-HASH-TABLE-TEST. Additionally, when an explicit
HASH-FUNCTION is provided (see below), any two argument equivalence
predicate can be used as the TEST.
:SIZE
A hint as to how many elements will be put in this hash table.
:REHASH-SIZE
Indicates how to expand the table when it fills up. If an integer, add
space for that many elements. If a floating point number (which must be
greater than 1.0), multiply the size by that amount.
:REHASH-THRESHOLD
Indicates how dense the table can become before forcing a rehash. Can be
any positive number <=1, with density approaching zero as the threshold
approaches 0. Density 1 means an average of one entry per bucket.
:HASH-FUNCTION
If unsupplied, a hash function based on the TEST argument is used,
which then must be one of the standardized hash table test functions, or
one for which a default hash function has been defined using
SB-EXT:DEFINE-HASH-TABLE-TEST. If HASH-FUNCTION is specified, the TEST
argument can be any two argument predicate consistent with it. The
HASH-FUNCTION is expected to return a non-negative fixnum hash code.
If TEST is neither standard nor defined by DEFINE-HASH-TABLE-TEST,
then the HASH-FUNCTION must be specified.
:WEAKNESS
When :WEAKNESS is not NIL, garbage collection may remove entries from the
hash table. The value of :WEAKNESS specifies how the presence of a key or
value in the hash table preserves their entries from garbage collection.
Valid values are:
:KEY means that the key of an entry must be live to guarantee that the
entry is preserved.
:VALUE means that the value of an entry must be live to guarantee that
the entry is preserved.
:KEY-AND-VALUE means that both the key and the value must be live to
guarantee that the entry is preserved.
:KEY-OR-VALUE means that either the key or the value must be live to
guarantee that the entry is preserved.
NIL (the default) means that entries are always preserved.
:SYNCHRONIZED
If NIL (the default), the hash-table may have multiple concurrent readers,
but results are undefined if a thread writes to the hash-table
concurrently with another reader or writer. If T, all concurrent accesses
are safe, but note that CLHS 3.6 (Traversal Rules and Side Effects)
remains in force. See also: SB-EXT:WITH-LOCKED-HASH-TABLE."
(declare (type (or function symbol) test))
(declare (type unsigned-byte size))
(multiple-value-bind (kind test test-fun hash-fun)
(cond ((or (eq test #'eq) (eq test 'eq))
(values 0 'eq #'eq #'eq-hash))
((or (eq test #'eql) (eq test 'eql))
(values 1 'eql #'eql #'eql-hash))
((or (eq test #'equal) (eq test 'equal))
(values 2 'equal #'equal #'equal-hash))
((or (eq test #'equalp) (eq test 'equalp))
(values 3 'equalp #'equalp #'equalp-hash))
(t
(dolist (info *user-hash-table-tests*
(flet ((proper-name (fun &aux (name (%fun-name fun)))
(if (and (symbolp name) (fboundp name) (eq (symbol-function name) fun))
name
fun)))
(if hash-function
(if (functionp test)
(values -1 (proper-name test) test nil)
(values -1 test (%coerce-callable-to-fun test) nil))
(error "Unknown :TEST for MAKE-HASH-TABLE: ~S" test))))
(destructuring-bind (test-name test-fun hash-fun) info
(when (or (eq test test-name) (eq test test-fun))
(return (values -1 test-name test-fun hash-fun)))))))
(when user-hashfun-p
;; It is permitted to specify a custom hash function with any of the standard predicates.
;; This forces use of the generalized table methods.
(setf hash-fun (%coerce-callable-to-fun hash-function)
kind -1))
(let* ((size (max +min-hash-table-size+
;; Our table sizes are capped by the 32-bit integers used as indices
;; into the chains. Prevent our code from failing if the user specified
;; most-positive-fixnum here. (fndb says that size is 'unsigned-byte')
(min size (ash 1 24)))) ; 16M key/value pairs
(rehash-size (if (integerp rehash-size)
rehash-size
(float rehash-size 1.0))) ; always single-float
(rehash-threshold (max #.+min-hash-table-rehash-threshold+
(float rehash-threshold 1.0)))) ; always single-float
(%make-hash-table
;; compute flags. The stored KIND bits don't matter for a user-supplied hash
;; and/or test fun, however we don't want to imply that it is an EQ table
;; because EQ tables don't get a hash-vector allocated.
(logior (if weakness
(or (loop for i below 4
when (eq (decode-hash-table-weakness i) weakness)
do (return (pack-ht-flags-weakness i)))
(unreachable))
0)
(pack-ht-flags-kind (logand kind 3)) ; kind -1 becomes 3
(if (or weakness synchronized) hash-table-synchronized-flag 0)
(if (eql kind -1) hash-table-userfun-flag 0))
test test-fun hash-fun
size rehash-size rehash-threshold))))
(defmacro make-index-vector (n)
`(let ((a (make-array ,n :element-type 'hash-table-index
:initial-element 0)))
a))
(defun validate-index-vector (tbl reason)
(let* ((iv (hash-table-index-vector tbl))
(pairs (hash-table-pairs tbl))
(npairs (length pairs)))
(dovector (indexval iv)
(when (> (* 2 indexval) npairs)
(bug "~a: Busted index vector on ~S, pairlen=~d 2*index=~d"
reason tbl npairs (* 2 indexval))))))
(defun %make-hash-table (flags test test-fun hash-fun size rehash-size rehash-threshold)
(binding* (
;; KLUDGE: The most natural way of expressing the below is
;; (round (/ (float size) rehash-threshold)), and indeed
;; it was expressed like that until 0.7.0. However,
;; MAKE-HASH-TABLE is called very early in cold-init, and
;; the SPARC has no primitive instructions for rounding,
;; but only for truncating; therefore, we fudge this issue
;; a little. The other uses of truncate, below, similarly
;; used to be round. -- CSR, 2002-10-01
;;
;; Note that this has not yet been audited for
;; correctness. It just seems to work. -- CSR, 2002-11-02
(scaled-size (truncate (/ (float size) rehash-threshold)))
(bucket-count (power-of-two-ceiling
(max scaled-size +min-hash-table-size+)))
(weakp (logtest flags hash-table-weak-flag))
;; Non-weak tables created with no options other than :TEST
;; are allocated at 0 size. Weak tables are complicated enough,
;; so just do their usual thing.
(defaultp (and (not weakp) (= size +min-hash-table-size+)))
(index-vector
(if defaultp
#.(sb-xc:make-array 2 :element-type '(unsigned-byte 32)
:initial-element 0)
(make-index-vector bucket-count)))
(kv-vector (if defaultp #(0 0 nil) (%alloc-kv-pairs size)))
;; Needs to be the half the length of the KV vector to link
;; KV entries - mapped to indices at 2i and 2i+1 -
;; together.
;; We don't need this to be initially 0-filled, so don't specify
;; an initial element (in case we ever meaningfully distinguish
;; between don't-care and 0-fill)
(next-vector (if defaultp
#.(sb-xc:make-array 0 :element-type '(unsigned-byte 32))
(make-array (1+ size) :element-type 'hash-table-index
;; For testing, preload huge values for all 'next' elements
;; so that we generate an error if any is inadvertently read
;; above the high-water-mark for the k/v vector.
#+sb-devel :initial-element #+sb-devel bad-next-value)))
(table-kind (ht-flags-kind flags))
(userfunp (logtest flags hash-table-userfun-flag))
;; same here - don't care about initial contents
(hash-vector (when (or userfunp (>= table-kind 2))
(if defaultp
#.(sb-xc:make-array 1 :element-type '(unsigned-byte 32))
(make-array (1+ size) :element-type 'hash-table-index))))
((getter setter remover)
(if weakp
(values #'gethash/weak #'puthash/weak #'remhash/weak)
(pick-table-methods (logtest flags hash-table-synchronized-flag)
(if userfunp -1 table-kind))))
(table
(funcall (if weakp #'%alloc-general-hash-table #'%alloc-hash-table)
flags getter setter remover #'clrhash-impl
test test-fun hash-fun
rehash-size rehash-threshold
kv-vector index-vector next-vector hash-vector)))
(declare (type index scaled-size))
;; The trailing metadata element is either the table itself or the hash-vector
;; depending on weakness. Non-weak hashing vectors can be GCed without looking
;; at the table. Weak hashing vectors need the table.
;; As a special-case, non-weak tables with EQL hashing put T in this slot.
;; GC can't get the table kind since it doesn't have access to the table.
(cond (defaultp
;; Stash the desired size for the first time the vectors are grown.
(setf (hash-table-cache table) size
;; Cause the overflow logic to be invoked on the first insert.
(hash-table-next-free-kv table) 0))
(t
(setf (kv-vector-supplement kv-vector)
(if weakp
table
(or hash-vector (= table-kind hash-table-kind-eql))))
(when weakp
(logior-array-flags kv-vector (logior sb-vm:vector-hashing-flag
sb-vm:vector-weak-flag)))))
(when (logtest flags hash-table-synchronized-flag)
(install-hash-table-lock table))
table))
;;; a "plain" hash-table has nothing fancy: default size, default growth rate,
;;; not weak, not synchronized, not a user-defined hash fun and/or comparator.
(defun make-hash-table-using-defaults (kind)
(declare ((integer 0 3) kind))
(let ((test (aref #(eq eql equal equalp) kind)))
(declare (optimize (safety 0))) ; skip FBOUNDP checks
(let ((test-fun (symbol-function test))
(hash-fun (symbol-function
(aref #(eq-hash eql-hash equal-hash equalp-hash) kind))))
(%make-hash-table (pack-ht-flags-kind kind)
test test-fun hash-fun
+min-hash-table-size+
#.default-rehash-size
1.0)))) ; rehash threshold
;;; I guess we might have more than one representation of a table,
;;; hence this small wrapper function. But why not for the others?
(defun hash-table-count (hash-table)
"Return the number of entries in the given HASH-TABLE."
(declare (type hash-table hash-table)
(values index))
(hash-table-%count hash-table))
(setf (documentation 'hash-table-rehash-size 'function)
"Return the rehash-size HASH-TABLE was created with.")
(setf (documentation 'hash-table-rehash-threshold 'function)
"Return the rehash-threshold HASH-TABLE was created with.")
(setf (documentation 'hash-table-synchronized-p 'function)
"Returns T if HASH-TABLE is synchronized.")
(declaim (inline hash-table-pairs-capacity))
(defun hash-table-pairs-capacity (pairs) (ash (- (length pairs) kv-pairs-overhead-slots) -1))
(defun hash-table-size (hash-table)
"Return a size that can be used with MAKE-HASH-TABLE to create a hash
table that can hold however many entries HASH-TABLE can hold without
having to be grown."
(let ((n (hash-table-pairs-capacity (hash-table-pairs hash-table))))
(if (= n 0) +min-hash-table-size+ n)))
(setf (documentation 'hash-table-test 'function)
"Return the test HASH-TABLE was created with.")
(defun signal-corrupt-hash-table (hash-table)
(error "Unsafe concurrent operations on ~A detected." hash-table))
;;; Called when we detect circular chains in a hash-table.
(defun signal-corrupt-hash-table-bucket (hash-table)
(error "Corrupt NEXT-chain in ~A. This is probably caused by ~
multiple threads accessing the same hash-table without locking."
hash-table))
;;;; accessing functions
;;; Clear rehash bit and bump the rolling count, wrapping around to keep it a fixnum.
;;; need-to-rehash is indicated by a stamp of #b______01 ; "initial stamp"
;;; which is changed during rehash to #b______10 ; "rehashing stamp"
;;; rolling count --------^^^^^^ (some number of bits)
(defmacro done-rehashing (table kv-vector initial-stamp)
(declare (ignorable table))
`(let ((rehashing-stamp (1+ ,initial-stamp))
;; new stamp has the "count" field bumped up by 1, and the low 2 bits are 0.
(new-stamp (sb-vm::+-modfx ,initial-stamp 3)))
#+hash-table-metrics (aver (= (logand ,initial-stamp #b11) #b01))
;; Assigning new stamp races with GC which might set the 'rehash' (low) bit again.
;; At most one more attempt is needed since no other state change can occur -
;; we don't need to keep trying to achieve a state in which 'rehash' is clear.
(let ((old (cas (svref ,kv-vector rehash-stamp-elt) rehashing-stamp new-stamp)))
(unless (eq old rehashing-stamp)
(aver (eq old (logior rehashing-stamp 1)))
#+hash-table-metrics (atomic-incf (hash-table-n-rehash-again ,table))
;; Bump the count field, but leave the least-significant bit on.
(aver (eq old (cas (svref ,kv-vector rehash-stamp-elt) old (logior new-stamp 1))))))))
;;; Rehash in one of two scenarios:
;;; - up-sizing a table, be it weak or not
;;; - rehashing a weak table due to key movement
;;; Absent is the case of rehashing a non-weak table due to key movement.
;;; That is special-cased in %REHASH-AND-FIND which does both at once as its name implies.
;;; Note that this will never be called on a KV-VECTOR with the weakness bit set.
;;; Therefore we can use SVREF in lieu of WEAK-KVV-REF for weak tables.
(macrolet
((push-in-chain (bucket-index-expr)
`(let ((bucket (the index ,bucket-index-expr)))
(setf (aref next-vector i) (aref index-vector bucket)
(aref index-vector bucket) i))))
(defun rehash (kv-vector hash-vector index-vector next-vector table
&aux (mask (1- (length index-vector)))
(next-free 0)
(hwm (kv-vector-high-water-mark kv-vector)))
(declare (simple-vector kv-vector)
(type (simple-array hash-table-index (*)) next-vector index-vector)
(type (or null (simple-array hash-table-index (*))) hash-vector))
(macrolet ((with-key ((key-var) &body body)
;; If KEY-VAR is empty, then push I onto the freelist, otherwise invoke BODY
`(let* ((key-index (* 2 i))
(,key-var (aref kv-vector key-index)))
(if (empty-ht-slot-p key)
(setf (aref next-vector i) next-free next-free i)
(progn ,@body)))))
(cond
(hash-vector
;; Scan backwards so that chains are in ascending index order.
(do ((i hwm (1- i))) ((zerop i))
(declare (type index/2 i))
(with-key (key)
(let* ((stored-hash (aref hash-vector i))
(bucket
(cond ((/= stored-hash +magic-hash-vector-value+)
;; Use the existing hash value (not address-based hash)
(mask-hash (aref hash-vector i) mask))
(t
;; Set address-sensitivity BEFORE depending on the bits.
;; Precise GC platforms can move any key except the ones which
;; are explicitly pinned, and we're not explictly pinning.
(logior-array-flags kv-vector sb-vm:vector-addr-hashing-flag)
(pointer-hash->bucket (pointer-hash key) mask)))))
(push-in-chain bucket)))))
((eq (hash-table-test table) 'eql)
;; There's a very tricky issue here with using EQL-HASH - you can't just
;; call it and then decide to set the address-sensitivity bit if the secondary
;; result is T. Normally we call the hash function with the key pinned,
;; so we have to do the same here. Consider if we didn't, on a precise GC
;; architecture given the initial condition that the kv-vector is not
;; marked as address-sensitive:
;; - call EQL hash, take PAIR-KEY's address as its hash
;; - GC observes that vector is not address-sensitive,
;; moves PAIR-KEY, gives it a new address, does not flag vector
;; as needing rehash.
;; - set the vector header as address-sensitive
;; - push in chain
;; After that sequence of operations, the item is in the wrong chain,
;; for its new address, but the need-rehash bit is not set in the vector.
;; It would work to call EQL-HASH twice per key: once to get the secondary
;; value, maybe set the vector bit, call it again. But that's not great.
;; Instead we use a macro that is like WITH-PINNED-OBJECTS, but cheaper
;; than binding a special variable once per key.
(sb-vm::with-pinned-object-iterator (pin-object)
(do ((i hwm (1- i))) ((zerop i))
(declare (type index/2 i))
(with-key (key)
(pin-object key)
(multiple-value-bind (hash address-based) (eql-hash key)
(when address-based
(logior-array-flags kv-vector sb-vm:vector-addr-hashing-flag))
(push-in-chain (mask-hash (prefuzz-hash hash) mask)))))))
(t
(do ((i hwm (1- i))) ((zerop i))
(declare (type index/2 i))
(with-key (key)
(when (sb-vm:is-lisp-pointer (get-lisp-obj-address key))
(logior-array-flags kv-vector sb-vm:vector-addr-hashing-flag))
(push-in-chain (pointer-hash->bucket (pointer-hash key) mask)))))))
;; This is identical to the calculation of next-free-kv in INSERT-AT.
(cond ((/= next-free 0) next-free)
((= hwm (hash-table-pairs-capacity kv-vector)) 0)
(t (1+ hwm))))
;;; Rehash due to key movement, and find KEY at the same time.
;;; Finding the key obviates the need for the rehashing thread to loop
;;; testing whether to rehash. Imagine an unlucky schedule wherein each rehash
;;; ends up invalid due to maximally bad timing of GC, and every reader sees
;;; nothing but 'need-to-rehash', and the INDEX vector is repeatedly overwritten
;;; with zeros. The -AND-FIND aspect of this ensures progress.
(defun %rehash-and-find (table epoch key
&aux (kv-vector (hash-table-pairs table))
(next-vector (hash-table-next-vector table))
(hash-vector (hash-table-hash-vector table))
(rehashing-state (1+ epoch)))
(declare (hash-table table) (fixnum epoch))
#+hash-table-metrics (atomic-incf (hash-table-n-rehash+find table))
;; Verify some invariants prior to disabling array bounds checking
(aver (>= (length kv-vector) #.(+ (* 2 +min-hash-table-size+)
kv-pairs-overhead-slots)))
(aver (= (ash (length kv-vector) -1) (length next-vector)))
(when hash-vector
(aver (= (length hash-vector) (length next-vector))))
;; Empty cells must be in the free chain already, and no smashed cells exist.
(when (typep table 'general-hash-table)
(aver (null (hash-table-smashed-cells table))))
;; Must not permit the rehashing state to stick due to a nonlocal exit.
;; All further normal use of the table would be prevented.
(without-interrupts
;; Transitioning from #b01 to #b10 clears the 'rehash' bit and sets the
;; rehash-in-progress bit. It also gives this thread exclusive write access
;; to the bucket chains since at most one thread can win this CAS.
(when (eq (cas (svref kv-vector rehash-stamp-elt) epoch rehashing-state) epoch)
;; Remove address-sensitivity, preserving the other flags.
(reset-array-flags kv-vector sb-vm:vector-addr-hashing-flag)
;; Rehash in place. For the duration of the rehash, readers who otherwise
;; might have seen intact chains (by which to find address-insensitive keys)
;; can't. No big deal. If we were willing to cons new vectors, we could
;; rehash into them and CAS them in, but the advantage would be minimal-
;; obsolete chains could only work for a possibly-empty subset of keys.
;; Leave the free cell chain untouched, since rehashing
;; due to key movement can not possibly affect that chain.
(let* ((index-vector (fill (hash-table-index-vector table) 0))
(mask (1- (length index-vector)))
(hwm (kv-vector-high-water-mark kv-vector))
(result 0))
(declare (optimize (sb-c:insert-array-bounds-checks 0)))
(macrolet ((with-key ((key-var) &body body)
;; Process body only if KEY-VAR is nonempty, and also look
;; for a probed key that is EQ to KEY.
`(let* ((key-index (* 2 i))
(,key-var (aref kv-vector key-index)))
(unless (empty-ht-slot-p ,key-var)
(when (eq ,key-var key) (setq result key-index))
,@body))))
(cond
(hash-vector
(do ((i hwm (1- i))) ((zerop i))
(declare (type index/2 i))
(with-key (pair-key)
(let* ((stored-hash (aref hash-vector i))
(bucket
(cond ((/= stored-hash +magic-hash-vector-value+)
(mask-hash stored-hash mask))
(t
(logior-array-flags kv-vector sb-vm:vector-addr-hashing-flag)
(pointer-hash->bucket (pointer-hash pair-key) mask)))))
(push-in-chain bucket)))))
((eq (hash-table-test table) 'eql)
(sb-vm::with-pinned-object-iterator (pin-object)
(do ((i hwm (1- i))) ((zerop i))
(declare (type index/2 i))
(with-key (pair-key)
(pin-object pair-key)
(multiple-value-bind (hash address-based) (eql-hash pair-key)
(when address-based
(logior-array-flags kv-vector sb-vm:vector-addr-hashing-flag))
(push-in-chain (mask-hash (prefuzz-hash hash) mask)))))))
(t
;; No hash vector and not an EQL table, so it's an EQ table
(do ((i hwm (1- i))) ((zerop i))
(declare (type index/2 i))
(with-key (pair-key)
(when (sb-vm:is-lisp-pointer (get-lisp-obj-address pair-key))
(logior-array-flags kv-vector sb-vm:vector-addr-hashing-flag))
(push-in-chain (pointer-hash->bucket (pointer-hash pair-key) mask)))))))
(done-rehashing table kv-vector epoch)
(unless (eql result 0)
(setf (hash-table-cache table) result))
result))))
) ; end MACROLET
(defun recompute-ht-vector-sizes (table old-size)
;; Compute new vector lengths for the table, extending the table based on the
;; rehash-size.
;; If I did the math right, the upper bound is a fixnum on 32-bit (and 64-bit of course)
(declare (type (integer 1 (#.(ash 1 29))) old-size))
(let* ((rehash-size (hash-table-rehash-size table))
(new-size (typecase rehash-size
;; Ensure that if the user specifies a float that is so close
;; to 1.0 as to disappear in the TRUNCATE that we actually grow.
;; (TRUNCATE (* 14 1.01)) => 14
(float (max (the index (truncate (* rehash-size old-size))) ; usually
(1+ old-size)))
(fixnum (+ rehash-size old-size)))) ; rarely, I imagine
(new-n-buckets
(let* ((pow2ceil (power-of-two-ceiling new-size))
(full-lf (/ new-size pow2ceil)))
;; If the default rehash-size was employed, let's try to keep the
;; load factor within a reasonable band. Otherwise don't bother.
;; The motivation for this decision is twofold:
;; - if using defaults, it would be ideal to attempt to be nominally
;; conscientious of the 1.5x resize amount.
;; - we can't really accommodate arbitrary resize amounts, especially if small.
;; (power-of-2 sizing can't do that- doubling is the only possibility)
;; But we can produce the smallest table consistent with the request.
;; Say e.g. REHASH-SIZE was 2 using the default initial size of 14.
;; Resizing computes 16 k/v pairs which coincides exactly with
;; 16 buckets (the nearest power of 2). But if we wish to avoid 100% load,
;; what can we do? Re-double the bin count to 32? Decrease the k/v pair count
;; to 15? Clearly neither of those make sense if the user is trying to say
;; that (s)he wants 2 entries more which means "don't increase by a lot".
;; Changing from 8 buckets (at the old size) to 32 buckets is a lot,
;; so why do that? Conversely, it makes no sense to reduce the k/v pair
;; limit just to keep the LF less than 100%. A similar problem occurs
;; if you specify 1.001 or other float near 1.
;; Anyway, chaining supports load factors in excess of 100%
(when (eql rehash-size default-rehash-size)
(cond ((> full-lf 9/10) ; .9 is unhappy in cross-float due to inexactness
;; If we're going to decrease the size, make sure we definitely
;; don't decrease below the old size.
(setq new-size (floor pow2ceil 100/85))) ; target LF = 85%
((< full-lf 55/100) ; and .55 is similarly unhappy
(setq new-size (floor pow2ceil 100/65))))) ; target LF = 65%
pow2ceil)))
(values new-size new-n-buckets)))
;;; Enlarge TABLE. If it is weak, then both the old and new vectors are temporarily
;;; made non-weak so that we don't have to deal with GC-related shenanigans.
(defun grow-hash-table (table)
(declare (type hash-table table))
(flet
((realloc (size n-buckets &aux (hash-vector-p (hash-table-hash-vector table)))
(declare (type (integer 0 #.(- array-dimension-limit 2)) size n-buckets))
(macrolet ((new-vectors ()
;; Return KV-VECTOR NEXT-VECTOR HASH-VECTOR INDEX-VECTOR)
`(values (%alloc-kv-pairs size)
(make-array size+1 :element-type 'hash-table-index
;; for robustness testing, as explained in %MAKE-HASH-TABLE
#+sb-devel :initial-element #+sb-devel bad-next-value)
(when hash-vector-p
(make-array size+1 :element-type 'hash-table-index))
(make-index-vector n-buckets))))
(declare (optimize (sb-c::type-check 0)))
(let ((size+1 (1+ size))
(old-kvv (hash-table-pairs table)))
(declare (ignorable old-kvv))
#-system-tlabs (new-vectors)
#+system-tlabs
;; If allocation was directed off the main heap when this table was made, then we assume
;; that reallocation will allocate off the heap. If the old table is in dynamic space,
;; then the new storage should be forced to dynamic space even if the user TLAB currently
;; points outside of dynamic space.
;; The reason for looking at TABLE here and not its storage, is that MAKE-HASH-TABLE can
;; install a k/v pair vector that does not inform us where the table is:
;; * (heap-allocated-p (sb-impl::hash-table-pairs (make-hash-table))) => :READ-ONLY
;; The read-only vector is an optimization reducing the size of never-used tables
;; down to the absolute minimum.
(if (dynamic-space-obj-p table)
(locally (declare (sb-c::tlab :system)) (new-vectors))
(new-vectors))))))
(when (= (hash-table-%count table) 0) ; special case for new table
;; CACHE holds the desired initial size. Read it and then set it to a bogusly high value
(binding* ((size (shiftf (hash-table-cache table) (- array-dimension-limit 2)))
(scaled-size (truncate (/ (float size) (hash-table-rehash-threshold table))))
(bucket-count (power-of-two-ceiling (max scaled-size +min-hash-table-size+)))
((kv-vector next-vector hash-vector index-vector) (realloc size bucket-count)))
(setf (kv-vector-supplement kv-vector) (or hash-vector (eq (hash-table-test table) 'eql))
(hash-table-pairs table) kv-vector
(hash-table-index-vector table) index-vector
(hash-table-next-vector table) next-vector
(hash-table-hash-vector table) hash-vector)
(return-from grow-hash-table 1)))
(binding* (((new-size new-n-buckets)
(recompute-ht-vector-sizes
table
;; Pass the old size. The NEXT vector's length is 1 greater than "size"
;; which is the number of k/v pairs stored at its full capacity.
(1- (length (hash-table-next-vector table)))))
(old-kv-vector (hash-table-pairs table))
((new-kv-vector new-next-vector new-hash-vector new-index-vector)
(realloc new-size new-n-buckets))
(hwm (kv-vector-high-water-mark old-kv-vector)))
(declare (type simple-vector new-kv-vector)
(type (simple-array hash-table-index (*)) new-next-vector new-index-vector))
;; Rehash + resize only occurs when:
;; (1) every usable pair was at some point filled (so HWM = SIZE)
;; (2) no cells below HWM are available (so COUNT = SIZE)
(aver (= hwm (hash-table-size table)))
(when (and (not (hash-table-weak-p table)) (/= (hash-table-count table) hwm))
;; If the table is not weak, then every cell pair has to be in use
;; as a precondition to resizing. If weak, this might not be true.
(signal-corrupt-hash-table table))
;; Copy over the hash-vector,
;; This is done early because when GC scans the new vector, it needs to see
;; each hash to know which keys were hashed address-sensitively.
(awhen (hash-table-hash-vector table)
(replace (the (simple-array hash-table-index (*)) new-hash-vector)
it :start1 1 :start2 1)) ; 1st element not used
;; Preserve only the 'hashing' bit on the OLD-KV-VECTOR so that
;; its high-water-mark can meaningfully be reduced to 0 when done.
;; Clearing the address-sensitivity is a performance improvement
;; since GC won't check on a per-key basis whether to flag the vector
;; for rehash (it's going to be zeroed out).
;; Clearing the weakness causes all entries to stay alive.
;; Furthermore, clearing both makes the trailing metadata ignorable.
(assign-vector-flags old-kv-vector sb-vm:vector-hashing-flag)
(setf (kv-vector-supplement old-kv-vector) nil)
;; The high-water-mark remains unchanged.
;; Set this before copying pairs, otherwise they would not be seen
;; in the new vector since GC scanning ignores elements below the HWM.
(setf (kv-vector-high-water-mark new-kv-vector) hwm)
;; Reference the hash-vector from the KV vector.
;; Normally a weak hash-table's KV vector would reference the table
;; (because cull needs to examine the table bucket-by-bucket), and
;; not the hash-vector directly. But we can't reference the table
;; since using the table's hash-vector gets the OLD hash vector.
;; It might be OK to point the table at the new hash-vector now,
;; but I'd rather the table remain in a consistent state, in case we
;; ever devise a way to allow concurrent reads with a single writer,
;; for example.
(setf (kv-vector-supplement new-kv-vector)
(or new-hash-vector (eq (hash-table-test table) 'eql)))
;; Copy the k/v pairs excluding leading and trailing metadata.
(replace new-kv-vector old-kv-vector
:start1 2 :start2 2 :end2 (* 2 (1+ hwm)))
(let ((next-free (rehash new-kv-vector new-hash-vector
new-index-vector new-next-vector table)))
(setf (hash-table-pairs table) new-kv-vector
(hash-table-hash-vector table) new-hash-vector
(hash-table-index-vector table) new-index-vector
(hash-table-next-vector table) new-next-vector
(hash-table-next-free-kv table) next-free)
(when (hash-table-weak-p table)
(setf (hash-table-smashed-cells table) nil)
;; Now that the table points to the right hash-vector
;; we can set the vector's backpointer and turn it weak.
(setf (kv-vector-supplement new-kv-vector) table)
(logior-array-flags new-kv-vector sb-vm:vector-weak-flag))