d40141fa3501c5909ced33863b78a7f94193dd03
[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   (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   `(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     (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     (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 (without-interrupts (pop *free-caches*)) (make-cache))))
514     (declare (type cache cache))
515     (multiple-value-bind (cache-mask actual-size line-size nlines)
516         (compute-cache-parameters nkeys valuep nlines)
517       (setf (cache-nkeys cache) nkeys
518             (cache-valuep cache) valuep
519             (cache-nlines cache) nlines
520             (cache-field cache) (first-wrapper-cache-number-index)
521             (cache-limit-fn cache) limit-fn
522             (cache-mask cache) cache-mask
523             (cache-size cache) actual-size
524             (cache-line-size cache) line-size
525             (cache-max-location cache) (let ((line (1- nlines)))
526                                          (if (= nkeys 1)
527                                              (* line line-size)
528                                              (1+ (* line line-size))))
529             (cache-vector cache) (get-cache-vector actual-size)
530             (cache-overflow cache) nil)
531       cache)))
532
533 (defun get-cache-from-cache (old-cache new-nlines
534                              &optional (new-field (first-wrapper-cache-number-index)))
535   (let ((nkeys (cache-nkeys old-cache))
536         (valuep (cache-valuep old-cache))
537         (cache (or (without-interrupts (pop *free-caches*)) (make-cache))))
538     (declare (type cache cache))
539     (multiple-value-bind (cache-mask actual-size line-size nlines)
540         (if (= new-nlines (cache-nlines old-cache))
541             (values (cache-mask old-cache) (cache-size old-cache)
542                     (cache-line-size old-cache) (cache-nlines old-cache))
543             (compute-cache-parameters nkeys valuep new-nlines))
544       (setf (cache-owner cache) (cache-owner old-cache)
545             (cache-nkeys cache) nkeys
546             (cache-valuep cache) valuep
547             (cache-nlines cache) nlines
548             (cache-field cache) new-field
549             (cache-limit-fn cache) (cache-limit-fn old-cache)
550             (cache-mask cache) cache-mask
551             (cache-size cache) actual-size
552             (cache-line-size cache) line-size
553             (cache-max-location cache) (let ((line (1- nlines)))
554                                          (if (= nkeys 1)
555                                              (* line line-size)
556                                              (1+ (* line line-size))))
557             (cache-vector cache) (get-cache-vector actual-size)
558             (cache-overflow cache) nil)
559       cache)))
560
561 (defun copy-cache (old-cache)
562   (let* ((new-cache (copy-cache-internal old-cache))
563          (size (cache-size old-cache))
564          (old-vector (cache-vector old-cache))
565          (new-vector (get-cache-vector size)))
566     (declare (simple-vector old-vector new-vector))
567     (dotimes-fixnum (i size)
568       (setf (svref new-vector i) (svref old-vector i)))
569     (setf (cache-vector new-cache) new-vector)
570     new-cache))
571
572 (defun free-cache (cache)
573   (free-cache-vector (cache-vector cache))
574   (setf (cache-vector cache) #())
575   (setf (cache-owner cache) nil)
576   (push cache *free-caches*)
577   nil)
578
579 (defun compute-line-size (x)
580   (power-of-two-ceiling x))
581
582 (defun compute-cache-parameters (nkeys valuep nlines-or-cache-vector)
583   ;;(declare (values cache-mask actual-size line-size nlines))
584   (declare (fixnum nkeys))
585   (if (= nkeys 1)
586       (let* ((line-size (if valuep 2 1))
587              (cache-size (if (typep nlines-or-cache-vector 'fixnum)
588                              (the fixnum
589                                   (* line-size
590                                      (the fixnum
591                                           (power-of-two-ceiling
592                                             nlines-or-cache-vector))))
593                              (cache-vector-size nlines-or-cache-vector))))
594         (declare (fixnum line-size cache-size))
595         (values (logxor (the fixnum (1- cache-size)) (the fixnum (1- line-size)))
596                 cache-size
597                 line-size
598                 (the fixnum (floor cache-size line-size))))
599       (let* ((line-size (power-of-two-ceiling (if valuep (1+ nkeys) nkeys)))
600              (cache-size (if (typep nlines-or-cache-vector 'fixnum)
601                              (the fixnum
602                                   (* line-size
603                                      (the fixnum
604                                           (power-of-two-ceiling
605                                             nlines-or-cache-vector))))
606                              (1- (cache-vector-size nlines-or-cache-vector)))))
607         (declare (fixnum line-size cache-size))
608         (values (logxor (the fixnum (1- cache-size)) (the fixnum (1- line-size)))
609                 (the fixnum (1+ cache-size))
610                 line-size
611                 (the fixnum (floor cache-size line-size))))))
612 \f
613 ;;; the various implementations of computing a primary cache location from
614 ;;; wrappers. Because some implementations of this must run fast there are
615 ;;; several implementations of the same algorithm.
616 ;;;
617 ;;; The algorithm is:
618 ;;;
619 ;;;  SUM       over the wrapper cache numbers,
620 ;;;  ENSURING  that the result is a fixnum
621 ;;;  MASK      the result against the mask argument.
622
623 ;;; COMPUTE-PRIMARY-CACHE-LOCATION
624 ;;;
625 ;;; The basic functional version. This is used by the cache miss code to
626 ;;; compute the primary location of an entry.
627 (defun compute-primary-cache-location (field mask wrappers)
628
629   (declare (type field-type field) (fixnum mask))
630   (if (not (listp wrappers))
631       (logand mask
632               (the fixnum (wrapper-cache-number-vector-ref wrappers field)))
633       (let ((location 0) (i 0))
634         (declare (fixnum location i))
635         (dolist (wrapper wrappers)
636           ;; First add the cache number of this wrapper to location.
637           (let ((wrapper-cache-number (wrapper-cache-number-vector-ref wrapper
638                                                                        field)))
639             (declare (fixnum wrapper-cache-number))
640             (if (zerop wrapper-cache-number)
641                 (return-from compute-primary-cache-location 0)
642                 (setq location
643                       (the fixnum (+ location wrapper-cache-number)))))
644           ;; Then, if we are working with lots of wrappers, deal with
645           ;; the wrapper-cache-number-mask stuff.
646           (when (and (not (zerop i))
647                      (zerop (mod i wrapper-cache-number-adds-ok)))
648             (setq location
649                   (logand location wrapper-cache-number-mask)))
650           (incf i))
651         (the fixnum (1+ (logand mask location))))))
652
653 ;;; COMPUTE-PRIMARY-CACHE-LOCATION-FROM-LOCATION
654 ;;;
655 ;;; This version is called on a cache line. It fetches the wrappers
656 ;;; from the cache line and determines the primary location. Various
657 ;;; parts of the cache filling code call this to determine whether it
658 ;;; is appropriate to displace a given cache entry.
659 ;;;
660 ;;; If this comes across a wrapper whose CACHE-NO is 0, it returns the
661 ;;; symbol invalid to suggest to its caller that it would be provident
662 ;;; to blow away the cache line in question.
663 (defun compute-primary-cache-location-from-location (to-cache
664                                                      from-location
665                                                      &optional
666                                                      (from-cache to-cache))
667   (declare (type cache to-cache from-cache) (fixnum from-location))
668   (let ((result 0)
669         (cache-vector (cache-vector from-cache))
670         (field (cache-field to-cache))
671         (mask (cache-mask to-cache))
672         (nkeys (cache-nkeys to-cache)))
673     (declare (type field-type field) (fixnum result mask nkeys)
674              (simple-vector cache-vector))
675     (dotimes-fixnum (i nkeys)
676       (let* ((wrapper (cache-vector-ref cache-vector (+ i from-location)))
677              (wcn (wrapper-cache-number-vector-ref wrapper field)))
678         (declare (fixnum wcn))
679         (setq result (+ result wcn)))
680       (when (and (not (zerop i))
681                  (zerop (mod i wrapper-cache-number-adds-ok)))
682         (setq result (logand result wrapper-cache-number-mask))))
683     (if (= nkeys 1)
684         (logand mask result)
685         (the fixnum (1+ (logand mask result))))))
686 \f
687 ;;;  NIL              means nothing so far, no actual arg info has NILs
688 ;;;                in the metatype
689 ;;;  CLASS          seen all sorts of metaclasses
690 ;;;                (specifically, more than one of the next 4 values)
691 ;;;  T          means everything so far is the class T
692 ;;;  STANDARD-CLASS   seen only standard classes
693 ;;;  BUILT-IN-CLASS   seen only built in classes
694 ;;;  STRUCTURE-CLASS  seen only structure classes
695 (defun raise-metatype (metatype new-specializer)
696   (let ((slot      (find-class 'slot-class))
697         (std       (find-class 'std-class))
698         (standard  (find-class 'standard-class))
699         (fsc       (find-class 'funcallable-standard-class))
700         (structure (find-class 'structure-class))
701         (built-in  (find-class 'built-in-class)))
702     (flet ((specializer->metatype (x)
703              (let ((meta-specializer
704                      (if (eq *boot-state* 'complete)
705                          (class-of (specializer-class x))
706                          (class-of x))))
707                (cond ((eq x *the-class-t*) t)
708                      ((*subtypep meta-specializer std)
709                       'standard-instance)
710                      ((*subtypep meta-specializer standard)
711                       'standard-instance)
712                      ((*subtypep meta-specializer fsc)
713                       'standard-instance)
714                      ((*subtypep meta-specializer structure)
715                       'structure-instance)
716                      ((*subtypep meta-specializer built-in)
717                       'built-in-instance)
718                      ((*subtypep meta-specializer slot)
719                       'slot-instance)
720                      (t (error "PCL cannot handle the specializer ~S (meta-specializer ~S)."
721                                new-specializer
722                                meta-specializer))))))
723       ;; We implement the following table. The notation is
724       ;; that X and Y are distinct meta specializer names.
725       ;;
726       ;;   NIL    <anything>    ===>  <anything>
727       ;;    X      X        ===>      X
728       ;;    X      Y        ===>    CLASS
729       (let ((new-metatype (specializer->metatype new-specializer)))
730         (cond ((eq new-metatype 'slot-instance) 'class)
731               ((null metatype) new-metatype)
732               ((eq metatype new-metatype) new-metatype)
733               (t 'class))))))
734
735 (defmacro with-dfun-wrappers ((args metatypes)
736                               (dfun-wrappers invalid-wrapper-p
737                                              &optional wrappers classes types)
738                               invalid-arguments-form
739                               &body body)
740   `(let* ((args-tail ,args) (,invalid-wrapper-p nil) (invalid-arguments-p nil)
741           (,dfun-wrappers nil) (dfun-wrappers-tail nil)
742           ,@(when wrappers
743               `((wrappers-rev nil) (types-rev nil) (classes-rev nil))))
744      (dolist (mt ,metatypes)
745        (unless args-tail
746          (setq invalid-arguments-p t)
747          (return nil))
748        (let* ((arg (pop args-tail))
749               (wrapper nil)
750               ,@(when wrappers
751                   `((class *the-class-t*)
752                     (type 't))))
753          (unless (eq mt 't)
754            (setq wrapper (wrapper-of arg))
755            (when (invalid-wrapper-p wrapper)
756              (setq ,invalid-wrapper-p t)
757              (setq wrapper (check-wrapper-validity arg)))
758            (cond ((null ,dfun-wrappers)
759                   (setq ,dfun-wrappers wrapper))
760                  ((not (consp ,dfun-wrappers))
761                   (setq dfun-wrappers-tail (list wrapper))
762                   (setq ,dfun-wrappers (cons ,dfun-wrappers dfun-wrappers-tail)))
763                  (t
764                   (let ((new-dfun-wrappers-tail (list wrapper)))
765                     (setf (cdr dfun-wrappers-tail) new-dfun-wrappers-tail)
766                     (setf dfun-wrappers-tail new-dfun-wrappers-tail))))
767            ,@(when wrappers
768                `((setq class (wrapper-class* wrapper))
769                  (setq type `(class-eq ,class)))))
770          ,@(when wrappers
771              `((push wrapper wrappers-rev)
772                (push class classes-rev)
773                (push type types-rev)))))
774      (if invalid-arguments-p
775          ,invalid-arguments-form
776          (let* (,@(when wrappers
777                     `((,wrappers (nreverse wrappers-rev))
778                       (,classes (nreverse classes-rev))
779                       (,types (mapcar #'(lambda (class)
780                                           `(class-eq ,class))
781                                       ,classes)))))
782            ,@body))))
783 \f
784 ;;;; some support stuff for getting a hold of symbols that we need when
785 ;;;; building the discriminator codes. It's OK for these to be interned
786 ;;;; symbols because we don't capture any user code in the scope in which
787 ;;;; these symbols are bound.
788
789 (defvar *dfun-arg-symbols* '(.ARG0. .ARG1. .ARG2. .ARG3.))
790
791 (defun dfun-arg-symbol (arg-number)
792   (or (nth arg-number (the list *dfun-arg-symbols*))
793       (intern (format nil ".ARG~A." arg-number) *pcl-package*)))
794
795 (defvar *slot-vector-symbols* '(.SLOTS0. .SLOTS1. .SLOTS2. .SLOTS3.))
796
797 (defun slot-vector-symbol (arg-number)
798   (or (nth arg-number (the list *slot-vector-symbols*))
799       (intern (format nil ".SLOTS~A." arg-number) *pcl-package*)))
800
801 (defun make-dfun-lambda-list (metatypes applyp)
802   (gathering1 (collecting)
803     (iterate ((i (interval :from 0))
804               (s (list-elements metatypes)))
805       (progn s)
806       (gather1 (dfun-arg-symbol i)))
807     (when applyp
808       (gather1 '&rest)
809       (gather1 '.dfun-rest-arg.))))
810
811 (defun make-dlap-lambda-list (metatypes applyp)
812   (gathering1 (collecting)
813     (iterate ((i (interval :from 0))
814               (s (list-elements metatypes)))
815       (progn s)
816       (gather1 (dfun-arg-symbol i)))
817     (when applyp
818       (gather1 '&rest))))
819
820 (defun make-emf-call (metatypes applyp fn-variable &optional emf-type)
821   (let ((required
822          (gathering1 (collecting)
823             (iterate ((i (interval :from 0))
824                       (s (list-elements metatypes)))
825               (progn s)
826               (gather1 (dfun-arg-symbol i))))))
827     `(,(if (eq emf-type 'fast-method-call)
828            'invoke-effective-method-function-fast
829            'invoke-effective-method-function)
830       ,fn-variable ,applyp ,@required ,@(when applyp `(.dfun-rest-arg.)))))
831
832 (defun make-dfun-call (metatypes applyp fn-variable)
833   (let ((required
834           (gathering1 (collecting)
835             (iterate ((i (interval :from 0))
836                       (s (list-elements metatypes)))
837               (progn s)
838               (gather1 (dfun-arg-symbol i))))))
839     (if applyp
840         `(function-apply   ,fn-variable ,@required .dfun-rest-arg.)
841         `(function-funcall ,fn-variable ,@required))))
842
843 (defun make-dfun-arg-list (metatypes applyp)
844   (let ((required
845           (gathering1 (collecting)
846             (iterate ((i (interval :from 0))
847                       (s (list-elements metatypes)))
848               (progn s)
849               (gather1 (dfun-arg-symbol i))))))
850     (if applyp
851         `(list* ,@required .dfun-rest-arg.)
852         `(list ,@required))))
853
854 (defun make-fast-method-call-lambda-list (metatypes applyp)
855   (gathering1 (collecting)
856     (gather1 '.pv-cell.)
857     (gather1 '.next-method-call.)
858     (iterate ((i (interval :from 0))
859               (s (list-elements metatypes)))
860       (progn s)
861       (gather1 (dfun-arg-symbol i)))
862     (when applyp
863       (gather1 '.dfun-rest-arg.))))
864 \f
865 ;;;; a comment from some PCL implementor:
866 ;;;;     Its too bad Common Lisp compilers freak out when you have a
867 ;;;;   DEFUN with a lot of LABELS in it. If I could do that I could
868 ;;;;   make this code much easier to read and work with.
869 ;;;;     Ahh Scheme...
870 ;;;;     In the absence of that, the following little macro makes the
871 ;;;;   code that follows a little bit more reasonable. I would like to
872 ;;;;   add that having to practically write my own compiler in order to
873 ;;;;   get just this simple thing is something of a drag.
874 ;;;;
875 ;;;; KLUDGE: Maybe we could actually implement this as LABELS now,
876 ;;;; since AFAIK CMU CL doesn't freak out when you have a DEFUN with a
877 ;;;; lot of LABELS in it (and if it does we can fix it instead of
878 ;;;; working around it). -- WHN 19991204
879
880 (eval-when (:compile-toplevel :load-toplevel :execute)
881
882 (defvar *cache* nil)
883
884 ;;; FIXME: should be undefined after bootstrapping
885 (defparameter *local-cache-functions*
886   '((cache () .cache.)
887     (nkeys () (cache-nkeys .cache.))
888     (line-size () (cache-line-size .cache.))
889     (vector () (cache-vector .cache.))
890     (valuep () (cache-valuep .cache.))
891     (nlines () (cache-nlines .cache.))
892     (max-location () (cache-max-location .cache.))
893     (limit-fn () (cache-limit-fn .cache.))
894     (size () (cache-size .cache.))
895     (mask () (cache-mask .cache.))
896     (field () (cache-field .cache.))
897     (overflow () (cache-overflow .cache.))
898
899     ;; Return T IFF this cache location is reserved. The only time
900     ;; this is true is for line number 0 of an nkeys=1 cache.
901     (line-reserved-p (line)
902       (declare (fixnum line))
903       (and (= (nkeys) 1)
904            (= line 0)))
905     (location-reserved-p (location)
906       (declare (fixnum location))
907       (and (= (nkeys) 1)
908            (= location 0)))
909     ;; Given a line number, return the cache location. This is the
910     ;; value that is the second argument to cache-vector-ref. Basically,
911     ;; this deals with the offset of nkeys>1 caches and multiplies
912     ;; by line size.
913     (line-location (line)
914       (declare (fixnum line))
915       (when (line-reserved-p line)
916         (error "Line is reserved."))
917       (if (= (nkeys) 1)
918           (the fixnum (* line (line-size)))
919           (the fixnum (1+ (the fixnum (* line (line-size)))))))
920
921     ;; Given a cache location, return the line. This is the inverse
922     ;; of LINE-LOCATION.
923     (location-line (location)
924       (declare (fixnum location))
925       (if (= (nkeys) 1)
926           (floor location (line-size))
927           (floor (the fixnum (1- location)) (line-size))))
928
929     ;; Given a line number, return the wrappers stored at that line.
930     ;; As usual, if nkeys=1, this returns a single value. Only when
931     ;; nkeys>1 does it return a list. An error is signalled if the
932     ;; line is reserved.
933     (line-wrappers (line)
934       (declare (fixnum line))
935       (when (line-reserved-p line) (error "Line is reserved."))
936       (location-wrappers (line-location line)))
937     (location-wrappers (location) ; avoid multiplies caused by line-location
938       (declare (fixnum location))
939       (if (= (nkeys) 1)
940           (cache-vector-ref (vector) location)
941           (let ((list (make-list (nkeys)))
942                 (vector (vector)))
943             (declare (simple-vector vector))
944             (dotimes-fixnum (i (nkeys) list)
945               (setf (nth i list) (cache-vector-ref vector (+ location i)))))))
946
947     ;; Given a line number, return true IFF the line's
948     ;; wrappers are the same as wrappers.
949     (line-matches-wrappers-p (line wrappers)
950       (declare (fixnum line))
951       (and (not (line-reserved-p line))
952            (location-matches-wrappers-p (line-location line) wrappers)))
953     (location-matches-wrappers-p (loc wrappers) ; must not be reserved
954       (declare (fixnum loc))
955       (let ((cache-vector (vector)))
956         (declare (simple-vector cache-vector))
957         (if (= (nkeys) 1)
958             (eq wrappers (cache-vector-ref cache-vector loc))
959             (dotimes-fixnum (i (nkeys) t)
960               (unless (eq (pop wrappers)
961                           (cache-vector-ref cache-vector (+ loc i)))
962                 (return nil))))))
963
964     ;; Given a line number, return the value stored at that line.
965     ;; If valuep is NIL, this returns NIL. As with line-wrappers,
966     ;; an error is signalled if the line is reserved.
967     (line-value (line)
968       (declare (fixnum line))
969       (when (line-reserved-p line) (error "Line is reserved."))
970       (location-value (line-location line)))
971     (location-value (loc)
972       (declare (fixnum loc))
973       (and (valuep)
974            (cache-vector-ref (vector) (+ loc (nkeys)))))
975
976     ;; Given a line number, return true iff that line has data in
977     ;; it. The state of the wrappers stored in the line is not
978     ;; checked. An error is signalled if line is reserved.
979     (line-full-p (line)
980       (when (line-reserved-p line) (error "Line is reserved."))
981       (not (null (cache-vector-ref (vector) (line-location line)))))
982
983     ;; Given a line number, return true iff the line is full and
984     ;; there are no invalid wrappers in the line, and the line's
985     ;; wrappers are different from wrappers.
986     ;; An error is signalled if the line is reserved.
987     (line-valid-p (line wrappers)
988       (declare (fixnum line))
989       (when (line-reserved-p line) (error "Line is reserved."))
990       (location-valid-p (line-location line) wrappers))
991     (location-valid-p (loc wrappers)
992       (declare (fixnum loc))
993       (let ((cache-vector (vector))
994             (wrappers-mismatch-p (null wrappers)))
995         (declare (simple-vector cache-vector))
996         (dotimes-fixnum (i (nkeys) wrappers-mismatch-p)
997           (let ((wrapper (cache-vector-ref cache-vector (+ loc i))))
998             (when (or (null wrapper)
999                       (invalid-wrapper-p wrapper))
1000               (return nil))
1001             (unless (and wrappers
1002                          (eq wrapper
1003                              (if (consp wrappers) (pop wrappers) wrappers)))
1004               (setq wrappers-mismatch-p t))))))
1005
1006     ;; how many unreserved lines separate line-1 and line-2
1007     (line-separation (line-1 line-2)
1008      (declare (fixnum line-1 line-2))
1009      (let ((diff (the fixnum (- line-2 line-1))))
1010        (declare (fixnum diff))
1011        (when (minusp diff)
1012          (setq diff (+ diff (nlines)))
1013          (when (line-reserved-p 0)
1014            (setq diff (1- diff))))
1015        diff))
1016
1017     ;; Given a cache line, get the next cache line. This will not
1018     ;; return a reserved line.
1019     (next-line (line)
1020      (declare (fixnum line))
1021      (if (= line (the fixnum (1- (nlines))))
1022          (if (line-reserved-p 0) 1 0)
1023          (the fixnum (1+ line))))
1024     (next-location (loc)
1025       (declare (fixnum loc))
1026       (if (= loc (max-location))
1027           (if (= (nkeys) 1)
1028               (line-size)
1029               1)
1030           (the fixnum (+ loc (line-size)))))
1031
1032     ;; Given a line which has a valid entry in it, this will return
1033     ;; the primary cache line of the wrappers in that line. We just
1034     ;; call COMPUTE-PRIMARY-CACHE-LOCATION-FROM-LOCATION, this is an
1035     ;; easier packaging up of the call to it.
1036     (line-primary (line)
1037       (declare (fixnum line))
1038       (location-line (line-primary-location line)))
1039     (line-primary-location (line)
1040      (declare (fixnum line))
1041      (compute-primary-cache-location-from-location
1042        (cache) (line-location line)))))
1043
1044 (defmacro with-local-cache-functions ((cache) &body body)
1045   `(let ((.cache. ,cache))
1046      (declare (type cache .cache.))
1047      (macrolet ,(mapcar #'(lambda (fn)
1048                             `(,(car fn) ,(cadr fn)
1049                                 `(let (,,@(mapcar #'(lambda (var)
1050                                                       ``(,',var ,,var))
1051                                                   (cadr fn)))
1052                                     ,@',(cddr fn))))
1053                         *local-cache-functions*)
1054        ,@body)))
1055
1056 ) ; EVAL-WHEN
1057 \f
1058 ;;; Here is where we actually fill, recache and expand caches.
1059 ;;;
1060 ;;; The functions FILL-CACHE and PROBE-CACHE are the ONLY external
1061 ;;; entrypoints into this code.
1062 ;;;
1063 ;;; FILL-CACHE returns 1 value: a new cache
1064 ;;;
1065 ;;;   a wrapper field number
1066 ;;;   a cache
1067 ;;;   a mask
1068 ;;;   an absolute cache size (the size of the actual vector)
1069 ;;; It tries to re-adjust the cache every time it makes a new fill.
1070 ;;; The intuition here is that we want uniformity in the number of
1071 ;;; probes needed to find an entry. Furthermore, adjusting has the
1072 ;;; nice property of throwing out any entries that are invalid.
1073 (defvar *cache-expand-threshold* 1.25)
1074
1075 (defun fill-cache (cache wrappers value &optional free-cache-p)
1076
1077   ;; FILL-CACHE won't return if WRAPPERS is nil, might as well check..
1078   (unless wrappers
1079     (error "fill-cache: WRAPPERS arg is NIL!"))
1080
1081   (or (fill-cache-p nil cache wrappers value)
1082       (and (< (ceiling (* (cache-count cache) 1.25))
1083               (if (= (cache-nkeys cache) 1)
1084                   (1- (cache-nlines cache))
1085                   (cache-nlines cache)))
1086            (adjust-cache cache wrappers value free-cache-p))
1087       (expand-cache cache wrappers value free-cache-p)))
1088
1089 (defvar *check-cache-p* nil)
1090
1091 (defmacro maybe-check-cache (cache)
1092   `(progn
1093      (when *check-cache-p*
1094        (check-cache ,cache))
1095      ,cache))
1096
1097 (defun check-cache (cache)
1098   (with-local-cache-functions (cache)
1099     (let ((location (if (= (nkeys) 1) 0 1))
1100           (limit (funcall (limit-fn) (nlines))))
1101       (dotimes-fixnum (i (nlines) cache)
1102         (when (and (not (location-reserved-p location))
1103                    (line-full-p i))
1104           (let* ((home-loc (compute-primary-cache-location-from-location
1105                             cache location))
1106                  (home (location-line (if (location-reserved-p home-loc)
1107                                           (next-location home-loc)
1108                                           home-loc)))
1109                  (sep (when home (line-separation home i))))
1110             (when (and sep (> sep limit))
1111               (error "bad cache ~S ~@
1112                       value at location ~D: ~D lines from its home. The limit is ~D."
1113                      cache location sep limit))))
1114         (setq location (next-location location))))))
1115
1116 (defun probe-cache (cache wrappers &optional default limit-fn)
1117   ;;(declare (values value))
1118   (unless wrappers
1119     ;; FIXME: This and another earlier test on a WRAPPERS arg can
1120     ;; be compact assertoids.
1121     (error "WRAPPERS arg is NIL!"))
1122   (with-local-cache-functions (cache)
1123     (let* ((location (compute-primary-cache-location (field) (mask) wrappers))
1124            (limit (funcall (or limit-fn (limit-fn)) (nlines))))
1125       (declare (fixnum location limit))
1126       (when (location-reserved-p location)
1127         (setq location (next-location location)))
1128       (dotimes-fixnum (i (1+ limit))
1129         (when (location-matches-wrappers-p location wrappers)
1130           (return-from probe-cache (or (not (valuep))
1131                                        (location-value location))))
1132         (setq location (next-location location)))
1133       (dolist (entry (overflow))
1134         (when (equal (car entry) wrappers)
1135           (return-from probe-cache (or (not (valuep))
1136                                        (cdr entry)))))
1137       default)))
1138
1139 (defun map-cache (function cache &optional set-p)
1140   (with-local-cache-functions (cache)
1141     (let ((set-p (and set-p (valuep))))
1142       (dotimes-fixnum (i (nlines) cache)
1143         (unless (or (line-reserved-p i) (not (line-valid-p i nil)))
1144           (let ((value (funcall function (line-wrappers i) (line-value i))))
1145             (when set-p
1146               (setf (cache-vector-ref (vector) (+ (line-location i) (nkeys)))
1147                     value)))))
1148       (dolist (entry (overflow))
1149         (let ((value (funcall function (car entry) (cdr entry))))
1150           (when set-p
1151             (setf (cdr entry) value))))))
1152   cache)
1153
1154 (defun cache-count (cache)
1155   (with-local-cache-functions (cache)
1156     (let ((count 0))
1157       (declare (fixnum count))
1158       (dotimes-fixnum (i (nlines) count)
1159         (unless (line-reserved-p i)
1160           (when (line-full-p i)
1161             (incf count)))))))
1162
1163 (defun entry-in-cache-p (cache wrappers value)
1164   (declare (ignore value))
1165   (with-local-cache-functions (cache)
1166     (dotimes-fixnum (i (nlines))
1167       (unless (line-reserved-p i)
1168         (when (equal (line-wrappers i) wrappers)
1169           (return t))))))
1170
1171 ;;; returns T or NIL
1172 (defun fill-cache-p (forcep cache wrappers value)
1173   (with-local-cache-functions (cache)
1174     (let* ((location (compute-primary-cache-location (field) (mask) wrappers))
1175            (primary (location-line location)))
1176       (declare (fixnum location primary))
1177       (multiple-value-bind (free emptyp)
1178           (find-free-cache-line primary cache wrappers)
1179         (when (or forcep emptyp)
1180           (when (not emptyp)
1181             (push (cons (line-wrappers free) (line-value free))
1182                   (cache-overflow cache)))
1183           ;;(fill-line free wrappers value)
1184           (let ((line free))
1185             (declare (fixnum line))
1186             (when (line-reserved-p line)
1187               (error "attempt to fill a reserved line"))
1188             (let ((loc (line-location line))
1189                   (cache-vector (vector)))
1190               (declare (fixnum loc) (simple-vector cache-vector))
1191               (cond ((= (nkeys) 1)
1192                      (setf (cache-vector-ref cache-vector loc) wrappers)
1193                      (when (valuep)
1194                        (setf (cache-vector-ref cache-vector (1+ loc)) value)))
1195                     (t
1196                      (let ((i 0))
1197                        (declare (fixnum i))
1198                        (dolist (w wrappers)
1199                          (setf (cache-vector-ref cache-vector (+ loc i)) w)
1200                          (setq i (the fixnum (1+ i)))))
1201                      (when (valuep)
1202                        (setf (cache-vector-ref cache-vector (+ loc (nkeys)))
1203                              value))))
1204               (maybe-check-cache cache))))))))
1205
1206 (defun fill-cache-from-cache-p (forcep cache from-cache from-line)
1207   (declare (fixnum from-line))
1208   (with-local-cache-functions (cache)
1209     (let ((primary (location-line
1210                     (compute-primary-cache-location-from-location
1211                      cache (line-location from-line) from-cache))))
1212       (declare (fixnum primary))
1213       (multiple-value-bind (free emptyp)
1214           (find-free-cache-line primary cache)
1215         (when (or forcep emptyp)
1216           (when (not emptyp)
1217             (push (cons (line-wrappers free) (line-value free))
1218                   (cache-overflow cache)))
1219           ;;(transfer-line from-cache-vector from-line cache-vector free)
1220           (let ((from-cache-vector (cache-vector from-cache))
1221                 (to-cache-vector (vector))
1222                 (to-line free))
1223             (declare (fixnum to-line))
1224             (if (line-reserved-p to-line)
1225                 (error "transferring something into a reserved cache line")
1226                 (let ((from-loc (line-location from-line))
1227                       (to-loc (line-location to-line)))
1228                   (declare (fixnum from-loc to-loc))
1229                   (modify-cache to-cache-vector
1230                                 (dotimes-fixnum (i (line-size))
1231                                   (setf (cache-vector-ref to-cache-vector
1232                                                           (+ to-loc i))
1233                                         (cache-vector-ref from-cache-vector
1234                                                           (+ from-loc i)))))))
1235             (maybe-check-cache cache)))))))
1236
1237 ;;; Returns NIL or (values <field> <cache-vector>)
1238 ;;;
1239 ;;; This is only called when it isn't possible to put the entry in the
1240 ;;; cache the easy way. That is, this function assumes that
1241 ;;; FILL-CACHE-P has been called as returned NIL.
1242 ;;;
1243 ;;; If this returns NIL, it means that it wasn't possible to find a
1244 ;;; wrapper field for which all of the entries could be put in the
1245 ;;; cache (within the limit).
1246 (defun adjust-cache (cache wrappers value free-old-cache-p)
1247   (with-local-cache-functions (cache)
1248     (let ((ncache (get-cache-from-cache cache (nlines) (field))))
1249       (do ((nfield (cache-field ncache) (next-wrapper-cache-number-index nfield)))
1250           ((null nfield) (free-cache ncache) nil)
1251         (setf (cache-field ncache) nfield)
1252         (labels ((try-one-fill-from-line (line)
1253                    (fill-cache-from-cache-p nil ncache cache line))
1254                  (try-one-fill (wrappers value)
1255                    (fill-cache-p nil ncache wrappers value)))
1256           (if (and (dotimes-fixnum (i (nlines) t)
1257                      (when (and (null (line-reserved-p i))
1258                                 (line-valid-p i wrappers))
1259                        (unless (try-one-fill-from-line i) (return nil))))
1260                    (dolist (wrappers+value (cache-overflow cache) t)
1261                      (unless (try-one-fill (car wrappers+value) (cdr wrappers+value))
1262                        (return nil)))
1263                    (try-one-fill wrappers value))
1264               (progn (when free-old-cache-p (free-cache cache))
1265                      (return (maybe-check-cache ncache)))
1266               (flush-cache-vector-internal (cache-vector ncache))))))))
1267
1268 ;;; returns: (values <cache>)
1269 (defun expand-cache (cache wrappers value free-old-cache-p)
1270   ;;(declare (values cache))
1271   (with-local-cache-functions (cache)
1272     (let ((ncache (get-cache-from-cache cache (* (nlines) 2))))
1273       (labels ((do-one-fill-from-line (line)
1274                  (unless (fill-cache-from-cache-p nil ncache cache line)
1275                    (do-one-fill (line-wrappers line) (line-value line))))
1276                (do-one-fill (wrappers value)
1277                  (setq ncache (or (adjust-cache ncache wrappers value t)
1278                                   (fill-cache-p t ncache wrappers value))))
1279                (try-one-fill (wrappers value)
1280                  (fill-cache-p nil ncache wrappers value)))
1281         (dotimes-fixnum (i (nlines))
1282           (when (and (null (line-reserved-p i))
1283                      (line-valid-p i wrappers))
1284             (do-one-fill-from-line i)))
1285         (dolist (wrappers+value (cache-overflow cache))
1286           (unless (try-one-fill (car wrappers+value) (cdr wrappers+value))
1287             (do-one-fill (car wrappers+value) (cdr wrappers+value))))
1288         (unless (try-one-fill wrappers value)
1289           (do-one-fill wrappers value))
1290         (when free-old-cache-p (free-cache cache))
1291         (maybe-check-cache ncache)))))
1292 \f
1293 ;;; This is the heart of the cache filling mechanism. It implements
1294 ;;; the decisions about where entries are placed.
1295 ;;;
1296 ;;; Find a line in the cache at which a new entry can be inserted.
1297 ;;;
1298 ;;;   <line>
1299 ;;;   <empty?>     is <line> in fact empty?
1300 (defun find-free-cache-line (primary cache &optional wrappers)
1301   ;;(declare (values line empty?))
1302   (declare (fixnum primary))
1303   (with-local-cache-functions (cache)
1304     (when (line-reserved-p primary) (setq primary (next-line primary)))
1305     (let ((limit (funcall (limit-fn) (nlines)))
1306           (wrappedp nil)
1307           (lines nil)
1308           (p primary) (s primary))
1309       (declare (fixnum p s limit))
1310       (block find-free
1311         (loop
1312          ;; Try to find a free line starting at <s>. <p> is the
1313          ;; primary line of the entry we are finding a free
1314          ;; line for, it is used to compute the separations.
1315          (do* ((line s (next-line line))
1316                (nsep (line-separation p s) (1+ nsep)))
1317               (())
1318            (declare (fixnum line nsep))
1319            (when (null (line-valid-p line wrappers)) ;If this line is empty or
1320              (push line lines)          ;invalid, just use it.
1321              (return-from find-free))
1322            (when (and wrappedp (>= line primary))
1323              ;; have gone all the way around the cache, time to quit
1324              (return-from find-free-cache-line (values primary nil)))
1325            (let ((osep (line-separation (line-primary line) line)))
1326              (when (>= osep limit)
1327                (return-from find-free-cache-line (values primary nil)))
1328              (when (cond ((= nsep limit) t)
1329                          ((= nsep osep) (zerop (random 2)))
1330                          ((> nsep osep) t)
1331                          (t nil))
1332                ;; See whether we can displace what is in this line so that we
1333                ;; can use the line.
1334                (when (= line (the fixnum (1- (nlines)))) (setq wrappedp t))
1335                (setq p (line-primary line))
1336                (setq s (next-line line))
1337                (push line lines)
1338                (return nil)))
1339            (when (= line (the fixnum (1- (nlines)))) (setq wrappedp t)))))
1340       ;; Do all the displacing.
1341       (loop
1342        (when (null (cdr lines)) (return nil))
1343        (let ((dline (pop lines))
1344              (line (car lines)))
1345          (declare (fixnum dline line))
1346          ;;Copy from line to dline (dline is known to be free).
1347          (let ((from-loc (line-location line))
1348                (to-loc (line-location dline))
1349                (cache-vector (vector)))
1350            (declare (fixnum from-loc to-loc) (simple-vector cache-vector))
1351            (modify-cache cache-vector
1352                          (dotimes-fixnum (i (line-size))
1353                            (setf (cache-vector-ref cache-vector
1354                                                    (+ to-loc i))
1355                                  (cache-vector-ref cache-vector
1356                                                    (+ from-loc i)))
1357                            (setf (cache-vector-ref cache-vector
1358                                                    (+ from-loc i))
1359                                  nil))))))
1360       (values (car lines) t))))
1361
1362 (defun default-limit-fn (nlines)
1363   (case nlines
1364     ((1 2 4) 1)
1365     ((8 16)  4)
1366     (otherwise 6)))
1367
1368 (defvar *empty-cache* (make-cache)) ; for defstruct slot initial value forms
1369 \f
1370 ;;; Pre-allocate generic function caches. The hope is that this will
1371 ;;; put them nicely together in memory, and that that may be a win. Of
1372 ;;; course the first GC copy will probably blow that out, this really
1373 ;;; wants to be wrapped in something that declares the area static.
1374 ;;;
1375 ;;; This preallocation only creates about 25% more caches than PCL
1376 ;;; itself uses. Some ports may want to preallocate some more of
1377 ;;; these.
1378 ;;;
1379 ;;; KLUDGE: Isn't something very similar going on in precom1.lisp? Do
1380 ;;; we need it both here and there? Why? -- WHN 19991203
1381 (eval-when (:load-toplevel)
1382   (dolist (n-size '((1 513)(3 257)(3 129)(14 128)(6 65)(2 64)(7 33)(16 32)
1383                     (16 17)(32 16)(64 9)(64 8)(6 5)(128 4)(35 2)))
1384     (let ((n (car n-size))
1385           (size (cadr n-size)))
1386       (mapcar #'free-cache-vector
1387               (mapcar #'get-cache-vector
1388                       (make-list n :initial-element size))))))
1389
1390 (defun caches-to-allocate ()
1391   (sort (let ((l nil))
1392           (maphash #'(lambda (size entry)
1393                        (push (list (car entry) size) l))
1394                    sb-pcl::*free-caches*)
1395           l)
1396         #'>
1397         :key #'cadr))