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