6c2c45ff3b89419a6a604885fb81fba92ddfeb25
[sbcl.git] / src / pcl / cache.lisp
1 ;;;; the basics of the PCL wrapper cache mechanism
2
3 ;;;; This software is part of the SBCL system. See the README file for
4 ;;;; more information.
5
6 ;;;; This software is derived from software originally released by Xerox
7 ;;;; Corporation. Copyright and release statements follow. Later modifications
8 ;;;; to the software are in the public domain and are provided with
9 ;;;; absolutely no warranty. See the COPYING and CREDITS files for more
10 ;;;; information.
11
12 ;;;; copyright information from original PCL sources:
13 ;;;;
14 ;;;; Copyright (c) 1985, 1986, 1987, 1988, 1989, 1990 Xerox Corporation.
15 ;;;; All rights reserved.
16 ;;;;
17 ;;;; Use and copying of this software and preparation of derivative works based
18 ;;;; upon this software are permitted. Any distribution of this software or
19 ;;;; derivative works must comply with all applicable United States export
20 ;;;; control laws.
21 ;;;;
22 ;;;; This software is made available AS IS, and Xerox Corporation makes no
23 ;;;; warranty about the software, its performance or its conformity to any
24 ;;;; specification.
25
26 (in-package "SB-PCL")
27 \f
28 ;;; FIXME: SB-PCL should probably USE-PACKAGE SB-KERNEL, since SB-PCL
29 ;;; is built on SB-KERNEL, and in the absence of USE-PACKAGE, it ends
30 ;;; up using a thundering herd of explicit prefixes to get to
31 ;;; SB-KERNEL symbols. Using the SB-INT and SB-EXT packages as well
32 ;;; would help reduce prefixing and make it more natural to reuse
33 ;;; things (ONCE-ONLY, *KEYWORD-PACKAGE*..) used in the main body of
34 ;;; the system. However, that would cause a conflict between the
35 ;;; SB-ITERATE:ITERATE macro and the SB-INT:ITERATE macro. (This could
36 ;;; be resolved by renaming SB-INT:ITERATE to SB-INT:NAMED-LET, or
37 ;;; with more gruntwork by punting the SB-ITERATE package and
38 ;;; replacing calls to SB-ITERATE:ITERATE with calls to CL:LOOP.
39 ;;; So perhaps:
40 ;;;   * Do some sort of automated check for overlap of symbols to make
41 ;;;     sure there wouldn't be any other clashes.
42 ;;;   * Rename SB-INT:ITERATE to SB-INT:NAMED-LET.
43 ;;;   * Make SB-PCL use SB-INT and SB-EXT.
44 ;;;   * Grep for SB-INT: and SB-EXT: prefixes in the pcl/ directory
45 ;;;     and delete them.
46
47 ;;; The caching algorithm implemented:
48 ;;;
49 ;;; << put a paper here >>
50 ;;;
51 ;;; For now, understand that as far as most of this code goes, a cache
52 ;;; has two important properties. The first is the number of wrappers
53 ;;; used as keys in each cache line. Throughout this code, this value
54 ;;; is always called NKEYS. The second is whether or not the cache
55 ;;; lines of a cache store a value. Throughout this code, this always
56 ;;; called VALUEP.
57 ;;;
58 ;;; Depending on these values, there are three kinds of caches.
59 ;;;
60 ;;; NKEYS = 1, VALUEP = NIL
61 ;;;
62 ;;; In this kind of cache, each line is 1 word long. No cache locking
63 ;;; is needed since all read's in the cache are a single value.
64 ;;; Nevertheless line 0 (location 0) is reserved, to ensure that
65 ;;; invalid wrappers will not get a first probe hit.
66 ;;;
67 ;;; To keep the code simpler, a cache lock count does appear in
68 ;;; location 0 of these caches, that count is incremented whenever
69 ;;; data is written to the cache. But, the actual lookup code (see
70 ;;; make-dlap) doesn't need to do locking when reading the cache.
71 ;;;
72 ;;; NKEYS = 1, VALUEP = T
73 ;;;
74 ;;; In this kind of cache, each line is 2 words long. Cache locking
75 ;;; must be done to ensure the synchronization of cache reads. Line 0
76 ;;; of the cache (location 0) is reserved for the cache lock count.
77 ;;; Location 1 of the cache is unused (in effect wasted).
78 ;;;
79 ;;; NKEYS > 1
80 ;;;
81 ;;; In this kind of cache, the 0 word of the cache holds the lock
82 ;;; count. The 1 word of the cache is line 0. Line 0 of these caches
83 ;;; is not reserved.
84 ;;;
85 ;;; This is done because in this sort of cache, the overhead of doing
86 ;;; the cache probe is high enough that the 1+ required to offset the
87 ;;; location is not a significant cost. In addition, because of the
88 ;;; larger line sizes, the space that would be wasted by reserving
89 ;;; line 0 to hold the lock count is more significant.
90 \f
91 ;;; caches
92 ;;;
93 ;;; A cache is essentially just a vector. The use of the individual
94 ;;; `words' in the vector depends on particular properties of the
95 ;;; cache as described above.
96 ;;;
97 ;;; This defines an abstraction for caches in terms of their most
98 ;;; obvious implementation as simple vectors. But, please notice that
99 ;;; part of the implementation of this abstraction, is the function
100 ;;; lap-out-cache-ref. This means that most port-specific
101 ;;; modifications to the implementation of caches will require
102 ;;; corresponding port-specific modifications to the lap code
103 ;;; assembler.
104 (defmacro cache-vector-ref (cache-vector location)
105   `(svref (the simple-vector ,cache-vector)
106           (sb-ext:truly-the fixnum ,location)))
107
108 (defmacro cache-vector-size (cache-vector)
109   `(array-dimension (the simple-vector ,cache-vector) 0))
110
111 (defun allocate-cache-vector (size)
112   (make-array size :adjustable nil))
113
114 (defmacro cache-vector-lock-count (cache-vector)
115   `(cache-vector-ref ,cache-vector 0))
116
117 (defun flush-cache-vector-internal (cache-vector)
118   (sb-sys:without-interrupts
119     (fill (the simple-vector cache-vector) nil)
120     (setf (cache-vector-lock-count cache-vector) 0))
121   cache-vector)
122
123 (defmacro modify-cache (cache-vector &body body)
124   `(sb-sys:without-interrupts
125      (multiple-value-prog1
126        (progn ,@body)
127        (let ((old-count (cache-vector-lock-count ,cache-vector)))
128          (declare (fixnum old-count))
129          (setf (cache-vector-lock-count ,cache-vector)
130                (if (= old-count most-positive-fixnum)
131                    1 (the fixnum (1+ old-count))))))))
132
133 (deftype field-type ()
134   '(mod #.sb-kernel:layout-clos-hash-length))
135
136 (eval-when (:compile-toplevel :load-toplevel :execute)
137 (defun power-of-two-ceiling (x)
138   (declare (fixnum x))
139   ;;(expt 2 (ceiling (log x 2)))
140   (the fixnum (ash 1 (integer-length (1- x)))))
141 ) ; EVAL-WHEN
142
143 (defconstant +nkeys-limit+ 256)
144
145 (defstruct (cache (:constructor make-cache ())
146                   (:copier copy-cache-internal))
147   (owner nil)
148   (nkeys 1 :type (integer 1 #.+nkeys-limit+))
149   (valuep nil :type (member nil t))
150   (nlines 0 :type fixnum)
151   (field 0 :type field-type)
152   (limit-fn #'default-limit-fn :type function)
153   (mask 0 :type fixnum)
154   (size 0 :type fixnum)
155   (line-size 1 :type (integer 1 #.(power-of-two-ceiling (1+ +nkeys-limit+))))
156   (max-location 0 :type fixnum)
157   (vector #() :type simple-vector)
158   (overflow nil :type list))
159
160 #-sb-fluid (declaim (sb-ext:freeze-type cache))
161
162 (defmacro cache-lock-count (cache)
163   `(cache-vector-lock-count (cache-vector ,cache)))
164 \f
165 ;;; some facilities for allocation and freeing caches as they are needed
166
167 ;;; This is done on the assumption that a better port of PCL will
168 ;;; arrange to cons these all in the same static area. Given that, the
169 ;;; fact that PCL tries to reuse them should be a win.
170
171 (defvar *free-cache-vectors* (make-hash-table :size 16 :test 'eql))
172
173 ;;; Return a cache that has had FLUSH-CACHE-VECTOR-INTERNAL called on
174 ;;; it. This returns a cache of exactly the size requested, it won't
175 ;;; ever return a larger cache.
176 (defun get-cache-vector (size)
177   (let ((entry (gethash size *free-cache-vectors*)))
178     (sb-sys:without-interrupts
179       (cond ((null entry)
180              (setf (gethash size *free-cache-vectors*) (cons 0 nil))
181              (get-cache-vector size))
182             ((null (cdr entry))
183              (incf (car entry))
184              (flush-cache-vector-internal (allocate-cache-vector size)))
185             (t
186              (let ((cache (cdr entry)))
187                (setf (cdr entry) (cache-vector-ref cache 0))
188                (flush-cache-vector-internal cache)))))))
189
190 (defun free-cache-vector (cache-vector)
191   (let ((entry (gethash (cache-vector-size cache-vector) *free-cache-vectors*)))
192     (sb-sys:without-interrupts
193       (if (null entry)
194           (error
195            "attempt to free a cache-vector not allocated by GET-CACHE-VECTOR")
196           (let ((thread (cdr entry)))
197             (loop (unless thread (return))
198                   (when (eq thread cache-vector)
199                     (error "freeing a cache twice"))
200                   (setq thread (cache-vector-ref thread 0)))
201             (flush-cache-vector-internal cache-vector) ; to help the GC
202             (setf (cache-vector-ref cache-vector 0) (cdr entry))
203             (setf (cdr entry) cache-vector)
204             nil)))))
205
206 ;;; This is just for debugging and analysis. It shows the state of the
207 ;;; free cache resource.
208 #+sb-show
209 (defun show-free-cache-vectors ()
210   (let ((elements ()))
211     (maphash #'(lambda (s e) (push (list s e) elements)) *free-cache-vectors*)
212     (setq elements (sort elements #'< :key #'car))
213     (dolist (e elements)
214       (let* ((size (car e))
215              (entry (cadr e))
216              (allocated (car entry))
217              (head (cdr entry))
218              (free 0))
219         (loop (when (null head) (return t))
220               (setq head (cache-vector-ref head 0))
221               (incf free))
222         (format t
223                 "~&There  ~4D are caches of size ~4D. (~D free  ~3D%)"
224                 allocated
225                 size
226                 free
227                 (floor (* 100 (/ free (float allocated)))))))))
228 \f
229 ;;;; wrapper cache numbers
230
231 ;;; The constant WRAPPER-CACHE-NUMBER-ADDS-OK controls the number of
232 ;;; non-zero bits wrapper cache numbers will have.
233 ;;;
234 ;;; The value of this constant is the number of wrapper cache numbers
235 ;;; which can be added and still be certain the result will be a
236 ;;; fixnum. This is used by all the code that computes primary cache
237 ;;; locations from multiple wrappers.
238 ;;;
239 ;;; The value of this constant is used to derive the next two which
240 ;;; are the forms of this constant which it is more convenient for the
241 ;;; runtime code to use.
242 (defconstant wrapper-cache-number-length
243   (integer-length sb-kernel:layout-clos-hash-max))
244 (defconstant wrapper-cache-number-mask sb-kernel:layout-clos-hash-max)
245 (defconstant wrapper-cache-number-adds-ok
246   (truncate most-positive-fixnum sb-kernel:layout-clos-hash-max))
247 \f
248 ;;;; wrappers themselves
249
250 ;;; This caching algorithm requires that wrappers have more than one
251 ;;; wrapper cache number. You should think of these multiple numbers
252 ;;; as being in columns. That is, for a given cache, the same column
253 ;;; of wrapper cache numbers will be used.
254 ;;;
255 ;;; If at some point the cache distribution of a cache gets bad, the
256 ;;; cache can be rehashed by switching to a different column.
257 ;;;
258 ;;; The columns are referred to by field number which is that number
259 ;;; which, when used as a second argument to wrapper-ref, will return
260 ;;; that column of wrapper cache number.
261 ;;;
262 ;;; This code is written to allow flexibility as to how many wrapper
263 ;;; cache numbers will be in each wrapper, and where they will be
264 ;;; located. It is also set up to allow port specific modifications to
265 ;;; `pack' the wrapper cache numbers on machines where the addressing
266 ;;; modes make that a good idea.
267
268 ;;; In SBCL, as in CMU CL, we want to do type checking as early as
269 ;;; possible; structures help this. The structures are hard-wired to
270 ;;; have a fixed number of cache hash values, and that number must
271 ;;; correspond to the number of cache lines we use.
272 (defconstant wrapper-cache-number-vector-length
273   sb-kernel:layout-clos-hash-length)
274
275 (unless (boundp '*the-class-t*)
276   (setq *the-class-t* nil))
277
278 ;;; Note that for SBCL, as for CMU CL, the WRAPPER of a built-in or
279 ;;; structure class will be some other kind of SB-KERNEL:LAYOUT, but
280 ;;; this shouldn't matter, since the only two slots that WRAPPER adds
281 ;;; are meaningless in those cases.
282 (defstruct (wrapper
283             (:include sb-kernel:layout
284                       ;; KLUDGE: In CMU CL, the initialization default
285                       ;; for LAYOUT-INVALID was NIL. In SBCL, that has
286                       ;; changed to :UNINITIALIZED, but PCL code might
287                       ;; still expect NIL for the initialization
288                       ;; default of WRAPPER-INVALID. Instead of trying
289                       ;; to find out, I just overrode the LAYOUT
290                       ;; default here. -- WHN 19991204
291                       (invalid nil))
292             (:conc-name %wrapper-)
293             (:constructor make-wrapper-internal))
294   (instance-slots-layout nil :type list)
295   (class-slots nil :type list))
296 #-sb-fluid (declaim (sb-ext:freeze-type wrapper))
297
298 (defmacro wrapper-class (wrapper)
299   `(sb-kernel:class-pcl-class (sb-kernel:layout-class ,wrapper)))
300 (defmacro wrapper-no-of-instance-slots (wrapper)
301   `(sb-kernel:layout-length ,wrapper))
302
303 ;;; WRAPPER-STATE returns T (not generalized boolean, but T exactly)
304 ;;; iff the wrapper is valid. Any other return value denotes some
305 ;;; invalid state. Special conventions have been set up for certain
306 ;;; invalid states, e.g. obsoleteness or flushedness, but I (WHN
307 ;;; 19991204) haven't been motivated to reverse engineer them from the
308 ;;; code and document them here.
309 ;;;
310 ;;; FIXME: This is awkward and unmnemonic. There is a function
311 ;;; (INVALID-WRAPPER-P) to test this return result abstractly for
312 ;;; invalidness but it's not called consistently; the functions that
313 ;;; need to know whether a wrapper is invalid often test (EQ
314 ;;; (WRAPPER-STATE X) T), ick. It would be good to use the abstract
315 ;;; test instead. It would probably be even better to switch the sense
316 ;;; of the WRAPPER-STATE function, renaming it to WRAPPER-INVALID and
317 ;;; making it synonymous with LAYOUT-INVALID. Then the
318 ;;; INVALID-WRAPPER-P function would become trivial and would go away
319 ;;; (replaced with WRAPPER-INVALID), since all the various invalid
320 ;;; wrapper states would become generalized boolean "true" values. --
321 ;;; WHN 19991204
322 #-sb-fluid (declaim (inline wrapper-state (setf wrapper-state)))
323 (defun wrapper-state (wrapper)
324   (let ((invalid (sb-kernel:layout-invalid wrapper)))
325     (cond ((null invalid)
326            t)
327           ((atom invalid)
328            ;; some non-PCL object. INVALID is probably :INVALID. We
329            ;; should arguably compute the new wrapper here instead of
330            ;; returning NIL, but we don't bother, since
331            ;; OBSOLETE-INSTANCE-TRAP can't use it.
332            '(:obsolete nil))
333           (t
334            invalid))))
335 (defun (setf wrapper-state) (new-value wrapper)
336   (setf (sb-kernel:layout-invalid wrapper)
337         (if (eq new-value 't)
338             nil
339           new-value)))
340
341 (defmacro wrapper-instance-slots-layout (wrapper)
342   `(%wrapper-instance-slots-layout ,wrapper))
343 (defmacro wrapper-class-slots (wrapper)
344   `(%wrapper-class-slots ,wrapper))
345 (defmacro wrapper-cache-number-vector (x) x)
346
347 ;;; This is called in BRAID when we are making wrappers for classes
348 ;;; whose slots are not initialized yet, and which may be built-in
349 ;;; classes. We pass in the class name in addition to the class.
350 (defun boot-make-wrapper (length name &optional class)
351   (let ((found (cl:find-class name nil)))
352     (cond
353      (found
354       (unless (sb-kernel:class-pcl-class found)
355         (setf (sb-kernel:class-pcl-class found) class))
356       (assert (eq (sb-kernel:class-pcl-class found) class))
357       (let ((layout (sb-kernel:class-layout found)))
358         (assert layout)
359         layout))
360      (t
361       (make-wrapper-internal
362        :length length
363        :class (sb-kernel:make-standard-class :name name :pcl-class class))))))
364
365 ;;; The following variable may be set to a standard-class that has
366 ;;; already been created by the lisp code and which is to be redefined
367 ;;; by PCL. This allows standard-classes to be defined and used for
368 ;;; type testing and dispatch before PCL is loaded.
369 (defvar *pcl-class-boot* nil)
370
371 ;;; In SBCL, as in CMU CL, the layouts (a.k.a wrappers) for built-in
372 ;;; and structure classes already exist when PCL is initialized, so we
373 ;;; don't necessarily always make a wrapper. Also, we help maintain
374 ;;; the mapping between cl:class and pcl::class objects.
375 (defun make-wrapper (length class)
376   (cond
377    ((typep class 'std-class)
378     (make-wrapper-internal
379      :length length
380      :class
381      (let ((owrap (class-wrapper class)))
382        (cond (owrap
383               (sb-kernel:layout-class owrap))
384              ((*subtypep (class-of class)
385                          *the-class-standard-class*)
386               (cond ((and *pcl-class-boot*
387                           (eq (slot-value class 'name) *pcl-class-boot*))
388                      (let ((found (cl:find-class (slot-value class 'name))))
389                        (unless (sb-kernel:class-pcl-class found)
390                          (setf (sb-kernel:class-pcl-class found) class))
391                        (assert (eq (sb-kernel:class-pcl-class found) class))
392                        found))
393                     (t
394                      (sb-kernel:make-standard-class :pcl-class class))))
395              (t
396               (sb-kernel:make-random-pcl-class :pcl-class class))))))
397    (t
398     (let* ((found (cl:find-class (slot-value class 'name)))
399            (layout (sb-kernel:class-layout found)))
400       (unless (sb-kernel:class-pcl-class found)
401         (setf (sb-kernel:class-pcl-class found) class))
402       (assert (eq (sb-kernel:class-pcl-class found) class))
403       (assert layout)
404       layout))))
405
406 ;;; FIXME: The immediately following macros could become inline functions.
407
408 (defmacro first-wrapper-cache-number-index ()
409   0)
410
411 (defmacro next-wrapper-cache-number-index (field-number)
412   `(and (< ,field-number #.(1- wrapper-cache-number-vector-length))
413         (1+ ,field-number)))
414
415 (defmacro cache-number-vector-ref (cnv n)
416   `(wrapper-cache-number-vector-ref ,cnv ,n))
417
418 (defmacro wrapper-cache-number-vector-ref (wrapper n)
419   `(sb-kernel:layout-clos-hash ,wrapper ,n))
420
421 (defmacro class-no-of-instance-slots (class)
422   `(wrapper-no-of-instance-slots (class-wrapper ,class)))
423
424 (defmacro wrapper-class* (wrapper)
425   `(let ((wrapper ,wrapper))
426      (or (wrapper-class wrapper)
427          (find-structure-class
428           (cl:class-name (sb-kernel:layout-class wrapper))))))
429
430 ;;; The wrapper cache machinery provides general mechanism for
431 ;;; trapping on the next access to any instance of a given class. This
432 ;;; mechanism is used to implement the updating of instances when the
433 ;;; class is redefined (MAKE-INSTANCES-OBSOLETE). The same mechanism
434 ;;; is also used to update generic function caches when there is a
435 ;;; change to the superclasses of a class.
436 ;;;
437 ;;; Basically, a given wrapper can be valid or invalid. If it is
438 ;;; invalid, it means that any attempt to do a wrapper cache lookup
439 ;;; using the wrapper should trap. Also, methods on
440 ;;; SLOT-VALUE-USING-CLASS check the wrapper validity as well. This is
441 ;;; done by calling CHECK-WRAPPER-VALIDITY.
442
443 ;;; FIXME: could become inline function
444 (defmacro invalid-wrapper-p (wrapper)
445   `(neq (wrapper-state ,wrapper) 't))
446
447 (defvar *previous-nwrappers* (make-hash-table))
448
449 (defun invalidate-wrapper (owrapper state nwrapper)
450   (ecase state
451     ((:flush :obsolete)
452      (let ((new-previous ()))
453        ;; First off, a previous call to INVALIDATE-WRAPPER may have
454        ;; recorded OWRAPPER as an NWRAPPER to update to. Since
455        ;; OWRAPPER is about to be invalid, it no longer makes sense to
456        ;; update to it.
457        ;;
458        ;; We go back and change the previously invalidated wrappers so
459        ;; that they will now update directly to NWRAPPER. This
460        ;; corresponds to a kind of transitivity of wrapper updates.
461        (dolist (previous (gethash owrapper *previous-nwrappers*))
462          (when (eq state ':obsolete)
463            (setf (car previous) ':obsolete))
464          (setf (cadr previous) nwrapper)
465          (push previous new-previous))
466
467        (let ((ocnv (wrapper-cache-number-vector owrapper)))
468          (dotimes (i sb-kernel:layout-clos-hash-length)
469            (setf (cache-number-vector-ref ocnv i) 0)))
470        (push (setf (wrapper-state owrapper) (list state nwrapper))
471              new-previous)
472
473        (setf (gethash owrapper *previous-nwrappers*) ()
474              (gethash nwrapper *previous-nwrappers*) new-previous)))))
475
476 (defun check-wrapper-validity (instance)
477   (let* ((owrapper (wrapper-of instance))
478          (state (wrapper-state owrapper)))
479     (if (eq state 't)
480         owrapper
481         (let ((nwrapper
482                 (ecase (car state)
483                   (:flush
484                     (flush-cache-trap owrapper (cadr state) instance))
485                   (:obsolete
486                     (obsolete-instance-trap owrapper (cadr state) instance)))))
487           ;; This little bit of error checking is superfluous. It only
488           ;; checks to see whether the person who implemented the trap
489           ;; handling screwed up. Since that person is hacking
490           ;; internal PCL code, and is not a user, this should be
491           ;; needless. Also, since this directly slows down instance
492           ;; update and generic function cache refilling, feel free to
493           ;; take it out sometime soon.
494           ;;
495           ;; FIXME: We probably need to add a #+SB-PARANOID feature to
496           ;; make stuff like this optional. Until then, it stays in.
497           (cond ((neq nwrapper (wrapper-of instance))
498                  (error "wrapper returned from trap not wrapper of instance"))
499                 ((invalid-wrapper-p nwrapper)
500                  (error "wrapper returned from trap invalid")))
501           nwrapper))))
502
503 (defmacro check-wrapper-validity1 (object)
504   (let ((owrapper (gensym)))
505     `(let ((,owrapper (sb-kernel:layout-of object)))
506        (if (sb-kernel:layout-invalid ,owrapper)
507            (check-wrapper-validity ,object)
508            ,owrapper))))
509 \f
510 (defvar *free-caches* nil)
511
512 (defun get-cache (nkeys valuep limit-fn nlines)
513   (let ((cache (or (sb-sys:without-interrupts (pop *free-caches*))
514                    (make-cache))))
515     (declare (type cache cache))
516     (multiple-value-bind (cache-mask actual-size line-size nlines)
517         (compute-cache-parameters nkeys valuep nlines)
518       (setf (cache-nkeys cache) nkeys
519             (cache-valuep cache) valuep
520             (cache-nlines cache) nlines
521             (cache-field cache) (first-wrapper-cache-number-index)
522             (cache-limit-fn cache) limit-fn
523             (cache-mask cache) cache-mask
524             (cache-size cache) actual-size
525             (cache-line-size cache) line-size
526             (cache-max-location cache) (let ((line (1- nlines)))
527                                          (if (= nkeys 1)
528                                              (* line line-size)
529                                              (1+ (* line line-size))))
530             (cache-vector cache) (get-cache-vector actual-size)
531             (cache-overflow cache) nil)
532       cache)))
533
534 (defun get-cache-from-cache (old-cache new-nlines
535                              &optional (new-field (first-wrapper-cache-number-index)))
536   (let ((nkeys (cache-nkeys old-cache))
537         (valuep (cache-valuep old-cache))
538         (cache (or (sb-sys:without-interrupts (pop *free-caches*))
539                    (make-cache))))
540     (declare (type cache cache))
541     (multiple-value-bind (cache-mask actual-size line-size nlines)
542         (if (= new-nlines (cache-nlines old-cache))
543             (values (cache-mask old-cache) (cache-size old-cache)
544                     (cache-line-size old-cache) (cache-nlines old-cache))
545             (compute-cache-parameters nkeys valuep new-nlines))
546       (setf (cache-owner cache) (cache-owner old-cache)
547             (cache-nkeys cache) nkeys
548             (cache-valuep cache) valuep
549             (cache-nlines cache) nlines
550             (cache-field cache) new-field
551             (cache-limit-fn cache) (cache-limit-fn old-cache)
552             (cache-mask cache) cache-mask
553             (cache-size cache) actual-size
554             (cache-line-size cache) line-size
555             (cache-max-location cache) (let ((line (1- nlines)))
556                                          (if (= nkeys 1)
557                                              (* line line-size)
558                                              (1+ (* line line-size))))
559             (cache-vector cache) (get-cache-vector actual-size)
560             (cache-overflow cache) nil)
561       cache)))
562
563 (defun copy-cache (old-cache)
564   (let* ((new-cache (copy-cache-internal old-cache))
565          (size (cache-size old-cache))
566          (old-vector (cache-vector old-cache))
567          (new-vector (get-cache-vector size)))
568     (declare (simple-vector old-vector new-vector))
569     (dotimes-fixnum (i size)
570       (setf (svref new-vector i) (svref old-vector i)))
571     (setf (cache-vector new-cache) new-vector)
572     new-cache))
573
574 (defun free-cache (cache)
575   (free-cache-vector (cache-vector cache))
576   (setf (cache-vector cache) #())
577   (setf (cache-owner cache) nil)
578   (push cache *free-caches*)
579   nil)
580
581 (defun compute-line-size (x)
582   (power-of-two-ceiling x))
583
584 (defun compute-cache-parameters (nkeys valuep nlines-or-cache-vector)
585   ;;(declare (values cache-mask actual-size line-size nlines))
586   (declare (fixnum nkeys))
587   (if (= nkeys 1)
588       (let* ((line-size (if valuep 2 1))
589              (cache-size (if (typep nlines-or-cache-vector 'fixnum)
590                              (the fixnum
591                                   (* line-size
592                                      (the fixnum
593                                           (power-of-two-ceiling
594                                             nlines-or-cache-vector))))
595                              (cache-vector-size nlines-or-cache-vector))))
596         (declare (fixnum line-size cache-size))
597         (values (logxor (the fixnum (1- cache-size)) (the fixnum (1- line-size)))
598                 cache-size
599                 line-size
600                 (the fixnum (floor cache-size line-size))))
601       (let* ((line-size (power-of-two-ceiling (if valuep (1+ nkeys) nkeys)))
602              (cache-size (if (typep nlines-or-cache-vector 'fixnum)
603                              (the fixnum
604                                   (* line-size
605                                      (the fixnum
606                                           (power-of-two-ceiling
607                                             nlines-or-cache-vector))))
608                              (1- (cache-vector-size nlines-or-cache-vector)))))
609         (declare (fixnum line-size cache-size))
610         (values (logxor (the fixnum (1- cache-size)) (the fixnum (1- line-size)))
611                 (the fixnum (1+ cache-size))
612                 line-size
613                 (the fixnum (floor cache-size line-size))))))
614 \f
615 ;;; the various implementations of computing a primary cache location from
616 ;;; wrappers. Because some implementations of this must run fast there are
617 ;;; several implementations of the same algorithm.
618 ;;;
619 ;;; The algorithm is:
620 ;;;
621 ;;;  SUM       over the wrapper cache numbers,
622 ;;;  ENSURING  that the result is a fixnum
623 ;;;  MASK      the result against the mask argument.
624
625 ;;; COMPUTE-PRIMARY-CACHE-LOCATION
626 ;;;
627 ;;; The basic functional version. This is used by the cache miss code to
628 ;;; compute the primary location of an entry.
629 (defun compute-primary-cache-location (field mask wrappers)
630
631   (declare (type field-type field) (fixnum mask))
632   (if (not (listp wrappers))
633       (logand mask
634               (the fixnum (wrapper-cache-number-vector-ref wrappers field)))
635       (let ((location 0) (i 0))
636         (declare (fixnum location i))
637         (dolist (wrapper wrappers)
638           ;; First add the cache number of this wrapper to location.
639           (let ((wrapper-cache-number (wrapper-cache-number-vector-ref wrapper
640                                                                        field)))
641             (declare (fixnum wrapper-cache-number))
642             (if (zerop wrapper-cache-number)
643                 (return-from compute-primary-cache-location 0)
644                 (setq location
645                       (the fixnum (+ location wrapper-cache-number)))))
646           ;; Then, if we are working with lots of wrappers, deal with
647           ;; the wrapper-cache-number-mask stuff.
648           (when (and (not (zerop i))
649                      (zerop (mod i wrapper-cache-number-adds-ok)))
650             (setq location
651                   (logand location wrapper-cache-number-mask)))
652           (incf i))
653         (the fixnum (1+ (logand mask location))))))
654
655 ;;; COMPUTE-PRIMARY-CACHE-LOCATION-FROM-LOCATION
656 ;;;
657 ;;; This version is called on a cache line. It fetches the wrappers
658 ;;; from the cache line and determines the primary location. Various
659 ;;; parts of the cache filling code call this to determine whether it
660 ;;; is appropriate to displace a given cache entry.
661 ;;;
662 ;;; If this comes across a wrapper whose CACHE-NO is 0, it returns the
663 ;;; symbol invalid to suggest to its caller that it would be provident
664 ;;; to blow away the cache line in question.
665 (defun compute-primary-cache-location-from-location (to-cache
666                                                      from-location
667                                                      &optional
668                                                      (from-cache to-cache))
669   (declare (type cache to-cache from-cache) (fixnum from-location))
670   (let ((result 0)
671         (cache-vector (cache-vector from-cache))
672         (field (cache-field to-cache))
673         (mask (cache-mask to-cache))
674         (nkeys (cache-nkeys to-cache)))
675     (declare (type field-type field) (fixnum result mask nkeys)
676              (simple-vector cache-vector))
677     (dotimes-fixnum (i nkeys)
678       (let* ((wrapper (cache-vector-ref cache-vector (+ i from-location)))
679              (wcn (wrapper-cache-number-vector-ref wrapper field)))
680         (declare (fixnum wcn))
681         (setq result (+ result wcn)))
682       (when (and (not (zerop i))
683                  (zerop (mod i wrapper-cache-number-adds-ok)))
684         (setq result (logand result wrapper-cache-number-mask))))
685     (if (= nkeys 1)
686         (logand mask result)
687         (the fixnum (1+ (logand mask result))))))
688 \f
689 ;;;  NIL              means nothing so far, no actual arg info has NILs
690 ;;;                in the metatype
691 ;;;  CLASS          seen all sorts of metaclasses
692 ;;;                (specifically, more than one of the next 4 values)
693 ;;;  T          means everything so far is the class T
694 ;;;  STANDARD-CLASS   seen only standard classes
695 ;;;  BUILT-IN-CLASS   seen only built in classes
696 ;;;  STRUCTURE-CLASS  seen only structure classes
697 (defun raise-metatype (metatype new-specializer)
698   (let ((slot      (find-class 'slot-class))
699         (std       (find-class 'std-class))
700         (standard  (find-class 'standard-class))
701         (fsc       (find-class 'funcallable-standard-class))
702         (structure (find-class 'structure-class))
703         (built-in  (find-class 'built-in-class)))
704     (flet ((specializer->metatype (x)
705              (let ((meta-specializer
706                      (if (eq *boot-state* 'complete)
707                          (class-of (specializer-class x))
708                          (class-of x))))
709                (cond ((eq x *the-class-t*) t)
710                      ((*subtypep meta-specializer std)
711                       'standard-instance)
712                      ((*subtypep meta-specializer standard)
713                       'standard-instance)
714                      ((*subtypep meta-specializer fsc)
715                       'standard-instance)
716                      ((*subtypep meta-specializer structure)
717                       'structure-instance)
718                      ((*subtypep meta-specializer built-in)
719                       'built-in-instance)
720                      ((*subtypep meta-specializer slot)
721                       'slot-instance)
722                      (t (error "PCL cannot handle the specializer ~S (meta-specializer ~S)."
723                                new-specializer
724                                meta-specializer))))))
725       ;; We implement the following table. The notation is
726       ;; that X and Y are distinct meta specializer names.
727       ;;
728       ;;   NIL    <anything>    ===>  <anything>
729       ;;    X      X        ===>      X
730       ;;    X      Y        ===>    CLASS
731       (let ((new-metatype (specializer->metatype new-specializer)))
732         (cond ((eq new-metatype 'slot-instance) 'class)
733               ((null metatype) new-metatype)
734               ((eq metatype new-metatype) new-metatype)
735               (t 'class))))))
736
737 (defmacro with-dfun-wrappers ((args metatypes)
738                               (dfun-wrappers invalid-wrapper-p
739                                              &optional wrappers classes types)
740                               invalid-arguments-form
741                               &body body)
742   `(let* ((args-tail ,args) (,invalid-wrapper-p nil) (invalid-arguments-p nil)
743           (,dfun-wrappers nil) (dfun-wrappers-tail nil)
744           ,@(when wrappers
745               `((wrappers-rev nil) (types-rev nil) (classes-rev nil))))
746      (dolist (mt ,metatypes)
747        (unless args-tail
748          (setq invalid-arguments-p t)
749          (return nil))
750        (let* ((arg (pop args-tail))
751               (wrapper nil)
752               ,@(when wrappers
753                   `((class *the-class-t*)
754                     (type 't))))
755          (unless (eq mt 't)
756            (setq wrapper (wrapper-of arg))
757            (when (invalid-wrapper-p wrapper)
758              (setq ,invalid-wrapper-p t)
759              (setq wrapper (check-wrapper-validity arg)))
760            (cond ((null ,dfun-wrappers)
761                   (setq ,dfun-wrappers wrapper))
762                  ((not (consp ,dfun-wrappers))
763                   (setq dfun-wrappers-tail (list wrapper))
764                   (setq ,dfun-wrappers (cons ,dfun-wrappers dfun-wrappers-tail)))
765                  (t
766                   (let ((new-dfun-wrappers-tail (list wrapper)))
767                     (setf (cdr dfun-wrappers-tail) new-dfun-wrappers-tail)
768                     (setf dfun-wrappers-tail new-dfun-wrappers-tail))))
769            ,@(when wrappers
770                `((setq class (wrapper-class* wrapper))
771                  (setq type `(class-eq ,class)))))
772          ,@(when wrappers
773              `((push wrapper wrappers-rev)
774                (push class classes-rev)
775                (push type types-rev)))))
776      (if invalid-arguments-p
777          ,invalid-arguments-form
778          (let* (,@(when wrappers
779                     `((,wrappers (nreverse wrappers-rev))
780                       (,classes (nreverse classes-rev))
781                       (,types (mapcar #'(lambda (class)
782                                           `(class-eq ,class))
783                                       ,classes)))))
784            ,@body))))
785 \f
786 ;;;; some support stuff for getting a hold of symbols that we need when
787 ;;;; building the discriminator codes. It's OK for these to be interned
788 ;;;; symbols because we don't capture any user code in the scope in which
789 ;;;; these symbols are bound.
790
791 (defvar *dfun-arg-symbols* '(.ARG0. .ARG1. .ARG2. .ARG3.))
792
793 (defun dfun-arg-symbol (arg-number)
794   (or (nth arg-number (the list *dfun-arg-symbols*))
795       (intern (format nil ".ARG~A." arg-number) *pcl-package*)))
796
797 (defvar *slot-vector-symbols* '(.SLOTS0. .SLOTS1. .SLOTS2. .SLOTS3.))
798
799 (defun slot-vector-symbol (arg-number)
800   (or (nth arg-number (the list *slot-vector-symbols*))
801       (intern (format nil ".SLOTS~A." arg-number) *pcl-package*)))
802
803 (defun make-dfun-lambda-list (metatypes applyp)
804   (gathering1 (collecting)
805     (iterate ((i (interval :from 0))
806               (s (list-elements metatypes)))
807       (progn s)
808       (gather1 (dfun-arg-symbol i)))
809     (when applyp
810       (gather1 '&rest)
811       (gather1 '.dfun-rest-arg.))))
812
813 (defun make-dlap-lambda-list (metatypes applyp)
814   (gathering1 (collecting)
815     (iterate ((i (interval :from 0))
816               (s (list-elements metatypes)))
817       (progn s)
818       (gather1 (dfun-arg-symbol i)))
819     (when applyp
820       (gather1 '&rest))))
821
822 (defun make-emf-call (metatypes applyp fn-variable &optional emf-type)
823   (let ((required
824          (gathering1 (collecting)
825             (iterate ((i (interval :from 0))
826                       (s (list-elements metatypes)))
827               (progn s)
828               (gather1 (dfun-arg-symbol i))))))
829     `(,(if (eq emf-type 'fast-method-call)
830            'invoke-effective-method-function-fast
831            'invoke-effective-method-function)
832       ,fn-variable ,applyp ,@required ,@(when applyp `(.dfun-rest-arg.)))))
833
834 (defun make-dfun-call (metatypes applyp fn-variable)
835   (let ((required
836           (gathering1 (collecting)
837             (iterate ((i (interval :from 0))
838                       (s (list-elements metatypes)))
839               (progn s)
840               (gather1 (dfun-arg-symbol i))))))
841     (if applyp
842         `(function-apply   ,fn-variable ,@required .dfun-rest-arg.)
843         `(function-funcall ,fn-variable ,@required))))
844
845 (defun make-dfun-arg-list (metatypes applyp)
846   (let ((required
847           (gathering1 (collecting)
848             (iterate ((i (interval :from 0))
849                       (s (list-elements metatypes)))
850               (progn s)
851               (gather1 (dfun-arg-symbol i))))))
852     (if applyp
853         `(list* ,@required .dfun-rest-arg.)
854         `(list ,@required))))
855
856 (defun make-fast-method-call-lambda-list (metatypes applyp)
857   (gathering1 (collecting)
858     (gather1 '.pv-cell.)
859     (gather1 '.next-method-call.)
860     (iterate ((i (interval :from 0))
861               (s (list-elements metatypes)))
862       (progn s)
863       (gather1 (dfun-arg-symbol i)))
864     (when applyp
865       (gather1 '.dfun-rest-arg.))))
866 \f
867 ;;;; a comment from some PCL implementor:
868 ;;;;     Its too bad Common Lisp compilers freak out when you have a
869 ;;;;   DEFUN with a lot of LABELS in it. If I could do that I could
870 ;;;;   make this code much easier to read and work with.
871 ;;;;     Ahh Scheme...
872 ;;;;     In the absence of that, the following little macro makes the
873 ;;;;   code that follows a little bit more reasonable. I would like to
874 ;;;;   add that having to practically write my own compiler in order to
875 ;;;;   get just this simple thing is something of a drag.
876 ;;;;
877 ;;;; KLUDGE: Maybe we could actually implement this as LABELS now,
878 ;;;; since AFAIK CMU CL doesn't freak out when you have a DEFUN with a
879 ;;;; lot of LABELS in it (and if it does we can fix it instead of
880 ;;;; working around it). -- WHN 19991204
881
882 (eval-when (:compile-toplevel :load-toplevel :execute)
883
884 (defvar *cache* nil)
885
886 ;;; FIXME: should be undefined after bootstrapping
887 (defparameter *local-cache-functions*
888   '((cache () .cache.)
889     (nkeys () (cache-nkeys .cache.))
890     (line-size () (cache-line-size .cache.))
891     (vector () (cache-vector .cache.))
892     (valuep () (cache-valuep .cache.))
893     (nlines () (cache-nlines .cache.))
894     (max-location () (cache-max-location .cache.))
895     (limit-fn () (cache-limit-fn .cache.))
896     (size () (cache-size .cache.))
897     (mask () (cache-mask .cache.))
898     (field () (cache-field .cache.))
899     (overflow () (cache-overflow .cache.))
900
901     ;; Return T IFF this cache location is reserved. The only time
902     ;; this is true is for line number 0 of an nkeys=1 cache.
903     (line-reserved-p (line)
904       (declare (fixnum line))
905       (and (= (nkeys) 1)
906            (= line 0)))
907     (location-reserved-p (location)
908       (declare (fixnum location))
909       (and (= (nkeys) 1)
910            (= location 0)))
911     ;; Given a line number, return the cache location. This is the
912     ;; value that is the second argument to cache-vector-ref. Basically,
913     ;; this deals with the offset of nkeys>1 caches and multiplies
914     ;; by line size.
915     (line-location (line)
916       (declare (fixnum line))
917       (when (line-reserved-p line)
918         (error "Line is reserved."))
919       (if (= (nkeys) 1)
920           (the fixnum (* line (line-size)))
921           (the fixnum (1+ (the fixnum (* line (line-size)))))))
922
923     ;; Given a cache location, return the line. This is the inverse
924     ;; of LINE-LOCATION.
925     (location-line (location)
926       (declare (fixnum location))
927       (if (= (nkeys) 1)
928           (floor location (line-size))
929           (floor (the fixnum (1- location)) (line-size))))
930
931     ;; Given a line number, return the wrappers stored at that line.
932     ;; As usual, if nkeys=1, this returns a single value. Only when
933     ;; nkeys>1 does it return a list. An error is signalled if the
934     ;; line is reserved.
935     (line-wrappers (line)
936       (declare (fixnum line))
937       (when (line-reserved-p line) (error "Line is reserved."))
938       (location-wrappers (line-location line)))
939     (location-wrappers (location) ; avoid multiplies caused by line-location
940       (declare (fixnum location))
941       (if (= (nkeys) 1)
942           (cache-vector-ref (vector) location)
943           (let ((list (make-list (nkeys)))
944                 (vector (vector)))
945             (declare (simple-vector vector))
946             (dotimes-fixnum (i (nkeys) list)
947               (setf (nth i list) (cache-vector-ref vector (+ location i)))))))
948
949     ;; Given a line number, return true IFF the line's
950     ;; wrappers are the same as wrappers.
951     (line-matches-wrappers-p (line wrappers)
952       (declare (fixnum line))
953       (and (not (line-reserved-p line))
954            (location-matches-wrappers-p (line-location line) wrappers)))
955     (location-matches-wrappers-p (loc wrappers) ; must not be reserved
956       (declare (fixnum loc))
957       (let ((cache-vector (vector)))
958         (declare (simple-vector cache-vector))
959         (if (= (nkeys) 1)
960             (eq wrappers (cache-vector-ref cache-vector loc))
961             (dotimes-fixnum (i (nkeys) t)
962               (unless (eq (pop wrappers)
963                           (cache-vector-ref cache-vector (+ loc i)))
964                 (return nil))))))
965
966     ;; Given a line number, return the value stored at that line.
967     ;; If valuep is NIL, this returns NIL. As with line-wrappers,
968     ;; an error is signalled if the line is reserved.
969     (line-value (line)
970       (declare (fixnum line))
971       (when (line-reserved-p line) (error "Line is reserved."))
972       (location-value (line-location line)))
973     (location-value (loc)
974       (declare (fixnum loc))
975       (and (valuep)
976            (cache-vector-ref (vector) (+ loc (nkeys)))))
977
978     ;; Given a line number, return true iff that line has data in
979     ;; it. The state of the wrappers stored in the line is not
980     ;; checked. An error is signalled if line is reserved.
981     (line-full-p (line)
982       (when (line-reserved-p line) (error "Line is reserved."))
983       (not (null (cache-vector-ref (vector) (line-location line)))))
984
985     ;; Given a line number, return true iff the line is full and
986     ;; there are no invalid wrappers in the line, and the line's
987     ;; wrappers are different from wrappers.
988     ;; An error is signalled if the line is reserved.
989     (line-valid-p (line wrappers)
990       (declare (fixnum line))
991       (when (line-reserved-p line) (error "Line is reserved."))
992       (location-valid-p (line-location line) wrappers))
993     (location-valid-p (loc wrappers)
994       (declare (fixnum loc))
995       (let ((cache-vector (vector))
996             (wrappers-mismatch-p (null wrappers)))
997         (declare (simple-vector cache-vector))
998         (dotimes-fixnum (i (nkeys) wrappers-mismatch-p)
999           (let ((wrapper (cache-vector-ref cache-vector (+ loc i))))
1000             (when (or (null wrapper)
1001                       (invalid-wrapper-p wrapper))
1002               (return nil))
1003             (unless (and wrappers
1004                          (eq wrapper
1005                              (if (consp wrappers) (pop wrappers) wrappers)))
1006               (setq wrappers-mismatch-p t))))))
1007
1008     ;; how many unreserved lines separate line-1 and line-2
1009     (line-separation (line-1 line-2)
1010      (declare (fixnum line-1 line-2))
1011      (let ((diff (the fixnum (- line-2 line-1))))
1012        (declare (fixnum diff))
1013        (when (minusp diff)
1014          (setq diff (+ diff (nlines)))
1015          (when (line-reserved-p 0)
1016            (setq diff (1- diff))))
1017        diff))
1018
1019     ;; Given a cache line, get the next cache line. This will not
1020     ;; return a reserved line.
1021     (next-line (line)
1022      (declare (fixnum line))
1023      (if (= line (the fixnum (1- (nlines))))
1024          (if (line-reserved-p 0) 1 0)
1025          (the fixnum (1+ line))))
1026     (next-location (loc)
1027       (declare (fixnum loc))
1028       (if (= loc (max-location))
1029           (if (= (nkeys) 1)
1030               (line-size)
1031               1)
1032           (the fixnum (+ loc (line-size)))))
1033
1034     ;; Given a line which has a valid entry in it, this will return
1035     ;; the primary cache line of the wrappers in that line. We just
1036     ;; call COMPUTE-PRIMARY-CACHE-LOCATION-FROM-LOCATION, this is an
1037     ;; easier packaging up of the call to it.
1038     (line-primary (line)
1039       (declare (fixnum line))
1040       (location-line (line-primary-location line)))
1041     (line-primary-location (line)
1042      (declare (fixnum line))
1043      (compute-primary-cache-location-from-location
1044        (cache) (line-location line)))))
1045
1046 (defmacro with-local-cache-functions ((cache) &body body)
1047   `(let ((.cache. ,cache))
1048      (declare (type cache .cache.))
1049      (macrolet ,(mapcar #'(lambda (fn)
1050                             `(,(car fn) ,(cadr fn)
1051                                 `(let (,,@(mapcar #'(lambda (var)
1052                                                       ``(,',var ,,var))
1053                                                   (cadr fn)))
1054                                     ,@',(cddr fn))))
1055                         *local-cache-functions*)
1056        ,@body)))
1057
1058 ) ; EVAL-WHEN
1059 \f
1060 ;;; Here is where we actually fill, recache and expand caches.
1061 ;;;
1062 ;;; The functions FILL-CACHE and PROBE-CACHE are the ONLY external
1063 ;;; entrypoints into this code.
1064 ;;;
1065 ;;; FILL-CACHE returns 1 value: a new cache
1066 ;;;
1067 ;;;   a wrapper field number
1068 ;;;   a cache
1069 ;;;   a mask
1070 ;;;   an absolute cache size (the size of the actual vector)
1071 ;;; It tries to re-adjust the cache every time it makes a new fill.
1072 ;;; The intuition here is that we want uniformity in the number of
1073 ;;; probes needed to find an entry. Furthermore, adjusting has the
1074 ;;; nice property of throwing out any entries that are invalid.
1075 (defvar *cache-expand-threshold* 1.25)
1076
1077 (defun fill-cache (cache wrappers value &optional free-cache-p)
1078
1079   ;; FILL-CACHE won't return if WRAPPERS is nil, might as well check..
1080   (unless wrappers
1081     (error "fill-cache: WRAPPERS arg is NIL!"))
1082
1083   (or (fill-cache-p nil cache wrappers value)
1084       (and (< (ceiling (* (cache-count cache) 1.25))
1085               (if (= (cache-nkeys cache) 1)
1086                   (1- (cache-nlines cache))
1087                   (cache-nlines cache)))
1088            (adjust-cache cache wrappers value free-cache-p))
1089       (expand-cache cache wrappers value free-cache-p)))
1090
1091 (defvar *check-cache-p* nil)
1092
1093 (defmacro maybe-check-cache (cache)
1094   `(progn
1095      (when *check-cache-p*
1096        (check-cache ,cache))
1097      ,cache))
1098
1099 (defun check-cache (cache)
1100   (with-local-cache-functions (cache)
1101     (let ((location (if (= (nkeys) 1) 0 1))
1102           (limit (funcall (limit-fn) (nlines))))
1103       (dotimes-fixnum (i (nlines) cache)
1104         (when (and (not (location-reserved-p location))
1105                    (line-full-p i))
1106           (let* ((home-loc (compute-primary-cache-location-from-location
1107                             cache location))
1108                  (home (location-line (if (location-reserved-p home-loc)
1109                                           (next-location home-loc)
1110                                           home-loc)))
1111                  (sep (when home (line-separation home i))))
1112             (when (and sep (> sep limit))
1113               (error "bad cache ~S ~@
1114                       value at location ~D: ~D lines from its home. The limit is ~D."
1115                      cache location sep limit))))
1116         (setq location (next-location location))))))
1117
1118 (defun probe-cache (cache wrappers &optional default limit-fn)
1119   ;;(declare (values value))
1120   (unless wrappers
1121     ;; FIXME: This and another earlier test on a WRAPPERS arg can
1122     ;; be compact assertoids.
1123     (error "WRAPPERS arg is NIL!"))
1124   (with-local-cache-functions (cache)
1125     (let* ((location (compute-primary-cache-location (field) (mask) wrappers))
1126            (limit (funcall (or limit-fn (limit-fn)) (nlines))))
1127       (declare (fixnum location limit))
1128       (when (location-reserved-p location)
1129         (setq location (next-location location)))
1130       (dotimes-fixnum (i (1+ limit))
1131         (when (location-matches-wrappers-p location wrappers)
1132           (return-from probe-cache (or (not (valuep))
1133                                        (location-value location))))
1134         (setq location (next-location location)))
1135       (dolist (entry (overflow))
1136         (when (equal (car entry) wrappers)
1137           (return-from probe-cache (or (not (valuep))
1138                                        (cdr entry)))))
1139       default)))
1140
1141 (defun map-cache (function cache &optional set-p)
1142   (with-local-cache-functions (cache)
1143     (let ((set-p (and set-p (valuep))))
1144       (dotimes-fixnum (i (nlines) cache)
1145         (unless (or (line-reserved-p i) (not (line-valid-p i nil)))
1146           (let ((value (funcall function (line-wrappers i) (line-value i))))
1147             (when set-p
1148               (setf (cache-vector-ref (vector) (+ (line-location i) (nkeys)))
1149                     value)))))
1150       (dolist (entry (overflow))
1151         (let ((value (funcall function (car entry) (cdr entry))))
1152           (when set-p
1153             (setf (cdr entry) value))))))
1154   cache)
1155
1156 (defun cache-count (cache)
1157   (with-local-cache-functions (cache)
1158     (let ((count 0))
1159       (declare (fixnum count))
1160       (dotimes-fixnum (i (nlines) count)
1161         (unless (line-reserved-p i)
1162           (when (line-full-p i)
1163             (incf count)))))))
1164
1165 (defun entry-in-cache-p (cache wrappers value)
1166   (declare (ignore value))
1167   (with-local-cache-functions (cache)
1168     (dotimes-fixnum (i (nlines))
1169       (unless (line-reserved-p i)
1170         (when (equal (line-wrappers i) wrappers)
1171           (return t))))))
1172
1173 ;;; returns T or NIL
1174 (defun fill-cache-p (forcep cache wrappers value)
1175   (with-local-cache-functions (cache)
1176     (let* ((location (compute-primary-cache-location (field) (mask) wrappers))
1177            (primary (location-line location)))
1178       (declare (fixnum location primary))
1179       (multiple-value-bind (free emptyp)
1180           (find-free-cache-line primary cache wrappers)
1181         (when (or forcep emptyp)
1182           (when (not emptyp)
1183             (push (cons (line-wrappers free) (line-value free))
1184                   (cache-overflow cache)))
1185           ;;(fill-line free wrappers value)
1186           (let ((line free))
1187             (declare (fixnum line))
1188             (when (line-reserved-p line)
1189               (error "attempt to fill a reserved line"))
1190             (let ((loc (line-location line))
1191                   (cache-vector (vector)))
1192               (declare (fixnum loc) (simple-vector cache-vector))
1193               (cond ((= (nkeys) 1)
1194                      (setf (cache-vector-ref cache-vector loc) wrappers)
1195                      (when (valuep)
1196                        (setf (cache-vector-ref cache-vector (1+ loc)) value)))
1197                     (t
1198                      (let ((i 0))
1199                        (declare (fixnum i))
1200                        (dolist (w wrappers)
1201                          (setf (cache-vector-ref cache-vector (+ loc i)) w)
1202                          (setq i (the fixnum (1+ i)))))
1203                      (when (valuep)
1204                        (setf (cache-vector-ref cache-vector (+ loc (nkeys)))
1205                              value))))
1206               (maybe-check-cache cache))))))))
1207
1208 (defun fill-cache-from-cache-p (forcep cache from-cache from-line)
1209   (declare (fixnum from-line))
1210   (with-local-cache-functions (cache)
1211     (let ((primary (location-line
1212                     (compute-primary-cache-location-from-location
1213                      cache (line-location from-line) from-cache))))
1214       (declare (fixnum primary))
1215       (multiple-value-bind (free emptyp)
1216           (find-free-cache-line primary cache)
1217         (when (or forcep emptyp)
1218           (when (not emptyp)
1219             (push (cons (line-wrappers free) (line-value free))
1220                   (cache-overflow cache)))
1221           ;;(transfer-line from-cache-vector from-line cache-vector free)
1222           (let ((from-cache-vector (cache-vector from-cache))
1223                 (to-cache-vector (vector))
1224                 (to-line free))
1225             (declare (fixnum to-line))
1226             (if (line-reserved-p to-line)
1227                 (error "transferring something into a reserved cache line")
1228                 (let ((from-loc (line-location from-line))
1229                       (to-loc (line-location to-line)))
1230                   (declare (fixnum from-loc to-loc))
1231                   (modify-cache to-cache-vector
1232                                 (dotimes-fixnum (i (line-size))
1233                                   (setf (cache-vector-ref to-cache-vector
1234                                                           (+ to-loc i))
1235                                         (cache-vector-ref from-cache-vector
1236                                                           (+ from-loc i)))))))
1237             (maybe-check-cache cache)))))))
1238
1239 ;;; Returns NIL or (values <field> <cache-vector>)
1240 ;;;
1241 ;;; This is only called when it isn't possible to put the entry in the
1242 ;;; cache the easy way. That is, this function assumes that
1243 ;;; FILL-CACHE-P has been called as returned NIL.
1244 ;;;
1245 ;;; If this returns NIL, it means that it wasn't possible to find a
1246 ;;; wrapper field for which all of the entries could be put in the
1247 ;;; cache (within the limit).
1248 (defun adjust-cache (cache wrappers value free-old-cache-p)
1249   (with-local-cache-functions (cache)
1250     (let ((ncache (get-cache-from-cache cache (nlines) (field))))
1251       (do ((nfield (cache-field ncache) (next-wrapper-cache-number-index nfield)))
1252           ((null nfield) (free-cache ncache) nil)
1253         (setf (cache-field ncache) nfield)
1254         (labels ((try-one-fill-from-line (line)
1255                    (fill-cache-from-cache-p nil ncache cache line))
1256                  (try-one-fill (wrappers value)
1257                    (fill-cache-p nil ncache wrappers value)))
1258           (if (and (dotimes-fixnum (i (nlines) t)
1259                      (when (and (null (line-reserved-p i))
1260                                 (line-valid-p i wrappers))
1261                        (unless (try-one-fill-from-line i) (return nil))))
1262                    (dolist (wrappers+value (cache-overflow cache) t)
1263                      (unless (try-one-fill (car wrappers+value) (cdr wrappers+value))
1264                        (return nil)))
1265                    (try-one-fill wrappers value))
1266               (progn (when free-old-cache-p (free-cache cache))
1267                      (return (maybe-check-cache ncache)))
1268               (flush-cache-vector-internal (cache-vector ncache))))))))
1269
1270 ;;; returns: (values <cache>)
1271 (defun expand-cache (cache wrappers value free-old-cache-p)
1272   ;;(declare (values cache))
1273   (with-local-cache-functions (cache)
1274     (let ((ncache (get-cache-from-cache cache (* (nlines) 2))))
1275       (labels ((do-one-fill-from-line (line)
1276                  (unless (fill-cache-from-cache-p nil ncache cache line)
1277                    (do-one-fill (line-wrappers line) (line-value line))))
1278                (do-one-fill (wrappers value)
1279                  (setq ncache (or (adjust-cache ncache wrappers value t)
1280                                   (fill-cache-p t ncache wrappers value))))
1281                (try-one-fill (wrappers value)
1282                  (fill-cache-p nil ncache wrappers value)))
1283         (dotimes-fixnum (i (nlines))
1284           (when (and (null (line-reserved-p i))
1285                      (line-valid-p i wrappers))
1286             (do-one-fill-from-line i)))
1287         (dolist (wrappers+value (cache-overflow cache))
1288           (unless (try-one-fill (car wrappers+value) (cdr wrappers+value))
1289             (do-one-fill (car wrappers+value) (cdr wrappers+value))))
1290         (unless (try-one-fill wrappers value)
1291           (do-one-fill wrappers value))
1292         (when free-old-cache-p (free-cache cache))
1293         (maybe-check-cache ncache)))))
1294 \f
1295 ;;; This is the heart of the cache filling mechanism. It implements
1296 ;;; the decisions about where entries are placed.
1297 ;;;
1298 ;;; Find a line in the cache at which a new entry can be inserted.
1299 ;;;
1300 ;;;   <line>
1301 ;;;   <empty?>     is <line> in fact empty?
1302 (defun find-free-cache-line (primary cache &optional wrappers)
1303   ;;(declare (values line empty?))
1304   (declare (fixnum primary))
1305   (with-local-cache-functions (cache)
1306     (when (line-reserved-p primary) (setq primary (next-line primary)))
1307     (let ((limit (funcall (limit-fn) (nlines)))
1308           (wrappedp nil)
1309           (lines nil)
1310           (p primary) (s primary))
1311       (declare (fixnum p s limit))
1312       (block find-free
1313         (loop
1314          ;; Try to find a free line starting at <s>. <p> is the
1315          ;; primary line of the entry we are finding a free
1316          ;; line for, it is used to compute the separations.
1317          (do* ((line s (next-line line))
1318                (nsep (line-separation p s) (1+ nsep)))
1319               (())
1320            (declare (fixnum line nsep))
1321            (when (null (line-valid-p line wrappers)) ;If this line is empty or
1322              (push line lines)          ;invalid, just use it.
1323              (return-from find-free))
1324            (when (and wrappedp (>= line primary))
1325              ;; have gone all the way around the cache, time to quit
1326              (return-from find-free-cache-line (values primary nil)))
1327            (let ((osep (line-separation (line-primary line) line)))
1328              (when (>= osep limit)
1329                (return-from find-free-cache-line (values primary nil)))
1330              (when (cond ((= nsep limit) t)
1331                          ((= nsep osep) (zerop (random 2)))
1332                          ((> nsep osep) t)
1333                          (t nil))
1334                ;; See whether we can displace what is in this line so that we
1335                ;; can use the line.
1336                (when (= line (the fixnum (1- (nlines)))) (setq wrappedp t))
1337                (setq p (line-primary line))
1338                (setq s (next-line line))
1339                (push line lines)
1340                (return nil)))
1341            (when (= line (the fixnum (1- (nlines)))) (setq wrappedp t)))))
1342       ;; Do all the displacing.
1343       (loop
1344        (when (null (cdr lines)) (return nil))
1345        (let ((dline (pop lines))
1346              (line (car lines)))
1347          (declare (fixnum dline line))
1348          ;;Copy from line to dline (dline is known to be free).
1349          (let ((from-loc (line-location line))
1350                (to-loc (line-location dline))
1351                (cache-vector (vector)))
1352            (declare (fixnum from-loc to-loc) (simple-vector cache-vector))
1353            (modify-cache cache-vector
1354                          (dotimes-fixnum (i (line-size))
1355                            (setf (cache-vector-ref cache-vector
1356                                                    (+ to-loc i))
1357                                  (cache-vector-ref cache-vector
1358                                                    (+ from-loc i)))
1359                            (setf (cache-vector-ref cache-vector
1360                                                    (+ from-loc i))
1361                                  nil))))))
1362       (values (car lines) t))))
1363
1364 (defun default-limit-fn (nlines)
1365   (case nlines
1366     ((1 2 4) 1)
1367     ((8 16)  4)
1368     (otherwise 6)))
1369
1370 (defvar *empty-cache* (make-cache)) ; for defstruct slot initial value forms
1371 \f
1372 ;;; Pre-allocate generic function caches. The hope is that this will
1373 ;;; put them nicely together in memory, and that that may be a win. Of
1374 ;;; course the first GC copy will probably blow that out, this really
1375 ;;; wants to be wrapped in something that declares the area static.
1376 ;;;
1377 ;;; This preallocation only creates about 25% more caches than PCL
1378 ;;; itself uses. Some ports may want to preallocate some more of
1379 ;;; these.
1380 ;;;
1381 ;;; KLUDGE: Isn't something very similar going on in precom1.lisp? Do
1382 ;;; we need it both here and there? Why? -- WHN 19991203
1383 (eval-when (:load-toplevel)
1384   (dolist (n-size '((1 513)(3 257)(3 129)(14 128)(6 65)(2 64)(7 33)(16 32)
1385                     (16 17)(32 16)(64 9)(64 8)(6 5)(128 4)(35 2)))
1386     (let ((n (car n-size))
1387           (size (cadr n-size)))
1388       (mapcar #'free-cache-vector
1389               (mapcar #'get-cache-vector
1390                       (make-list n :initial-element size))))))
1391
1392 (defun caches-to-allocate ()
1393   (sort (let ((l nil))
1394           (maphash #'(lambda (size entry)
1395                        (push (list (car entry) size) l))
1396                    sb-pcl::*free-caches*)
1397           l)
1398         #'>
1399         :key #'cadr))