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