0.6.11.43:
[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 |#
79 \f
80 ;;; an alist in which each entry is of the form
81 ;;;   (<generator> . (<subentry> ...)).
82 ;;; Each subentry is of the form
83 ;;;   (<args> <constructor> <system>).
84 (defvar *dfun-constructors* ())                 
85
86 ;;; If this is NIL, then the whole mechanism for caching dfun constructors is
87 ;;; turned off. The only time that makes sense is when debugging LAP code.
88 (defvar *enable-dfun-constructor-caching* t)    
89
90 (defun show-dfun-constructors ()
91   (format t "~&DFUN constructor caching is ~A."
92           (if *enable-dfun-constructor-caching*
93               "enabled" "disabled"))
94   (dolist (generator-entry *dfun-constructors*)
95     (dolist (args-entry (cdr generator-entry))
96       (format t "~&~S ~S"
97               (cons (car generator-entry) (caar args-entry))
98               (caddr args-entry)))))
99
100 (defvar *raise-metatypes-to-class-p* t)
101
102 (defun get-dfun-constructor (generator &rest args)
103   (when (and *raise-metatypes-to-class-p*
104              (member generator '(emit-checking emit-caching
105                                  emit-in-checking-cache-p emit-constant-value)))
106     (setq args (cons (mapcar #'(lambda (mt)
107                                  (if (eq mt t)
108                                      mt
109                                      'class))
110                              (car args))
111                      (cdr args))))
112   (let* ((generator-entry (assq generator *dfun-constructors*))
113          (args-entry (assoc args (cdr generator-entry) :test #'equal)))
114     (if (null *enable-dfun-constructor-caching*)
115         (apply (fdefinition generator) args)
116         (or (cadr args-entry)
117             (multiple-value-bind (new not-best-p)
118                 (apply (symbol-function generator) args)
119               (let ((entry (list (copy-list args) new (unless not-best-p 'pcl)
120                                  not-best-p)))
121                 (if generator-entry
122                     (push entry (cdr generator-entry))
123                     (push (list generator entry)
124                           *dfun-constructors*)))
125               (values new not-best-p))))))
126
127 (defun load-precompiled-dfun-constructor (generator args system constructor)
128   (let* ((generator-entry (assq generator *dfun-constructors*))
129          (args-entry (assoc args (cdr generator-entry) :test #'equal)))
130     (if args-entry
131         (when (fourth args-entry)
132           (let* ((dfun-type (case generator
133                               (emit-checking 'checking)
134                               (emit-caching 'caching)
135                               (emit-constant-value 'constant-value)
136                               (emit-default-only 'default-method-only)))
137                  (metatypes (car args))
138                  (gfs (when dfun-type (gfs-of-type dfun-type))))
139             (dolist (gf gfs)
140               (when (and (equal metatypes
141                                 (arg-info-metatypes (gf-arg-info gf)))
142                          (let ((gf-name (generic-function-name gf)))
143                            (and (not (eq gf-name 'slot-value-using-class))
144                                 (not (equal gf-name
145                                             '(setf slot-value-using-class)))
146                                 (not (eq gf-name 'slot-boundp-using-class)))))
147                 (update-dfun gf)))
148             (setf (second args-entry) constructor)
149             (setf (third args-entry) system)
150             (setf (fourth args-entry) nil)))
151         (let ((entry (list args constructor system nil)))
152           (if generator-entry
153               (push entry (cdr generator-entry))
154               (push (list generator entry) *dfun-constructors*))))))
155
156 (defmacro precompile-dfun-constructors (&optional system)
157   (let ((*precompiling-lap* t))
158     `(progn
159        ,@(gathering1 (collecting)
160            (dolist (generator-entry *dfun-constructors*)
161              (dolist (args-entry (cdr generator-entry))
162                (when (or (null (caddr args-entry))
163                          (eq (caddr args-entry) system))
164                  (when system (setf (caddr args-entry) system))
165                  (gather1
166                   `(load-precompiled-dfun-constructor
167                     ',(car generator-entry)
168                     ',(car args-entry)
169                     ',system
170                     ,(apply (fdefinition (car generator-entry))
171                             (car args-entry)))))))))))
172 \f
173 ;;; When all the methods of a generic function are automatically
174 ;;; generated reader or writer methods a number of special
175 ;;; optimizations are possible. These are important because of the
176 ;;; large number of generic functions of this type.
177 ;;;
178 ;;; There are a number of cases:
179 ;;;
180 ;;;   ONE-CLASS-ACCESSOR
181 ;;;     In this case, the accessor generic function has only been
182 ;;;     called with one class of argument. There is no cache vector,
183 ;;;     the wrapper of the one class, and the slot index are stored
184 ;;;     directly as closure variables of the discriminating function.
185 ;;;     This case can convert to either of the next kind.
186 ;;;
187 ;;;   TWO-CLASS-ACCESSOR
188 ;;;     Like above, but two classes. This is common enough to do
189 ;;;     specially. There is no cache vector. The two classes are
190 ;;;     stored a separate closure variables.
191 ;;;
192 ;;;   ONE-INDEX-ACCESSOR
193 ;;;     In this case, the accessor generic function has seen more than
194 ;;;     one class of argument, but the index of the slot is the same
195 ;;;     for all the classes that have been seen. A cache vector is
196 ;;;     used to store the wrappers that have been seen, the slot index
197 ;;;     is stored directly as a closure variable of the discriminating
198 ;;;     function. This case can convert to the next kind.
199 ;;;
200 ;;;   N-N-ACCESSOR
201 ;;;     This is the most general case. In this case, the accessor
202 ;;;     generic function has seen more than one class of argument and
203 ;;;     more than one slot index. A cache vector stores the wrappers
204 ;;;     and corresponding slot indexes. Because each cache line is
205 ;;;     more than one element long, a cache lock count is used.
206 (defstruct (dfun-info (:constructor nil)
207                       (:copier nil))
208   (cache nil))
209
210 (defstruct (no-methods (:constructor no-methods-dfun-info ())
211                        (:include dfun-info)
212                        (:copier nil)))
213
214 (defstruct (initial (:constructor initial-dfun-info ())
215                     (:include dfun-info)
216                     (:copier nil)))
217
218 (defstruct (initial-dispatch (:constructor initial-dispatch-dfun-info ())
219                              (:include dfun-info)
220                              (:copier nil)))
221
222 (defstruct (dispatch (:constructor dispatch-dfun-info ())
223                      (:include dfun-info)
224                      (:copier nil)))
225
226 (defstruct (default-method-only (:constructor default-method-only-dfun-info ())
227                                 (:include dfun-info)
228                                 (:copier nil)))
229
230 ;without caching:
231 ;  dispatch one-class two-class default-method-only
232
233 ;with caching:
234 ;  one-index n-n checking caching
235
236 ;accessor:
237 ;  one-class two-class one-index n-n
238 (defstruct (accessor-dfun-info (:constructor nil)
239                                (:include dfun-info)
240                                (:copier nil))
241   accessor-type) ; (member reader writer)
242
243 (defmacro dfun-info-accessor-type (di)
244   `(accessor-dfun-info-accessor-type ,di))
245
246 (defstruct (one-index-dfun-info (:constructor nil)
247                                 (:include accessor-dfun-info)
248                                 (:copier nil))
249   index)
250
251 (defmacro dfun-info-index (di)
252   `(one-index-dfun-info-index ,di))
253
254 (defstruct (n-n (:constructor n-n-dfun-info (accessor-type cache))
255                 (:include accessor-dfun-info)
256                 (:copier nil)))
257
258 (defstruct (one-class (:constructor one-class-dfun-info
259                                     (accessor-type index wrapper0))
260                       (:include one-index-dfun-info)
261                       (:copier nil))
262   wrapper0)
263
264 (defmacro dfun-info-wrapper0 (di)
265   `(one-class-wrapper0 ,di))
266
267 (defstruct (two-class (:constructor two-class-dfun-info
268                                     (accessor-type index wrapper0 wrapper1))
269                       (:include one-class)
270                       (:copier nil))
271   wrapper1)
272
273 (defmacro dfun-info-wrapper1 (di)
274   `(two-class-wrapper1 ,di))
275
276 (defstruct (one-index (:constructor one-index-dfun-info
277                                     (accessor-type index cache))
278                       (:include one-index-dfun-info)
279                       (:copier nil)))
280
281 (defstruct (checking (:constructor checking-dfun-info (function cache))
282                      (:include dfun-info)
283                      (:copier nil))
284   function)
285
286 (defmacro dfun-info-function (di)
287   `(checking-function ,di))
288
289 (defstruct (caching (:constructor caching-dfun-info (cache))
290                     (:include dfun-info)
291                     (:copier nil)))
292
293 (defstruct (constant-value (:constructor constant-value-dfun-info (cache))
294                            (:include dfun-info)
295                            (:copier nil)))
296
297 (defmacro dfun-update (generic-function function &rest args)
298   `(multiple-value-bind (dfun cache info)
299        (funcall ,function ,generic-function ,@args)
300      (update-dfun ,generic-function dfun cache info)))
301
302 (defun accessor-miss-function (gf dfun-info)
303   (ecase (dfun-info-accessor-type dfun-info)
304     (reader
305      (lambda (arg)
306        (accessor-miss gf nil arg dfun-info)))
307     (writer
308      (lambda (new arg)
309        (accessor-miss gf new arg dfun-info)))))
310
311 #-sb-fluid (declaim (sb-ext:freeze-type dfun-info))
312 \f
313 (defun make-one-class-accessor-dfun (gf type wrapper index)
314   (let ((emit (if (eq type 'reader) 'emit-one-class-reader 'emit-one-class-writer))
315         (dfun-info (one-class-dfun-info type index wrapper)))
316     (values
317      (funcall (get-dfun-constructor emit (consp index))
318               wrapper index
319               (accessor-miss-function gf dfun-info))
320      nil
321      dfun-info)))
322
323 (defun make-two-class-accessor-dfun (gf type w0 w1 index)
324   (let ((emit (if (eq type 'reader) 'emit-two-class-reader 'emit-two-class-writer))
325         (dfun-info (two-class-dfun-info type index w0 w1)))
326     (values
327      (funcall (get-dfun-constructor emit (consp index))
328               w0 w1 index
329               (accessor-miss-function gf dfun-info))
330      nil
331      dfun-info)))
332
333 ;;; std accessors same index dfun
334 (defun make-one-index-accessor-dfun (gf type index &optional cache)
335   (let* ((emit (if (eq type 'reader) 'emit-one-index-readers 'emit-one-index-writers))
336          (cache (or cache (get-cache 1 nil #'one-index-limit-fn 4)))
337          (dfun-info (one-index-dfun-info type index cache)))
338     (declare (type cache cache))
339     (values
340      (funcall (get-dfun-constructor emit (consp index))
341               cache
342               index
343               (accessor-miss-function gf dfun-info))
344      cache
345      dfun-info)))
346
347 (defun make-final-one-index-accessor-dfun (gf type index table)
348   (let ((cache (fill-dfun-cache table nil 1 #'one-index-limit-fn)))
349     (make-one-index-accessor-dfun gf type index cache)))
350
351 (defun one-index-limit-fn (nlines)
352   (default-limit-fn nlines))
353
354 (defun make-n-n-accessor-dfun (gf type &optional cache)
355   (let* ((emit (if (eq type 'reader) 'emit-n-n-readers 'emit-n-n-writers))
356          (cache (or cache (get-cache 1 t #'n-n-accessors-limit-fn 2)))
357          (dfun-info (n-n-dfun-info type cache)))
358     (declare (type cache cache))
359     (values
360      (funcall (get-dfun-constructor emit)
361               cache
362               (accessor-miss-function gf dfun-info))
363      cache
364      dfun-info)))
365
366 (defun make-final-n-n-accessor-dfun (gf type table)
367   (let ((cache (fill-dfun-cache table t 1 #'n-n-accessors-limit-fn)))
368     (make-n-n-accessor-dfun gf type cache)))
369
370 (defun n-n-accessors-limit-fn (nlines)
371   (default-limit-fn nlines))
372
373 (defun make-checking-dfun (generic-function function &optional cache)
374   (unless cache
375     (when (use-caching-dfun-p generic-function)
376       (return-from make-checking-dfun (make-caching-dfun generic-function)))
377     (when (use-dispatch-dfun-p generic-function)
378       (return-from make-checking-dfun (make-dispatch-dfun generic-function))))
379   (multiple-value-bind (nreq applyp metatypes nkeys)
380       (get-generic-function-info generic-function)
381     (declare (ignore nreq))
382     (if (every #'(lambda (mt) (eq mt t)) metatypes)
383         (let ((dfun-info (default-method-only-dfun-info)))
384           (values
385            (funcall (get-dfun-constructor 'emit-default-only metatypes applyp)
386                     function)
387            nil
388            dfun-info))
389         (let* ((cache (or cache (get-cache nkeys nil #'checking-limit-fn 2)))
390                (dfun-info (checking-dfun-info function cache)))
391           (values
392            (funcall (get-dfun-constructor 'emit-checking metatypes applyp)
393                     cache
394                     function
395                     (lambda (&rest args)
396                       (checking-miss generic-function args dfun-info)))
397            cache
398            dfun-info)))))
399
400 (defun make-final-checking-dfun (generic-function function
401                                                   classes-list new-class)
402   (let ((metatypes (arg-info-metatypes (gf-arg-info generic-function))))
403     (if (every #'(lambda (mt) (eq mt t)) metatypes)
404         (values #'(lambda (&rest args)
405                     (invoke-emf function args))
406                 nil (default-method-only-dfun-info))
407         (let ((cache (make-final-ordinary-dfun-internal
408                       generic-function nil #'checking-limit-fn
409                       classes-list new-class)))
410           (make-checking-dfun generic-function function cache)))))
411
412 (defun use-default-method-only-dfun-p (generic-function)
413   (multiple-value-bind (nreq applyp metatypes nkeys)
414       (get-generic-function-info generic-function)
415     (declare (ignore nreq applyp nkeys))
416     (every #'(lambda (mt) (eq mt t)) metatypes)))
417
418 (defun use-caching-dfun-p (generic-function)
419   (some (lambda (method)
420           (let ((fmf (if (listp method)
421                          (third method)
422                          (method-fast-function method))))
423             (method-function-get fmf ':slot-name-lists)))
424         ;; KLUDGE: As of sbcl-0.6.4, it's very important for
425         ;; efficiency to know the type of the sequence argument to
426         ;; quantifiers (SOME/NOTANY/etc.) at compile time, but
427         ;; the compiler isn't smart enough to understand the :TYPE
428         ;; slot option for DEFCLASS, so we just tell
429         ;; it the type by hand here.
430         (the list 
431              (if (early-gf-p generic-function)
432                  (early-gf-methods generic-function)
433                  (generic-function-methods generic-function)))))
434
435 (defun checking-limit-fn (nlines)
436   (default-limit-fn nlines))
437 \f
438 (defun make-caching-dfun (generic-function &optional cache)
439   (unless cache
440     (when (use-constant-value-dfun-p generic-function)
441       (return-from make-caching-dfun (make-constant-value-dfun generic-function)))
442     (when (use-dispatch-dfun-p generic-function)
443       (return-from make-caching-dfun (make-dispatch-dfun generic-function))))
444   (multiple-value-bind (nreq applyp metatypes nkeys)
445       (get-generic-function-info generic-function)
446     (declare (ignore nreq))
447     (let* ((cache (or cache (get-cache nkeys t #'caching-limit-fn 2)))
448            (dfun-info (caching-dfun-info cache)))
449       (values
450        (funcall (get-dfun-constructor 'emit-caching metatypes applyp)
451                 cache
452                 (lambda (&rest args)
453                   (caching-miss generic-function args dfun-info)))
454        cache
455        dfun-info))))
456
457 (defun make-final-caching-dfun (generic-function classes-list new-class)
458   (let ((cache (make-final-ordinary-dfun-internal
459                 generic-function t #'caching-limit-fn
460                 classes-list new-class)))
461     (make-caching-dfun generic-function cache)))
462
463 (defun caching-limit-fn (nlines)
464   (default-limit-fn nlines))
465
466 (defun insure-caching-dfun (gf)
467   (multiple-value-bind (nreq applyp metatypes nkeys)
468       (get-generic-function-info gf)
469     (declare (ignore nreq nkeys))
470     (when (and metatypes
471                (not (null (car metatypes)))
472                (dolist (mt metatypes nil)
473                  (unless (eq mt t) (return t))))
474       (get-dfun-constructor 'emit-caching metatypes applyp))))
475
476 (defun use-constant-value-dfun-p (gf &optional boolean-values-p)
477   (multiple-value-bind (nreq applyp metatypes nkeys)
478       (get-generic-function-info gf)
479     (declare (ignore nreq metatypes nkeys))
480     (let* ((early-p (early-gf-p gf))
481            (methods (if early-p
482                         (early-gf-methods gf)
483                         (generic-function-methods gf)))
484            (default '(unknown)))
485       (and (null applyp)
486            (or (not (eq *boot-state* 'complete))
487                (compute-applicable-methods-emf-std-p gf))
488            (notany #'(lambda (method)
489                        (or (and (eq *boot-state* 'complete)
490                                 (some #'eql-specializer-p
491                                       (method-specializers method)))
492                            (let ((value (method-function-get
493                                          (if early-p
494                                              (or (third method) (second method))
495                                              (or (method-fast-function method)
496                                                  (method-function method)))
497                                          :constant-value default)))
498                              (if boolean-values-p
499                                  (not (or (eq value t) (eq value nil)))
500                                  (eq value default)))))
501                    methods)))))
502
503 (defun make-constant-value-dfun (generic-function &optional cache)
504   (multiple-value-bind (nreq applyp metatypes nkeys)
505       (get-generic-function-info generic-function)
506     (declare (ignore nreq applyp))
507     (let* ((cache (or cache (get-cache nkeys t #'caching-limit-fn 2)))
508            (dfun-info (constant-value-dfun-info cache)))
509       (values
510        (funcall (get-dfun-constructor 'emit-constant-value metatypes)
511                 cache
512                 (lambda (&rest args)
513                   (constant-value-miss generic-function args dfun-info)))
514        cache
515        dfun-info))))
516
517 (defun make-final-constant-value-dfun (generic-function classes-list new-class)
518   (let ((cache (make-final-ordinary-dfun-internal
519                 generic-function :constant-value #'caching-limit-fn
520                 classes-list new-class)))
521     (make-constant-value-dfun generic-function cache)))
522
523 (defun use-dispatch-dfun-p (gf &optional (caching-p (use-caching-dfun-p gf)))
524   (when (eq *boot-state* 'complete)
525     (unless caching-p
526       ;; This should return T when almost all dispatching is by
527       ;; eql specializers or built-in classes. In other words,
528       ;; return NIL if we might ever need to do more than
529       ;; one (non built-in) typep.
530       ;; Otherwise, it is probably at least as fast to use
531       ;; a caching dfun first, possibly followed by secondary dispatching.
532
533       #||;;; Original found in cmu 17f -- S L O W
534       (< (dispatch-dfun-cost gf) (caching-dfun-cost gf))
535       ||#
536       ;; This uses improved dispatch-dfun-cost below
537       (let ((cdc  (caching-dfun-cost gf))) ; fast
538         (> cdc (dispatch-dfun-cost gf cdc))))))
539
540 (defparameter *non-built-in-typep-cost* 1)
541 (defparameter *structure-typep-cost* 1)
542 (defparameter *built-in-typep-cost* 0)
543
544 ;;; According to comments in the original CMU CL version of PCL,
545 ;;; the cost LIMIT is important to cut off exponential growth for
546 ;;; large numbers of gf methods and argument lists.
547 (defun dispatch-dfun-cost (gf &optional limit)
548   (generate-discrimination-net-internal
549    gf (generic-function-methods gf) nil
550    #'(lambda (methods known-types)
551        (declare (ignore methods known-types))
552        0)
553    #'(lambda (position type true-value false-value)
554        (declare (ignore position))
555        (let* ((type-test-cost
556                (if (eq 'class (car type))
557                    (let* ((metaclass (class-of (cadr type)))
558                           (mcpl (class-precedence-list metaclass)))
559                      (cond ((memq *the-class-built-in-class* mcpl)
560                             *built-in-typep-cost*)
561                            ((memq *the-class-structure-class* mcpl)
562                             *structure-typep-cost*)
563                            (t
564                             *non-built-in-typep-cost*)))
565                    0))
566               (max-cost-so-far
567                (+ (max true-value false-value) type-test-cost)))
568          (when (and limit (<= limit max-cost-so-far))
569            (return-from dispatch-dfun-cost max-cost-so-far))
570            max-cost-so-far))
571    #'identity))
572
573 (defparameter *cache-lookup-cost* 1)
574 (defparameter *wrapper-of-cost* 0)
575 (defparameter *secondary-dfun-call-cost* 1)
576
577 (defun caching-dfun-cost (gf)
578   (let* ((arg-info (gf-arg-info gf))
579          (nreq (length (arg-info-metatypes arg-info))))
580     (+ *cache-lookup-cost*
581        (* *wrapper-of-cost* nreq)
582        (if (methods-contain-eql-specializer-p
583             (generic-function-methods gf))
584            *secondary-dfun-call-cost*
585            0))))
586
587 (setq *non-built-in-typep-cost* 100)
588 (setq *structure-typep-cost* 15)
589 (setq *built-in-typep-cost* 5)
590 (setq *cache-lookup-cost* 30)
591 (setq *wrapper-of-cost* 15)
592 (setq *secondary-dfun-call-cost* 30)
593
594 (defun make-dispatch-dfun (gf)
595   (values (get-dispatch-function gf) nil (dispatch-dfun-info)))
596
597 (defun get-dispatch-function (gf)
598   (let ((methods (generic-function-methods gf)))
599     (function-funcall (get-secondary-dispatch-function1 gf methods nil nil nil
600                                                         nil nil t)
601                       nil nil)))
602
603 (defun make-final-dispatch-dfun (gf)
604   (make-dispatch-dfun gf))
605
606 (defun update-dispatch-dfuns ()
607   (dolist (gf (gfs-of-type '(dispatch initial-dispatch)))
608     (dfun-update gf #'make-dispatch-dfun)))
609
610 (defun fill-dfun-cache (table valuep nkeys limit-fn &optional cache)
611   (let ((cache (or cache (get-cache nkeys valuep limit-fn
612                                     (+ (hash-table-count table) 3)))))
613     (maphash #'(lambda (classes value)
614                  (setq cache (fill-cache cache
615                                          (class-wrapper classes)
616                                          value
617                                          t)))
618              table)
619     cache))
620
621 (defun make-final-ordinary-dfun-internal (generic-function valuep limit-fn
622                                                            classes-list new-class)
623   (let* ((arg-info (gf-arg-info generic-function))
624          (nkeys (arg-info-nkeys arg-info))
625          (new-class (and new-class
626                          (equal (type-of (gf-dfun-info generic-function))
627                                 (cond ((eq valuep t) 'caching)
628                                       ((eq valuep :constant-value) 'constant-value)
629                                       ((null valuep) 'checking)))
630                          new-class))
631          (cache (if new-class
632                     (copy-cache (gf-dfun-cache generic-function))
633                     (get-cache nkeys (not (null valuep)) limit-fn 4))))
634       (make-emf-cache generic-function valuep cache classes-list new-class)))
635 \f
636 (defvar *dfun-miss-gfs-on-stack* ())
637
638 (defmacro dfun-miss ((gf args wrappers invalidp nemf
639                       &optional type index caching-p applicable)
640                      &body body)
641   (unless applicable (setq applicable (gensym)))
642   `(multiple-value-bind (,nemf ,applicable ,wrappers ,invalidp
643                          ,@(when type `(,type ,index)))
644        (cache-miss-values ,gf ,args ',(cond (caching-p 'caching)
645                                             (type 'accessor)
646                                             (t 'checking)))
647      (when (and ,applicable (not (memq ,gf *dfun-miss-gfs-on-stack*)))
648        (let ((*dfun-miss-gfs-on-stack* (cons ,gf *dfun-miss-gfs-on-stack*)))
649          ,@body))
650      (invoke-emf ,nemf ,args)))
651
652 ;;; The dynamically adaptive method lookup algorithm is implemented is
653 ;;; implemented as a kind of state machine. The kinds of
654 ;;; discriminating function is the state, the various kinds of reasons
655 ;;; for a cache miss are the state transitions.
656 ;;;
657 ;;; The code which implements the transitions is all in the miss
658 ;;; handlers for each kind of dfun. Those appear here.
659 ;;;
660 ;;; Note that within the states that cache, there are dfun updates
661 ;;; which simply select a new cache or cache field. Those are not
662 ;;; considered as state transitions.
663 (defvar *lazy-dfun-compute-p* t)
664 (defvar *early-p* nil)
665
666 (defun make-initial-dfun (gf)
667   (let ((initial-dfun
668          #'(sb-kernel:instance-lambda (&rest args)
669              (initial-dfun gf args))))
670     (multiple-value-bind (dfun cache info)
671         (if (and (eq *boot-state* 'complete)
672                  (compute-applicable-methods-emf-std-p gf))
673             (let* ((caching-p (use-caching-dfun-p gf))
674                    (classes-list (precompute-effective-methods
675                                   gf caching-p
676                                   (not *lazy-dfun-compute-p*))))
677               (if *lazy-dfun-compute-p*
678                   (cond ((use-dispatch-dfun-p gf caching-p)
679                          (values initial-dfun
680                                  nil
681                                  (initial-dispatch-dfun-info)))
682                         (caching-p
683                          (insure-caching-dfun gf)
684                          (values initial-dfun nil (initial-dfun-info)))
685                         (t
686                          (values initial-dfun nil (initial-dfun-info))))
687                   (make-final-dfun-internal gf classes-list)))
688             (let ((arg-info (if (early-gf-p gf)
689                                 (early-gf-arg-info gf)
690                                 (gf-arg-info gf)))
691                   (type nil))
692               (if (and (gf-precompute-dfun-and-emf-p arg-info)
693                        (setq type (final-accessor-dfun-type gf)))
694                   (if *early-p*
695                       (values (make-early-accessor gf type) nil nil)
696                       (make-final-accessor-dfun gf type))
697                   (values initial-dfun nil (initial-dfun-info)))))
698       (set-dfun gf dfun cache info))))
699
700 (defun make-early-accessor (gf type)
701   (let* ((methods (early-gf-methods gf))
702          (slot-name (early-method-standard-accessor-slot-name (car methods))))
703     (ecase type
704       (reader #'(sb-kernel:instance-lambda (instance)
705                   (let* ((class (class-of instance))
706                          (class-name (!bootstrap-get-slot 'class class 'name)))
707                     (!bootstrap-get-slot class-name instance slot-name))))
708       (writer #'(sb-kernel:instance-lambda (new-value instance)
709                   (let* ((class (class-of instance))
710                          (class-name (!bootstrap-get-slot 'class class 'name)))
711                     (!bootstrap-set-slot class-name instance slot-name new-value)))))))
712
713 (defun initial-dfun (gf args)
714   (dfun-miss (gf args wrappers invalidp nemf ntype nindex)
715     (cond (invalidp)
716           ((and ntype nindex)
717            (dfun-update
718             gf #'make-one-class-accessor-dfun ntype wrappers nindex))
719           ((use-caching-dfun-p gf)
720            (dfun-update gf #'make-caching-dfun))
721           (t
722            (dfun-update
723             gf #'make-checking-dfun
724             ;; nemf is suitable only for caching, have to do this:
725             (cache-miss-values gf args 'checking))))))
726
727 (defun make-final-dfun (gf &optional classes-list)
728   (multiple-value-bind (dfun cache info)
729       (make-final-dfun-internal gf classes-list)
730     (set-dfun gf dfun cache info)))
731
732 (defvar *new-class* nil)
733
734 (defvar *free-hash-tables* (mapcar #'list '(eq equal eql)))
735
736 (defmacro with-hash-table ((table test) &body forms)
737   `(let* ((.free. (assoc ',test *free-hash-tables*))
738           (,table (if (cdr .free.)
739                       (pop (cdr .free.))
740                       (make-hash-table :test ',test))))
741      (multiple-value-prog1
742          (progn ,@forms)
743        (clrhash ,table)
744        (push ,table (cdr .free.)))))
745
746 (defmacro with-eq-hash-table ((table) &body forms)
747   `(with-hash-table (,table eq) ,@forms))
748
749 (defun final-accessor-dfun-type (gf)
750   (let ((methods (if (early-gf-p gf)
751                      (early-gf-methods gf)
752                      (generic-function-methods gf))))
753     (cond ((every #'(lambda (method)
754                       (if (consp method)
755                           (eq *the-class-standard-reader-method*
756                               (early-method-class method))
757                           (standard-reader-method-p method)))
758                   methods)
759            'reader)
760           ((every #'(lambda (method)
761                       (if (consp method)
762                           (eq *the-class-standard-writer-method*
763                               (early-method-class method))
764                           (standard-writer-method-p method)))
765                   methods)
766            'writer))))
767
768 (defun make-final-accessor-dfun (gf type &optional classes-list new-class)
769   (with-eq-hash-table (table)
770     (multiple-value-bind (table all-index first second size no-class-slots-p)
771         (make-accessor-table gf type table)
772       (if table
773           (cond ((= size 1)
774                  (let ((w (class-wrapper first)))
775                    (make-one-class-accessor-dfun gf type w all-index)))
776                 ((and (= size 2) (or (integerp all-index) (consp all-index)))
777                  (let ((w0 (class-wrapper first))
778                        (w1 (class-wrapper second)))
779                    (make-two-class-accessor-dfun gf type w0 w1 all-index)))
780                 ((or (integerp all-index) (consp all-index))
781                  (make-final-one-index-accessor-dfun
782                   gf type all-index table))
783                 (no-class-slots-p
784                  (make-final-n-n-accessor-dfun gf type table))
785                 (t
786                  (make-final-caching-dfun gf classes-list new-class)))
787           (make-final-caching-dfun gf classes-list new-class)))))
788
789 (defun make-final-dfun-internal (gf &optional classes-list)
790   (let ((methods (generic-function-methods gf)) type
791         (new-class *new-class*) (*new-class* nil)
792         specls all-same-p)
793     (cond ((null methods)
794            (values
795             #'(sb-kernel:instance-lambda (&rest args)
796                 (apply #'no-applicable-method gf args))
797             nil
798             (no-methods-dfun-info)))
799           ((setq type (final-accessor-dfun-type gf))
800            (make-final-accessor-dfun gf type classes-list new-class))
801           ((and (not (and (every #'(lambda (specl) (eq specl *the-class-t*))
802                                  (setq specls
803                                        (method-specializers (car methods))))
804                           (setq all-same-p
805                                 (every #'(lambda (method)
806                                            (and (equal specls
807                                                        (method-specializers
808                                                         method))))
809                                        methods))))
810                 (use-constant-value-dfun-p gf))
811            (make-final-constant-value-dfun gf classes-list new-class))
812           ((use-dispatch-dfun-p gf)
813            (make-final-dispatch-dfun gf))
814           ((and all-same-p (not (use-caching-dfun-p gf)))
815            (let ((emf (get-secondary-dispatch-function gf methods nil)))
816              (make-final-checking-dfun gf emf classes-list new-class)))
817           (t
818            (make-final-caching-dfun gf classes-list new-class)))))
819
820 (defun accessor-miss (gf new object dfun-info)
821   (let* ((ostate (type-of dfun-info))
822          (otype (dfun-info-accessor-type dfun-info))
823          oindex ow0 ow1 cache
824          (args (ecase otype                     ; The congruence rules ensure
825                 (reader (list object))          ; that this is safe despite not
826                 (writer (list new object)))))   ; knowing the new type yet.
827     (dfun-miss (gf args wrappers invalidp nemf ntype nindex)
828
829       ;; The following lexical functions change the state of the
830       ;; dfun to that which is their name. They accept arguments
831       ;; which are the parameters of the new state, and get other
832       ;; information from the lexical variables bound above.
833       (flet ((two-class (index w0 w1)
834                (when (zerop (random 2)) (psetf w0 w1 w1 w0))
835                (dfun-update gf
836                             #'make-two-class-accessor-dfun
837                             ntype
838                             w0
839                             w1
840                             index))
841              (one-index (index &optional cache)
842                (dfun-update gf
843                             #'make-one-index-accessor-dfun
844                             ntype
845                             index
846                             cache))
847              (n-n (&optional cache)
848                (if (consp nindex)
849                    (dfun-update gf #'make-checking-dfun nemf)
850                    (dfun-update gf #'make-n-n-accessor-dfun ntype cache)))
851              (caching () ; because cached accessor emfs are much faster
852                          ; for accessors
853                (dfun-update gf #'make-caching-dfun))
854              (do-fill (update-fn)
855                (let ((ncache (fill-cache cache wrappers nindex)))
856                  (unless (eq ncache cache)
857                    (funcall update-fn ncache)))))
858
859         (cond ((null ntype)
860                (caching))
861               ((or invalidp
862                    (null nindex)))
863               ((not (pcl-instance-p object))
864                (caching))
865               ((or (neq ntype otype) (listp wrappers))
866                (caching))
867               (t
868                (ecase ostate
869                  (one-class
870                   (setq oindex (dfun-info-index dfun-info))
871                   (setq ow0 (dfun-info-wrapper0 dfun-info))
872                   (unless (eq ow0 wrappers)
873                     (if (eql nindex oindex)
874                         (two-class nindex ow0 wrappers)
875                         (n-n))))
876                  (two-class
877                   (setq oindex (dfun-info-index dfun-info))
878                   (setq ow0 (dfun-info-wrapper0 dfun-info))
879                   (setq ow1 (dfun-info-wrapper1 dfun-info))
880                   (unless (or (eq ow0 wrappers) (eq ow1 wrappers))
881                     (if (eql nindex oindex)
882                         (one-index nindex)
883                         (n-n))))
884                  (one-index
885                   (setq oindex (dfun-info-index dfun-info))
886                   (setq cache (dfun-info-cache dfun-info))
887                   (if (eql nindex oindex)
888                       (do-fill #'(lambda (ncache)
889                                    (one-index nindex ncache)))
890                       (n-n)))
891                  (n-n
892                   (setq cache (dfun-info-cache dfun-info))
893                   (if (consp nindex)
894                       (caching)
895                       (do-fill #'n-n))))))))))
896
897 (defun checking-miss (generic-function args dfun-info)
898   (let ((oemf (dfun-info-function dfun-info))
899         (cache (dfun-info-cache dfun-info)))
900     (dfun-miss (generic-function args wrappers invalidp nemf)
901       (cond (invalidp)
902             ((eq oemf nemf)
903              (let ((ncache (fill-cache cache wrappers nil)))
904                (unless (eq ncache cache)
905                  (dfun-update generic-function #'make-checking-dfun
906                               nemf ncache))))
907             (t
908              (dfun-update generic-function #'make-caching-dfun))))))
909
910 (defun caching-miss (generic-function args dfun-info)
911   (let ((ocache (dfun-info-cache dfun-info)))
912     (dfun-miss (generic-function args wrappers invalidp emf nil nil t)
913       (cond (invalidp)
914             (t
915              (let ((ncache (fill-cache ocache wrappers emf)))
916                (unless (eq ncache ocache)
917                  (dfun-update generic-function
918                               #'make-caching-dfun ncache))))))))
919
920 (defun constant-value-miss (generic-function args dfun-info)
921   (let ((ocache (dfun-info-cache dfun-info)))
922     (dfun-miss (generic-function args wrappers invalidp emf nil nil t)
923       (cond (invalidp)
924             (t
925              (let* ((function (typecase emf
926                                 (fast-method-call (fast-method-call-function
927                                                    emf))
928                                 (method-call (method-call-function emf))))
929                     (value (method-function-get function :constant-value))
930                     (ncache (fill-cache ocache wrappers value)))
931                (unless (eq ncache ocache)
932                  (dfun-update generic-function
933                               #'make-constant-value-dfun ncache))))))))
934 \f
935 ;;; Given a generic function and a set of arguments to that generic
936 ;;; function, return a mess of values.
937 ;;;
938 ;;;  <function>   The compiled effective method function for this set of
939 ;;;            arguments.
940 ;;;
941 ;;;  <applicable> Sorted list of applicable methods.
942 ;;;
943 ;;;  <wrappers>   Is a single wrapper if the generic function has only
944 ;;;            one key, that is arg-info-nkeys of the arg-info is 1.
945 ;;;            Otherwise a list of the wrappers of the specialized
946 ;;;            arguments to the generic function.
947 ;;;
948 ;;;            Note that all these wrappers are valid. This function
949 ;;;            does invalid wrapper traps when it finds an invalid
950 ;;;            wrapper and then returns the new, valid wrapper.
951 ;;;
952 ;;;  <invalidp>   True if any of the specialized arguments had an invalid
953 ;;;            wrapper, false otherwise.
954 ;;;
955 ;;;  <type>       READER or WRITER when the only method that would be run
956 ;;;            is a standard reader or writer method. To be specific,
957 ;;;            the value is READER when the method combination is eq to
958 ;;;            *standard-method-combination*; there are no applicable
959 ;;;            :before, :after or :around methods; and the most specific
960 ;;;            primary method is a standard reader method.
961 ;;;
962 ;;;  <index>      If <type> is READER or WRITER, and the slot accessed is
963 ;;;            an :instance slot, this is the index number of that slot
964 ;;;            in the object argument.
965 (defun cache-miss-values (gf args state)
966   (if (null (if (early-gf-p gf)
967                 (early-gf-methods gf)
968                 (generic-function-methods gf)))
969       (apply #'no-applicable-method gf args)
970       (multiple-value-bind (nreq applyp metatypes nkeys arg-info)
971           (get-generic-function-info gf)
972         (declare (ignore nreq applyp nkeys))
973         (with-dfun-wrappers (args metatypes)
974           (dfun-wrappers invalid-wrapper-p wrappers classes types)
975           (error-need-at-least-n-args gf (length metatypes))
976           (multiple-value-bind (emf methods accessor-type index)
977               (cache-miss-values-internal
978                gf arg-info wrappers classes types state)
979             (values emf methods
980                     dfun-wrappers
981                     invalid-wrapper-p
982                     accessor-type index))))))
983
984 (defun cache-miss-values-internal (gf arg-info wrappers classes types state)
985   (let* ((for-accessor-p (eq state 'accessor))
986          (for-cache-p (or (eq state 'caching) (eq state 'accessor)))
987          (cam-std-p (or (null arg-info)
988                         (gf-info-c-a-m-emf-std-p arg-info))))
989     (multiple-value-bind (methods all-applicable-and-sorted-p)
990         (if cam-std-p
991             (compute-applicable-methods-using-types gf types)
992             (compute-applicable-methods-using-classes gf classes))
993       (let ((emf (if (or cam-std-p all-applicable-and-sorted-p)
994                      (function-funcall (get-secondary-dispatch-function1
995                                         gf methods types nil (and for-cache-p
996                                                                   wrappers)
997                                         all-applicable-and-sorted-p)
998                                        nil (and for-cache-p wrappers))
999                      (default-secondary-dispatch-function gf))))
1000         (multiple-value-bind (index accessor-type)
1001             (and for-accessor-p all-applicable-and-sorted-p methods
1002                  (accessor-values gf arg-info classes methods))
1003           (values (if (integerp index) index emf)
1004                   methods accessor-type index))))))
1005
1006 (defun accessor-values (gf arg-info classes methods)
1007   (declare (ignore gf))
1008   (let* ((accessor-type (gf-info-simple-accessor-type arg-info))
1009          (accessor-class (case accessor-type
1010                            (reader (car classes))
1011                            (writer (cadr classes))
1012                            (boundp (car classes)))))
1013     (accessor-values-internal accessor-type accessor-class methods)))
1014
1015 (defun accessor-values1 (gf accessor-type accessor-class)
1016   (let* ((type `(class-eq ,accessor-class))
1017          (types (if (eq accessor-type 'writer) `(t ,type) `(,type)))
1018          (methods (compute-applicable-methods-using-types gf types)))
1019     (accessor-values-internal accessor-type accessor-class methods)))
1020
1021 (defun accessor-values-internal (accessor-type accessor-class methods)
1022   (dolist (meth methods)
1023     (when (if (consp meth)
1024               (early-method-qualifiers meth)
1025               (method-qualifiers meth))
1026       (return-from accessor-values-internal (values nil nil))))
1027   (let* ((meth (car methods))
1028          (early-p (not (eq *boot-state* 'complete)))
1029          (slot-name (when accessor-class
1030                       (if (consp meth)
1031                           (and (early-method-standard-accessor-p meth)
1032                                (early-method-standard-accessor-slot-name meth))
1033                           (and (member *the-class-std-object*
1034                                        (if early-p
1035                                            (early-class-precedence-list
1036                                             accessor-class)
1037                                            (class-precedence-list
1038                                             accessor-class)))
1039                                (if early-p
1040                                    (not (eq *the-class-standard-method*
1041                                             (early-method-class meth)))
1042                                    (standard-accessor-method-p meth))
1043                                (if early-p
1044                                    (early-accessor-method-slot-name meth)
1045                                    (accessor-method-slot-name meth))))))
1046          (slotd (and accessor-class
1047                      (if early-p
1048                          (dolist (slot (early-class-slotds accessor-class) nil)
1049                            (when (eql slot-name
1050                                       (early-slot-definition-name slot))
1051                              (return slot)))
1052                          (find-slot-definition accessor-class slot-name)))))
1053     (when (and slotd
1054                (or early-p
1055                    (slot-accessor-std-p slotd accessor-type)))
1056       (values (if early-p
1057                   (early-slot-definition-location slotd)
1058                   (slot-definition-location slotd))
1059               accessor-type))))
1060
1061 (defun make-accessor-table (gf type &optional table)
1062   (unless table (setq table (make-hash-table :test 'eq)))
1063   (let ((methods (if (early-gf-p gf)
1064                      (early-gf-methods gf)
1065                      (generic-function-methods gf)))
1066         (all-index nil)
1067         (no-class-slots-p t)
1068         (early-p (not (eq *boot-state* 'complete)))
1069         first second (size 0))
1070     (declare (fixnum size))
1071     ;; class -> {(specl slotd)}
1072     (dolist (method methods)
1073       (let* ((specializers (if (consp method)
1074                                (early-method-specializers method t)
1075                                (method-specializers method)))
1076              (specl (if (eq type 'reader)
1077                         (car specializers)
1078                         (cadr specializers)))
1079              (specl-cpl (if early-p
1080                             (early-class-precedence-list specl)
1081                             (and (class-finalized-p specl)
1082                                  (class-precedence-list specl))))
1083              (so-p (member *the-class-std-object* specl-cpl))
1084              (slot-name (if (consp method)
1085                             (and (early-method-standard-accessor-p method)
1086                                  (early-method-standard-accessor-slot-name
1087                                   method))
1088                             (accessor-method-slot-name method))))
1089         (when (or (null specl-cpl)
1090                   (member *the-class-structure-object* specl-cpl))
1091           (return-from make-accessor-table nil))
1092         (maphash #'(lambda (class slotd)
1093                      (let ((cpl (if early-p
1094                                     (early-class-precedence-list class)
1095                                     (class-precedence-list class))))
1096                        (when (memq specl cpl)
1097                          (unless (and (or so-p
1098                                           (member *the-class-std-object* cpl))
1099                                       (or early-p
1100                                           (slot-accessor-std-p slotd type)))
1101                            (return-from make-accessor-table nil))
1102                          (push (cons specl slotd) (gethash class table)))))
1103                  (gethash slot-name *name->class->slotd-table*))))
1104     (maphash #'(lambda (class specl+slotd-list)
1105                  (dolist (sclass (if early-p
1106                                     (early-class-precedence-list class)
1107                                     (class-precedence-list class))
1108                           (error "This can't happen."))
1109                    (let ((a (assq sclass specl+slotd-list)))
1110                      (when a
1111                        (let* ((slotd (cdr a))
1112                               (index (if early-p
1113                                          (early-slot-definition-location slotd)
1114                                          (slot-definition-location slotd))))
1115                          (unless index (return-from make-accessor-table nil))
1116                          (setf (gethash class table) index)
1117                          (when (consp index) (setq no-class-slots-p nil))
1118                          (setq all-index (if (or (null all-index)
1119                                                  (eql all-index index))
1120                                              index t))
1121                          (incf size)
1122                          (cond ((= size 1) (setq first class))
1123                                ((= size 2) (setq second class)))
1124                          (return nil))))))
1125              table)
1126     (values table all-index first second size no-class-slots-p)))
1127
1128 (defun compute-applicable-methods-using-types (generic-function types)
1129   (let ((definite-p t) (possibly-applicable-methods nil))
1130     (dolist (method (if (early-gf-p generic-function)
1131                         (early-gf-methods generic-function)
1132                         (generic-function-methods generic-function)))
1133       (let ((specls (if (consp method)
1134                         (early-method-specializers method t)
1135                         (method-specializers method)))
1136             (types types)
1137             (possibly-applicable-p t) (applicable-p t))
1138         (dolist (specl specls)
1139           (multiple-value-bind (specl-applicable-p specl-possibly-applicable-p)
1140               (specializer-applicable-using-type-p specl (pop types))
1141             (unless specl-applicable-p
1142               (setq applicable-p nil))
1143             (unless specl-possibly-applicable-p
1144               (setq possibly-applicable-p nil)
1145               (return nil))))
1146         (when possibly-applicable-p
1147           (unless applicable-p (setq definite-p nil))
1148           (push method possibly-applicable-methods))))
1149     (let ((precedence (arg-info-precedence (if (early-gf-p generic-function)
1150                                                (early-gf-arg-info
1151                                                 generic-function)
1152                                                (gf-arg-info
1153                                                 generic-function)))))
1154       (values (sort-applicable-methods precedence
1155                                        (nreverse possibly-applicable-methods)
1156                                        types)
1157               definite-p))))
1158
1159 (defun sort-applicable-methods (precedence methods types)
1160   (sort-methods methods
1161                 precedence
1162                 #'(lambda (class1 class2 index)
1163                     (let* ((class (type-class (nth index types)))
1164                            (cpl (if (eq *boot-state* 'complete)
1165                                     (class-precedence-list class)
1166                                     (early-class-precedence-list class))))
1167                       (if (memq class2 (memq class1 cpl))
1168                           class1 class2)))))
1169
1170 (defun sort-methods (methods precedence compare-classes-function)
1171   (flet ((sorter (method1 method2)
1172            (dolist (index precedence)
1173              (let* ((specl1 (nth index (if (listp method1)
1174                                            (early-method-specializers method1
1175                                                                       t)
1176                                            (method-specializers method1))))
1177                     (specl2 (nth index (if (listp method2)
1178                                            (early-method-specializers method2
1179                                                                       t)
1180                                            (method-specializers method2))))
1181                     (order (order-specializers
1182                              specl1 specl2 index compare-classes-function)))
1183                (when order
1184                  (return-from sorter (eq order specl1)))))))
1185     (stable-sort methods #'sorter)))
1186
1187 (defun order-specializers (specl1 specl2 index compare-classes-function)
1188   (let ((type1 (if (eq *boot-state* 'complete)
1189                    (specializer-type specl1)
1190                    (!bootstrap-get-slot 'specializer specl1 'type)))
1191         (type2 (if (eq *boot-state* 'complete)
1192                    (specializer-type specl2)
1193                    (!bootstrap-get-slot 'specializer specl2 'type))))
1194     (cond ((eq specl1 specl2)
1195            nil)
1196           ((atom type1)
1197            specl2)
1198           ((atom type2)
1199            specl1)
1200           (t
1201            (case (car type1)
1202              (class    (case (car type2)
1203                          (class (funcall compare-classes-function
1204                                          specl1 specl2 index))
1205                          (t specl2)))
1206              (prototype (case (car type2)
1207                          (class (funcall compare-classes-function
1208                                          specl1 specl2 index))
1209                          (t specl2)))
1210              (class-eq (case (car type2)
1211                          (eql specl2)
1212                          (class-eq nil)
1213                          (class type1)))
1214              (eql      (case (car type2)
1215                          (eql nil)
1216                          (t specl1))))))))
1217
1218 (defun map-all-orders (methods precedence function)
1219   (let ((choices nil))
1220     (flet ((compare-classes-function (class1 class2 index)
1221              (declare (ignore index))
1222              (let ((choice nil))
1223                (dolist (c choices nil)
1224                  (when (or (and (eq (first c) class1)
1225                                 (eq (second c) class2))
1226                            (and (eq (first c) class2)
1227                                 (eq (second c) class1)))
1228                    (return (setq choice c))))
1229                (unless choice
1230                  (setq choice
1231                        (if (class-might-precede-p class1 class2)
1232                            (if (class-might-precede-p class2 class1)
1233                                (list class1 class2 nil t)
1234                                (list class1 class2 t))
1235                            (if (class-might-precede-p class2 class1)
1236                                (list class2 class1 t)
1237                                (let ((name1 (class-name class1))
1238                                      (name2 (class-name class2)))
1239                                  (if (and name1
1240                                           name2
1241                                           (symbolp name1)
1242                                           (symbolp name2)
1243                                           (string< (symbol-name name1)
1244                                                    (symbol-name name2)))
1245                                      (list class1 class2 t)
1246                                      (list class2 class1 t))))))
1247                  (push choice choices))
1248                (car choice))))
1249       (loop (funcall function
1250                      (sort-methods methods
1251                                    precedence
1252                                    #'compare-classes-function))
1253             (unless (dolist (c choices nil)
1254                       (unless (third c)
1255                         (rotatef (car c) (cadr c))
1256                         (return (setf (third c) t))))
1257               (return nil))))))
1258
1259 (defvar *in-precompute-effective-methods-p* nil)
1260
1261 ;used only in map-all-orders
1262 (defun class-might-precede-p (class1 class2)
1263   (if (not *in-precompute-effective-methods-p*)
1264       (not (member class1 (cdr (class-precedence-list class2))))
1265       (class-can-precede-p class1 class2)))
1266
1267 (defun compute-precedence (lambda-list nreq argument-precedence-order)
1268   (if (null argument-precedence-order)
1269       (let ((list nil))
1270         (dotimes-fixnum (i nreq list) (push (- (1- nreq) i) list)))
1271       (mapcar (lambda (x) (position x lambda-list))
1272               argument-precedence-order)))
1273
1274 (defun saut-and (specl type)
1275   (let ((applicable nil)
1276         (possibly-applicable t))
1277     (dolist (type (cdr type))
1278       (multiple-value-bind (appl poss-appl)
1279           (specializer-applicable-using-type-p specl type)
1280         (when appl (return (setq applicable t)))
1281         (unless poss-appl (return (setq possibly-applicable nil)))))
1282     (values applicable possibly-applicable)))
1283
1284 (defun saut-not (specl type)
1285   (let ((ntype (cadr type)))
1286     (values nil
1287             (case (car ntype)
1288               (class      (saut-not-class specl ntype))
1289               (class-eq   (saut-not-class-eq specl ntype))
1290               (prototype  (saut-not-prototype specl ntype))
1291               (eql      (saut-not-eql specl ntype))
1292               (t (error "~S cannot handle the second argument ~S"
1293                         'specializer-applicable-using-type-p type))))))
1294
1295 (defun saut-not-class (specl ntype)
1296   (let* ((class (type-class specl))
1297          (cpl (class-precedence-list class)))
1298      (not (memq (cadr ntype) cpl))))
1299
1300 (defun saut-not-prototype (specl ntype)
1301   (let* ((class (case (car specl)
1302                   (eql       (class-of (cadr specl)))
1303                   (class-eq  (cadr specl))
1304                   (prototype (cadr specl))
1305                   (class     (cadr specl))))
1306          (cpl (class-precedence-list class)))
1307      (not (memq (cadr ntype) cpl))))
1308
1309 (defun saut-not-class-eq (specl ntype)
1310   (let ((class (case (car specl)
1311                  (eql      (class-of (cadr specl)))
1312                  (class-eq (cadr specl)))))
1313     (not (eq class (cadr ntype)))))
1314
1315 (defun saut-not-eql (specl ntype)
1316   (case (car specl)
1317     (eql (not (eql (cadr specl) (cadr ntype))))
1318     (t   t)))
1319
1320 (defun class-applicable-using-class-p (specl type)
1321   (let ((pred (memq specl (if (eq *boot-state* 'complete)
1322                               (class-precedence-list type)
1323                               (early-class-precedence-list type)))))
1324     (values pred
1325             (or pred
1326                 (if (not *in-precompute-effective-methods-p*)
1327                     ;; classes might get common subclass
1328                     (superclasses-compatible-p specl type)
1329                     ;; worry only about existing classes
1330                     (classes-have-common-subclass-p specl type))))))
1331
1332 (defun classes-have-common-subclass-p (class1 class2)
1333   (or (eq class1 class2)
1334       (let ((class1-subs (class-direct-subclasses class1)))
1335         (or (memq class2 class1-subs)
1336             (dolist (class1-sub class1-subs nil)
1337               (when (classes-have-common-subclass-p class1-sub class2)
1338                 (return t)))))))
1339
1340 (defun saut-class (specl type)
1341   (case (car specl)
1342     (class (class-applicable-using-class-p (cadr specl) (cadr type)))
1343     (t     (values nil (let ((class (type-class specl)))
1344                          (memq (cadr type)
1345                                (class-precedence-list class)))))))
1346
1347 (defun saut-class-eq (specl type)
1348   (if (eq (car specl) 'eql)
1349       (values nil (eq (class-of (cadr specl)) (cadr type)))
1350       (let ((pred (case (car specl)
1351                     (class-eq
1352                      (eq (cadr specl) (cadr type)))
1353                     (class
1354                      (or (eq (cadr specl) (cadr type))
1355                          (memq (cadr specl)
1356                                (if (eq *boot-state* 'complete)
1357                                    (class-precedence-list (cadr type))
1358                                    (early-class-precedence-list
1359                                     (cadr type)))))))))
1360         (values pred pred))))
1361
1362 (defun saut-prototype (specl type)
1363   (declare (ignore specl type))
1364   (values nil nil)) ; XXX original PCL comment: fix this someday
1365
1366 (defun saut-eql (specl type)
1367   (let ((pred (case (car specl)
1368                 (eql    (eql (cadr specl) (cadr type)))
1369                 (class-eq   (eq (cadr specl) (class-of (cadr type))))
1370                 (class      (memq (cadr specl)
1371                                   (let ((class (class-of (cadr type))))
1372                                     (if (eq *boot-state* 'complete)
1373                                         (class-precedence-list class)
1374                                         (early-class-precedence-list
1375                                          class))))))))
1376     (values pred pred)))
1377
1378 (defun specializer-applicable-using-type-p (specl type)
1379   (setq specl (type-from-specializer specl))
1380   (when (eq specl t)
1381     (return-from specializer-applicable-using-type-p (values t t)))
1382   ;; This is used by C-A-M-U-T and GENERATE-DISCRIMINATION-NET-INTERNAL,
1383   ;; and has only what they need.
1384   (if (or (atom type) (eq (car type) t))
1385       (values nil t)
1386       (case (car type)
1387         (and    (saut-and specl type))
1388         (not    (saut-not specl type))
1389         (class      (saut-class specl type))
1390         (prototype  (saut-prototype specl type))
1391         (class-eq   (saut-class-eq specl type))
1392         (eql    (saut-eql specl type))
1393         (t        (error "~S cannot handle the second argument ~S."
1394                            'specializer-applicable-using-type-p
1395                            type)))))
1396
1397 (defun map-all-classes (function &optional (root t))
1398   (let ((braid-p (or (eq *boot-state* 'braid)
1399                      (eq *boot-state* 'complete))))
1400     (labels ((do-class (class)
1401                (mapc #'do-class
1402                      (if braid-p
1403                          (class-direct-subclasses class)
1404                          (early-class-direct-subclasses class)))
1405                (funcall function class)))
1406       (do-class (if (symbolp root)
1407                     (find-class root)
1408                     root)))))
1409 \f
1410 ;;; NOTE: We are assuming a restriction on user code that the method
1411 ;;;       combination must not change once it is connected to the
1412 ;;;       generic function.
1413 ;;;
1414 ;;;       This has to be legal, because otherwise any kind of method
1415 ;;;       lookup caching couldn't work. See this by saying that this
1416 ;;;       cache, is just a backing cache for the fast cache. If that
1417 ;;;       cache is legal, this one must be too.
1418 ;;;
1419 ;;; Don't clear this table!
1420 (defvar *effective-method-table* (make-hash-table :test 'eq))
1421
1422 (defun get-secondary-dispatch-function (gf methods types &optional
1423                                                          method-alist wrappers)
1424   (function-funcall (get-secondary-dispatch-function1
1425                      gf methods types
1426                      (not (null method-alist))
1427                      (not (null wrappers))
1428                      (not (methods-contain-eql-specializer-p methods)))
1429                     method-alist wrappers))
1430
1431 (defun get-secondary-dispatch-function1 (gf methods types method-alist-p
1432                                             wrappers-p
1433                                             &optional
1434                                             all-applicable-p
1435                                             (all-sorted-p t)
1436                                             function-p)
1437   (if (null methods)
1438       (if function-p
1439           #'(lambda (method-alist wrappers)
1440               (declare (ignore method-alist wrappers))
1441               #'(sb-kernel:instance-lambda (&rest args)
1442                   (apply #'no-applicable-method gf args)))
1443           #'(lambda (method-alist wrappers)
1444               (declare (ignore method-alist wrappers))
1445               #'(lambda (&rest args)
1446                   (apply #'no-applicable-method gf args))))
1447       (let* ((key (car methods))
1448              (ht-value (or (gethash key *effective-method-table*)
1449                            (setf (gethash key *effective-method-table*)
1450                                  (cons nil nil)))))
1451         (if (and (null (cdr methods)) all-applicable-p ; the most common case
1452                  (null method-alist-p) wrappers-p (not function-p))
1453             (or (car ht-value)
1454                 (setf (car ht-value)
1455                       (get-secondary-dispatch-function2
1456                        gf methods types method-alist-p wrappers-p
1457                        all-applicable-p all-sorted-p function-p)))
1458             (let ((akey (list methods
1459                               (if all-applicable-p 'all-applicable types)
1460                               method-alist-p wrappers-p function-p)))
1461               (or (cdr (assoc akey (cdr ht-value) :test #'equal))
1462                   (let ((value (get-secondary-dispatch-function2
1463                                 gf methods types method-alist-p wrappers-p
1464                                 all-applicable-p all-sorted-p function-p)))
1465                     (push (cons akey value) (cdr ht-value))
1466                     value)))))))
1467
1468 (defun get-secondary-dispatch-function2 (gf methods types method-alist-p
1469                                             wrappers-p all-applicable-p
1470                                             all-sorted-p function-p)
1471   (if (and all-applicable-p all-sorted-p (not function-p))
1472       (if (eq *boot-state* 'complete)
1473           (let* ((combin (generic-function-method-combination gf))
1474                  (effective (compute-effective-method gf combin methods)))
1475             (make-effective-method-function1 gf effective method-alist-p
1476                                              wrappers-p))
1477           (let ((effective (standard-compute-effective-method gf nil methods)))
1478             (make-effective-method-function1 gf effective method-alist-p
1479                                              wrappers-p)))
1480       (let ((net (generate-discrimination-net
1481                   gf methods types all-sorted-p)))
1482         (compute-secondary-dispatch-function1 gf net function-p))))
1483
1484 (defun get-effective-method-function (gf methods
1485                                          &optional method-alist wrappers)
1486   (function-funcall (get-secondary-dispatch-function1 gf methods nil
1487                                                       (not (null method-alist))
1488                                                       (not (null wrappers))
1489                                                       t)
1490                     method-alist wrappers))
1491
1492 (defun get-effective-method-function1 (gf methods &optional (sorted-p t))
1493   (get-secondary-dispatch-function1 gf methods nil nil nil t sorted-p))
1494
1495 (defun methods-contain-eql-specializer-p (methods)
1496   (and (eq *boot-state* 'complete)
1497        (dolist (method methods nil)
1498          (when (dolist (spec (method-specializers method) nil)
1499                  (when (eql-specializer-p spec) (return t)))
1500            (return t)))))
1501 \f
1502 (defun update-dfun (generic-function &optional dfun cache info)
1503   (let* ((early-p (early-gf-p generic-function))
1504          (gf-name (if early-p
1505                       (!early-gf-name generic-function)
1506                       (generic-function-name generic-function)))
1507          (ocache (gf-dfun-cache generic-function)))
1508     (set-dfun generic-function dfun cache info)
1509     (let ((dfun (if early-p
1510                     (or dfun (make-initial-dfun generic-function))
1511                     (compute-discriminating-function generic-function))))
1512       (set-funcallable-instance-function generic-function dfun)
1513       (set-function-name generic-function gf-name)
1514       (when (and ocache (not (eq ocache cache))) (free-cache ocache))
1515       dfun)))
1516 \f
1517 (defvar *dfun-count* nil)
1518 (defvar *dfun-list* nil)
1519 (defvar *minimum-cache-size-to-list*)
1520
1521 ;;; These functions aren't used in SBCL, or documented anywhere that
1522 ;;; I'm aware of, but they look like they might be useful for
1523 ;;; debugging or performance tweaking or something, so I've just
1524 ;;; commented them out instead of deleting them. -- WHN 2001-03-28
1525 #|
1526 (defun list-dfun (gf)
1527   (let* ((sym (type-of (gf-dfun-info gf)))
1528          (a (assq sym *dfun-list*)))
1529     (unless a
1530       (push (setq a (list sym)) *dfun-list*))
1531     (push (generic-function-name gf) (cdr a))))
1532
1533 (defun list-all-dfuns ()
1534   (setq *dfun-list* nil)
1535   (map-all-generic-functions #'list-dfun)
1536   *dfun-list*)
1537
1538 (defun list-large-cache (gf)
1539   (let* ((sym (type-of (gf-dfun-info gf)))
1540          (cache (gf-dfun-cache gf)))
1541     (when cache
1542       (let ((size (cache-size cache)))
1543         (when (>= size *minimum-cache-size-to-list*)
1544           (let ((a (assoc size *dfun-list*)))
1545             (unless a
1546               (push (setq a (list size)) *dfun-list*))
1547             (push (let ((name (generic-function-name gf)))
1548                     (if (eq sym 'caching) name (list name sym)))
1549                   (cdr a))))))))
1550
1551 (defun list-large-caches (&optional (*minimum-cache-size-to-list* 130))
1552   (setq *dfun-list* nil)
1553   (map-all-generic-functions #'list-large-cache)
1554   (setq *dfun-list* (sort *dfun-list* #'< :key #'car))
1555   (mapc #'print *dfun-list*)
1556   (values))
1557
1558 (defun count-dfun (gf)
1559   (let* ((sym (type-of (gf-dfun-info gf)))
1560          (cache (gf-dfun-cache gf))
1561          (a (assq sym *dfun-count*)))
1562     (unless a
1563       (push (setq a (list sym 0 nil)) *dfun-count*))
1564     (incf (cadr a))
1565     (when cache
1566       (let* ((size (cache-size cache))
1567              (b (assoc size (third a))))
1568         (unless b
1569           (push (setq b (cons size 0)) (third a)))
1570         (incf (cdr b))))))
1571
1572 (defun count-all-dfuns ()
1573   (setq *dfun-count* (mapcar #'(lambda (type) (list type 0 nil))
1574                              '(ONE-CLASS TWO-CLASS DEFAULT-METHOD-ONLY
1575                                ONE-INDEX N-N CHECKING CACHING
1576                                DISPATCH)))
1577   (map-all-generic-functions #'count-dfun)
1578   (mapc #'(lambda (type+count+sizes)
1579             (setf (third type+count+sizes)
1580                   (sort (third type+count+sizes) #'< :key #'car)))
1581         *dfun-count*)
1582   (mapc #'(lambda (type+count+sizes)
1583             (format t "~&There are ~D dfuns of type ~S."
1584                     (cadr type+count+sizes) (car type+count+sizes))
1585             (format t "~%   ~S~%" (caddr type+count+sizes)))
1586         *dfun-count*)
1587   (values))
1588 |#
1589
1590 (defun gfs-of-type (type)
1591   (unless (consp type) (setq type (list type)))
1592   (let ((gf-list nil))
1593     (map-all-generic-functions #'(lambda (gf)
1594                                    (when (memq (type-of (gf-dfun-info gf))
1595                                                type)
1596                                      (push gf gf-list))))
1597     gf-list))