6a81d8c06de0a03fbba9dadd9f4e7dd74209b32a
[sbcl.git] / src / pcl / ctor.lisp
1 ;;;; This file contains the optimization machinery for make-instance.
2
3 ;;;; This software is part of the SBCL system. See the README file for
4 ;;;; more information.
5
6 ;;;; This software is derived from software originally released by
7 ;;;; Gerd Moellmann.  Copyright and release statements follow.  Later
8 ;;;; modifications to the software are in the public domain and are
9 ;;;; provided with absolutely no warranty.  See the COPYING and
10 ;;;; CREDITS files for more information.
11
12 ;;; Copyright (C) 2002 Gerd Moellmann <gerd.moellmann@t-online.de>
13 ;;; All rights reserved.
14 ;;;
15 ;;; Redistribution and use in source and binary forms, with or without
16 ;;; modification, are permitted provided that the following conditions
17 ;;; are met:
18 ;;;
19 ;;; 1. Redistributions of source code must retain the above copyright
20 ;;;    notice, this list of conditions and the following disclaimer.
21 ;;; 2. Redistributions in binary form must reproduce the above copyright
22 ;;;    notice, this list of conditions and the following disclaimer in the
23 ;;;    documentation and/or other materials provided with the distribution.
24 ;;; 3. The name of the author may not be used to endorse or promote
25 ;;;    products derived from this software without specific prior written
26 ;;;    permission.
27 ;;;
28 ;;; THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS
29 ;;; OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
30 ;;; WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
31 ;;; ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE
32 ;;; LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
33 ;;; CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
34 ;;; OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
35 ;;; BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
36 ;;; LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
37 ;;; (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
38 ;;; USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
39 ;;; DAMAGE.
40
41 ;;; ***************
42 ;;; Overview  *****
43 ;;; ***************
44 ;;;
45 ;;; Compiler macro for MAKE-INSTANCE, and load-time generation of
46 ;;; optimized instance constructor functions.
47 ;;;
48 ;;; ********************
49 ;;; Entry Points  ******
50 ;;; ********************
51 ;;;
52 ;;; UPDATE-CTORS must be called when methods are added/removed,
53 ;;; classes are changed, etc., which affect instance creation.
54 ;;;
55 ;;; PRECOMPILE-CTORS can be called to precompile constructor functions
56 ;;; for classes whose definitions are known at the time the function
57 ;;; is called.
58
59 (in-package "SB-PCL")
60
61 ;;; ******************
62 ;;; Utilities  *******
63 ;;; ******************
64
65 (defun quote-plist-keys (plist)
66   (loop for (key . more) on plist by #'cddr
67         if (null more) do
68           (error "Not a property list: ~S" plist)
69         else
70           collect `(quote ,key)
71           and collect (car more)))
72
73 (defun plist-keys (plist &key test)
74   (loop for (key . more) on plist by #'cddr
75         if (null more) do
76           (error "Not a property list: ~S" plist)
77         else if (or (null test) (funcall test key))
78           collect key))
79
80 (defun plist-values (plist &key test)
81   (loop for (key . more) on plist by #'cddr
82         if (null more) do
83           (error "Not a property list: ~S" plist)
84         else if (or (null test) (funcall test (car more)))
85           collect (car more)))
86
87 (defun constant-class-arg-p (form)
88   (and (constantp form)
89        (let ((constant (constant-form-value form)))
90          (or (and (symbolp constant)
91                   (not (null (symbol-package constant))))
92              (classp form)))))
93
94 (defun constant-symbol-p (form)
95   (and (constantp form)
96        (let ((constant (constant-form-value form)))
97          (and (symbolp constant)
98               (not (null (symbol-package constant)))))))
99
100 ;;; somewhat akin to DEFAULT-INITARGS (SLOT-CLASS T T), but just
101 ;;; collecting the defaulted initargs for the call.
102 (defun ctor-default-initkeys (supplied-initargs class-default-initargs)
103   (loop for (key) in class-default-initargs
104         when (eq (getf supplied-initargs key '.not-there.) '.not-there.)
105         collect key))
106 \f
107 ;;; *****************
108 ;;; CTORS   *********
109 ;;; *****************
110 ;;;
111 ;;; Ctors are funcallable instances whose initial function is a
112 ;;; function computing an optimized constructor function when called.
113 ;;; When the optimized function is computed, the function of the
114 ;;; funcallable instance is set to it.
115 ;;;
116 (!defstruct-with-alternate-metaclass ctor
117   :slot-names (function-name class-or-name class initargs safe-p)
118   :boa-constructor %make-ctor
119   :superclass-name function
120   :metaclass-name static-classoid
121   :metaclass-constructor make-static-classoid
122   :dd-type funcallable-structure
123   :runtime-type-checks-p nil)
124
125 ;;; List of all defined ctors.
126 (defvar *all-ctors* ())
127
128 (defun make-ctor-parameter-list (ctor)
129   (plist-values (ctor-initargs ctor) :test (complement #'constantp)))
130
131 ;;; Reset CTOR to use a default function that will compute an
132 ;;; optimized constructor function when called.
133 (defun install-initial-constructor (ctor &key force-p)
134   (when (or force-p (ctor-class ctor))
135     (setf (ctor-class ctor) nil)
136     (setf (funcallable-instance-fun ctor)
137           #'(lambda (&rest args)
138               (install-optimized-constructor ctor)
139               (apply ctor args)))
140     (setf (%funcallable-instance-info ctor 1)
141           (ctor-function-name ctor))))
142
143 (defun make-ctor-function-name (class-name initargs safe-code-p)
144   (list* 'ctor class-name safe-code-p initargs))
145
146 ;;; Keep this a separate function for testing.
147 (defun ensure-ctor (function-name class-name initargs safe-code-p)
148   (unless (fboundp function-name)
149     (make-ctor function-name class-name initargs safe-code-p)))
150
151 ;;; Keep this a separate function for testing.
152 (defun make-ctor (function-name class-name initargs safe-p)
153   (without-package-locks ; for (setf symbol-function)
154    (let ((ctor (%make-ctor function-name class-name nil initargs safe-p)))
155      (push ctor *all-ctors*)
156      (setf (fdefinition function-name) ctor)
157      (install-initial-constructor ctor :force-p t)
158      ctor)))
159 \f
160 ;;; *****************
161 ;;; Inline CTOR cache
162 ;;; *****************
163 ;;;
164 ;;; The cache starts out as a list of CTORs, sorted with the most recently
165 ;;; used CTORs near the head. If it expands too much, we switch to a vector
166 ;;; with a simple hashing scheme.
167
168 ;;; Find CTOR for KEY (which is a class or class name) in a list. If the CTOR
169 ;;; is in the list but not one of the 4 first ones, return a new list with the
170 ;;; found CTOR at the head. Thread-safe: the new list shares structure with
171 ;;; the old, but is not desctructively modified. Returning the old list for
172 ;;; hits close to the head reduces ping-ponging with multiple threads seeking
173 ;;; the same list.
174 (defun find-ctor (key list)
175   (labels ((walk (tail from-head depth)
176              (declare (fixnum depth))
177              (if tail
178                  (let ((ctor (car tail)))
179                    (if (eq (ctor-class-or-name ctor) key)
180                        (if (> depth 3)
181                            (values ctor
182                                    (nconc (list ctor) (nreverse from-head) (cdr tail)))
183                            (values ctor
184                                    list))
185                        (walk (cdr tail)
186                              (cons ctor from-head)
187                              (logand #xf (1+ depth)))))
188                  (values nil list))))
189     (walk list nil 0)))
190
191 (declaim (inline sxhash-symbol-or-class))
192 (defun sxhash-symbol-or-class (x)
193   (cond ((symbolp x) (sxhash x))
194         ((std-instance-p x) (std-instance-hash x))
195         ((fsc-instance-p x) (fsc-instance-hash x))
196         (t
197          (bug "Something strange where symbol or class expected."))))
198
199 ;;; Max number of CTORs kept in an inline list cache. Once this is
200 ;;; exceeded we switch to a table.
201 (defconstant +ctor-list-max-size+ 12)
202 ;;; Max table size for CTOR cache. If the table fills up at this size
203 ;;; we keep the same size and drop 50% of the old entries.
204 (defconstant +ctor-table-max-size+ (expt 2 8))
205 ;;; Even if there is space in the cache, if we cannot fit a new entry
206 ;;; with max this number of collisions we expand the table (if possible)
207 ;;; and rehash.
208 (defconstant +ctor-table-max-probe-depth+ 5)
209
210 (defun make-ctor-table (size)
211   (declare (index size))
212   (let ((real-size (power-of-two-ceiling size)))
213     (if (< real-size +ctor-table-max-size+)
214         (values (make-array real-size :initial-element nil) nil)
215         (values (make-array +ctor-table-max-size+ :initial-element nil) t))))
216
217 (declaim (inline mix-ctor-hash))
218 (defun mix-ctor-hash (hash base)
219   (logand most-positive-fixnum (+ hash base 1)))
220
221 (defun put-ctor (ctor table)
222   (cond ((try-put-ctor ctor table)
223          (values ctor table))
224         (t
225          (expand-ctor-table ctor table))))
226
227 ;;; Thread-safe: if two threads write to the same index in parallel, the other
228 ;;; result is just lost. This is not an issue as the CTORs are used as their
229 ;;; own keys. If both were EQ, we're good. If non-EQ, the next time the other
230 ;;; one is needed we just cache it again -- hopefully not getting stomped on
231 ;;; that time.
232 (defun try-put-ctor (ctor table)
233   (declare (simple-vector table) (optimize speed))
234   (let* ((class (ctor-class-or-name ctor))
235          (base (sxhash-symbol-or-class class))
236          (hash base)
237          (mask (1- (length table))))
238     (declare (fixnum base hash mask))
239     (loop repeat +ctor-table-max-probe-depth+
240           do (let* ((index (logand mask hash))
241                     (old (aref table index)))
242                (cond ((and old (neq class (ctor-class-or-name old)))
243                       (setf hash (mix-ctor-hash hash base)))
244                      (t
245                       (setf (aref table index) ctor)
246                       (return-from try-put-ctor t)))))
247     ;; Didn't fit, must expand
248     nil))
249
250 (defun get-ctor (class table)
251   (declare (simple-vector table) (optimize speed))
252   (let* ((base (sxhash-symbol-or-class class))
253          (hash base)
254          (mask (1- (length table))))
255     (declare (fixnum base hash mask))
256     (loop repeat +ctor-table-max-probe-depth+
257           do (let* ((index (logand mask hash))
258                     (old (aref table index)))
259                (if (and old (eq class (ctor-class-or-name old)))
260                    (return-from get-ctor old)
261                    (setf hash (mix-ctor-hash hash base)))))
262     ;; Nothing.
263     nil))
264
265 ;;; Thread safe: the old table is read, but if another thread mutates
266 ;;; it while we're reading we still get a sane result -- either the old
267 ;;; or the new entry. The new table is locally allocated, so that's ok
268 ;;; too.
269 (defun expand-ctor-table (ctor old)
270   (declare (simple-vector old))
271   (let* ((old-size (length old))
272          (new-size (* 2 old-size))
273          (drop-random-entries nil))
274     (tagbody
275      :again
276        (multiple-value-bind (new max-size-p) (make-ctor-table new-size)
277          (let ((action (if drop-random-entries
278                            ;; Same logic as in method caches -- see comment
279                            ;; there.
280                            (randomly-punting-lambda (old-ctor)
281                              (try-put-ctor old-ctor new))
282                            (lambda (old-ctor)
283                              (unless (try-put-ctor old-ctor new)
284                                (if max-size-p
285                                    (setf drop-random-entries t)
286                                    (setf new-size (* 2 new-size)))
287                                (go :again))))))
288            (aver (try-put-ctor ctor new))
289            (dotimes (i old-size)
290              (let ((old-ctor (aref old i)))
291                (when old-ctor
292                  (funcall action old-ctor))))
293            (return-from expand-ctor-table (values ctor new)))))))
294
295 (defun ctor-list-to-table (list)
296   (let ((table (make-ctor-table (length list))))
297     (dolist (ctor list)
298       (setf table (nth-value 1 (put-ctor ctor table))))
299     table))
300
301 (defun ctor-for-caching (class-name initargs safe-code-p)
302   (let ((name (make-ctor-function-name class-name initargs safe-code-p)))
303     (or (ensure-ctor name class-name initargs safe-code-p)
304         (fdefinition name))))
305
306 (defun ensure-cached-ctor (class-name store initargs safe-code-p)
307   (if (listp store)
308       (multiple-value-bind (ctor list) (find-ctor class-name store)
309         (if ctor
310             (values ctor list)
311             (let ((ctor (ctor-for-caching class-name initargs safe-code-p)))
312               (if (< (length list) +ctor-list-max-size+)
313                   (values ctor (cons ctor list))
314                   (values ctor (ctor-list-to-table list))))))
315       (let ((ctor (get-ctor class-name store)))
316         (if ctor
317             (values ctor store)
318             (put-ctor (ctor-for-caching class-name initargs safe-code-p)
319                       store)))))
320 \f
321 ;;; ***********************************************
322 ;;; Compile-Time Expansion of MAKE-INSTANCE *******
323 ;;; ***********************************************
324
325 (defvar *compiling-optimized-constructor* nil)
326
327 (define-compiler-macro make-instance (&whole form &rest args &environment env)
328   (declare (ignore args))
329   ;; Compiling an optimized constructor for a non-standard class means compiling a
330   ;; lambda with (MAKE-INSTANCE #<SOME-CLASS X> ...) in it -- need
331   ;; to make sure we don't recurse there.
332   (or (unless *compiling-optimized-constructor*
333         (make-instance->constructor-call form (safe-code-p env)))
334       form))
335
336 (defun make-instance->constructor-call (form safe-code-p)
337   (destructuring-bind (class-arg &rest args) (cdr form)
338     (flet (;;
339            ;; Return the name of parameter number I of a constructor
340            ;; function.
341            (parameter-name (i)
342              (let ((ps #(.p0. .p1. .p2. .p3. .p4. .p5.)))
343                (if (array-in-bounds-p ps i)
344                    (aref ps i)
345                    (format-symbol *pcl-package* ".P~D." i))))
346            ;; Check if CLASS-ARG is a constant symbol.  Give up if
347            ;; not.
348            (constant-class-p ()
349              (and class-arg (constant-class-arg-p class-arg)))
350            ;; Check if ARGS are suitable for an optimized constructor.
351            ;; Return NIL from the outer function if not.
352            (check-args ()
353              (loop for (key . more) on args by #'cddr do
354                       (when (or (null more)
355                                 (not (constant-symbol-p key))
356                                 (eq :allow-other-keys (constant-form-value key)))
357                         (return-from make-instance->constructor-call nil)))))
358       (check-args)
359       ;; Collect a plist of initargs and constant values/parameter names
360       ;; in INITARGS.  Collect non-constant initialization forms in
361       ;; VALUE-FORMS.
362       (multiple-value-bind (initargs value-forms)
363           (loop for (key value) on args by #'cddr and i from 0
364                 collect (constant-form-value key) into initargs
365                 if (constantp value)
366                 collect value into initargs
367                 else
368                 collect (parameter-name i) into initargs
369                 and collect value into value-forms
370                 finally
371                 (return (values initargs value-forms)))
372         (if (constant-class-p)
373             (let* ((class-or-name (constant-form-value class-arg))
374                    (function-name (make-ctor-function-name class-or-name initargs
375                                                            safe-code-p)))
376               ;; Prevent compiler warnings for calling the ctor.
377               (proclaim-as-fun-name function-name)
378               (note-name-defined function-name :function)
379               (when (eq (info :function :where-from function-name) :assumed)
380                 (setf (info :function :where-from function-name) :defined)
381                 (when (info :function :assumed-type function-name)
382                   (setf (info :function :assumed-type function-name) nil)))
383               ;; Return code constructing a ctor at load time, which, when
384               ;; called, will set its funcallable instance function to an
385               ;; optimized constructor function.
386               `(locally
387                    (declare (disable-package-locks ,function-name))
388                  (let ((.x. (load-time-value
389                              (ensure-ctor ',function-name ',class-or-name ',initargs
390                                           ',safe-code-p))))
391                    (declare (ignore .x.))
392                    ;; ??? check if this is worth it.
393                    (declare
394                     (ftype (or (function ,(make-list (length value-forms)
395                                                      :initial-element t)
396                                          t)
397                                (function (&rest t) t))
398                            ,function-name))
399                    (funcall (function ,function-name) ,@value-forms))))
400             (when class-arg
401               ;; Build an inline cache: a CONS, with the actual cache in the CDR.
402               `(locally (declare (disable-package-locks .cache. .class-arg. .store. .fun.
403                                                         make-instance))
404                  (let* ((.cache. (load-time-value (cons 'ctor-cache nil)))
405                         (.store. (cdr .cache.))
406                         (.class-arg. ,class-arg))
407                    (multiple-value-bind (.fun. .new-store.)
408                        (ensure-cached-ctor .class-arg. .store. ',initargs ',safe-code-p)
409                      ;; Thread safe: if multiple threads hit this in paralle, the update
410                      ;; from the other one is just lost -- no harm done, except for the
411                      ;; need to redo the work next time.
412                      (unless (eq .store. .new-store.)
413                        (setf (cdr .cache.) .new-store.))
414                      (funcall (truly-the function .fun.) ,@value-forms))))))))))
415 \f
416 ;;; **************************************************
417 ;;; Load-Time Constructor Function Generation  *******
418 ;;; **************************************************
419
420 ;;; The system-supplied primary INITIALIZE-INSTANCE and
421 ;;; SHARED-INITIALIZE methods.  One cannot initialize these variables
422 ;;; to the right values here because said functions don't exist yet
423 ;;; when this file is first loaded.
424 (defvar *the-system-ii-method* nil)
425 (defvar *the-system-si-method* nil)
426
427 (defun install-optimized-constructor (ctor)
428   (with-world-lock ()
429     (let* ((class-or-name (ctor-class-or-name ctor))
430            (class (if (symbolp class-or-name)
431                       (find-class class-or-name)
432                       class-or-name)))
433       (unless (class-finalized-p class)
434         (finalize-inheritance class))
435       ;; We can have a class with an invalid layout here.  Such a class
436       ;; cannot have a LAYOUT-INVALID of (:FLUSH ...) or (:OBSOLETE
437       ;; ...), because part of the deal is that those only happen from
438       ;; FORCE-CACHE-FLUSHES, which create a new valid wrapper for the
439       ;; class.  An invalid layout of T needs to be flushed, however.
440       (when (eq (layout-invalid (class-wrapper class)) t)
441         (%force-cache-flushes class))
442       (setf (ctor-class ctor) class)
443       (pushnew ctor (plist-value class 'ctors) :test #'eq)
444       (setf (funcallable-instance-fun ctor)
445             (multiple-value-bind (form locations names)
446                 (constructor-function-form ctor)
447               (apply
448                (let ((*compiling-optimized-constructor* t))
449                  (compile nil `(lambda ,names ,form)))
450                locations))))))
451
452 (defun constructor-function-form (ctor)
453   (let* ((class (ctor-class ctor))
454          (proto (class-prototype class))
455          (make-instance-methods
456           (compute-applicable-methods #'make-instance (list class)))
457          (allocate-instance-methods
458           (compute-applicable-methods #'allocate-instance (list class)))
459          ;; I stared at this in confusion for a while, thinking
460          ;; carefully about the possibility of the class prototype not
461          ;; being of sufficient discrimiating power, given the
462          ;; possibility of EQL-specialized methods on
463          ;; INITIALIZE-INSTANCE or SHARED-INITIALIZE.  However, given
464          ;; that this is a constructor optimization, the user doesn't
465          ;; yet have the instance to create a method with such an EQL
466          ;; specializer.
467          ;;
468          ;; There remains the (theoretical) possibility of someone
469          ;; coming along with code of the form
470          ;;
471          ;; (defmethod initialize-instance :before ((o foo) ...)
472          ;;   (eval `(defmethod shared-initialize :before ((o foo) ...) ...)))
473          ;;
474          ;; but probably we can afford not to worry about this too
475          ;; much for now.  -- CSR, 2004-07-12
476          (ii-methods
477           (compute-applicable-methods #'initialize-instance (list proto)))
478          (si-methods
479           (compute-applicable-methods #'shared-initialize (list proto t)))
480          (setf-svuc-slots-methods
481           (loop for slot in (class-slots class)
482                 collect (compute-applicable-methods
483                          #'(setf slot-value-using-class)
484                          (list nil class proto slot))))
485          (sbuc-slots-methods
486           (loop for slot in (class-slots class)
487                 collect (compute-applicable-methods
488                          #'slot-boundp-using-class
489                          (list class proto slot)))))
490     ;; Cannot initialize these variables earlier because the generic
491     ;; functions don't exist when PCL is built.
492     (when (null *the-system-si-method*)
493       (setq *the-system-si-method*
494             (find-method #'shared-initialize
495                          () (list *the-class-slot-object* *the-class-t*)))
496       (setq *the-system-ii-method*
497             (find-method #'initialize-instance
498                          () (list *the-class-slot-object*))))
499     ;; Note that when there are user-defined applicable methods on
500     ;; MAKE-INSTANCE and/or ALLOCATE-INSTANCE, these will show up
501     ;; together with the system-defined ones in what
502     ;; COMPUTE-APPLICABLE-METHODS returns.
503     (let ((maybe-invalid-initargs
504            (check-initargs-1
505             class
506             (append
507              (ctor-default-initkeys
508               (ctor-initargs ctor) (class-default-initargs class))
509              (plist-keys (ctor-initargs ctor)))
510             (append ii-methods si-methods) nil nil))
511           (custom-make-instance
512            (not (null (cdr make-instance-methods)))))
513       (if (and (not (structure-class-p class))
514                (not (condition-class-p class))
515                (not custom-make-instance)
516                (null (cdr allocate-instance-methods))
517                (every (lambda (x)
518                         (member (slot-definition-allocation x)
519                                 '(:instance :class)))
520                       (class-slots class))
521                (not maybe-invalid-initargs)
522                (not (around-or-nonstandard-primary-method-p
523                      ii-methods *the-system-ii-method*))
524                (not (around-or-nonstandard-primary-method-p
525                      si-methods *the-system-si-method*))
526                ;; the instance structure protocol goes through
527                ;; slot-value(-using-class) and friends (actually just
528                ;; (SETF SLOT-VALUE-USING-CLASS) and
529                ;; SLOT-BOUNDP-USING-CLASS), so if there are non-standard
530                ;; applicable methods we can't shortcircuit them.
531                (every (lambda (x) (= (length x) 1)) setf-svuc-slots-methods)
532                (every (lambda (x) (= (length x) 1)) sbuc-slots-methods))
533           (optimizing-generator ctor ii-methods si-methods)
534           (fallback-generator ctor ii-methods si-methods
535                               (or maybe-invalid-initargs custom-make-instance))))))
536
537 (defun around-or-nonstandard-primary-method-p
538     (methods &optional standard-method)
539   (loop with primary-checked-p = nil
540         for method in methods
541         as qualifiers = (if (consp method)
542                             (early-method-qualifiers method)
543                             (safe-method-qualifiers method))
544         when (or (eq :around (car qualifiers))
545                  (and (null qualifiers)
546                       (not primary-checked-p)
547                       (not (null standard-method))
548                       (not (eq standard-method method))))
549           return t
550         when (null qualifiers) do
551           (setq primary-checked-p t)))
552
553 (defun fallback-generator (ctor ii-methods si-methods use-make-instance)
554   (declare (ignore ii-methods si-methods))
555   (let ((class (ctor-class ctor))
556         (lambda-list (make-ctor-parameter-list ctor))
557         (initargs (quote-plist-keys (ctor-initargs ctor))))
558     (if use-make-instance
559         `(lambda ,lambda-list
560            (declare #.*optimize-speed*)
561            ;; The CTOR MAKE-INSTANCE optimization checks for
562            ;; *COMPILING-OPTIMIZED-CONSTRUCTOR* which is bound around compilation of
563            ;; the constructor, hence avoiding the possibility of endless recursion.
564            (make-instance ,class ,@initargs))
565         (let ((defaults (class-default-initargs class)))
566           (when defaults
567             (setf initargs (default-initargs initargs defaults)))
568           `(lambda ,lambda-list
569              (declare #.*optimize-speed*)
570              (fast-make-instance ,class ,@initargs))))))
571
572 ;;; Not as good as the real optimizing generator, but faster than going
573 ;;; via MAKE-INSTANCE: 1 GF call less, and no need to check initargs.
574 (defun fast-make-instance (class &rest initargs)
575   (declare #.*optimize-speed*)
576   (declare (dynamic-extent initargs))
577   (let ((.instance. (apply #'allocate-instance class initargs)))
578     (apply #'initialize-instance .instance. initargs)
579     .instance.))
580
581 (defun optimizing-generator (ctor ii-methods si-methods)
582   (multiple-value-bind (locations names body before-method-p)
583       (fake-initialization-emf ctor ii-methods si-methods)
584     (let ((wrapper (class-wrapper (ctor-class ctor))))
585       (values
586        `(lambda ,(make-ctor-parameter-list ctor)
587          (declare #.*optimize-speed*)
588          (block nil
589            (when (layout-invalid ,wrapper)
590              (install-initial-constructor ,ctor)
591              (return (funcall ,ctor ,@(make-ctor-parameter-list ctor))))
592            ,(wrap-in-allocate-forms ctor body before-method-p)))
593        locations
594        names))))
595
596 ;;; Return a form wrapped around BODY that allocates an instance
597 ;;; constructed by CTOR.  BEFORE-METHOD-P set means we have to run
598 ;;; before-methods, in which case we initialize instance slots to
599 ;;; +SLOT-UNBOUND+.  The resulting form binds the local variables
600 ;;; .INSTANCE. to the instance, and .SLOTS. to the instance's slot
601 ;;; vector around BODY.
602 (defun wrap-in-allocate-forms (ctor body before-method-p)
603   (let* ((class (ctor-class ctor))
604          (wrapper (class-wrapper class))
605          (allocation-function (raw-instance-allocator class))
606          (slots-fetcher (slots-fetcher class)))
607     (if (eq allocation-function 'allocate-standard-instance)
608         `(let ((.instance. (%make-standard-instance nil
609                                                     (get-instance-hash-code)))
610                (.slots. (make-array
611                          ,(layout-length wrapper)
612                          ,@(when before-method-p
613                              '(:initial-element +slot-unbound+)))))
614            (setf (std-instance-wrapper .instance.) ,wrapper)
615            (setf (std-instance-slots .instance.) .slots.)
616            ,body
617            .instance.)
618         `(let* ((.instance. (,allocation-function ,wrapper))
619                 (.slots. (,slots-fetcher .instance.)))
620            (declare (ignorable .slots.))
621            ,body
622            .instance.))))
623
624 ;;; Return a form for invoking METHOD with arguments from ARGS.  As
625 ;;; can be seen in METHOD-FUNCTION-FROM-FAST-FUNCTION, method
626 ;;; functions look like (LAMBDA (ARGS NEXT-METHODS) ...).  We could
627 ;;; call fast method functions directly here, but benchmarks show that
628 ;;; there's no speed to gain, so lets avoid the hair here.
629 (defmacro invoke-method (method args)
630   `(funcall ,(method-function method) ,args ()))
631
632 ;;; Return a form that is sort of an effective method comprising all
633 ;;; calls to INITIALIZE-INSTANCE and SHARED-INITIALIZE that would
634 ;;; normally have taken place when calling MAKE-INSTANCE.
635 (defun fake-initialization-emf (ctor ii-methods si-methods)
636   (multiple-value-bind (ii-around ii-before ii-primary ii-after)
637       (standard-sort-methods ii-methods)
638     (declare (ignore ii-primary))
639     (multiple-value-bind (si-around si-before si-primary si-after)
640         (standard-sort-methods si-methods)
641       (declare (ignore si-primary))
642       (aver (and (null ii-around) (null si-around)))
643       (let ((initargs (ctor-initargs ctor)))
644         (multiple-value-bind (locations names bindings vars defaulting-initargs body)
645             (slot-init-forms ctor (or ii-before si-before))
646         (values
647          locations
648          names
649          `(let ,bindings
650            (declare (ignorable ,@vars))
651            (let (,@(when (or ii-before ii-after)
652                      `((.ii-args.
653                         (list .instance. ,@(quote-plist-keys initargs) ,@defaulting-initargs))))
654                  ,@(when (or si-before si-after)
655                      `((.si-args.
656                         (list .instance. t ,@(quote-plist-keys initargs) ,@defaulting-initargs)))))
657             ,@(loop for method in ii-before
658                     collect `(invoke-method ,method .ii-args.))
659             ,@(loop for method in si-before
660                     collect `(invoke-method ,method .si-args.))
661             ,@body
662             ,@(loop for method in si-after
663                     collect `(invoke-method ,method .si-args.))
664             ,@(loop for method in ii-after
665                     collect `(invoke-method ,method .ii-args.))))
666          (or ii-before si-before)))))))
667
668 ;;; Return four values from APPLICABLE-METHODS: around methods, before
669 ;;; methods, the applicable primary method, and applicable after
670 ;;; methods.  Before and after methods are sorted in the order they
671 ;;; must be called.
672 (defun standard-sort-methods (applicable-methods)
673   (loop for method in applicable-methods
674         as qualifiers = (if (consp method)
675                             (early-method-qualifiers method)
676                             (safe-method-qualifiers method))
677         if (null qualifiers)
678           collect method into primary
679         else if (eq :around (car qualifiers))
680           collect method into around
681         else if (eq :after (car qualifiers))
682           collect method into after
683         else if (eq :before (car qualifiers))
684           collect method into before
685         finally
686           (return (values around before (first primary) (reverse after)))))
687
688 (defmacro with-type-checked ((type safe-p) &body body)
689   (if safe-p
690       ;; To handle FUNCTION types reasonable, we use SAFETY 3 and
691       ;; THE instead of e.g. CHECK-TYPE.
692       `(locally
693            (declare (optimize (safety 3)))
694          (the ,type (progn ,@body)))
695       `(progn ,@body)))
696
697 ;;; Return as multiple values bindings for default initialization
698 ;;; arguments, variable names, defaulting initargs and a body for
699 ;;; initializing instance and class slots of an object costructed by
700 ;;; CTOR.  The variable .SLOTS. is assumed to bound to the instance's
701 ;;; slot vector.  BEFORE-METHOD-P T means before-methods will be
702 ;;; called, which means that 1) other code will initialize instance
703 ;;; slots to +SLOT-UNBOUND+ before the before-methods are run, and
704 ;;; that we have to check if these before-methods have set slots.
705 (defun slot-init-forms (ctor before-method-p)
706   (let* ((class (ctor-class ctor))
707          (initargs (ctor-initargs ctor))
708          (initkeys (plist-keys initargs))
709          (safe-p (ctor-safe-p ctor))
710          (slot-vector
711           (make-array (layout-length (class-wrapper class))
712                       :initial-element nil))
713          (class-inits ())
714          (default-inits ())
715          (defaulting-initargs ())
716          (default-initargs (class-default-initargs class))
717          (initarg-locations
718           (compute-initarg-locations
719            class (append initkeys (mapcar #'car default-initargs)))))
720     (labels ((initarg-locations (initarg)
721                (cdr (assoc initarg initarg-locations :test #'eq)))
722              (initializedp (location)
723                (cond
724                  ((consp location)
725                   (assoc location class-inits :test #'eq))
726                  ((integerp location)
727                   (not (null (aref slot-vector location))))
728                  (t (bug "Weird location in ~S" 'slot-init-forms))))
729              (class-init (location kind val type)
730                (aver (consp location))
731                (unless (initializedp location)
732                  (push (list location kind val type) class-inits)))
733              (instance-init (location kind val type)
734                (aver (integerp location))
735                (unless (initializedp location)
736                  (setf (aref slot-vector location) (list kind val type))))
737              (default-init-var-name (i)
738                (let ((ps #(.d0. .d1. .d2. .d3. .d4. .d5.)))
739                  (if (array-in-bounds-p ps i)
740                      (aref ps i)
741                      (format-symbol *pcl-package* ".D~D." i))))
742              (location-var-name (i)
743                (let ((ls #(.l0. .l1. .l2. .l3. .l4. .l5.)))
744                  (if (array-in-bounds-p ls i)
745                      (aref ls i)
746                      (format-symbol *pcl-package* ".L~D." i)))))
747       ;; Loop over supplied initargs and values and record which
748       ;; instance and class slots they initialize.
749       (loop for (key value) on initargs by #'cddr
750             as kind = (if (constantp value) 'constant 'param)
751             as locations = (initarg-locations key)
752             do (loop for (location . type) in locations
753                      do (if (consp location)
754                             (class-init location kind value type)
755                             (instance-init location kind value type))))
756       ;; Loop over default initargs of the class, recording
757       ;; initializations of slots that have not been initialized
758       ;; above.  Default initargs which are not in the supplied
759       ;; initargs are treated as if they were appended to supplied
760       ;; initargs, that is, their values must be evaluated even
761       ;; if not actually used for initializing a slot.
762       (loop for (key initform initfn) in default-initargs and i from 0
763             unless (member key initkeys :test #'eq)
764             do (let* ((kind (if (constantp initform) 'constant 'var))
765                       (init (if (eq kind 'var) initfn initform)))
766                  (ecase kind
767                    (constant
768                     (push (list 'quote key) defaulting-initargs)
769                     (push initform defaulting-initargs))
770                    (var
771                     (push (list 'quote key) defaulting-initargs)
772                     (push (default-init-var-name i) defaulting-initargs)))
773               (when (eq kind 'var)
774                 (let ((init-var (default-init-var-name i)))
775                   (setq init init-var)
776                   (push (cons init-var initfn) default-inits)))
777               (loop for (location . type) in (initarg-locations key)
778                     do (if (consp location)
779                            (class-init location kind init type)
780                            (instance-init location kind init type)))))
781       ;; Loop over all slots of the class, filling in the rest from
782       ;; slot initforms.
783       (loop for slotd in (class-slots class)
784             as location = (slot-definition-location slotd)
785             as type = (slot-definition-type slotd)
786             as allocation = (slot-definition-allocation slotd)
787             as initfn = (slot-definition-initfunction slotd)
788             as initform = (slot-definition-initform slotd) do
789               (unless (or (eq allocation :class)
790                           (null initfn)
791                           (initializedp location))
792                 (if (constantp initform)
793                     (instance-init location 'initform initform type)
794                     (instance-init location 'initform/initfn initfn type))))
795       ;; Generate the forms for initializing instance and class slots.
796       (let ((instance-init-forms
797              (loop for slot-entry across slot-vector and i from 0
798                    as (kind value type) = slot-entry collect
799                      (ecase kind
800                        ((nil)
801                         (unless before-method-p
802                           `(setf (clos-slots-ref .slots. ,i) +slot-unbound+)))
803                        ((param var)
804                         `(setf (clos-slots-ref .slots. ,i)
805                                (with-type-checked (,type ,safe-p)
806                                    ,value)))
807                        (initfn
808                         `(setf (clos-slots-ref .slots. ,i)
809                                (with-type-checked (,type ,safe-p)
810                                  (funcall ,value))))
811                        (initform/initfn
812                         (if before-method-p
813                             `(when (eq (clos-slots-ref .slots. ,i)
814                                        +slot-unbound+)
815                                (setf (clos-slots-ref .slots. ,i)
816                                      (with-type-checked (,type ,safe-p)
817                                        (funcall ,value))))
818                             `(setf (clos-slots-ref .slots. ,i)
819                                    (with-type-checked (,type ,safe-p)
820                                      (funcall ,value)))))
821                        (initform
822                         (if before-method-p
823                             `(when (eq (clos-slots-ref .slots. ,i)
824                                        +slot-unbound+)
825                                (setf (clos-slots-ref .slots. ,i)
826                                      (with-type-checked (,type ,safe-p)
827                                        ',(constant-form-value value))))
828                             `(setf (clos-slots-ref .slots. ,i)
829                                    (with-type-checked (,type ,safe-p)
830                                      ',(constant-form-value value)))))
831                        (constant
832                         `(setf (clos-slots-ref .slots. ,i)
833                                (with-type-checked (,type ,safe-p)
834                                  ',(constant-form-value value))))))))
835         ;; we are not allowed to modify QUOTEd locations, so we can't
836         ;; generate code like (setf (cdr ',location) arg).  Instead,
837         ;; we have to do (setf (cdr .L0.) arg) and arrange for .L0. to
838         ;; be bound to the location.
839         (multiple-value-bind (names locations class-init-forms)
840             (loop for (location kind value type) in class-inits
841                   for i upfrom 0
842                   for name = (location-var-name i)
843                   collect name into names
844                   collect location into locations
845                   collect `(setf (cdr ,name)
846                                  (with-type-checked (,type ,safe-p)
847                                    ,(case kind
848                                           (constant `',(constant-form-value value))
849                                           ((param var) `,value)
850                                           (initfn `(funcall ,value)))))
851                   into class-init-forms
852                   finally (return (values names locations class-init-forms)))
853           (multiple-value-bind (vars bindings)
854               (loop for (var . initfn) in (nreverse default-inits)
855                     collect var into vars
856                     collect `(,var (funcall ,initfn)) into bindings
857                     finally (return (values vars bindings)))
858             (values locations names
859                     bindings vars
860                     (nreverse defaulting-initargs)
861                     `(,@(delete nil instance-init-forms)
862                       ,@class-init-forms))))))))
863
864 ;;; Return an alist of lists (KEY (LOCATION . TYPE-SPECIFIER) ...)
865 ;;; telling, for each key in INITKEYS, which locations the initarg
866 ;;; initializes and the associated type with the location.  CLASS is
867 ;;; the class of the instance being initialized.
868 (defun compute-initarg-locations (class initkeys)
869   (loop with slots = (class-slots class)
870         for key in initkeys collect
871           (loop for slot in slots
872                 if (memq key (slot-definition-initargs slot))
873                   collect (cons (slot-definition-location slot)
874                                 (slot-definition-type slot))
875                           into locations
876                 else
877                   collect slot into remaining-slots
878                 finally
879                   (setq slots remaining-slots)
880                   (return (cons key locations)))))
881
882 \f
883 ;;; *******************************
884 ;;; External Entry Points  ********
885 ;;; *******************************
886
887 (defun update-ctors (reason &key class name generic-function method)
888   (labels ((reset (class &optional ri-cache-p (ctorsp t))
889              (when ctorsp
890                (dolist (ctor (plist-value class 'ctors))
891                  (install-initial-constructor ctor)))
892              (when ri-cache-p
893                (setf (plist-value class 'ri-initargs) ()))
894              (dolist (subclass (class-direct-subclasses class))
895                (reset subclass ri-cache-p ctorsp))))
896     (ecase reason
897       ;; CLASS must have been specified.
898       (finalize-inheritance
899        (reset class t))
900       ;; NAME must have been specified.
901       (setf-find-class
902        (loop for ctor in *all-ctors*
903              when (eq (ctor-class-or-name ctor) name) do
904              (when (ctor-class ctor)
905                (reset (ctor-class ctor)))
906              (loop-finish)))
907       ;; GENERIC-FUNCTION and METHOD must have been specified.
908       ((add-method remove-method)
909        (flet ((class-of-1st-method-param (method)
910                 (type-class (first (method-specializers method)))))
911          (case (generic-function-name generic-function)
912            ((make-instance allocate-instance
913              initialize-instance shared-initialize)
914             (reset (class-of-1st-method-param method) t t))
915            ((reinitialize-instance)
916             (reset (class-of-1st-method-param method) t nil))
917            (t (when (or (eq (generic-function-name generic-function)
918                             'slot-boundp-using-class)
919                         (equal (generic-function-name generic-function)
920                                '(setf slot-value-using-class)))
921                 ;; this looks awfully expensive, but given that one
922                 ;; can specialize on the SLOTD argument, nothing is
923                 ;; safe.  -- CSR, 2004-07-12
924                 (reset (find-class 'standard-object))))))))))
925
926 (defun precompile-ctors ()
927   (dolist (ctor *all-ctors*)
928     (when (null (ctor-class ctor))
929       (let ((class (find-class (ctor-class-or-name ctor) nil)))
930         (when (and class (class-finalized-p class))
931           (install-optimized-constructor ctor))))))
932
933 (defun check-ri-initargs (instance initargs)
934   (let* ((class (class-of instance))
935          (keys (plist-keys initargs))
936          (cached (assoc keys (plist-value class 'ri-initargs)
937                         :test #'equal))
938          (invalid-keys
939           (if (consp cached)
940               (cdr cached)
941               (let ((invalid
942                      ;; FIXME: give CHECK-INITARGS-1 and friends a
943                      ;; more mnemonic name and (possibly) a nicer,
944                      ;; more orthogonal interface.
945                      (check-initargs-1
946                       class initargs
947                       (list (list* 'reinitialize-instance instance initargs)
948                             (list* 'shared-initialize instance nil initargs))
949                       t nil)))
950                 (setf (plist-value class 'ri-initargs)
951                       (acons keys invalid cached))
952                 invalid))))
953     (when invalid-keys
954       (error 'initarg-error :class class :initargs invalid-keys))))
955
956 ;;; end of ctor.lisp