0.8pre.2
[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   (with-pcl-lock
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   `(with-pcl-lock
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 #.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 ;;; Return a cache that has had FLUSH-CACHE-VECTOR-INTERNAL called on
147 ;;; it. This returns a cache of exactly the size requested, it won't
148 ;;; ever return a larger cache.
149 (defun get-cache-vector (size)
150   (flush-cache-vector-internal (make-array size)))
151   
152 \f
153 ;;;; wrapper cache numbers
154
155 ;;; The constant WRAPPER-CACHE-NUMBER-ADDS-OK controls the number of
156 ;;; non-zero bits wrapper cache numbers will have.
157 ;;;
158 ;;; The value of this constant is the number of wrapper cache numbers
159 ;;; which can be added and still be certain the result will be a
160 ;;; fixnum. This is used by all the code that computes primary cache
161 ;;; locations from multiple wrappers.
162 ;;;
163 ;;; The value of this constant is used to derive the next two which
164 ;;; are the forms of this constant which it is more convenient for the
165 ;;; runtime code to use.
166 (defconstant wrapper-cache-number-length
167   (integer-length layout-clos-hash-max))
168 (defconstant wrapper-cache-number-mask layout-clos-hash-max)
169 (defconstant wrapper-cache-number-adds-ok
170   (truncate most-positive-fixnum layout-clos-hash-max))
171 \f
172 ;;;; wrappers themselves
173
174 ;;; This caching algorithm requires that wrappers have more than one
175 ;;; wrapper cache number. You should think of these multiple numbers
176 ;;; as being in columns. That is, for a given cache, the same column
177 ;;; of wrapper cache numbers will be used.
178 ;;;
179 ;;; If at some point the cache distribution of a cache gets bad, the
180 ;;; cache can be rehashed by switching to a different column.
181 ;;;
182 ;;; The columns are referred to by field number which is that number
183 ;;; which, when used as a second argument to wrapper-ref, will return
184 ;;; that column of wrapper cache number.
185 ;;;
186 ;;; This code is written to allow flexibility as to how many wrapper
187 ;;; cache numbers will be in each wrapper, and where they will be
188 ;;; located. It is also set up to allow port specific modifications to
189 ;;; `pack' the wrapper cache numbers on machines where the addressing
190 ;;; modes make that a good idea.
191
192 ;;; In SBCL, as in CMU CL, we want to do type checking as early as
193 ;;; possible; structures help this. The structures are hard-wired to
194 ;;; have a fixed number of cache hash values, and that number must
195 ;;; correspond to the number of cache lines we use.
196 (defconstant wrapper-cache-number-vector-length
197   layout-clos-hash-length)
198
199 (unless (boundp '*the-class-t*)
200   (setq *the-class-t* nil))
201
202 (defmacro wrapper-class (wrapper)
203   `(classoid-pcl-class (layout-classoid ,wrapper)))
204 (defmacro wrapper-no-of-instance-slots (wrapper)
205   `(layout-length ,wrapper))
206
207 (defmacro wrapper-instance-slots-layout (wrapper)
208   `(%wrapper-instance-slots-layout ,wrapper))
209 (defmacro wrapper-class-slots (wrapper)
210   `(%wrapper-class-slots ,wrapper))
211 (defmacro wrapper-cache-number-vector (x) x)
212
213 ;;; This is called in BRAID when we are making wrappers for classes
214 ;;; whose slots are not initialized yet, and which may be built-in
215 ;;; classes. We pass in the class name in addition to the class.
216 (defun boot-make-wrapper (length name &optional class)
217   (let ((found (find-classoid name nil)))
218     (cond
219      (found
220       (unless (classoid-pcl-class found)
221         (setf (classoid-pcl-class found) class))
222       (aver (eq (classoid-pcl-class found) class))
223       (let ((layout (classoid-layout found)))
224         (aver layout)
225         layout))
226      (t
227       (make-wrapper-internal
228        :length length
229        :classoid (make-standard-classoid
230                   :name name :pcl-class class))))))
231
232 ;;; The following variable may be set to a STANDARD-CLASS that has
233 ;;; already been created by the lisp code and which is to be redefined
234 ;;; by PCL. This allows STANDARD-CLASSes to be defined and used for
235 ;;; type testing and dispatch before PCL is loaded.
236 (defvar *pcl-class-boot* nil)
237
238 ;;; In SBCL, as in CMU CL, the layouts (a.k.a wrappers) for built-in
239 ;;; and structure classes already exist when PCL is initialized, so we
240 ;;; don't necessarily always make a wrapper. Also, we help maintain
241 ;;; the mapping between CL:CLASS and SB-KERNEL:CLASSOID objects.
242 (defun make-wrapper (length class)
243   (cond
244    ((typep class 'std-class)
245     (make-wrapper-internal
246      :length length
247      :classoid
248      (let ((owrap (class-wrapper class)))
249        (cond (owrap
250               (layout-classoid owrap))
251              ((*subtypep (class-of class)
252                          *the-class-standard-class*)
253               (cond ((and *pcl-class-boot*
254                           (eq (slot-value class 'name) *pcl-class-boot*))
255                      (let ((found (find-classoid
256                                    (slot-value class 'name))))
257                        (unless (classoid-pcl-class found)
258                          (setf (classoid-pcl-class found) class))
259                        (aver (eq (classoid-pcl-class found) class))
260                        found))
261                     (t
262                      (make-standard-classoid :pcl-class class))))
263              (t
264               (make-random-pcl-classoid :pcl-class class))))))
265    (t
266     (let* ((found (find-classoid (slot-value class 'name)))
267            (layout (classoid-layout found)))
268       (unless (classoid-pcl-class found)
269         (setf (classoid-pcl-class found) class))
270       (aver (eq (classoid-pcl-class found) class))
271       (aver layout)
272       layout))))
273
274 (defconstant +first-wrapper-cache-number-index+ 0)
275
276 (declaim (inline next-wrapper-cache-number-index))
277 (defun next-wrapper-cache-number-index (field-number)
278   (and (< field-number #.(1- wrapper-cache-number-vector-length))
279        (1+ field-number)))
280
281 ;;; FIXME: Why are there two layers here, with one operator trivially
282 ;;; defined in terms of the other? It'd be nice either to have a
283 ;;; comment explaining why the separation is valuable, or to collapse
284 ;;; it into a single layer.
285 ;;;
286 ;;; FIXME (?): These are logically inline functions, but they need to
287 ;;; be SETFable, and for now it seems not worth the trouble to DEFUN
288 ;;; both inline FOO and inline (SETF FOO) for each one instead of a
289 ;;; single macro. Perhaps the best thing would be to make them
290 ;;; immutable (since it seems sort of surprising and gross to be able
291 ;;; to modify hash values) so that they can become inline functions
292 ;;; with no muss or fuss. I (WHN) didn't do this only because I didn't
293 ;;; know whether any code anywhere depends on the values being
294 ;;; modified.
295 (defmacro cache-number-vector-ref (cnv n)
296   `(wrapper-cache-number-vector-ref ,cnv ,n))
297 (defmacro wrapper-cache-number-vector-ref (wrapper n)
298   `(layout-clos-hash ,wrapper ,n))
299
300 (declaim (inline wrapper-class*))
301 (defun wrapper-class* (wrapper)
302   (or (wrapper-class wrapper)
303       (ensure-non-standard-class
304        (classoid-name (layout-classoid wrapper)))))
305
306 ;;; The wrapper cache machinery provides general mechanism for
307 ;;; trapping on the next access to any instance of a given class. This
308 ;;; mechanism is used to implement the updating of instances when the
309 ;;; class is redefined (MAKE-INSTANCES-OBSOLETE). The same mechanism
310 ;;; is also used to update generic function caches when there is a
311 ;;; change to the superclasses of a class.
312 ;;;
313 ;;; Basically, a given wrapper can be valid or invalid. If it is
314 ;;; invalid, it means that any attempt to do a wrapper cache lookup
315 ;;; using the wrapper should trap. Also, methods on
316 ;;; SLOT-VALUE-USING-CLASS check the wrapper validity as well. This is
317 ;;; done by calling CHECK-WRAPPER-VALIDITY.
318
319 (declaim (inline invalid-wrapper-p))
320 (defun invalid-wrapper-p (wrapper)
321   (not (null (layout-invalid wrapper))))
322
323 (defvar *previous-nwrappers* (make-hash-table))
324
325 (defun invalidate-wrapper (owrapper state nwrapper)
326   (aver (member state '(:flush :obsolete) :test #'eq))
327   (let ((new-previous ()))
328     ;; First off, a previous call to INVALIDATE-WRAPPER may have
329     ;; recorded OWRAPPER as an NWRAPPER to update to. Since OWRAPPER
330     ;; is about to be invalid, it no longer makes sense to update to
331     ;; it.
332     ;;
333     ;; We go back and change the previously invalidated wrappers so
334     ;; that they will now update directly to NWRAPPER. This
335     ;; corresponds to a kind of transitivity of wrapper updates.
336     (dolist (previous (gethash owrapper *previous-nwrappers*))
337       (when (eq state :obsolete)
338         (setf (car previous) :obsolete))
339       (setf (cadr previous) nwrapper)
340       (push previous new-previous))
341
342     (let ((ocnv (wrapper-cache-number-vector owrapper)))
343       (dotimes (i layout-clos-hash-length)
344         (setf (cache-number-vector-ref ocnv i) 0)))
345
346     (push (setf (layout-invalid owrapper) (list state nwrapper))
347           new-previous)
348
349     (setf (gethash owrapper *previous-nwrappers*) ()
350           (gethash nwrapper *previous-nwrappers*) new-previous)))
351
352 (defun check-wrapper-validity (instance)
353   (let* ((owrapper (wrapper-of instance))
354          (state (layout-invalid owrapper)))
355     (if (null state)
356         owrapper
357         (ecase (car state)
358           (:flush
359            (flush-cache-trap owrapper (cadr state) instance))
360           (:obsolete
361            (obsolete-instance-trap owrapper (cadr state) instance))))))
362
363 (declaim (inline check-obsolete-instance))
364 (defun check-obsolete-instance (instance)
365   (when (invalid-wrapper-p (layout-of instance))
366     (check-wrapper-validity instance)))
367 \f
368
369 (defun get-cache (nkeys valuep limit-fn nlines)
370   (let ((cache (make-cache)))
371     (declare (type cache cache))
372     (multiple-value-bind (cache-mask actual-size line-size nlines)
373         (compute-cache-parameters nkeys valuep nlines)
374       (setf (cache-nkeys cache) nkeys
375             (cache-valuep cache) valuep
376             (cache-nlines cache) nlines
377             (cache-field cache) +first-wrapper-cache-number-index+
378             (cache-limit-fn cache) limit-fn
379             (cache-mask cache) cache-mask
380             (cache-size cache) actual-size
381             (cache-line-size cache) line-size
382             (cache-max-location cache) (let ((line (1- nlines)))
383                                          (if (= nkeys 1)
384                                              (* line line-size)
385                                              (1+ (* line line-size))))
386             (cache-vector cache) (get-cache-vector actual-size)
387             (cache-overflow cache) nil)
388       cache)))
389
390 (defun get-cache-from-cache (old-cache new-nlines
391                              &optional (new-field +first-wrapper-cache-number-index+))
392   (let ((nkeys (cache-nkeys old-cache))
393         (valuep (cache-valuep old-cache))
394         (cache (make-cache)))
395     (declare (type cache cache))
396     (multiple-value-bind (cache-mask actual-size line-size nlines)
397         (if (= new-nlines (cache-nlines old-cache))
398             (values (cache-mask old-cache) (cache-size old-cache)
399                     (cache-line-size old-cache) (cache-nlines old-cache))
400             (compute-cache-parameters nkeys valuep new-nlines))
401       (setf (cache-owner cache) (cache-owner old-cache)
402             (cache-nkeys cache) nkeys
403             (cache-valuep cache) valuep
404             (cache-nlines cache) nlines
405             (cache-field cache) new-field
406             (cache-limit-fn cache) (cache-limit-fn old-cache)
407             (cache-mask cache) cache-mask
408             (cache-size cache) actual-size
409             (cache-line-size cache) line-size
410             (cache-max-location cache) (let ((line (1- nlines)))
411                                          (if (= nkeys 1)
412                                              (* line line-size)
413                                              (1+ (* line line-size))))
414             (cache-vector cache) (get-cache-vector actual-size)
415             (cache-overflow cache) nil)
416       cache)))
417
418 (defun copy-cache (old-cache)
419   (let* ((new-cache (copy-cache-internal old-cache))
420          (size (cache-size old-cache))
421          (old-vector (cache-vector old-cache))
422          (new-vector (get-cache-vector size)))
423     (declare (simple-vector old-vector new-vector))
424     (dotimes-fixnum (i size)
425       (setf (svref new-vector i) (svref old-vector i)))
426     (setf (cache-vector new-cache) new-vector)
427     new-cache))
428
429 (defun compute-line-size (x)
430   (power-of-two-ceiling x))
431
432 (defun compute-cache-parameters (nkeys valuep nlines-or-cache-vector)
433   ;;(declare (values cache-mask actual-size line-size nlines))
434   (declare (fixnum nkeys))
435   (if (= nkeys 1)
436       (let* ((line-size (if valuep 2 1))
437              (cache-size (if (typep nlines-or-cache-vector 'fixnum)
438                              (the fixnum
439                                   (* line-size
440                                      (the fixnum
441                                           (power-of-two-ceiling
442                                             nlines-or-cache-vector))))
443                              (cache-vector-size nlines-or-cache-vector))))
444         (declare (fixnum line-size cache-size))
445         (values (logxor (the fixnum (1- cache-size)) (the fixnum (1- line-size)))
446                 cache-size
447                 line-size
448                 (the (values fixnum t) (floor cache-size line-size))))
449       (let* ((line-size (power-of-two-ceiling (if valuep (1+ nkeys) nkeys)))
450              (cache-size (if (typep nlines-or-cache-vector 'fixnum)
451                              (the fixnum
452                                   (* line-size
453                                      (the fixnum
454                                           (power-of-two-ceiling
455                                             nlines-or-cache-vector))))
456                              (1- (cache-vector-size nlines-or-cache-vector)))))
457         (declare (fixnum line-size cache-size))
458         (values (logxor (the fixnum (1- cache-size)) (the fixnum (1- line-size)))
459                 (the fixnum (1+ cache-size))
460                 line-size
461                 (the (values fixnum t) (floor cache-size line-size))))))
462 \f
463 ;;; the various implementations of computing a primary cache location from
464 ;;; wrappers. Because some implementations of this must run fast there are
465 ;;; several implementations of the same algorithm.
466 ;;;
467 ;;; The algorithm is:
468 ;;;
469 ;;;  SUM       over the wrapper cache numbers,
470 ;;;  ENSURING  that the result is a fixnum
471 ;;;  MASK      the result against the mask argument.
472
473 ;;; The basic functional version. This is used by the cache miss code to
474 ;;; compute the primary location of an entry.
475 (defun compute-primary-cache-location (field mask wrappers)
476
477   (declare (type field-type field) (fixnum mask))
478   (if (not (listp wrappers))
479       (logand mask
480               (the fixnum (wrapper-cache-number-vector-ref wrappers field)))
481       (let ((location 0) (i 0))
482         (declare (fixnum location i))
483         (dolist (wrapper wrappers)
484           ;; First add the cache number of this wrapper to location.
485           (let ((wrapper-cache-number (wrapper-cache-number-vector-ref wrapper
486                                                                        field)))
487             (declare (fixnum wrapper-cache-number))
488             (if (zerop wrapper-cache-number)
489                 (return-from compute-primary-cache-location 0)
490                 (setq location
491                       (the fixnum (+ location wrapper-cache-number)))))
492           ;; Then, if we are working with lots of wrappers, deal with
493           ;; the wrapper-cache-number-mask stuff.
494           (when (and (not (zerop i))
495                      (zerop (mod i wrapper-cache-number-adds-ok)))
496             (setq location
497                   (logand location wrapper-cache-number-mask)))
498           (incf i))
499         (the fixnum (1+ (logand mask location))))))
500
501 ;;; This version is called on a cache line. It fetches the wrappers
502 ;;; from the cache line and determines the primary location. Various
503 ;;; parts of the cache filling code call this to determine whether it
504 ;;; is appropriate to displace a given cache entry.
505 ;;;
506 ;;; If this comes across a wrapper whose CACHE-NO is 0, it returns the
507 ;;; symbol invalid to suggest to its caller that it would be provident
508 ;;; to blow away the cache line in question.
509 (defun compute-primary-cache-location-from-location (to-cache
510                                                      from-location
511                                                      &optional
512                                                      (from-cache to-cache))
513   (declare (type cache to-cache from-cache) (fixnum from-location))
514   (let ((result 0)
515         (cache-vector (cache-vector from-cache))
516         (field (cache-field to-cache))
517         (mask (cache-mask to-cache))
518         (nkeys (cache-nkeys to-cache)))
519     (declare (type field-type field) (fixnum result mask nkeys)
520              (simple-vector cache-vector))
521     (dotimes-fixnum (i nkeys)
522       (let* ((wrapper (cache-vector-ref cache-vector (+ i from-location)))
523              (wcn (wrapper-cache-number-vector-ref wrapper field)))
524         (declare (fixnum wcn))
525         (setq result (+ result wcn)))
526       (when (and (not (zerop i))
527                  (zerop (mod i wrapper-cache-number-adds-ok)))
528         (setq result (logand result wrapper-cache-number-mask))))
529     (if (= nkeys 1)
530         (logand mask result)
531         (the fixnum (1+ (logand mask result))))))
532 \f
533 ;;;  NIL              means nothing so far, no actual arg info has NILs
534 ;;;                in the metatype
535 ;;;  CLASS          seen all sorts of metaclasses
536 ;;;                (specifically, more than one of the next 4 values)
537 ;;;  T          means everything so far is the class T
538 ;;;  STANDARD-CLASS   seen only standard classes
539 ;;;  BUILT-IN-CLASS   seen only built in classes
540 ;;;  STRUCTURE-CLASS  seen only structure classes
541 (defun raise-metatype (metatype new-specializer)
542   (let ((slot      (find-class 'slot-class))
543         (std       (find-class 'std-class))
544         (standard  (find-class 'standard-class))
545         (fsc       (find-class 'funcallable-standard-class))
546         (condition (find-class 'condition-class))
547         (structure (find-class 'structure-class))
548         (built-in  (find-class 'built-in-class)))
549     (flet ((specializer->metatype (x)
550              (let ((meta-specializer
551                      (if (eq *boot-state* 'complete)
552                          (class-of (specializer-class x))
553                          (class-of x))))
554                (cond
555                  ((eq x *the-class-t*) t)
556                  ((*subtypep meta-specializer std) 'standard-instance)
557                  ((*subtypep meta-specializer standard) 'standard-instance)
558                  ((*subtypep meta-specializer fsc) 'standard-instance)
559                  ((*subtypep meta-specializer condition) 'condition-instance)
560                  ((*subtypep meta-specializer structure) 'structure-instance)
561                  ((*subtypep meta-specializer built-in) 'built-in-instance)
562                  ((*subtypep meta-specializer slot) 'slot-instance)
563                  (t (error "~@<PCL cannot handle the specializer ~S ~
564                             (meta-specializer ~S).~@:>"
565                            new-specializer
566                            meta-specializer))))))
567       ;; We implement the following table. The notation is
568       ;; that X and Y are distinct meta specializer names.
569       ;;
570       ;;   NIL    <anything>    ===>  <anything>
571       ;;    X      X        ===>      X
572       ;;    X      Y        ===>    CLASS
573       (let ((new-metatype (specializer->metatype new-specializer)))
574         (cond ((eq new-metatype 'slot-instance) 'class)
575               ((null metatype) new-metatype)
576               ((eq metatype new-metatype) new-metatype)
577               (t 'class))))))
578
579 (defmacro with-dfun-wrappers ((args metatypes)
580                               (dfun-wrappers invalid-wrapper-p
581                                              &optional wrappers classes types)
582                               invalid-arguments-form
583                               &body body)
584   `(let* ((args-tail ,args) (,invalid-wrapper-p nil) (invalid-arguments-p nil)
585           (,dfun-wrappers nil) (dfun-wrappers-tail nil)
586           ,@(when wrappers
587               `((wrappers-rev nil) (types-rev nil) (classes-rev nil))))
588      (dolist (mt ,metatypes)
589        (unless args-tail
590          (setq invalid-arguments-p t)
591          (return nil))
592        (let* ((arg (pop args-tail))
593               (wrapper nil)
594               ,@(when wrappers
595                   `((class *the-class-t*)
596                     (type t))))
597          (unless (eq mt t)
598            (setq wrapper (wrapper-of arg))
599            (when (invalid-wrapper-p wrapper)
600              (setq ,invalid-wrapper-p t)
601              (setq wrapper (check-wrapper-validity arg)))
602            (cond ((null ,dfun-wrappers)
603                   (setq ,dfun-wrappers wrapper))
604                  ((not (consp ,dfun-wrappers))
605                   (setq dfun-wrappers-tail (list wrapper))
606                   (setq ,dfun-wrappers (cons ,dfun-wrappers dfun-wrappers-tail)))
607                  (t
608                   (let ((new-dfun-wrappers-tail (list wrapper)))
609                     (setf (cdr dfun-wrappers-tail) new-dfun-wrappers-tail)
610                     (setf dfun-wrappers-tail new-dfun-wrappers-tail))))
611            ,@(when wrappers
612                `((setq class (wrapper-class* wrapper))
613                  (setq type `(class-eq ,class)))))
614          ,@(when wrappers
615              `((push wrapper wrappers-rev)
616                (push class classes-rev)
617                (push type types-rev)))))
618      (if invalid-arguments-p
619          ,invalid-arguments-form
620          (let* (,@(when wrappers
621                     `((,wrappers (nreverse wrappers-rev))
622                       (,classes (nreverse classes-rev))
623                       (,types (mapcar (lambda (class)
624                                         `(class-eq ,class))
625                                       ,classes)))))
626            ,@body))))
627 \f
628 ;;;; some support stuff for getting a hold of symbols that we need when
629 ;;;; building the discriminator codes. It's OK for these to be interned
630 ;;;; symbols because we don't capture any user code in the scope in which
631 ;;;; these symbols are bound.
632
633 (defvar *dfun-arg-symbols* '(.ARG0. .ARG1. .ARG2. .ARG3.))
634
635 (defun dfun-arg-symbol (arg-number)
636   (or (nth arg-number (the list *dfun-arg-symbols*))
637       (intern (format nil ".ARG~A." arg-number) *pcl-package*)))
638
639 (defvar *slot-vector-symbols* '(.SLOTS0. .SLOTS1. .SLOTS2. .SLOTS3.))
640
641 (defun slot-vector-symbol (arg-number)
642   (or (nth arg-number (the list *slot-vector-symbols*))
643       (intern (format nil ".SLOTS~A." arg-number) *pcl-package*)))
644
645 ;; FIXME: There ought to be a good way to factor out the idiom:
646 ;;
647 ;; (dotimes (i (length metatypes))
648 ;;   (push (dfun-arg-symbol i) lambda-list))
649 ;;
650 ;; used in the following four functions into common code that we can
651 ;; declare inline or something.  --njf 2001-12-20
652 (defun make-dfun-lambda-list (metatypes applyp)
653   (let ((lambda-list nil))
654     (dotimes (i (length metatypes))
655       (push (dfun-arg-symbol i) lambda-list))
656     (when applyp
657       (push '&rest lambda-list)
658       (push '.dfun-rest-arg. lambda-list))
659     (nreverse lambda-list)))
660
661 (defun make-dlap-lambda-list (metatypes applyp)
662   (let ((lambda-list nil))
663     (dotimes (i (length metatypes))
664       (push (dfun-arg-symbol i) lambda-list))
665     ;; FIXME: This is translated directly from the old PCL code.
666     ;; It didn't have a (PUSH '.DFUN-REST-ARG. LAMBDA-LIST) or
667     ;; something similar, so we don't either.  It's hard to see how
668     ;; this could be correct, since &REST wants an argument after
669     ;; it.  This function works correctly because the caller
670     ;; magically tacks on something after &REST.  The calling functions
671     ;; (in dlisp.lisp) should be fixed and this function rewritten.
672     ;; --njf 2001-12-20
673     (when applyp
674       (push '&rest lambda-list))
675     (nreverse lambda-list)))
676
677 ;; FIXME: The next two functions suffer from having a `.DFUN-REST-ARG.'
678 ;; in their lambda lists, but no corresponding `&REST' symbol.  We assume
679 ;; this should be the case by analogy with the previous two functions.
680 ;; It works, and I don't know why.  Check the calling functions and
681 ;; fix these too.  --njf 2001-12-20
682 (defun make-emf-call (metatypes applyp fn-variable &optional emf-type)
683   (let ((required
684          (let ((required nil))
685            (dotimes (i (length metatypes))
686              (push (dfun-arg-symbol i) required))
687            (nreverse required))))
688     `(,(if (eq emf-type 'fast-method-call)
689            'invoke-effective-method-function-fast
690            'invoke-effective-method-function)
691       ,fn-variable ,applyp ,@required ,@(when applyp `(.dfun-rest-arg.)))))
692
693 (defun make-fast-method-call-lambda-list (metatypes applyp)
694   (let ((reversed-lambda-list nil))
695     (push '.pv-cell. reversed-lambda-list)
696     (push '.next-method-call. reversed-lambda-list)
697     (dotimes (i (length metatypes))
698       (push (dfun-arg-symbol i) reversed-lambda-list))
699     (when applyp
700       (push '.dfun-rest-arg. reversed-lambda-list))
701     (nreverse reversed-lambda-list)))
702 \f
703 (defmacro with-local-cache-functions ((cache) &body body)
704   `(let ((.cache. ,cache))
705      (declare (type cache .cache.))
706      (labels ((cache () .cache.)
707               (nkeys () (cache-nkeys .cache.))
708               (line-size () (cache-line-size .cache.))
709               (vector () (cache-vector .cache.))
710               (valuep () (cache-valuep .cache.))
711               (nlines () (cache-nlines .cache.))
712               (max-location () (cache-max-location .cache.))
713               (limit-fn () (cache-limit-fn .cache.))
714               (size () (cache-size .cache.))
715               (mask () (cache-mask .cache.))
716               (field () (cache-field .cache.))
717               (overflow () (cache-overflow .cache.))
718               ;;
719               ;; Return T IFF this cache location is reserved.  The
720               ;; only time this is true is for line number 0 of an
721               ;; nkeys=1 cache.
722               ;;
723               (line-reserved-p (line)
724                 (declare (fixnum line))
725                 (and (= (nkeys) 1)
726                      (= line 0)))
727               ;;
728               (location-reserved-p (location)
729                 (declare (fixnum location))
730                 (and (= (nkeys) 1)
731                      (= location 0)))
732               ;;
733               ;; Given a line number, return the cache location.
734               ;; This is the value that is the second argument to
735               ;; cache-vector-ref.  Basically, this deals with the
736               ;; offset of nkeys>1 caches and multiplies by line
737               ;; size.
738               ;;          
739               (line-location (line)
740                 (declare (fixnum line))
741                 (when (line-reserved-p line)
742                   (error "line is reserved"))
743                 (if (= (nkeys) 1)
744                     (the fixnum (* line (line-size)))
745                     (the fixnum (1+ (the fixnum (* line (line-size)))))))
746               ;;
747               ;; Given a cache location, return the line.  This is
748               ;; the inverse of LINE-LOCATION.
749               ;;          
750               (location-line (location)
751                 (declare (fixnum location))
752                 (if (= (nkeys) 1)
753                     (floor location (line-size))
754                     (floor (the fixnum (1- location)) (line-size))))
755               ;;
756               ;; Given a line number, return the wrappers stored at
757               ;; that line.  As usual, if nkeys=1, this returns a
758               ;; single value.  Only when nkeys>1 does it return a
759               ;; list.  An error is signalled if the line is
760               ;; reserved.
761               ;;
762               (line-wrappers (line)
763                 (declare (fixnum line))
764                 (when (line-reserved-p line) (error "Line is reserved."))
765                 (location-wrappers (line-location line)))
766               ;;
767               (location-wrappers (location) ; avoid multiplies caused by line-location
768                 (declare (fixnum location))
769                 (if (= (nkeys) 1)
770                     (cache-vector-ref (vector) location)
771                     (let ((list (make-list (nkeys)))
772                           (vector (vector)))
773                       (declare (simple-vector vector))
774                       (dotimes (i (nkeys) list)
775                         (declare (fixnum i))
776                         (setf (nth i list)
777                               (cache-vector-ref vector (+ location i)))))))
778               ;;
779               ;; Given a line number, return true IFF the line's
780               ;; wrappers are the same as wrappers.
781               ;;
782               (line-matches-wrappers-p (line wrappers)
783                 (declare (fixnum line))
784                 (and (not (line-reserved-p line))
785                      (location-matches-wrappers-p (line-location line)
786                                                   wrappers)))
787               ;;
788               (location-matches-wrappers-p (loc wrappers) ; must not be reserved
789                 (declare (fixnum loc))
790                 (let ((cache-vector (vector)))
791                   (declare (simple-vector cache-vector))
792                   (if (= (nkeys) 1)
793                       (eq wrappers (cache-vector-ref cache-vector loc))
794                       (dotimes (i (nkeys) t)
795                         (declare (fixnum i))
796                         (unless (eq (pop wrappers)
797                                     (cache-vector-ref cache-vector (+ loc i)))
798                           (return nil))))))
799               ;;
800               ;; Given a line number, return the value stored at that line.
801               ;; If valuep is NIL, this returns NIL.  As with line-wrappers,
802               ;; an error is signalled if the line is reserved.
803               ;; 
804               (line-value (line)
805                 (declare (fixnum line))
806                 (when (line-reserved-p line) (error "Line is reserved."))
807                 (location-value (line-location line)))
808               ;;
809               (location-value (loc)
810                 (declare (fixnum loc))
811                 (and (valuep)
812                      (cache-vector-ref (vector) (+ loc (nkeys)))))
813               ;;
814               ;; Given a line number, return true IFF that line has data in
815               ;; it.  The state of the wrappers stored in the line is not
816               ;; checked.  An error is signalled if line is reserved.
817               (line-full-p (line)
818                 (when (line-reserved-p line) (error "Line is reserved."))
819                 (not (null (cache-vector-ref (vector) (line-location line)))))
820               ;;
821               ;; Given a line number, return true IFF the line is full and
822               ;; there are no invalid wrappers in the line, and the line's
823               ;; wrappers are different from wrappers.
824               ;; An error is signalled if the line is reserved.
825               ;;
826               (line-valid-p (line wrappers)
827                 (declare (fixnum line))
828                 (when (line-reserved-p line) (error "Line is reserved."))
829                 (location-valid-p (line-location line) wrappers))
830               ;;
831               (location-valid-p (loc wrappers)
832                 (declare (fixnum loc))
833                 (let ((cache-vector (vector))
834                       (wrappers-mismatch-p (null wrappers)))
835                   (declare (simple-vector cache-vector))
836                   (dotimes (i (nkeys) wrappers-mismatch-p)
837                     (declare (fixnum i))
838                     (let ((wrapper (cache-vector-ref cache-vector (+ loc i))))
839                       (when (or (null wrapper)
840                                 (invalid-wrapper-p wrapper))
841                         (return nil))
842                       (unless (and wrappers
843                                    (eq wrapper
844                                        (if (consp wrappers)
845                                            (pop wrappers)
846                                            wrappers)))
847                         (setq wrappers-mismatch-p t))))))
848               ;;
849               ;; How many unreserved lines separate line-1 and line-2.
850               ;;
851               (line-separation (line-1 line-2)
852                 (declare (fixnum line-1 line-2))
853                 (let ((diff (the fixnum (- line-2 line-1))))
854                   (declare (fixnum diff))
855                   (when (minusp diff)
856                     (setq diff (+ diff (nlines)))
857                     (when (line-reserved-p 0)
858                       (setq diff (1- diff))))
859                   diff))
860               ;;
861               ;; Given a cache line, get the next cache line.  This will not
862               ;; return a reserved line.
863               ;; 
864               (next-line (line)
865                 (declare (fixnum line))
866                 (if (= line (the fixnum (1- (nlines))))
867                     (if (line-reserved-p 0) 1 0)
868                     (the fixnum (1+ line))))
869               ;;
870               (next-location (loc)
871                 (declare (fixnum loc))
872                 (if (= loc (max-location))
873                     (if (= (nkeys) 1)
874                         (line-size)
875                         1)
876                     (the fixnum (+ loc (line-size)))))
877               ;;
878               ;; Given a line which has a valid entry in it, this
879               ;; will return the primary cache line of the wrappers
880               ;; in that line.  We just call
881               ;; COMPUTE-PRIMARY-CACHE-LOCATION-FROM-LOCATION, this
882               ;; is an easier packaging up of the call to it.
883               ;; 
884               (line-primary (line)
885                 (declare (fixnum line))
886                 (location-line (line-primary-location line)))
887               ;;
888               (line-primary-location (line)
889                 (declare (fixnum line))
890                 (compute-primary-cache-location-from-location
891                  (cache) (line-location line))))
892        (declare (ignorable #'cache #'nkeys #'line-size #'vector #'valuep
893                            #'nlines #'max-location #'limit-fn #'size
894                            #'mask #'field #'overflow #'line-reserved-p
895                            #'location-reserved-p #'line-location
896                            #'location-line #'line-wrappers #'location-wrappers
897                            #'line-matches-wrappers-p
898                            #'location-matches-wrappers-p
899                            #'line-value #'location-value #'line-full-p
900                            #'line-valid-p #'location-valid-p
901                            #'line-separation #'next-line #'next-location
902                            #'line-primary #'line-primary-location))
903        ,@body)))
904 \f
905 ;;; Here is where we actually fill, recache and expand caches.
906 ;;;
907 ;;; The functions FILL-CACHE and PROBE-CACHE are the ONLY external
908 ;;; entrypoints into this code.
909 ;;;
910 ;;; FILL-CACHE returns 1 value: a new cache
911 ;;;
912 ;;;   a wrapper field number
913 ;;;   a cache
914 ;;;   a mask
915 ;;;   an absolute cache size (the size of the actual vector)
916 ;;; It tries to re-adjust the cache every time it makes a new fill.
917 ;;; The intuition here is that we want uniformity in the number of
918 ;;; probes needed to find an entry. Furthermore, adjusting has the
919 ;;; nice property of throwing out any entries that are invalid.
920 (defvar *cache-expand-threshold* 1.25)
921
922 (defun fill-cache (cache wrappers value)
923   ;; FILL-CACHE won't return if WRAPPERS is nil, might as well check..
924   (assert wrappers)
925
926   (or (fill-cache-p nil cache wrappers value)
927       (and (< (ceiling (* (cache-count cache) 1.25))
928               (if (= (cache-nkeys cache) 1)
929                   (1- (cache-nlines cache))
930                   (cache-nlines cache)))
931            (adjust-cache cache wrappers value))
932       (expand-cache cache wrappers value)))
933
934 (defvar *check-cache-p* nil)
935
936 (defmacro maybe-check-cache (cache)
937   `(progn
938      (when *check-cache-p*
939        (check-cache ,cache))
940      ,cache))
941
942 (defun check-cache (cache)
943   (with-local-cache-functions (cache)
944     (let ((location (if (= (nkeys) 1) 0 1))
945           (limit (funcall (limit-fn) (nlines))))
946       (dotimes-fixnum (i (nlines) cache)
947         (when (and (not (location-reserved-p location))
948                    (line-full-p i))
949           (let* ((home-loc (compute-primary-cache-location-from-location
950                             cache location))
951                  (home (location-line (if (location-reserved-p home-loc)
952                                           (next-location home-loc)
953                                           home-loc)))
954                  (sep (when home (line-separation home i))))
955             (when (and sep (> sep limit))
956               (error "bad cache ~S ~@
957                       value at location ~W: ~W lines from its home. The limit is ~W."
958                      cache location sep limit))))
959         (setq location (next-location location))))))
960
961 (defun probe-cache (cache wrappers &optional default limit-fn)
962   ;;(declare (values value))
963   (unless wrappers
964     ;; FIXME: This and another earlier test on a WRAPPERS arg can
965     ;; be compact assertoids.
966     (error "WRAPPERS arg is NIL!"))
967   (with-local-cache-functions (cache)
968     (let* ((location (compute-primary-cache-location (field) (mask) wrappers))
969            (limit (funcall (or limit-fn (limit-fn)) (nlines))))
970       (declare (fixnum location limit))
971       (when (location-reserved-p location)
972         (setq location (next-location location)))
973       (dotimes-fixnum (i (1+ limit))
974         (when (location-matches-wrappers-p location wrappers)
975           (return-from probe-cache (or (not (valuep))
976                                        (location-value location))))
977         (setq location (next-location location)))
978       (dolist (entry (overflow))
979         (when (equal (car entry) wrappers)
980           (return-from probe-cache (or (not (valuep))
981                                        (cdr entry)))))
982       default)))
983
984 (defun map-cache (function cache &optional set-p)
985   (with-local-cache-functions (cache)
986     (let ((set-p (and set-p (valuep))))
987       (dotimes-fixnum (i (nlines) cache)
988         (unless (or (line-reserved-p i) (not (line-valid-p i nil)))
989           (let ((value (funcall function (line-wrappers i) (line-value i))))
990             (when set-p
991               (setf (cache-vector-ref (vector) (+ (line-location i) (nkeys)))
992                     value)))))
993       (dolist (entry (overflow))
994         (let ((value (funcall function (car entry) (cdr entry))))
995           (when set-p
996             (setf (cdr entry) value))))))
997   cache)
998
999 (defun cache-count (cache)
1000   (with-local-cache-functions (cache)
1001     (let ((count 0))
1002       (declare (fixnum count))
1003       (dotimes-fixnum (i (nlines) count)
1004         (unless (line-reserved-p i)
1005           (when (line-full-p i)
1006             (incf count)))))))
1007
1008 (defun entry-in-cache-p (cache wrappers value)
1009   (declare (ignore value))
1010   (with-local-cache-functions (cache)
1011     (dotimes-fixnum (i (nlines))
1012       (unless (line-reserved-p i)
1013         (when (equal (line-wrappers i) wrappers)
1014           (return t))))))
1015
1016 ;;; returns T or NIL
1017 (defun fill-cache-p (forcep cache wrappers value)
1018   (with-local-cache-functions (cache)
1019     (let* ((location (compute-primary-cache-location (field) (mask) wrappers))
1020            (primary (location-line location)))
1021       (declare (fixnum location primary))
1022       (multiple-value-bind (free emptyp)
1023           (find-free-cache-line primary cache wrappers)
1024         (when (or forcep emptyp)
1025           (when (not emptyp)
1026             (push (cons (line-wrappers free) (line-value free))
1027                   (cache-overflow cache)))
1028           ;;(fill-line free wrappers value)
1029           (let ((line free))
1030             (declare (fixnum line))
1031             (when (line-reserved-p line)
1032               (error "attempt to fill a reserved line"))
1033             (let ((loc (line-location line))
1034                   (cache-vector (vector)))
1035               (declare (fixnum loc) (simple-vector cache-vector))
1036               (cond ((= (nkeys) 1)
1037                      (setf (cache-vector-ref cache-vector loc) wrappers)
1038                      (when (valuep)
1039                        (setf (cache-vector-ref cache-vector (1+ loc)) value)))
1040                     (t
1041                      (let ((i 0))
1042                        (declare (fixnum i))
1043                        (dolist (w wrappers)
1044                          (setf (cache-vector-ref cache-vector (+ loc i)) w)
1045                          (setq i (the fixnum (1+ i)))))
1046                      (when (valuep)
1047                        (setf (cache-vector-ref cache-vector (+ loc (nkeys)))
1048                              value))))
1049               (maybe-check-cache cache))))))))
1050
1051 (defun fill-cache-from-cache-p (forcep cache from-cache from-line)
1052   (declare (fixnum from-line))
1053   (with-local-cache-functions (cache)
1054     (let ((primary (location-line
1055                     (compute-primary-cache-location-from-location
1056                      cache (line-location from-line) from-cache))))
1057       (declare (fixnum primary))
1058       (multiple-value-bind (free emptyp)
1059           (find-free-cache-line primary cache)
1060         (when (or forcep emptyp)
1061           (when (not emptyp)
1062             (push (cons (line-wrappers free) (line-value free))
1063                   (cache-overflow cache)))
1064           ;;(transfer-line from-cache-vector from-line cache-vector free)
1065           (let ((from-cache-vector (cache-vector from-cache))
1066                 (to-cache-vector (vector))
1067                 (to-line free))
1068             (declare (fixnum to-line))
1069             (if (line-reserved-p to-line)
1070                 (error "transferring something into a reserved cache line")
1071                 (let ((from-loc (line-location from-line))
1072                       (to-loc (line-location to-line)))
1073                   (declare (fixnum from-loc to-loc))
1074                   (modify-cache to-cache-vector
1075                                 (dotimes-fixnum (i (line-size))
1076                                   (setf (cache-vector-ref to-cache-vector
1077                                                           (+ to-loc i))
1078                                         (cache-vector-ref from-cache-vector
1079                                                           (+ from-loc i)))))))
1080             (maybe-check-cache cache)))))))
1081
1082 ;;; Returns NIL or (values <field> <cache-vector>)
1083 ;;;
1084 ;;; This is only called when it isn't possible to put the entry in the
1085 ;;; cache the easy way. That is, this function assumes that
1086 ;;; FILL-CACHE-P has been called as returned NIL.
1087 ;;;
1088 ;;; If this returns NIL, it means that it wasn't possible to find a
1089 ;;; wrapper field for which all of the entries could be put in the
1090 ;;; cache (within the limit).
1091 (defun adjust-cache (cache wrappers value)
1092   (with-local-cache-functions (cache)
1093     (let ((ncache (get-cache-from-cache cache (nlines) (field))))
1094       (do ((nfield (cache-field ncache)
1095                    (next-wrapper-cache-number-index nfield)))
1096           ((null nfield) nil)
1097         (setf (cache-field ncache) nfield)
1098         (labels ((try-one-fill-from-line (line)
1099                    (fill-cache-from-cache-p nil ncache cache line))
1100                  (try-one-fill (wrappers value)
1101                    (fill-cache-p nil ncache wrappers value)))
1102           (if (and (dotimes-fixnum (i (nlines) t)
1103                      (when (and (null (line-reserved-p i))
1104                                 (line-valid-p i wrappers))
1105                        (unless (try-one-fill-from-line i) (return nil))))
1106                    (dolist (wrappers+value (cache-overflow cache) t)
1107                      (unless (try-one-fill (car wrappers+value) (cdr wrappers+value))
1108                        (return nil)))
1109                    (try-one-fill wrappers value))
1110               (return (maybe-check-cache ncache))
1111               (flush-cache-vector-internal (cache-vector ncache))))))))
1112
1113 ;;; returns: (values <cache>)
1114 (defun expand-cache (cache wrappers value)
1115   ;;(declare (values cache))
1116   (with-local-cache-functions (cache)
1117     (let ((ncache (get-cache-from-cache cache (* (nlines) 2))))
1118       (labels ((do-one-fill-from-line (line)
1119                  (unless (fill-cache-from-cache-p nil ncache cache line)
1120                    (do-one-fill (line-wrappers line) (line-value line))))
1121                (do-one-fill (wrappers value)
1122                  (setq ncache (or (adjust-cache ncache wrappers value)
1123                                   (fill-cache-p t ncache wrappers value))))
1124                (try-one-fill (wrappers value)
1125                  (fill-cache-p nil ncache wrappers value)))
1126         (dotimes-fixnum (i (nlines))
1127           (when (and (null (line-reserved-p i))
1128                      (line-valid-p i wrappers))
1129             (do-one-fill-from-line i)))
1130         (dolist (wrappers+value (cache-overflow cache))
1131           (unless (try-one-fill (car wrappers+value) (cdr wrappers+value))
1132             (do-one-fill (car wrappers+value) (cdr wrappers+value))))
1133         (unless (try-one-fill wrappers value)
1134           (do-one-fill wrappers value))
1135         (maybe-check-cache ncache)))))
1136 \f
1137 ;;; This is the heart of the cache filling mechanism. It implements
1138 ;;; the decisions about where entries are placed.
1139 ;;;
1140 ;;; Find a line in the cache at which a new entry can be inserted.
1141 ;;;
1142 ;;;   <line>
1143 ;;;   <empty?>     is <line> in fact empty?
1144 (defun find-free-cache-line (primary cache &optional wrappers)
1145   ;;(declare (values line empty?))
1146   (declare (fixnum primary))
1147   (with-local-cache-functions (cache)
1148     (when (line-reserved-p primary) (setq primary (next-line primary)))
1149     (let ((limit (funcall (limit-fn) (nlines)))
1150           (wrappedp nil)
1151           (lines nil)
1152           (p primary) (s primary))
1153       (declare (fixnum p s limit))
1154       (block find-free
1155         (loop
1156          ;; Try to find a free line starting at <s>. <p> is the
1157          ;; primary line of the entry we are finding a free
1158          ;; line for, it is used to compute the separations.
1159          (do* ((line s (next-line line))
1160                (nsep (line-separation p s) (1+ nsep)))
1161               (())
1162            (declare (fixnum line nsep))
1163            (when (null (line-valid-p line wrappers)) ;If this line is empty or
1164              (push line lines)          ;invalid, just use it.
1165              (return-from find-free))
1166            (when (and wrappedp (>= line primary))
1167              ;; have gone all the way around the cache, time to quit
1168              (return-from find-free-cache-line (values primary nil)))
1169            (let ((osep (line-separation (line-primary line) line)))
1170              (when (>= osep limit)
1171                (return-from find-free-cache-line (values primary nil)))
1172              (when (cond ((= nsep limit) t)
1173                          ((= nsep osep) (zerop (random 2)))
1174                          ((> nsep osep) t)
1175                          (t nil))
1176                ;; See whether we can displace what is in this line so that we
1177                ;; can use the line.
1178                (when (= line (the fixnum (1- (nlines)))) (setq wrappedp t))
1179                (setq p (line-primary line))
1180                (setq s (next-line line))
1181                (push line lines)
1182                (return nil)))
1183            (when (= line (the fixnum (1- (nlines)))) (setq wrappedp t)))))
1184       ;; Do all the displacing.
1185       (loop
1186        (when (null (cdr lines)) (return nil))
1187        (let ((dline (pop lines))
1188              (line (car lines)))
1189          (declare (fixnum dline line))
1190          ;;Copy from line to dline (dline is known to be free).
1191          (let ((from-loc (line-location line))
1192                (to-loc (line-location dline))
1193                (cache-vector (vector)))
1194            (declare (fixnum from-loc to-loc) (simple-vector cache-vector))
1195            (modify-cache cache-vector
1196                          (dotimes-fixnum (i (line-size))
1197                            (setf (cache-vector-ref cache-vector
1198                                                    (+ to-loc i))
1199                                  (cache-vector-ref cache-vector
1200                                                    (+ from-loc i)))
1201                            (setf (cache-vector-ref cache-vector
1202                                                    (+ from-loc i))
1203                                  nil))))))
1204       (values (car lines) t))))
1205
1206 (defun default-limit-fn (nlines)
1207   (case nlines
1208     ((1 2 4) 1)
1209     ((8 16)  4)
1210     (otherwise 6)))
1211
1212 (defvar *empty-cache* (make-cache)) ; for defstruct slot initial value forms