1.0.21.22: COMPILE-FILE and toplevel symbols
[sbcl.git] / src / pcl / dfun.lisp
1 ;;;; This software is part of the SBCL system. See the README file for
2 ;;;; more information.
3
4 ;;;; This software is derived from software originally released by Xerox
5 ;;;; Corporation. Copyright and release statements follow. Later modifications
6 ;;;; to the software are in the public domain and are provided with
7 ;;;; absolutely no warranty. See the COPYING and CREDITS files for more
8 ;;;; information.
9
10 ;;;; copyright information from original PCL sources:
11 ;;;;
12 ;;;; Copyright (c) 1985, 1986, 1987, 1988, 1989, 1990 Xerox Corporation.
13 ;;;; All rights reserved.
14 ;;;;
15 ;;;; Use and copying of this software and preparation of derivative works based
16 ;;;; upon this software are permitted. Any distribution of this software or
17 ;;;; derivative works must comply with all applicable United States export
18 ;;;; control laws.
19 ;;;;
20 ;;;; This software is made available AS IS, and Xerox Corporation makes no
21 ;;;; warranty about the software, its performance or its conformity to any
22 ;;;; specification.
23
24 (in-package "SB-PCL")
25 \f
26 #|
27
28 This implementation of method lookup was redone in early August of 89.
29
30 It has the following properties:
31
32  - Its modularity makes it easy to modify the actual caching algorithm.
33    The caching algorithm is almost completely separated into the files
34    cache.lisp and dlap.lisp. This file just contains the various uses
35    of it. There will be more tuning as we get more results from Luis'
36    measurements of caching behavior.
37
38  - The metacircularity issues have been dealt with properly. All of
39    PCL now grounds out properly. Moreover, it is now possible to have
40    metaobject classes which are themselves not instances of standard
41    metaobject classes.
42
43 ** Modularity of the code **
44
45 The actual caching algorithm is isolated in a modest number of functions.
46 The code which generates cache lookup code is all found in cache.lisp and
47 dlap.lisp. Certain non-wrapper-caching special cases are in this file.
48
49 ** Handling the metacircularity **
50
51 In CLOS, method lookup is the potential source of infinite metacircular
52 regress. The metaobject protocol specification gives us wide flexibility
53 in how to address this problem. PCL uses a technique which handles the
54 problem not only for the metacircular language described in Chapter 3, but
55 also for the PCL protocol which includes additional generic functions
56 which control more aspects of the CLOS implementation.
57
58 The source of the metacircular regress can be seen in a number of ways.
59 One is that the specified method lookup protocol must, as part of doing
60 the method lookup (or at least the cache miss case), itself call generic
61 functions. It is easy to see that if the method lookup for a generic
62 function ends up calling that same generic function there can be trouble.
63
64 Fortunately, there is an easy solution at hand. The solution is based on
65 the restriction that portable code cannot change the class of a specified
66 metaobject. This restriction implies that for specified generic functions,
67 the method lookup protocol they follow is fixed.
68
69 More precisely, for such specified generic functions, most generic functions
70 that are called during their own method lookup will not run portable methods.
71 This allows the implementation to usurp the actual generic function call in
72 this case. In short, method lookup of a standard generic function, in the
73 case where the only applicable methods are themselves standard doesn't
74 have to do any method lookup to implement itself.
75
76 And so, we are saved.
77
78 Except see also BREAK-VICIOUS-METACIRCLE.  -- CSR, 2003-05-28
79
80 |#
81 \f
82 ;;; an alist in which each entry is of the form
83 ;;;   (<generator> . (<subentry> ...)).
84 ;;; Each subentry is of the form
85 ;;;   (<args> <constructor> <system>).
86 (defvar *dfun-constructors* ())
87
88 ;;; If this is NIL, then the whole mechanism for caching dfun constructors is
89 ;;; turned off. The only time that makes sense is when debugging LAP code.
90 (defvar *enable-dfun-constructor-caching* t)
91
92 (defun show-dfun-constructors ()
93   (format t "~&DFUN constructor caching is ~A."
94           (if *enable-dfun-constructor-caching*
95               "enabled" "disabled"))
96   (dolist (generator-entry *dfun-constructors*)
97     (dolist (args-entry (cdr generator-entry))
98       (format t "~&~S ~S"
99               (cons (car generator-entry) (caar args-entry))
100               (caddr args-entry)))))
101
102 (defvar *raise-metatypes-to-class-p* t)
103
104 (defun get-dfun-constructor (generator &rest args)
105   (when (and *raise-metatypes-to-class-p*
106              (member generator '(emit-checking emit-caching
107                                  emit-in-checking-cache-p emit-constant-value)))
108     (setq args (cons (mapcar (lambda (mt)
109                                (if (eq mt t)
110                                    mt
111                                    'class))
112                              (car args))
113                      (cdr args))))
114   (let* ((generator-entry (assq generator *dfun-constructors*))
115          (args-entry (assoc args (cdr generator-entry) :test #'equal)))
116     (if (null *enable-dfun-constructor-caching*)
117         (apply (fdefinition generator) args)
118         (or (cadr args-entry)
119             (multiple-value-bind (new not-best-p)
120                 (apply (symbol-function generator) args)
121               (let ((entry (list (copy-list args) new (unless not-best-p 'pcl)
122                                  not-best-p)))
123                 (if generator-entry
124                     (push entry (cdr generator-entry))
125                     (push (list generator entry)
126                           *dfun-constructors*)))
127               (values new not-best-p))))))
128
129 (defun load-precompiled-dfun-constructor (generator args system constructor)
130   (let* ((generator-entry (assq generator *dfun-constructors*))
131          (args-entry (assoc args (cdr generator-entry) :test #'equal)))
132     (if args-entry
133         (when (fourth args-entry)
134           (let* ((dfun-type (case generator
135                               (emit-checking 'checking)
136                               (emit-caching 'caching)
137                               (emit-constant-value 'constant-value)
138                               (emit-default-only 'default-method-only)))
139                  (metatypes (car args))
140                  (gfs (when dfun-type (gfs-of-type dfun-type))))
141             (dolist (gf gfs)
142               (when (and (equal metatypes
143                                 (arg-info-metatypes (gf-arg-info gf)))
144                          (let ((gf-name (generic-function-name gf)))
145                            (and (not (eq gf-name 'slot-value-using-class))
146                                 (not (equal gf-name
147                                             '(setf slot-value-using-class)))
148                                 (not (eq gf-name 'slot-boundp-using-class)))))
149                 (update-dfun gf)))
150             (setf (second args-entry) constructor)
151             (setf (third args-entry) system)
152             (setf (fourth args-entry) nil)))
153         (let ((entry (list args constructor system nil)))
154           (if generator-entry
155               (push entry (cdr generator-entry))
156               (push (list generator entry) *dfun-constructors*))))))
157
158 (defmacro precompile-dfun-constructors (&optional system)
159   (let ((*precompiling-lap* t))
160     `(progn
161        ,@(let (collect)
162            (dolist (generator-entry *dfun-constructors*)
163              (dolist (args-entry (cdr generator-entry))
164                (when (or (null (caddr args-entry))
165                          (eq (caddr args-entry) system))
166                  (when system (setf (caddr args-entry) system))
167                  (push `(load-precompiled-dfun-constructor
168                          ',(car generator-entry)
169                          ',(car args-entry)
170                          ',system
171                          ,(apply (fdefinition (car generator-entry))
172                                  (car args-entry)))
173                        collect))))
174            (nreverse collect)))))
175 \f
176 ;;; Standardized class slot access: when trying to break vicious
177 ;;; metacircles, we need a way to get at the values of slots of some
178 ;;; standard classes without going through the whole meta machinery,
179 ;;; because that would likely enter the vicious circle again.  The
180 ;;; following are helper functions that short-circuit the generic
181 ;;; lookup machinery.
182
183 (defvar *standard-classes*
184   '(standard-method standard-generic-function standard-class
185     standard-effective-slot-definition))
186
187 (defvar *standard-slot-locations* (make-hash-table :test 'equal))
188
189 (defun compute-standard-slot-locations ()
190   (clrhash *standard-slot-locations*)
191   (dolist (class-name *standard-classes*)
192     (let ((class (find-class class-name)))
193       (dolist (slot (class-slots class))
194         (setf (gethash (cons class (slot-definition-name slot))
195                        *standard-slot-locations*)
196               (slot-definition-location slot))))))
197
198 ;;; FIXME: harmonize the names between COMPUTE-STANDARD-SLOT-LOCATIONS
199 ;;; and MAYBE-UPDATE-STANDARD-CLASS-LOCATIONS.
200 (defun maybe-update-standard-class-locations (class)
201   (when (and (eq *boot-state* 'complete)
202              (memq (class-name class) *standard-classes*))
203     (compute-standard-slot-locations)))
204
205 (defun standard-slot-value (object slot-name class)
206   (let ((location (gethash (cons class slot-name) *standard-slot-locations*)))
207     (if location
208         (let ((value (if (funcallable-instance-p object)
209                          (funcallable-standard-instance-access object location)
210                          (standard-instance-access object location))))
211           (when (eq +slot-unbound+ value)
212             (error "~@<slot ~S of class ~S is unbound in object ~S~@:>"
213                    slot-name class object))
214           value)
215         (error "~@<cannot get standard value of slot ~S of class ~S ~
216                 in object ~S~@:>"
217                slot-name class object))))
218
219 (defun standard-slot-value/gf (gf slot-name)
220   (standard-slot-value gf slot-name *the-class-standard-generic-function*))
221
222 (defun standard-slot-value/method (method slot-name)
223   (standard-slot-value method slot-name *the-class-standard-method*))
224
225 (defun standard-slot-value/eslotd (slotd slot-name)
226   (standard-slot-value slotd slot-name
227                        *the-class-standard-effective-slot-definition*))
228
229 (defun standard-slot-value/class (class slot-name)
230   (standard-slot-value class slot-name *the-class-standard-class*))
231 \f
232 ;;; When all the methods of a generic function are automatically
233 ;;; generated reader or writer methods a number of special
234 ;;; optimizations are possible. These are important because of the
235 ;;; large number of generic functions of this type.
236 ;;;
237 ;;; There are a number of cases:
238 ;;;
239 ;;;   ONE-CLASS-ACCESSOR
240 ;;;     In this case, the accessor generic function has only been
241 ;;;     called with one class of argument. There is no cache vector,
242 ;;;     the wrapper of the one class, and the slot index are stored
243 ;;;     directly as closure variables of the discriminating function.
244 ;;;     This case can convert to either of the next kind.
245 ;;;
246 ;;;   TWO-CLASS-ACCESSOR
247 ;;;     Like above, but two classes. This is common enough to do
248 ;;;     specially. There is no cache vector. The two classes are
249 ;;;     stored a separate closure variables.
250 ;;;
251 ;;;   ONE-INDEX-ACCESSOR
252 ;;;     In this case, the accessor generic function has seen more than
253 ;;;     one class of argument, but the index of the slot is the same
254 ;;;     for all the classes that have been seen. A cache vector is
255 ;;;     used to store the wrappers that have been seen, the slot index
256 ;;;     is stored directly as a closure variable of the discriminating
257 ;;;     function. This case can convert to the next kind.
258 ;;;
259 ;;;   N-N-ACCESSOR
260 ;;;     This is the most general case. In this case, the accessor
261 ;;;     generic function has seen more than one class of argument and
262 ;;;     more than one slot index. A cache vector stores the wrappers
263 ;;;     and corresponding slot indexes.
264
265 (defstruct (dfun-info (:constructor nil)
266                       (:copier nil))
267   (cache nil))
268
269 (defstruct (no-methods (:constructor no-methods-dfun-info ())
270                        (:include dfun-info)
271                        (:copier nil)))
272
273 (defstruct (initial (:constructor initial-dfun-info ())
274                     (:include dfun-info)
275                     (:copier nil)))
276
277 (defstruct (initial-dispatch (:constructor initial-dispatch-dfun-info ())
278                              (:include dfun-info)
279                              (:copier nil)))
280
281 (defstruct (dispatch (:constructor dispatch-dfun-info ())
282                      (:include dfun-info)
283                      (:copier nil)))
284
285 (defstruct (default-method-only (:constructor default-method-only-dfun-info ())
286                                 (:include dfun-info)
287                                 (:copier nil)))
288
289 ;without caching:
290 ;  dispatch one-class two-class default-method-only
291
292 ;with caching:
293 ;  one-index n-n checking caching
294
295 ;accessor:
296 ;  one-class two-class one-index n-n
297 (defstruct (accessor-dfun-info (:constructor nil)
298                                (:include dfun-info)
299                                (:copier nil))
300   accessor-type) ; (member reader writer)
301
302 (defmacro dfun-info-accessor-type (di)
303   `(accessor-dfun-info-accessor-type ,di))
304
305 (defstruct (one-index-dfun-info (:constructor nil)
306                                 (:include accessor-dfun-info)
307                                 (:copier nil))
308   index)
309
310 (defmacro dfun-info-index (di)
311   `(one-index-dfun-info-index ,di))
312
313 (defstruct (n-n (:constructor n-n-dfun-info (accessor-type cache))
314                 (:include accessor-dfun-info)
315                 (:copier nil)))
316
317 (defstruct (one-class (:constructor one-class-dfun-info
318                                     (accessor-type index wrapper0))
319                       (:include one-index-dfun-info)
320                       (:copier nil))
321   wrapper0)
322
323 (defmacro dfun-info-wrapper0 (di)
324   `(one-class-wrapper0 ,di))
325
326 (defstruct (two-class (:constructor two-class-dfun-info
327                                     (accessor-type index wrapper0 wrapper1))
328                       (:include one-class)
329                       (:copier nil))
330   wrapper1)
331
332 (defmacro dfun-info-wrapper1 (di)
333   `(two-class-wrapper1 ,di))
334
335 (defstruct (one-index (:constructor one-index-dfun-info
336                                     (accessor-type index cache))
337                       (:include one-index-dfun-info)
338                       (:copier nil)))
339
340 (defstruct (checking (:constructor checking-dfun-info (function cache))
341                      (:include dfun-info)
342                      (:copier nil))
343   function)
344
345 (defmacro dfun-info-function (di)
346   `(checking-function ,di))
347
348 (defstruct (caching (:constructor caching-dfun-info (cache))
349                     (:include dfun-info)
350                     (:copier nil)))
351
352 (defstruct (constant-value (:constructor constant-value-dfun-info (cache))
353                            (:include dfun-info)
354                            (:copier nil)))
355
356 (defmacro dfun-update (generic-function function &rest args)
357   `(multiple-value-bind (dfun cache info)
358        (funcall ,function ,generic-function ,@args)
359      (update-dfun ,generic-function dfun cache info)))
360
361 (defun accessor-miss-function (gf dfun-info)
362   (ecase (dfun-info-accessor-type dfun-info)
363     ((reader boundp)
364      (lambda (arg)
365        (accessor-miss gf nil arg dfun-info)))
366     (writer
367      (lambda (new arg)
368        (accessor-miss gf new arg dfun-info)))))
369
370 #-sb-fluid (declaim (sb-ext:freeze-type dfun-info))
371 \f
372 (defun make-one-class-accessor-dfun (gf type wrapper index)
373   (let ((emit (ecase type
374                 (reader 'emit-one-class-reader)
375                 (boundp 'emit-one-class-boundp)
376                 (writer 'emit-one-class-writer)))
377         (dfun-info (one-class-dfun-info type index wrapper)))
378     (values
379      (funcall (get-dfun-constructor emit (consp index))
380               wrapper index
381               (accessor-miss-function gf dfun-info))
382      nil
383      dfun-info)))
384
385 (defun make-two-class-accessor-dfun (gf type w0 w1 index)
386   (let ((emit (ecase type
387                 (reader 'emit-two-class-reader)
388                 (boundp 'emit-two-class-boundp)
389                 (writer 'emit-two-class-writer)))
390         (dfun-info (two-class-dfun-info type index w0 w1)))
391     (values
392      (funcall (get-dfun-constructor emit (consp index))
393               w0 w1 index
394               (accessor-miss-function gf dfun-info))
395      nil
396      dfun-info)))
397
398 ;;; std accessors same index dfun
399 (defun make-one-index-accessor-dfun (gf type index &optional cache)
400   (let* ((emit (ecase type
401                  (reader 'emit-one-index-readers)
402                  (boundp 'emit-one-index-boundps)
403                  (writer 'emit-one-index-writers)))
404          (cache (or cache (make-cache :key-count 1 :value nil :size 4)))
405          (dfun-info (one-index-dfun-info type index cache)))
406     (declare (type cache cache))
407     (values
408      (funcall (get-dfun-constructor emit (consp index))
409               cache
410               index
411               (accessor-miss-function gf dfun-info))
412      cache
413      dfun-info)))
414
415 (defun make-n-n-accessor-dfun (gf type &optional cache)
416   (let* ((emit (ecase type
417                  (reader 'emit-n-n-readers)
418                  (boundp 'emit-n-n-boundps)
419                  (writer 'emit-n-n-writers)))
420          (cache (or cache (make-cache :key-count 1 :value t :size 2)))
421          (dfun-info (n-n-dfun-info type cache)))
422     (declare (type cache cache))
423     (values
424      (funcall (get-dfun-constructor emit)
425               cache
426               (accessor-miss-function gf dfun-info))
427      cache
428      dfun-info)))
429
430 (defun make-checking-dfun (generic-function function &optional cache)
431   (unless cache
432     (when (use-caching-dfun-p generic-function)
433       (return-from make-checking-dfun (make-caching-dfun generic-function)))
434     (when (use-dispatch-dfun-p generic-function)
435       (return-from make-checking-dfun (make-dispatch-dfun generic-function))))
436   (multiple-value-bind (nreq applyp metatypes nkeys)
437       (get-generic-fun-info generic-function)
438     (declare (ignore nreq))
439     (if (every (lambda (mt) (eq mt t)) metatypes)
440         (let ((dfun-info (default-method-only-dfun-info)))
441           (values
442            (funcall (get-dfun-constructor 'emit-default-only metatypes applyp)
443                     function)
444            nil
445            dfun-info))
446         (let* ((cache (or cache (make-cache :key-count nkeys :value nil :size 2)))
447                (dfun-info (checking-dfun-info function cache)))
448           (values
449            (funcall (get-dfun-constructor 'emit-checking metatypes applyp)
450                     cache
451                     function
452                     (lambda (&rest args)
453                       (checking-miss generic-function args dfun-info)))
454            cache
455            dfun-info)))))
456
457 (defun make-final-checking-dfun (generic-function function classes-list new-class)
458   (multiple-value-bind (nreq applyp metatypes nkeys)
459       (get-generic-fun-info generic-function)
460     (declare (ignore nreq applyp nkeys))
461     (if (every (lambda (mt) (eq mt t)) metatypes)
462         (values (lambda (&rest args)
463                   (invoke-emf function args))
464                 nil (default-method-only-dfun-info))
465         (let ((cache (make-final-ordinary-dfun-cache
466                       generic-function nil classes-list new-class)))
467           (make-checking-dfun generic-function function cache)))))
468
469 (defun use-default-method-only-dfun-p (generic-function)
470   (multiple-value-bind (nreq applyp metatypes nkeys)
471       (get-generic-fun-info generic-function)
472     (declare (ignore nreq applyp nkeys))
473     (every (lambda (mt) (eq mt t)) metatypes)))
474
475 (defun use-caching-dfun-p (generic-function)
476   (some (lambda (method) (method-plist-value method :slot-name-lists))
477         ;; KLUDGE: As of sbcl-0.6.4, it's very important for
478         ;; efficiency to know the type of the sequence argument to
479         ;; quantifiers (SOME/NOTANY/etc.) at compile time, but
480         ;; the compiler isn't smart enough to understand the :TYPE
481         ;; slot option for DEFCLASS, so we just tell
482         ;; it the type by hand here.
483         (the list
484              (if (early-gf-p generic-function)
485                  (early-gf-methods generic-function)
486                  (generic-function-methods generic-function)))))
487 \f
488 (defun make-caching-dfun (generic-function &optional cache)
489   (unless cache
490     (when (use-constant-value-dfun-p generic-function)
491       (return-from make-caching-dfun
492         (make-constant-value-dfun generic-function)))
493     (when (use-dispatch-dfun-p generic-function)
494       (return-from make-caching-dfun
495         (make-dispatch-dfun generic-function))))
496   (multiple-value-bind (nreq applyp metatypes nkeys)
497       (get-generic-fun-info generic-function)
498     (declare (ignore nreq))
499     (let* ((cache (or cache (make-cache :key-count nkeys :value t :size 2)))
500            (dfun-info (caching-dfun-info cache)))
501       (values
502        (funcall (get-dfun-constructor 'emit-caching metatypes applyp)
503                 cache
504                 (lambda (&rest args)
505                   (caching-miss generic-function args dfun-info)))
506        cache
507        dfun-info))))
508
509 (defun make-final-caching-dfun (generic-function classes-list new-class)
510   (let ((cache (make-final-ordinary-dfun-cache
511                 generic-function t classes-list new-class)))
512     (make-caching-dfun generic-function cache)))
513
514 (defun insure-caching-dfun (gf)
515   (multiple-value-bind (nreq applyp metatypes nkeys)
516       (get-generic-fun-info gf)
517     (declare (ignore nreq nkeys))
518     (when (and metatypes
519                (not (null (car metatypes)))
520                (dolist (mt metatypes nil)
521                  (unless (eq mt t) (return t))))
522       (get-dfun-constructor 'emit-caching metatypes applyp))))
523
524 (defun use-constant-value-dfun-p (gf &optional boolean-values-p)
525   (multiple-value-bind (nreq applyp metatypes nkeys)
526       (get-generic-fun-info gf)
527     (declare (ignore nreq metatypes nkeys))
528     (let* ((early-p (early-gf-p gf))
529            (methods (if early-p
530                         (early-gf-methods gf)
531                         (generic-function-methods gf)))
532            (default '(unknown)))
533       (and (null applyp)
534            (or (not (eq *boot-state* 'complete))
535                ;; If COMPUTE-APPLICABLE-METHODS is specialized, we
536                ;; can't use this, of course, because we can't tell
537                ;; which methods will be considered applicable.
538                ;;
539                ;; Also, don't use this dfun method if the generic
540                ;; function has a non-standard method combination,
541                ;; because if it has, it's not sure that method
542                ;; functions are used directly as effective methods,
543                ;; which CONSTANT-VALUE-MISS depends on.  The
544                ;; pre-defined method combinations like LIST are
545                ;; examples of that.
546                (and (compute-applicable-methods-emf-std-p gf)
547                     (eq (generic-function-method-combination gf)
548                         *standard-method-combination*)))
549            ;; Check that no method is eql-specialized, and that all
550            ;; methods return a constant value.  If BOOLEAN-VALUES-P,
551            ;; check that all return T or NIL.  Also, check that no
552            ;; method has qualifiers, to make sure that emfs are really
553            ;; method functions; see above.
554            (dolist (method methods t)
555              (when (eq *boot-state* 'complete)
556                (when (or (some #'eql-specializer-p
557                                (safe-method-specializers method))
558                          (safe-method-qualifiers method))
559                  (return nil)))
560              (let ((value (method-plist-value method :constant-value default)))
561                (when (or (eq value default)
562                          (and boolean-values-p
563                               (not (member value '(t nil)))))
564                  (return nil))))))))
565
566 (defun make-constant-value-dfun (generic-function &optional cache)
567   (multiple-value-bind (nreq applyp metatypes nkeys)
568       (get-generic-fun-info generic-function)
569     (declare (ignore nreq applyp))
570     (let* ((cache (or cache (make-cache :key-count nkeys :value t :size 2)))
571            (dfun-info (constant-value-dfun-info cache)))
572       (declare (type cache cache))
573       (values
574        (funcall (get-dfun-constructor 'emit-constant-value metatypes)
575                 cache
576                 (lambda (&rest args)
577                   (constant-value-miss generic-function args dfun-info)))
578        cache
579        dfun-info))))
580
581 (defun make-final-constant-value-dfun (generic-function classes-list new-class)
582   (let ((cache (make-final-ordinary-dfun-cache
583                 generic-function :constant-value classes-list new-class)))
584     (make-constant-value-dfun generic-function cache)))
585
586 (defun gf-has-method-with-nonstandard-specializer-p (gf)
587   (let ((methods (generic-function-methods gf)))
588     (dolist (method methods nil)
589       (unless (every (lambda (s) (standard-specializer-p s))
590                      (method-specializers method))
591         (return t)))))
592
593 (defun use-dispatch-dfun-p (gf &optional (caching-p (use-caching-dfun-p gf)))
594   (when (eq *boot-state* 'complete)
595     (unless (or caching-p
596                 (gf-requires-emf-keyword-checks gf)
597                 ;; DISPATCH-DFUN-COST will error if it encounters a
598                 ;; method with a non-standard specializer.
599                 (gf-has-method-with-nonstandard-specializer-p gf))
600       ;; This should return T when almost all dispatching is by
601       ;; eql specializers or built-in classes. In other words,
602       ;; return NIL if we might ever need to do more than
603       ;; one (non built-in) typep.
604       ;; Otherwise, it is probably at least as fast to use
605       ;; a caching dfun first, possibly followed by secondary dispatching.
606
607       #||;;; Original found in cmu 17f -- S L O W
608       (< (dispatch-dfun-cost gf) (caching-dfun-cost gf))
609       ||#
610       ;; This uses improved dispatch-dfun-cost below
611       (let ((cdc  (caching-dfun-cost gf))) ; fast
612         (> cdc (dispatch-dfun-cost gf cdc))))))
613
614 (defparameter *non-built-in-typep-cost* 100)
615 (defparameter *structure-typep-cost*  15)
616 (defparameter *built-in-typep-cost* 5)
617
618 ;;; According to comments in the original CMU CL version of PCL,
619 ;;; the cost LIMIT is important to cut off exponential growth for
620 ;;; large numbers of gf methods and argument lists.
621 (defun dispatch-dfun-cost (gf &optional limit)
622   (generate-discrimination-net-internal
623    gf (generic-function-methods gf) nil
624    (lambda (methods known-types)
625      (declare (ignore methods known-types))
626      0)
627    (lambda (position type true-value false-value)
628      (declare (ignore position))
629      (let* ((type-test-cost
630              (if (eq 'class (car type))
631                  (let* ((metaclass (class-of (cadr type)))
632                         (mcpl (class-precedence-list metaclass)))
633                    (cond ((memq *the-class-built-in-class* mcpl)
634                           *built-in-typep-cost*)
635                          ((memq *the-class-structure-class* mcpl)
636                           *structure-typep-cost*)
637                          (t
638                           *non-built-in-typep-cost*)))
639                  0))
640             (max-cost-so-far
641              (+ (max true-value false-value) type-test-cost)))
642        (when (and limit (<= limit max-cost-so-far))
643          (return-from dispatch-dfun-cost max-cost-so-far))
644        max-cost-so-far))
645    #'identity))
646
647 (defparameter *cache-lookup-cost*  30)
648 (defparameter *wrapper-of-cost* 15)
649 (defparameter *secondary-dfun-call-cost* 30)
650
651 (defun caching-dfun-cost (gf)
652   (let ((nreq (get-generic-fun-info gf)))
653     (+ *cache-lookup-cost*
654        (* *wrapper-of-cost* nreq)
655        (if (methods-contain-eql-specializer-p
656             (generic-function-methods gf))
657            *secondary-dfun-call-cost*
658            0))))
659
660 (declaim (inline make-callable))
661 (defun make-callable (gf methods generator method-alist wrappers)
662   (let* ((*applicable-methods* methods)
663          (callable (function-funcall generator method-alist wrappers)))
664     callable))
665
666 (defun make-dispatch-dfun (gf)
667   (values (get-dispatch-function gf) nil (dispatch-dfun-info)))
668
669 (defun get-dispatch-function (gf)
670   (let* ((methods (generic-function-methods gf))
671          (generator (get-secondary-dispatch-function1
672                      gf methods nil nil nil nil nil t)))
673     (make-callable gf methods generator nil nil)))
674
675 (defun make-final-dispatch-dfun (gf)
676   (make-dispatch-dfun gf))
677
678 (defun update-dispatch-dfuns ()
679   (dolist (gf (gfs-of-type '(dispatch initial-dispatch)))
680     (dfun-update gf #'make-dispatch-dfun)))
681
682 (defun make-final-ordinary-dfun-cache
683     (generic-function valuep classes-list new-class)
684   (let* ((arg-info (gf-arg-info generic-function))
685          (nkeys (arg-info-nkeys arg-info))
686          (new-class (and new-class
687                          (equal (type-of (gf-dfun-info generic-function))
688                                 (cond ((eq valuep t) 'caching)
689                                       ((eq valuep :constant-value) 'constant-value)
690                                       ((null valuep) 'checking)))
691                          new-class))
692          (cache (if new-class
693                     (copy-cache (gf-dfun-cache generic-function))
694                     (make-cache :key-count nkeys :value (not (null valuep))
695                                 :size 4))))
696     (make-emf-cache generic-function valuep cache classes-list new-class)))
697 \f
698 (defvar *dfun-miss-gfs-on-stack* ())
699
700 (defmacro dfun-miss ((gf args wrappers invalidp nemf
701                       &optional type index caching-p applicable)
702                      &body body)
703   (unless applicable (setq applicable (gensym)))
704   `(multiple-value-bind (,nemf ,applicable ,wrappers ,invalidp
705                          ,@(when type `(,type ,index)))
706        (cache-miss-values ,gf ,args ',(cond (caching-p 'caching)
707                                             (type 'accessor)
708                                             (t 'checking)))
709     (when (and ,applicable (not (memq ,gf *dfun-miss-gfs-on-stack*)))
710       (let ((*dfun-miss-gfs-on-stack* (cons ,gf *dfun-miss-gfs-on-stack*)))
711         ,@body))
712     ;; Create a FAST-INSTANCE-BOUNDP structure instance for a cached
713     ;; SLOT-BOUNDP so that INVOKE-EMF does the right thing, that is,
714     ;; does not signal a SLOT-UNBOUND error for a boundp test.
715     ,@(if type
716           ;; FIXME: could the NEMF not be a CONS (for :CLASS-allocated
717           ;; slots?)
718           `((if (and (eq ,type 'boundp) (integerp ,nemf))
719                 (invoke-emf (make-fast-instance-boundp :index ,nemf) ,args)
720                 (invoke-emf ,nemf ,args)))
721           `((invoke-emf ,nemf ,args)))))
722
723 ;;; The dynamically adaptive method lookup algorithm is implemented is
724 ;;; implemented as a kind of state machine. The kinds of
725 ;;; discriminating function is the state, the various kinds of reasons
726 ;;; for a cache miss are the state transitions.
727 ;;;
728 ;;; The code which implements the transitions is all in the miss
729 ;;; handlers for each kind of dfun. Those appear here.
730 ;;;
731 ;;; Note that within the states that cache, there are dfun updates
732 ;;; which simply select a new cache or cache field. Those are not
733 ;;; considered as state transitions.
734 (defvar *lazy-dfun-compute-p* t)
735 (defvar *early-p* nil)
736
737 ;;; This variable is used for controlling the load-time effective
738 ;;; method precomputation: precomputation will only be done for emfs
739 ;;; with fewer than methods than this value. This value has
740 ;;; traditionally been NIL on SBCL (meaning that precomputation will
741 ;;; always be done) but that makes method loading O(n^2). Use a small
742 ;;; value for now, to flush out any possible problems that doing a
743 ;;; limited amount of precomputation might cause. If none appear, we
744 ;;; might change it to a larger value later. -- JES, 2006-12-01
745 (declaim (type (or null unsigned-byte) *max-emf-precomputation-methods*))
746 (defvar *max-emf-precomputation-methods* 1)
747
748 (defun finalize-specializers (gf)
749   (let ((methods (generic-function-methods gf)))
750     (when (or (null *max-emf-precomputation-methods*)
751               (<= (length methods) *max-emf-precomputation-methods*))
752       (let ((all-finalized t))
753         (dolist (method methods all-finalized)
754           (dolist (specializer (method-specializers method))
755             (when (and (classp specializer)
756                        (not (class-finalized-p specializer)))
757               (if (class-has-a-forward-referenced-superclass-p specializer)
758                   (setq all-finalized nil)
759                   (finalize-inheritance specializer)))))))))
760
761 (defun make-initial-dfun (gf)
762   (let ((initial-dfun
763          #'(lambda (&rest args)
764              (initial-dfun gf args))))
765     (multiple-value-bind (dfun cache info)
766         (cond
767           ((and (eq *boot-state* 'complete)
768                 (not (finalize-specializers gf)))
769            (values initial-dfun nil (initial-dfun-info)))
770           ((and (eq *boot-state* 'complete)
771                 (compute-applicable-methods-emf-std-p gf))
772            (let* ((caching-p (use-caching-dfun-p gf))
773                   ;; KLUDGE: the only effect of this (when
774                   ;; *LAZY-DFUN-COMPUTE-P* is true, as it usually is)
775                   ;; is to signal an error when we try to add methods
776                   ;; with the wrong qualifiers to a generic function.
777                   (classes-list (precompute-effective-methods
778                                  gf caching-p
779                                  (not *lazy-dfun-compute-p*))))
780              (if *lazy-dfun-compute-p*
781                  (cond ((use-dispatch-dfun-p gf caching-p)
782                         (values initial-dfun
783                                 nil
784                                 (initial-dispatch-dfun-info)))
785                        (caching-p
786                         (insure-caching-dfun gf)
787                         (values initial-dfun nil (initial-dfun-info)))
788                        (t
789                         (values initial-dfun nil (initial-dfun-info))))
790                  (make-final-dfun-internal gf classes-list))))
791           (t
792            (let ((arg-info (if (early-gf-p gf)
793                                (early-gf-arg-info gf)
794                                (gf-arg-info gf)))
795                  (type nil))
796              (if (and (gf-precompute-dfun-and-emf-p arg-info)
797                       (setq type (final-accessor-dfun-type gf)))
798                  (if *early-p*
799                      (values (make-early-accessor gf type) nil nil)
800                      (make-final-accessor-dfun gf type))
801                  (values initial-dfun nil (initial-dfun-info))))))
802       (set-dfun gf dfun cache info))))
803
804 (defun make-early-accessor (gf type)
805   (let* ((methods (early-gf-methods gf))
806          (slot-name (early-method-standard-accessor-slot-name (car methods))))
807     (ecase type
808       (reader #'(lambda (instance)
809                   (let* ((class (class-of instance))
810                          (class-name (!bootstrap-get-slot 'class class 'name)))
811                     (!bootstrap-get-slot class-name instance slot-name))))
812       (boundp #'(lambda (instance)
813                   (let* ((class (class-of instance))
814                          (class-name (!bootstrap-get-slot 'class class 'name)))
815                     (not (eq +slot-unbound+
816                              (!bootstrap-get-slot class-name
817                                                   instance slot-name))))))
818       (writer #'(lambda (new-value instance)
819                   (let* ((class (class-of instance))
820                          (class-name (!bootstrap-get-slot 'class class 'name)))
821                     (!bootstrap-set-slot class-name instance slot-name new-value)))))))
822
823 (defun initial-dfun (gf args)
824   (dfun-miss (gf args wrappers invalidp nemf ntype nindex)
825     (cond (invalidp)
826           ((and ntype nindex)
827            (dfun-update
828             gf #'make-one-class-accessor-dfun ntype wrappers nindex))
829           ((use-caching-dfun-p gf)
830            (dfun-update gf #'make-caching-dfun))
831           (t
832            (dfun-update gf #'make-checking-dfun
833             ;; nemf is suitable only for caching, have to do this:
834             (cache-miss-values gf args 'checking))))))
835
836 (defun make-final-dfun (gf &optional classes-list)
837   (multiple-value-bind (dfun cache info)
838       (make-final-dfun-internal gf classes-list)
839     (set-dfun gf dfun cache info)))
840
841 ;;; FIXME: What is this?
842 (defvar *new-class* nil)
843
844 (defun final-accessor-dfun-type (gf)
845   (let ((methods (if (early-gf-p gf)
846                      (early-gf-methods gf)
847                      (generic-function-methods gf))))
848     (cond ((every (lambda (method)
849                     (if (consp method)
850                         (let ((class (early-method-class method)))
851                           (or (eq class *the-class-standard-reader-method*)
852                               (eq class *the-class-global-reader-method*)))
853                         (or (standard-reader-method-p method)
854                             (global-reader-method-p method))))
855                   methods)
856            'reader)
857           ((every (lambda (method)
858                     (if (consp method)
859                         (let ((class (early-method-class method)))
860                           (or (eq class *the-class-standard-boundp-method*)
861                               (eq class *the-class-global-boundp-method*)))
862                         (or (standard-boundp-method-p method)
863                             (global-boundp-method-p method))))
864                   methods)
865            'boundp)
866           ((every (lambda (method)
867                     (if (consp method)
868                         (let ((class (early-method-class method)))
869                           (or (eq class *the-class-standard-writer-method*)
870                               (eq class *the-class-global-writer-method*)))
871                         (and
872                          (or (standard-writer-method-p method)
873                              (global-writer-method-p method))
874                          (not (safe-p
875                                (slot-definition-class
876                                 (accessor-method-slot-definition method)))))))
877                   methods)
878            'writer))))
879
880 (defun make-final-accessor-dfun (gf type &optional classes-list new-class)
881   (let ((table (make-hash-table :test #'eq)))
882     (multiple-value-bind (table all-index first second size no-class-slots-p)
883         (make-accessor-table gf type table)
884       (if table
885           (cond ((= size 1)
886                  (let ((w (class-wrapper first)))
887                    (make-one-class-accessor-dfun gf type w all-index)))
888                 ((and (= size 2) (or (integerp all-index) (consp all-index)))
889                  (let ((w0 (class-wrapper first))
890                        (w1 (class-wrapper second)))
891                    (make-two-class-accessor-dfun gf type w0 w1 all-index)))
892                 ((or (integerp all-index) (consp all-index))
893                  (let ((cache (hash-table-to-cache table :value nil :key-count 1)))
894                    (make-one-index-accessor-dfun gf type all-index cache)))
895                 (no-class-slots-p
896                  (let ((cache (hash-table-to-cache table :value t :key-count 1)))
897                    (make-n-n-accessor-dfun gf type cache)))
898                 (t
899                  (make-final-caching-dfun gf classes-list new-class)))
900           (make-final-caching-dfun gf classes-list new-class)))))
901
902 (defun make-final-dfun-internal (gf &optional classes-list)
903   (let ((methods (generic-function-methods gf)) type
904         (new-class *new-class*) (*new-class* nil)
905         specls all-same-p)
906     (cond ((null methods)
907            (values
908             #'(lambda (&rest args)
909                 (apply #'no-applicable-method gf args))
910             nil
911             (no-methods-dfun-info)))
912           ((setq type (final-accessor-dfun-type gf))
913            (make-final-accessor-dfun gf type classes-list new-class))
914           ((and (not (and (every (lambda (specl) (eq specl *the-class-t*))
915                                  (setq specls
916                                        (method-specializers (car methods))))
917                           (setq all-same-p
918                                 (every (lambda (method)
919                                          (and (equal specls
920                                                      (method-specializers
921                                                       method))))
922                                        methods))))
923                 (use-constant-value-dfun-p gf))
924            (make-final-constant-value-dfun gf classes-list new-class))
925           ((use-dispatch-dfun-p gf)
926            (make-final-dispatch-dfun gf))
927           ((and all-same-p (not (use-caching-dfun-p gf)))
928            (let ((emf (get-secondary-dispatch-function gf methods nil)))
929              (make-final-checking-dfun gf emf classes-list new-class)))
930           (t
931            (make-final-caching-dfun gf classes-list new-class)))))
932
933 (defvar *pcl-misc-random-state* (make-random-state))
934
935 (defun accessor-miss (gf new object dfun-info)
936   (let* ((ostate (type-of dfun-info))
937          (otype (dfun-info-accessor-type dfun-info))
938          oindex ow0 ow1 cache
939          (args (ecase otype
940                  ((reader boundp) (list object))
941                  (writer (list new object)))))
942     (dfun-miss (gf args wrappers invalidp nemf ntype nindex)
943       ;; The following lexical functions change the state of the
944       ;; dfun to that which is their name.  They accept arguments
945       ;; which are the parameters of the new state, and get other
946       ;; information from the lexical variables bound above.
947       (flet ((two-class (index w0 w1)
948                (when (zerop (random 2 *pcl-misc-random-state*))
949                  (psetf w0 w1 w1 w0))
950                (dfun-update gf
951                             #'make-two-class-accessor-dfun
952                             ntype
953                             w0
954                             w1
955                             index))
956              (one-index (index &optional cache)
957                (dfun-update gf
958                             #'make-one-index-accessor-dfun
959                             ntype
960                             index
961                             cache))
962              (n-n (&optional cache)
963                (if (consp nindex)
964                    (dfun-update gf #'make-checking-dfun nemf)
965                    (dfun-update gf #'make-n-n-accessor-dfun ntype cache)))
966              (caching () ; because cached accessor emfs are much faster
967                          ; for accessors
968                (dfun-update gf #'make-caching-dfun))
969              (do-fill (update-fn)
970                (let ((ncache (fill-cache cache wrappers nindex)))
971                  (unless (eq ncache cache)
972                    (funcall update-fn ncache)))))
973         (cond ((null ntype)
974                (caching))
975               ((or invalidp
976                    (null nindex)))
977               ((not (pcl-instance-p object))
978                (caching))
979               ((or (neq ntype otype) (listp wrappers))
980                (caching))
981               (t
982                (ecase ostate
983                  (one-class
984                   (setq oindex (dfun-info-index dfun-info))
985                   (setq ow0 (dfun-info-wrapper0 dfun-info))
986                   (unless (eq ow0 wrappers)
987                     (if (eql nindex oindex)
988                         (two-class nindex ow0 wrappers)
989                         (n-n))))
990                  (two-class
991                   (setq oindex (dfun-info-index dfun-info))
992                   (setq ow0 (dfun-info-wrapper0 dfun-info))
993                   (setq ow1 (dfun-info-wrapper1 dfun-info))
994                   (unless (or (eq ow0 wrappers) (eq ow1 wrappers))
995                     (if (eql nindex oindex)
996                         (one-index nindex)
997                         (n-n))))
998                  (one-index
999                   (setq oindex (dfun-info-index dfun-info))
1000                   (setq cache (dfun-info-cache dfun-info))
1001                   (if (eql nindex oindex)
1002                       (do-fill (lambda (ncache)
1003                                  (one-index nindex ncache)))
1004                       (n-n)))
1005                  (n-n
1006                   (setq cache (dfun-info-cache dfun-info))
1007                   (if (consp nindex)
1008                       (caching)
1009                       (do-fill #'n-n))))))))))
1010
1011 (defun checking-miss (generic-function args dfun-info)
1012   (let ((oemf (dfun-info-function dfun-info))
1013         (cache (dfun-info-cache dfun-info)))
1014     (dfun-miss (generic-function args wrappers invalidp nemf)
1015       (cond (invalidp)
1016             ((eq oemf nemf)
1017              ;; The cache of a checking dfun doesn't hold any values,
1018              ;; so this NIL appears to be just a dummy-value we use in
1019              ;; order to insert the wrappers into the cache.
1020              (let ((ncache (fill-cache cache wrappers nil)))
1021                (unless (eq ncache cache)
1022                  (dfun-update generic-function #'make-checking-dfun
1023                               nemf ncache))))
1024             (t
1025              (dfun-update generic-function #'make-caching-dfun))))))
1026
1027 (defun caching-miss (generic-function args dfun-info)
1028   (let ((ocache (dfun-info-cache dfun-info)))
1029     (dfun-miss (generic-function args wrappers invalidp emf nil nil t)
1030       (cond (invalidp)
1031             (t
1032              (let ((ncache (fill-cache ocache wrappers emf)))
1033                (unless (eq ncache ocache)
1034                  (dfun-update generic-function
1035                               #'make-caching-dfun ncache))))))))
1036
1037 (defun constant-value-miss (generic-function args dfun-info)
1038   (let ((ocache (dfun-info-cache dfun-info)))
1039     (dfun-miss (generic-function args wrappers invalidp emf nil nil t)
1040       (unless invalidp
1041         (let* ((value
1042                 (typecase emf
1043                   (constant-fast-method-call
1044                    (constant-fast-method-call-value emf))
1045                   (constant-method-call
1046                    (constant-method-call-value emf))
1047                   (t
1048                    (bug "~S with non-constant EMF ~S" 'constant-value-miss emf))))
1049                (ncache (fill-cache ocache wrappers value)))
1050           (unless (eq ncache ocache)
1051             (dfun-update generic-function
1052                          #'make-constant-value-dfun ncache)))))))
1053 \f
1054 ;;; Given a generic function and a set of arguments to that generic
1055 ;;; function, return a mess of values.
1056 ;;;
1057 ;;;  <function>   The compiled effective method function for this set of
1058 ;;;            arguments.
1059 ;;;
1060 ;;;  <applicable> Sorted list of applicable methods.
1061 ;;;
1062 ;;;  <wrappers>   Is a single wrapper if the generic function has only
1063 ;;;            one key, that is arg-info-nkeys of the arg-info is 1.
1064 ;;;            Otherwise a list of the wrappers of the specialized
1065 ;;;            arguments to the generic function.
1066 ;;;
1067 ;;;            Note that all these wrappers are valid. This function
1068 ;;;            does invalid wrapper traps when it finds an invalid
1069 ;;;            wrapper and then returns the new, valid wrapper.
1070 ;;;
1071 ;;;  <invalidp>   True if any of the specialized arguments had an invalid
1072 ;;;            wrapper, false otherwise.
1073 ;;;
1074 ;;;  <type>       READER or WRITER when the only method that would be run
1075 ;;;            is a standard reader or writer method. To be specific,
1076 ;;;            the value is READER when the method combination is eq to
1077 ;;;            *standard-method-combination*; there are no applicable
1078 ;;;            :before, :after or :around methods; and the most specific
1079 ;;;            primary method is a standard reader method.
1080 ;;;
1081 ;;;  <index>      If <type> is READER or WRITER, and the slot accessed is
1082 ;;;            an :instance slot, this is the index number of that slot
1083 ;;;            in the object argument.
1084 (defvar *cache-miss-values-stack* ())
1085
1086 (defun cache-miss-values (gf args state)
1087   (multiple-value-bind (nreq applyp metatypes nkeys arg-info)
1088       (get-generic-fun-info gf)
1089     (declare (ignore nreq applyp nkeys))
1090     (with-dfun-wrappers (args metatypes)
1091       (dfun-wrappers invalid-wrapper-p wrappers classes types)
1092       (error-need-at-least-n-args gf (length metatypes))
1093       (multiple-value-bind (emf methods accessor-type index)
1094           (cache-miss-values-internal
1095            gf arg-info wrappers classes types state)
1096         (values emf methods
1097                 dfun-wrappers
1098                 invalid-wrapper-p
1099                 accessor-type index)))))
1100
1101 (defun cache-miss-values-internal (gf arg-info wrappers classes types state)
1102   (if (and classes (equal classes (cdr (assq gf *cache-miss-values-stack*))))
1103       (break-vicious-metacircle gf classes arg-info)
1104       (let ((*cache-miss-values-stack*
1105              (acons gf classes *cache-miss-values-stack*))
1106             (cam-std-p (or (null arg-info)
1107                            (gf-info-c-a-m-emf-std-p arg-info))))
1108         (multiple-value-bind (methods all-applicable-and-sorted-p)
1109             (if cam-std-p
1110                 (compute-applicable-methods-using-types gf types)
1111                 (compute-applicable-methods-using-classes gf classes))
1112
1113   (let* ((for-accessor-p (eq state 'accessor))
1114          (for-cache-p (or (eq state 'caching) (eq state 'accessor)))
1115          (emf (if (or cam-std-p all-applicable-and-sorted-p)
1116                   (let ((generator
1117                          (get-secondary-dispatch-function1
1118                           gf methods types nil (and for-cache-p wrappers)
1119                           all-applicable-and-sorted-p)))
1120                     (make-callable gf methods generator
1121                                    nil (and for-cache-p wrappers)))
1122                   (default-secondary-dispatch-function gf))))
1123     (multiple-value-bind (index accessor-type)
1124         (and for-accessor-p all-applicable-and-sorted-p methods
1125              (accessor-values gf arg-info classes methods))
1126       (values (if (integerp index) index emf)
1127               methods accessor-type index)))))))
1128
1129 ;;; Try to break a vicious circle while computing a cache miss.
1130 ;;; GF is the generic function, CLASSES are the classes of actual
1131 ;;; arguments, and ARG-INFO is the generic functions' arg-info.
1132 ;;;
1133 ;;; A vicious circle can be entered when the computation of the cache
1134 ;;; miss values itself depends on the values being computed.  For
1135 ;;; instance, adding a method which is an instance of a subclass of
1136 ;;; STANDARD-METHOD leads to cache misses for slot accessors of
1137 ;;; STANDARD-METHOD like METHOD-SPECIALIZERS, and METHOD-SPECIALIZERS
1138 ;;; is itself used while we compute cache miss values.
1139 (defun break-vicious-metacircle (gf classes arg-info)
1140   (when (typep gf 'standard-generic-function)
1141     (multiple-value-bind (class slotd accessor-type)
1142         (accesses-standard-class-slot-p gf)
1143       (when class
1144         (let ((method (find-standard-class-accessor-method
1145                        gf class accessor-type))
1146               (index (standard-slot-value/eslotd slotd 'location))
1147               (type (gf-info-simple-accessor-type arg-info)))
1148           (when (and method
1149                      (subtypep (ecase accessor-type
1150                                  ((reader) (car classes))
1151                                  ((writer) (cadr classes)))
1152                                class))
1153             (return-from break-vicious-metacircle
1154               (values index (list method) type index)))))))
1155   (error "~@<vicious metacircle:  The computation of an ~
1156           effective method of ~s for arguments of types ~s uses ~
1157           the effective method being computed.~@:>"
1158          gf classes))
1159
1160 ;;; Return (CLASS SLOTD ACCESSOR-TYPE) if some method of generic
1161 ;;; function GF accesses a slot of some class in *STANDARD-CLASSES*.
1162 ;;; CLASS is the class accessed, SLOTD is the effective slot definition
1163 ;;; object of the slot accessed, and ACCESSOR-TYPE is one of the symbols
1164 ;;; READER or WRITER describing the slot access.
1165 (defun accesses-standard-class-slot-p (gf)
1166   (flet ((standard-class-slot-access (gf class)
1167            (loop with gf-name = (standard-slot-value/gf gf 'name)
1168                  for slotd in (standard-slot-value/class class 'slots)
1169                  ;; FIXME: where does BOUNDP fit in here?  Is it
1170                  ;; relevant?
1171                  as readers = (standard-slot-value/eslotd slotd 'readers)
1172                  as writers = (standard-slot-value/eslotd slotd 'writers)
1173                  if (member gf-name readers :test #'equal)
1174                    return (values slotd 'reader)
1175                  else if (member gf-name writers :test #'equal)
1176                    return (values slotd 'writer))))
1177     (dolist (class-name *standard-classes*)
1178       (let ((class (find-class class-name)))
1179         (multiple-value-bind (slotd accessor-type)
1180             (standard-class-slot-access gf class)
1181           (when slotd
1182             (return (values class slotd accessor-type))))))))
1183
1184 ;;; Find a slot reader/writer method among the methods of generic
1185 ;;; function GF which reads/writes instances of class CLASS.
1186 ;;; TYPE is one of the symbols READER or WRITER.
1187 (defun find-standard-class-accessor-method (gf class type)
1188   (let ((cpl (standard-slot-value/class class '%class-precedence-list))
1189         (found-specializer *the-class-t*)
1190         (found-method nil))
1191     (dolist (method (standard-slot-value/gf gf 'methods) found-method)
1192       (let ((specializers (standard-slot-value/method method 'specializers))
1193             (qualifiers (standard-slot-value/method method 'qualifiers)))
1194         (when (and (null qualifiers)
1195                    (let ((subcpl (member (ecase type
1196                                            (reader (car specializers))
1197                                            (writer (cadr specializers)))
1198                                          cpl :test #'eq)))
1199                      (and subcpl (member found-specializer subcpl :test #'eq))))
1200           (setf found-specializer (ecase type
1201                                     (reader (car specializers))
1202                                     (writer (cadr specializers))))
1203           (setf found-method method))))))
1204
1205 (defun accessor-values (gf arg-info classes methods)
1206   (declare (ignore gf))
1207   (let* ((accessor-type (gf-info-simple-accessor-type arg-info))
1208          (accessor-class (case accessor-type
1209                            ((reader boundp) (car classes))
1210                            (writer (cadr classes)))))
1211     (accessor-values-internal accessor-type accessor-class methods)))
1212
1213 (defun accessor-values1 (gf accessor-type accessor-class)
1214   (let* ((type `(class-eq ,accessor-class))
1215          (types (ecase accessor-type
1216                   ((reader boundp) `(,type))
1217                   (writer `(t ,type))))
1218          (methods (compute-applicable-methods-using-types gf types)))
1219     (accessor-values-internal accessor-type accessor-class methods)))
1220
1221 (defun accessor-values-internal (accessor-type accessor-class methods)
1222   (dolist (meth methods)
1223     (when (if (consp meth)
1224               (early-method-qualifiers meth)
1225               (safe-method-qualifiers meth))
1226       (return-from accessor-values-internal (values nil nil))))
1227   (let* ((meth (car methods))
1228          (early-p (not (eq *boot-state* 'complete)))
1229          (slot-name (when accessor-class
1230                       (if (consp meth)
1231                           (and (early-method-standard-accessor-p meth)
1232                                (early-method-standard-accessor-slot-name meth))
1233                           (and (member *the-class-standard-object*
1234                                        (if early-p
1235                                            (early-class-precedence-list
1236                                             accessor-class)
1237                                            (class-precedence-list
1238                                             accessor-class))
1239                                        :test #'eq)
1240                                (if early-p
1241                                    (not (eq *the-class-standard-method*
1242                                             (early-method-class meth)))
1243                                    (accessor-method-p meth))
1244                                (if early-p
1245                                    (early-accessor-method-slot-name meth)
1246                                    (accessor-method-slot-name meth))))))
1247          (slotd (and accessor-class
1248                      (if early-p
1249                          (dolist (slot (early-class-slotds accessor-class) nil)
1250                            (when (eql slot-name
1251                                       (early-slot-definition-name slot))
1252                              (return slot)))
1253                          (find-slot-definition accessor-class slot-name)))))
1254     (when (and slotd
1255                (or early-p
1256                    (slot-accessor-std-p slotd accessor-type))
1257                (or early-p
1258                    (not (safe-p accessor-class))))
1259       (values (if early-p
1260                   (early-slot-definition-location slotd)
1261                   (slot-definition-location slotd))
1262               accessor-type))))
1263
1264 (defun make-accessor-table (gf type &optional table)
1265   (unless table (setq table (make-hash-table :test 'eq)))
1266   (let ((methods (if (early-gf-p gf)
1267                      (early-gf-methods gf)
1268                      (generic-function-methods gf)))
1269         (all-index nil)
1270         (no-class-slots-p t)
1271         (early-p (not (eq *boot-state* 'complete)))
1272         first second (size 0))
1273     (declare (fixnum size))
1274     ;; class -> {(specl slotd)}
1275     (dolist (method methods)
1276       (let* ((specializers (if (consp method)
1277                                (early-method-specializers method t)
1278                                (method-specializers method)))
1279              (specl (ecase type
1280                       ((reader boundp) (car specializers))
1281                       (writer (cadr specializers))))
1282              (specl-cpl (if early-p
1283                             (early-class-precedence-list specl)
1284                             (when (class-finalized-p specl)
1285                               (class-precedence-list specl))))
1286              (so-p (member *the-class-standard-object* specl-cpl :test #'eq))
1287              (slot-name (if (consp method)
1288                             (and (early-method-standard-accessor-p method)
1289                                  (early-method-standard-accessor-slot-name
1290                                   method))
1291                             (accessor-method-slot-name method))))
1292         (when (or (null specl-cpl)
1293                   (null so-p)
1294                   (member *the-class-structure-object* specl-cpl :test #'eq))
1295           (return-from make-accessor-table nil))
1296         ;; Collect all the slot-definitions for SLOT-NAME from SPECL and
1297         ;; all of its subclasses. If either SPECL or one of the subclasses
1298         ;; is not a standard-class, bail out.
1299         (labels ((aux (class)
1300                    (let ((slotd (find-slot-definition class slot-name)))
1301                      (when slotd
1302                        (unless (or early-p (slot-accessor-std-p slotd type))
1303                          (return-from make-accessor-table nil))
1304                        (push (cons specl slotd) (gethash class table))))
1305                    (dolist (subclass (sb-pcl::class-direct-subclasses class))
1306                      (unless (class-finalized-p subclass)
1307                        (return-from make-accessor-table nil))
1308                      (aux subclass))))
1309           (aux specl))))
1310     (maphash (lambda (class specl+slotd-list)
1311                (dolist (sclass (if early-p
1312                                    (early-class-precedence-list class)
1313                                    (class-precedence-list class))
1314                                (error "This can't happen."))
1315                  (let ((a (assq sclass specl+slotd-list)))
1316                    (when a
1317                      (let* ((slotd (cdr a))
1318                             (index (if early-p
1319                                        (early-slot-definition-location slotd)
1320                                        (slot-definition-location slotd))))
1321                        (unless index (return-from make-accessor-table nil))
1322                        (setf (gethash class table) index)
1323                        (when (consp index) (setq no-class-slots-p nil))
1324                        (setq all-index (if (or (null all-index)
1325                                                (eql all-index index))
1326                                            index t))
1327                        (incf size)
1328                        (cond ((= size 1) (setq first class))
1329                              ((= size 2) (setq second class)))
1330                        (return nil))))))
1331              table)
1332     (values table all-index first second size no-class-slots-p)))
1333
1334 (defun compute-applicable-methods-using-types (generic-function types)
1335   (let ((definite-p t) (possibly-applicable-methods nil))
1336     (dolist (method (if (early-gf-p generic-function)
1337                         (early-gf-methods generic-function)
1338                         (safe-generic-function-methods generic-function)))
1339       (let ((specls (if (consp method)
1340                         (early-method-specializers method t)
1341                         (safe-method-specializers method)))
1342             (types types)
1343             (possibly-applicable-p t) (applicable-p t))
1344         (dolist (specl specls)
1345           (multiple-value-bind (specl-applicable-p specl-possibly-applicable-p)
1346               (specializer-applicable-using-type-p specl (pop types))
1347             (unless specl-applicable-p
1348               (setq applicable-p nil))
1349             (unless specl-possibly-applicable-p
1350               (setq possibly-applicable-p nil)
1351               (return nil))))
1352         (when possibly-applicable-p
1353           (unless applicable-p (setq definite-p nil))
1354           (push method possibly-applicable-methods))))
1355     (multiple-value-bind (nreq applyp metatypes nkeys arg-info)
1356         (get-generic-fun-info generic-function)
1357       (declare (ignore nreq applyp metatypes nkeys))
1358       (let* ((precedence (arg-info-precedence arg-info)))
1359         (values (sort-applicable-methods precedence
1360                                          (nreverse possibly-applicable-methods)
1361                                          types)
1362                 definite-p)))))
1363
1364 (defun sort-applicable-methods (precedence methods types)
1365   (sort-methods methods
1366                 precedence
1367                 (lambda (class1 class2 index)
1368                   (let* ((class (type-class (nth index types)))
1369                          (cpl (if (eq *boot-state* 'complete)
1370                                   (class-precedence-list class)
1371                                   (early-class-precedence-list class))))
1372                     (if (memq class2 (memq class1 cpl))
1373                         class1 class2)))))
1374
1375 (defun sort-methods (methods precedence compare-classes-function)
1376   (flet ((sorter (method1 method2)
1377            (dolist (index precedence)
1378              (let* ((specl1 (nth index (if (listp method1)
1379                                            (early-method-specializers method1
1380                                                                       t)
1381                                            (method-specializers method1))))
1382                     (specl2 (nth index (if (listp method2)
1383                                            (early-method-specializers method2
1384                                                                       t)
1385                                            (method-specializers method2))))
1386                     (order (order-specializers
1387                              specl1 specl2 index compare-classes-function)))
1388                (when order
1389                  (return-from sorter (eq order specl1)))))))
1390     (stable-sort methods #'sorter)))
1391
1392 (defun order-specializers (specl1 specl2 index compare-classes-function)
1393   (let ((type1 (if (eq *boot-state* 'complete)
1394                    (specializer-type specl1)
1395                    (!bootstrap-get-slot 'specializer specl1 '%type)))
1396         (type2 (if (eq *boot-state* 'complete)
1397                    (specializer-type specl2)
1398                    (!bootstrap-get-slot 'specializer specl2 '%type))))
1399     (cond ((eq specl1 specl2)
1400            nil)
1401           ((atom type1)
1402            specl2)
1403           ((atom type2)
1404            specl1)
1405           (t
1406            (case (car type1)
1407              (class    (case (car type2)
1408                          (class (funcall compare-classes-function
1409                                          specl1 specl2 index))
1410                          (t specl2)))
1411              (prototype (case (car type2)
1412                          (class (funcall compare-classes-function
1413                                          specl1 specl2 index))
1414                          (t specl2)))
1415              (class-eq (case (car type2)
1416                          (eql specl2)
1417                          ;; FIXME: This says that all CLASS-EQ
1418                          ;; specializers are equally specific, which
1419                          ;; is fair enough because only one CLASS-EQ
1420                          ;; specializer can ever be appliable.  If
1421                          ;; ORDER-SPECIALIZERS should only ever be
1422                          ;; called on specializers from applicable
1423                          ;; methods, we could replace this with a BUG.
1424                          (class-eq nil)
1425                          (class type1)))
1426              (eql      (case (car type2)
1427                          ;; similarly.
1428                          (eql nil)
1429                          (t specl1))))))))
1430
1431 (defun map-all-orders (methods precedence function)
1432   (let ((choices nil))
1433     (flet ((compare-classes-function (class1 class2 index)
1434              (declare (ignore index))
1435              (let ((choice nil))
1436                (dolist (c choices nil)
1437                  (when (or (and (eq (first c) class1)
1438                                 (eq (second c) class2))
1439                            (and (eq (first c) class2)
1440                                 (eq (second c) class1)))
1441                    (return (setq choice c))))
1442                (unless choice
1443                  (setq choice
1444                        (if (class-might-precede-p class1 class2)
1445                            (if (class-might-precede-p class2 class1)
1446                                (list class1 class2 nil t)
1447                                (list class1 class2 t))
1448                            (if (class-might-precede-p class2 class1)
1449                                (list class2 class1 t)
1450                                (let ((name1 (class-name class1))
1451                                      (name2 (class-name class2)))
1452                                  (if (and name1
1453                                           name2
1454                                           (symbolp name1)
1455                                           (symbolp name2)
1456                                           (string< (symbol-name name1)
1457                                                    (symbol-name name2)))
1458                                      (list class1 class2 t)
1459                                      (list class2 class1 t))))))
1460                  (push choice choices))
1461                (car choice))))
1462       (loop (funcall function
1463                      (sort-methods methods
1464                                    precedence
1465                                    #'compare-classes-function))
1466             (unless (dolist (c choices nil)
1467                       (unless (third c)
1468                         (rotatef (car c) (cadr c))
1469                         (return (setf (third c) t))))
1470               (return nil))))))
1471
1472 ;;; CMUCL comment: used only in map-all-orders
1473 (defun class-might-precede-p (class1 class2)
1474   (if (not *in-precompute-effective-methods-p*)
1475       (not (member class1 (cdr (class-precedence-list class2)) :test #'eq))
1476       (class-can-precede-p class1 class2)))
1477
1478 (defun compute-precedence (lambda-list nreq argument-precedence-order)
1479   (if (null argument-precedence-order)
1480       (let ((list nil))
1481         (dotimes-fixnum (i nreq list) (push (- (1- nreq) i) list)))
1482       (mapcar (lambda (x) (position x lambda-list))
1483               argument-precedence-order)))
1484
1485 (defun cpl-or-nil (class)
1486   (if (eq *boot-state* 'complete)
1487       (progn
1488         ;; KLUDGE: why not use (slot-boundp class
1489         ;; 'class-precedence-list)?  Well, unfortunately, CPL-OR-NIL is
1490         ;; used within COMPUTE-APPLICABLE-METHODS, including for
1491         ;; SLOT-BOUNDP-USING-CLASS... and the available mechanism for
1492         ;; breaking such nasty cycles in effective method computation
1493         ;; only works for readers and writers, not boundps.  It might
1494         ;; not be too hard to make it work for BOUNDP accessors, but in
1495         ;; the meantime we use an extra slot for exactly the result of
1496         ;; the SLOT-BOUNDP that we want.  (We cannot use
1497         ;; CLASS-FINALIZED-P, because in the process of class
1498         ;; finalization we need to use the CPL which has been computed
1499         ;; to cache effective methods for slot accessors.) -- CSR,
1500         ;; 2004-09-19.
1501
1502         (when (cpl-available-p class)
1503           (return-from cpl-or-nil (class-precedence-list class)))
1504
1505         ;; if we can finalize an unfinalized class, then do so
1506         (when (and (not (class-finalized-p class))
1507                    (not (class-has-a-forward-referenced-superclass-p class)))
1508           (finalize-inheritance class)
1509           (class-precedence-list class)))
1510
1511       (early-class-precedence-list class)))
1512
1513 (defun saut-and (specl type)
1514   (let ((applicable nil)
1515         (possibly-applicable t))
1516     (dolist (type (cdr type))
1517       (multiple-value-bind (appl poss-appl)
1518           (specializer-applicable-using-type-p specl type)
1519         (when appl (return (setq applicable t)))
1520         (unless poss-appl (return (setq possibly-applicable nil)))))
1521     (values applicable possibly-applicable)))
1522
1523 (defun saut-not (specl type)
1524   (let ((ntype (cadr type)))
1525     (values nil
1526             (case (car ntype)
1527               (class      (saut-not-class specl ntype))
1528               (class-eq   (saut-not-class-eq specl ntype))
1529               (prototype  (saut-not-prototype specl ntype))
1530               (eql      (saut-not-eql specl ntype))
1531               (t (error "~S cannot handle the second argument ~S"
1532                         'specializer-applicable-using-type-p type))))))
1533
1534 (defun saut-not-class (specl ntype)
1535   (let* ((class (type-class specl))
1536          (cpl (cpl-or-nil class)))
1537     (not (memq (cadr ntype) cpl))))
1538
1539 (defun saut-not-prototype (specl ntype)
1540   (let* ((class (case (car specl)
1541                   (eql       (class-of (cadr specl)))
1542                   (class-eq  (cadr specl))
1543                   (prototype (cadr specl))
1544                   (class     (cadr specl))))
1545          (cpl (cpl-or-nil class)))
1546     (not (memq (cadr ntype) cpl))))
1547
1548 (defun saut-not-class-eq (specl ntype)
1549   (let ((class (case (car specl)
1550                  (eql      (class-of (cadr specl)))
1551                  (class-eq (cadr specl)))))
1552     (not (eq class (cadr ntype)))))
1553
1554 (defun saut-not-eql (specl ntype)
1555   (case (car specl)
1556     (eql (not (eql (cadr specl) (cadr ntype))))
1557     (t   t)))
1558
1559 (defun class-applicable-using-class-p (specl type)
1560   (let ((pred (memq specl (cpl-or-nil type))))
1561     (values pred
1562             (or pred
1563                 (if (not *in-precompute-effective-methods-p*)
1564                     ;; classes might get common subclass
1565                     (superclasses-compatible-p specl type)
1566                     ;; worry only about existing classes
1567                     (classes-have-common-subclass-p specl type))))))
1568
1569 (defun classes-have-common-subclass-p (class1 class2)
1570   (or (eq class1 class2)
1571       (let ((class1-subs (class-direct-subclasses class1)))
1572         (or (memq class2 class1-subs)
1573             (dolist (class1-sub class1-subs nil)
1574               (when (classes-have-common-subclass-p class1-sub class2)
1575                 (return t)))))))
1576
1577 (defun saut-class (specl type)
1578   (case (car specl)
1579     (class (class-applicable-using-class-p (cadr specl) (cadr type)))
1580     (t     (values nil (let ((class (type-class specl)))
1581                          (memq (cadr type)
1582                                (cpl-or-nil class)))))))
1583
1584 (defun saut-class-eq (specl type)
1585   (if (eq (car specl) 'eql)
1586       (values nil (eq (class-of (cadr specl)) (cadr type)))
1587       (let ((pred (case (car specl)
1588                     (class-eq
1589                      (eq (cadr specl) (cadr type)))
1590                     (class
1591                      (or (eq (cadr specl) (cadr type))
1592                          (memq (cadr specl) (cpl-or-nil (cadr type))))))))
1593         (values pred pred))))
1594
1595 (defun saut-prototype (specl type)
1596   (declare (ignore specl type))
1597   (values nil nil)) ; XXX original PCL comment: fix this someday
1598
1599 (defun saut-eql (specl type)
1600   (let ((pred (case (car specl)
1601                 (eql    (eql (cadr specl) (cadr type)))
1602                 (class-eq   (eq (cadr specl) (class-of (cadr type))))
1603                 (class      (memq (cadr specl)
1604                                   (let ((class (class-of (cadr type))))
1605                                     (cpl-or-nil class)))))))
1606     (values pred pred)))
1607
1608 (defun specializer-applicable-using-type-p (specl type)
1609   (setq specl (type-from-specializer specl))
1610   (when (eq specl t)
1611     (return-from specializer-applicable-using-type-p (values t t)))
1612   ;; This is used by C-A-M-U-T and GENERATE-DISCRIMINATION-NET-INTERNAL,
1613   ;; and has only what they need.
1614   (if (or (atom type) (eq (car type) t))
1615       (values nil t)
1616       (case (car type)
1617         (and    (saut-and specl type))
1618         (not    (saut-not specl type))
1619         (class      (saut-class specl type))
1620         (prototype  (saut-prototype specl type))
1621         (class-eq   (saut-class-eq specl type))
1622         (eql    (saut-eql specl type))
1623         (t        (error "~S cannot handle the second argument ~S."
1624                            'specializer-applicable-using-type-p
1625                            type)))))
1626
1627 (defun map-all-classes (fun &optional (root t))
1628   (let ((all-classes (make-hash-table :test 'eq))
1629         (braid-p (or (eq *boot-state* 'braid)
1630                      (eq *boot-state* 'complete))))
1631     (labels ((do-class (class)
1632                (unless (gethash class all-classes)
1633                  (setf (gethash class all-classes) t)
1634                  (funcall fun class)
1635                  (mapc #'do-class
1636                        (if braid-p
1637                            (class-direct-subclasses class)
1638                            (early-class-direct-subclasses class))))))
1639       (do-class (if (symbolp root)
1640                     (find-class root)
1641                     root)))
1642     nil))
1643 \f
1644 ;;; Not synchronized, as all the uses we have for it are multiple ones
1645 ;;; and need WITH-LOCKED-HASH-TABLE in any case.
1646 ;;;
1647 ;;; FIXME: Is it really more efficient to store this stuff in a global
1648 ;;; table instead of having a slot in each method?
1649 ;;;
1650 ;;; FIXME: This table also seems to contain early methods, which should
1651 ;;; presumably be dropped during the bootstrap.
1652 (defvar *effective-method-cache* (make-hash-table :test 'eq))
1653
1654 (defun flush-effective-method-cache (generic-function)
1655   (let ((cache *effective-method-cache*))
1656     (with-locked-hash-table (cache)
1657       (dolist (method (generic-function-methods generic-function))
1658         (remhash method cache)))))
1659
1660 (defun get-secondary-dispatch-function (gf methods types
1661                                         &optional method-alist wrappers)
1662   (let ((generator
1663          (get-secondary-dispatch-function1
1664           gf methods types (not (null method-alist)) (not (null wrappers))
1665           (not (methods-contain-eql-specializer-p methods)))))
1666     (make-callable gf methods generator method-alist wrappers)))
1667
1668 (defun get-secondary-dispatch-function1 (gf methods types method-alist-p
1669                                             wrappers-p
1670                                             &optional
1671                                             all-applicable-p
1672                                             (all-sorted-p t)
1673                                             function-p)
1674    (if (null methods)
1675       (if function-p
1676           (lambda (method-alist wrappers)
1677             (declare (ignore method-alist wrappers))
1678             #'(lambda (&rest args)
1679                 (apply #'no-applicable-method gf args)))
1680           (lambda (method-alist wrappers)
1681             (declare (ignore method-alist wrappers))
1682             (lambda (&rest args)
1683               (apply #'no-applicable-method gf args))))
1684       (let* ((key (car methods))
1685              (ht *effective-method-cache*)
1686              (ht-value (with-locked-hash-table (ht)
1687                          (or (gethash key ht)
1688                              (setf (gethash key ht) (cons nil nil))))))
1689         (if (and (null (cdr methods)) all-applicable-p ; the most common case
1690                  (null method-alist-p) wrappers-p (not function-p))
1691             (or (car ht-value)
1692                 (setf (car ht-value)
1693                       (get-secondary-dispatch-function2
1694                        gf methods types method-alist-p wrappers-p
1695                        all-applicable-p all-sorted-p function-p)))
1696             (let ((akey (list methods
1697                               (if all-applicable-p 'all-applicable types)
1698                               method-alist-p wrappers-p function-p)))
1699               (or (cdr (assoc akey (cdr ht-value) :test #'equal))
1700                   (let ((value (get-secondary-dispatch-function2
1701                                 gf methods types method-alist-p wrappers-p
1702                                 all-applicable-p all-sorted-p function-p)))
1703                     (push (cons akey value) (cdr ht-value))
1704                     value)))))))
1705
1706 (defun get-secondary-dispatch-function2 (gf methods types method-alist-p
1707                                             wrappers-p all-applicable-p
1708                                             all-sorted-p function-p)
1709   (if (and all-applicable-p all-sorted-p (not function-p))
1710       (if (eq *boot-state* 'complete)
1711           (let* ((combin (generic-function-method-combination gf))
1712                  (effective (compute-effective-method gf combin methods)))
1713             (make-effective-method-function1 gf effective method-alist-p
1714                                              wrappers-p))
1715           (let ((effective (standard-compute-effective-method gf nil methods)))
1716             (make-effective-method-function1 gf effective method-alist-p
1717                                              wrappers-p)))
1718       (let ((net (generate-discrimination-net
1719                   gf methods types all-sorted-p)))
1720         (compute-secondary-dispatch-function1 gf net function-p))))
1721
1722 (defun get-effective-method-function (gf methods
1723                                          &optional method-alist wrappers)
1724   (let ((generator
1725          (get-secondary-dispatch-function1
1726           gf methods nil (not (null method-alist)) (not (null wrappers)) t)))
1727     (make-callable gf methods generator method-alist wrappers)))
1728
1729 (defun get-effective-method-function1 (gf methods &optional (sorted-p t))
1730   (get-secondary-dispatch-function1 gf methods nil nil nil t sorted-p))
1731
1732 (defun methods-contain-eql-specializer-p (methods)
1733   (and (eq *boot-state* 'complete)
1734        (dolist (method methods nil)
1735          (when (dolist (spec (method-specializers method) nil)
1736                  (when (eql-specializer-p spec) (return t)))
1737            (return t)))))
1738 \f
1739 (defun update-dfun (generic-function &optional dfun cache info)
1740   (let ((early-p (early-gf-p generic-function)))
1741     (flet ((update ()
1742              ;; Save DFUN-STATE, so that COMPUTE-DISCRIMINATING-FUNCTION can
1743              ;; access it, and so that it's there for eg. future cache updates.
1744              (set-dfun generic-function dfun cache info)
1745              (let ((dfun (if early-p
1746                              (or dfun (make-initial-dfun generic-function))
1747                              (compute-discriminating-function generic-function))))
1748                (set-funcallable-instance-function generic-function dfun)
1749                (let ((gf-name (if early-p
1750                                   (!early-gf-name generic-function)
1751                                   (generic-function-name generic-function))))
1752                  (set-fun-name generic-function gf-name)
1753                  dfun))))
1754       ;; This needs to be atomic per generic function, consider:
1755       ;;   1. T1 sets dfun-state to S1 and computes discr. fun using S1
1756       ;;   2. T2 sets dfun-state to S2 and computes discr. fun using S2
1757       ;;   3. T2 sets fin
1758       ;;   4. T1 sets fin
1759       ;; Oops: now dfun-state and fin don't match! Since just calling
1760       ;; a generic can cause the dispatch function to be updated we
1761       ;; need a lock here.
1762       ;;
1763       ;; We need to accept recursion, because PCL is nasty and twisty,
1764       ;; and we need to disable interrupts because it would be bad if
1765       ;; we updated the DFUN-STATE but not the dispatch function.
1766       ;;
1767       ;; This is sufficient, because all the other calls to SET-DFUN
1768       ;; are part of this same code path (done while the lock is held),
1769       ;; which we AVER.
1770       ;;
1771       ;; FIXME: When our mutexes are smart about the need to wake up
1772       ;; sleepers we can put a mutex here instead -- but in the meantime
1773       ;; we use a spinlock to avoid a syscall for every dfun update.
1774       ;;
1775       ;; KLUDGE: No need to lock during bootstrap.
1776       (if early-p
1777           (update)
1778           (let ((lock (gf-lock generic-function)))
1779             ;; FIXME: GF-LOCK is a generic function... Are there cases
1780             ;; where we can end up in a metacircular loop here? In
1781             ;; case there are, better fetch it while interrupts are
1782             ;; still enabled...
1783             (sb-thread::call-with-recursive-system-spinlock #'update lock))))))
1784 \f
1785 (defvar *dfun-count* nil)
1786 (defvar *dfun-list* nil)
1787 (defvar *minimum-cache-size-to-list*)
1788
1789 ;;; These functions aren't used in SBCL, or documented anywhere that
1790 ;;; I'm aware of, but they look like they might be useful for
1791 ;;; debugging or performance tweaking or something, so I've just
1792 ;;; commented them out instead of deleting them. -- WHN 2001-03-28
1793 #||
1794 (defun list-dfun (gf)
1795   (let* ((sym (type-of (gf-dfun-info gf)))
1796          (a (assq sym *dfun-list*)))
1797     (unless a
1798       (push (setq a (list sym)) *dfun-list*))
1799     (push (generic-function-name gf) (cdr a))))
1800
1801 (defun list-all-dfuns ()
1802   (setq *dfun-list* nil)
1803   (map-all-generic-functions #'list-dfun)
1804   *dfun-list*)
1805
1806 (defun list-large-cache (gf)
1807   (let* ((sym (type-of (gf-dfun-info gf)))
1808          (cache (gf-dfun-cache gf)))
1809     (when cache
1810       (let ((size (cache-size cache)))
1811         (when (>= size *minimum-cache-size-to-list*)
1812           (let ((a (assoc size *dfun-list*)))
1813             (unless a
1814               (push (setq a (list size)) *dfun-list*))
1815             (push (let ((name (generic-function-name gf)))
1816                     (if (eq sym 'caching) name (list name sym)))
1817                   (cdr a))))))))
1818
1819 (defun list-large-caches (&optional (*minimum-cache-size-to-list* 130))
1820   (setq *dfun-list* nil)
1821   (map-all-generic-functions #'list-large-cache)
1822   (setq *dfun-list* (sort *dfun-list* #'< :key #'car))
1823   (mapc #'print *dfun-list*)
1824   (values))
1825
1826 (defun count-dfun (gf)
1827   (let* ((sym (type-of (gf-dfun-info gf)))
1828          (cache (gf-dfun-cache gf))
1829          (a (assq sym *dfun-count*)))
1830     (unless a
1831       (push (setq a (list sym 0 nil)) *dfun-count*))
1832     (incf (cadr a))
1833     (when cache
1834       (let* ((size (cache-size cache))
1835              (b (assoc size (third a))))
1836         (unless b
1837           (push (setq b (cons size 0)) (third a)))
1838         (incf (cdr b))))))
1839
1840 (defun count-all-dfuns ()
1841   (setq *dfun-count* (mapcar (lambda (type) (list type 0 nil))
1842                              '(ONE-CLASS TWO-CLASS DEFAULT-METHOD-ONLY
1843                                ONE-INDEX N-N CHECKING CACHING
1844                                DISPATCH)))
1845   (map-all-generic-functions #'count-dfun)
1846   (mapc (lambda (type+count+sizes)
1847           (setf (third type+count+sizes)
1848                 (sort (third type+count+sizes) #'< :key #'car)))
1849         *dfun-count*)
1850   (mapc (lambda (type+count+sizes)
1851           (format t "~&There are ~W dfuns of type ~S."
1852                   (cadr type+count+sizes) (car type+count+sizes))
1853           (format t "~%   ~S~%" (caddr type+count+sizes)))
1854         *dfun-count*)
1855   (values))
1856 ||#
1857
1858 (defun gfs-of-type (type)
1859   (unless (consp type) (setq type (list type)))
1860   (let ((gf-list nil))
1861     (map-all-generic-functions (lambda (gf)
1862                                  (when (memq (type-of (gf-dfun-info gf))
1863                                              type)
1864                                    (push gf gf-list))))
1865     gf-list))