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