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