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