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