5501a62b957b9996fcdd954082d54ee9b3697aa8
[sbcl.git] / src / compiler / ir1tran-lambda.lisp
1 ;;;; This file contains code which does the translation of lambda
2 ;;;; forms from Lisp code to the first intermediate representation
3 ;;;; (IR1).
4
5 ;;;; This software is part of the SBCL system. See the README file for
6 ;;;; more information.
7 ;;;;
8 ;;;; This software is derived from the CMU CL system, which was
9 ;;;; written at Carnegie Mellon University and released into the
10 ;;;; public domain. The software is in the public domain and is
11 ;;;; provided with absolutely no warranty. See the COPYING and CREDITS
12 ;;;; files for more information.
13
14 (in-package "SB!C")
15
16 ;;;; LAMBDA hackery
17
18 ;;;; Note: Take a look at the compiler-overview.tex section on "Hairy
19 ;;;; function representation" before you seriously mess with this
20 ;;;; stuff.
21
22 ;;; Verify that the NAME is a legal name for a variable and return a
23 ;;; VAR structure for it, filling in info if it is globally special.
24 ;;; If it is losing, we punt with a COMPILER-ERROR. NAMES-SO-FAR is a
25 ;;; list of names which have previously been bound. If the NAME is in
26 ;;; this list, then we error out.
27 (declaim (ftype (sfunction (t list &optional t) lambda-var) varify-lambda-arg))
28 (defun varify-lambda-arg (name names-so-far &optional (context "lambda list"))
29   (declare (inline member))
30   (unless (symbolp name)
31     (compiler-error "~S is not a symbol, and cannot be used as a variable." name))
32   (when (member name names-so-far :test #'eq)
33     (compiler-error "The variable ~S occurs more than once in the ~A."
34                     name
35                     context))
36   (let ((kind (info :variable :kind name)))
37     (cond ((keywordp name)
38            (compiler-error "~S is a keyword, and cannot be used as a local variable."
39                            name))
40           ((eq kind :constant)
41            (compiler-error "~@<~S names a defined constant, and cannot be used as a ~
42                             local variable.~:@>"
43                            name))
44           ((eq :global kind)
45            (compiler-error "~@<~S names a global lexical variable, and cannot be used ~
46                             as a local variable.~:@>"
47                            name))
48           ((eq kind :special)
49            (let ((specvar (find-free-var name)))
50              (make-lambda-var :%source-name name
51                               :type (leaf-type specvar)
52                               :where-from (leaf-where-from specvar)
53                               :specvar specvar)))
54           (t
55            (make-lambda-var :%source-name name)))))
56
57 ;;; Make the default keyword for a &KEY arg, checking that the keyword
58 ;;; isn't already used by one of the VARS.
59 (declaim (ftype (sfunction (symbol list t) symbol) make-keyword-for-arg))
60 (defun make-keyword-for-arg (symbol vars keywordify)
61   (let ((key (if (and keywordify (not (keywordp symbol)))
62                  (keywordicate symbol)
63                  symbol)))
64     (dolist (var vars)
65       (let ((info (lambda-var-arg-info var)))
66         (when (and info
67                    (eq (arg-info-kind info) :keyword)
68                    (eq (arg-info-key info) key))
69           (compiler-error
70            "The keyword ~S appears more than once in the lambda list."
71            key))))
72     key))
73
74 ;;; Parse a lambda list into a list of VAR structures, stripping off
75 ;;; any &AUX bindings. Each arg name is checked for legality, and
76 ;;; duplicate names are checked for. If an arg is globally special,
77 ;;; the var is marked as :SPECIAL instead of :LEXICAL. &KEY,
78 ;;; &OPTIONAL and &REST args are annotated with an ARG-INFO structure
79 ;;; which contains the extra information. If we hit something losing,
80 ;;; we bug out with COMPILER-ERROR. These values are returned:
81 ;;;  1. a list of the var structures for each top level argument;
82 ;;;  2. a flag indicating whether &KEY was specified;
83 ;;;  3. a flag indicating whether other &KEY args are allowed;
84 ;;;  4. a list of the &AUX variables; and
85 ;;;  5. a list of the &AUX values.
86 (declaim (ftype (sfunction (list) (values list boolean boolean list list))
87                 make-lambda-vars))
88 (defun make-lambda-vars (list)
89   (multiple-value-bind (required optional restp rest keyp keys allowp auxp aux
90                         morep more-context more-count)
91       (parse-lambda-list list)
92     (declare (ignore auxp)) ; since we just iterate over AUX regardless
93     (collect ((vars)
94               (names-so-far)
95               (aux-vars)
96               (aux-vals))
97       (flet (;; PARSE-DEFAULT deals with defaults and supplied-p args
98              ;; for optionals and keywords args.
99              (parse-default (spec info)
100                (when (consp (cdr spec))
101                  (setf (arg-info-default info) (second spec))
102                  (when (consp (cddr spec))
103                    (let* ((supplied-p (third spec))
104                           (supplied-var (varify-lambda-arg supplied-p
105                                                            (names-so-far))))
106                      (setf (arg-info-supplied-p info) supplied-var)
107                      (names-so-far supplied-p)
108                      (when (> (length (the list spec)) 3)
109                        (compiler-error
110                         "The list ~S is too long to be an arg specifier."
111                         spec)))))))
112
113         (dolist (name required)
114           (let ((var (varify-lambda-arg name (names-so-far))))
115             (vars var)
116             (names-so-far name)))
117
118         (dolist (spec optional)
119           (if (atom spec)
120               (let ((var (varify-lambda-arg spec (names-so-far))))
121                 (setf (lambda-var-arg-info var)
122                       (make-arg-info :kind :optional))
123                 (vars var)
124                 (names-so-far spec))
125               (let* ((name (first spec))
126                      (var (varify-lambda-arg name (names-so-far)))
127                      (info (make-arg-info :kind :optional)))
128                 (setf (lambda-var-arg-info var) info)
129                 (vars var)
130                 (names-so-far name)
131                 (parse-default spec info))))
132
133         (when restp
134           (let ((var (varify-lambda-arg rest (names-so-far))))
135             (setf (lambda-var-arg-info var) (make-arg-info :kind :rest))
136             (vars var)
137             (names-so-far rest)))
138
139         (when morep
140           (let ((var (varify-lambda-arg more-context (names-so-far))))
141             (setf (lambda-var-arg-info var)
142                   (make-arg-info :kind :more-context))
143             (vars var)
144             (names-so-far more-context))
145           (let ((var (varify-lambda-arg more-count (names-so-far))))
146             (setf (lambda-var-arg-info var)
147                   (make-arg-info :kind :more-count))
148             (vars var)
149             (names-so-far more-count)))
150
151         (dolist (spec keys)
152           (cond
153            ((atom spec)
154             (let ((var (varify-lambda-arg spec (names-so-far))))
155               (setf (lambda-var-arg-info var)
156                     (make-arg-info :kind :keyword
157                                    :key (make-keyword-for-arg spec
158                                                               (vars)
159                                                               t)))
160               (vars var)
161               (names-so-far spec)))
162            ((atom (first spec))
163             (let* ((name (first spec))
164                    (var (varify-lambda-arg name (names-so-far)))
165                    (info (make-arg-info
166                           :kind :keyword
167                           :key (make-keyword-for-arg name (vars) t))))
168               (setf (lambda-var-arg-info var) info)
169               (vars var)
170               (names-so-far name)
171               (parse-default spec info)))
172            (t
173             (let ((head (first spec)))
174               (unless (proper-list-of-length-p head 2)
175                 (error "malformed &KEY argument specifier: ~S" spec))
176               (let* ((name (second head))
177                      (var (varify-lambda-arg name (names-so-far)))
178                      (info (make-arg-info
179                             :kind :keyword
180                             :key (make-keyword-for-arg (first head)
181                                                        (vars)
182                                                        nil))))
183                 (setf (lambda-var-arg-info var) info)
184                 (vars var)
185                 (names-so-far name)
186                 (parse-default spec info))))))
187
188         (dolist (spec aux)
189           (cond ((atom spec)
190                  (let ((var (varify-lambda-arg spec nil)))
191                    (aux-vars var)
192                    (aux-vals nil)
193                    (names-so-far spec)))
194                 (t
195                  (unless (proper-list-of-length-p spec 1 2)
196                    (compiler-error "malformed &AUX binding specifier: ~S"
197                                    spec))
198                  (let* ((name (first spec))
199                         (var (varify-lambda-arg name nil)))
200                    (aux-vars var)
201                    (aux-vals (second spec))
202                    (names-so-far name)))))
203
204         (values (vars) keyp allowp (aux-vars) (aux-vals))))))
205
206 ;;; This is similar to IR1-CONVERT-PROGN-BODY except that we
207 ;;; sequentially bind each AUX-VAR to the corresponding AUX-VAL before
208 ;;; converting the body. If there are no bindings, just convert the
209 ;;; body, otherwise do one binding and recurse on the rest.
210 ;;;
211 ;;; FIXME: This could and probably should be converted to use
212 ;;; SOURCE-NAME and DEBUG-NAME. But I (WHN) don't use &AUX bindings,
213 ;;; so I'm not motivated. Patches will be accepted...
214 (defun ir1-convert-aux-bindings (start next result body aux-vars aux-vals
215                                  post-binding-lexenv)
216   (declare (type ctran start next) (type (or lvar null) result)
217            (list body aux-vars aux-vals))
218   (if (null aux-vars)
219       (let ((*lexenv* (make-lexenv :vars (copy-list post-binding-lexenv))))
220         (ir1-convert-progn-body start next result body))
221       (let ((ctran (make-ctran))
222             (fun-lvar (make-lvar))
223             (fun (ir1-convert-lambda-body body
224                                           (list (first aux-vars))
225                                           :aux-vars (rest aux-vars)
226                                           :aux-vals (rest aux-vals)
227                                           :post-binding-lexenv post-binding-lexenv
228                                           :debug-name (debug-name
229                                                        '&aux-bindings
230                                                        aux-vars))))
231         (reference-leaf start ctran fun-lvar fun)
232         (ir1-convert-combination-args fun-lvar ctran next result
233                                       (list (first aux-vals)))))
234   (values))
235
236 ;;; This is similar to IR1-CONVERT-PROGN-BODY except that code to bind
237 ;;; the SPECVAR for each SVAR to the value of the variable is wrapped
238 ;;; around the body. If there are no special bindings, we just convert
239 ;;; the body, otherwise we do one special binding and recurse on the
240 ;;; rest.
241 ;;;
242 ;;; We make a cleanup and introduce it into the lexical
243 ;;; environment. If there are multiple special bindings, the cleanup
244 ;;; for the blocks will end up being the innermost one. We force NEXT
245 ;;; to start a block outside of this cleanup, causing cleanup code to
246 ;;; be emitted when the scope is exited.
247 (defun ir1-convert-special-bindings
248     (start next result body aux-vars aux-vals svars post-binding-lexenv)
249   (declare (type ctran start next) (type (or lvar null) result)
250            (list body aux-vars aux-vals svars))
251   (cond
252    ((null svars)
253     (ir1-convert-aux-bindings start next result body aux-vars aux-vals
254                               post-binding-lexenv))
255    (t
256     (ctran-starts-block next)
257     (let ((cleanup (make-cleanup :kind :special-bind))
258           (var (first svars))
259           (bind-ctran (make-ctran))
260           (cleanup-ctran (make-ctran)))
261       (ir1-convert start bind-ctran nil
262                    `(%special-bind ',(lambda-var-specvar var) ,var))
263       (setf (cleanup-mess-up cleanup) (ctran-use bind-ctran))
264       (let ((*lexenv* (make-lexenv :cleanup cleanup)))
265         (ir1-convert bind-ctran cleanup-ctran nil '(%cleanup-point))
266         (ir1-convert-special-bindings cleanup-ctran next result
267                                       body aux-vars aux-vals
268                                       (rest svars)
269                                       post-binding-lexenv)))))
270   (values))
271
272 ;;; Create a lambda node out of some code, returning the result. The
273 ;;; bindings are specified by the list of VAR structures VARS. We deal
274 ;;; with adding the names to the LEXENV-VARS for the conversion. The
275 ;;; result is added to the NEW-FUNCTIONALS in the *CURRENT-COMPONENT*
276 ;;; and linked to the component head and tail.
277 ;;;
278 ;;; We detect special bindings here, replacing the original VAR in the
279 ;;; lambda list with a temporary variable. We then pass a list of the
280 ;;; special vars to IR1-CONVERT-SPECIAL-BINDINGS, which actually emits
281 ;;; the special binding code.
282 ;;;
283 ;;; We ignore any ARG-INFO in the VARS, trusting that someone else is
284 ;;; dealing with &NONSENSE, except for &REST vars with DYNAMIC-EXTENT.
285 ;;;
286 ;;; AUX-VARS is a list of VAR structures for variables that are to be
287 ;;; sequentially bound. Each AUX-VAL is a form that is to be evaluated
288 ;;; to get the initial value for the corresponding AUX-VAR.
289 (defun ir1-convert-lambda-body (body
290                                 vars
291                                 &key
292                                 aux-vars
293                                 aux-vals
294                                 (source-name '.anonymous.)
295                                 debug-name
296                                 (note-lexical-bindings t)
297                                 post-binding-lexenv
298                                 system-lambda)
299   (declare (list body vars aux-vars aux-vals))
300
301   ;; We're about to try to put new blocks into *CURRENT-COMPONENT*.
302   (aver-live-component *current-component*)
303
304   (let* ((bind (make-bind))
305          (lambda (make-lambda :vars vars
306                   :bind bind
307                   :%source-name source-name
308                   :%debug-name debug-name
309                   :system-lambda-p system-lambda))
310          (result-ctran (make-ctran))
311          (result-lvar (make-lvar)))
312
313     (awhen (lexenv-lambda *lexenv*)
314       (push lambda (lambda-children it))
315       (setf (lambda-parent lambda) it))
316
317     ;; just to check: This function should fail internal assertions if
318     ;; we didn't set up a valid debug name above.
319     ;;
320     ;; (In SBCL we try to make everything have a debug name, since we
321     ;; lack the omniscient perspective the original implementors used
322     ;; to decide which things didn't need one.)
323     (functional-debug-name lambda)
324
325     (setf (lambda-home lambda) lambda)
326     (collect ((svars)
327               (new-venv nil cons))
328
329       (dolist (var vars)
330         ;; As far as I can see, LAMBDA-VAR-HOME should never have
331         ;; been set before. Let's make sure. -- WHN 2001-09-29
332         (aver (not (lambda-var-home var)))
333         (setf (lambda-var-home var) lambda)
334         (let ((specvar (lambda-var-specvar var)))
335           (cond (specvar
336                  (svars var)
337                  (new-venv (cons (leaf-source-name specvar) specvar)))
338                 (t
339                  (when note-lexical-bindings
340                    (note-lexical-binding (leaf-source-name var)))
341                  (new-venv (cons (leaf-source-name var) var))))))
342
343       (let ((*lexenv* (make-lexenv :vars (new-venv)
344                                    :lambda lambda
345                                    :cleanup nil)))
346         (setf (bind-lambda bind) lambda)
347         (setf (node-lexenv bind) *lexenv*)
348
349         (let ((block (ctran-starts-block result-ctran)))
350           (let ((return (make-return :result result-lvar :lambda lambda))
351                 (tail-set (make-tail-set :funs (list lambda))))
352             (setf (lambda-tail-set lambda) tail-set)
353             (setf (lambda-return lambda) return)
354             (setf (lvar-dest result-lvar) return)
355             (link-node-to-previous-ctran return result-ctran)
356             (setf (block-last block) return))
357           (link-blocks block (component-tail *current-component*)))
358
359         (with-component-last-block (*current-component*
360                                     (ctran-block result-ctran))
361           (let ((prebind-ctran (make-ctran))
362                 (postbind-ctran (make-ctran)))
363             (ctran-starts-block prebind-ctran)
364             (link-node-to-previous-ctran bind prebind-ctran)
365             (use-ctran bind postbind-ctran)
366             (ir1-convert-special-bindings postbind-ctran result-ctran
367                                           result-lvar body
368                                           aux-vars aux-vals (svars)
369                                           post-binding-lexenv)))))
370
371     (link-blocks (component-head *current-component*) (node-block bind))
372     (push lambda (component-new-functionals *current-component*))
373
374     lambda))
375
376 ;;; Entry point CLAMBDAs have a special kind
377 (defun register-entry-point (entry dispatcher)
378   (declare (type clambda entry)
379            (type optional-dispatch dispatcher))
380   (setf (functional-kind entry) :optional)
381   (setf (leaf-ever-used entry) t)
382   (setf (lambda-optional-dispatch entry) dispatcher)
383   entry)
384
385 ;;; Create the actual entry-point function for an optional entry
386 ;;; point. The lambda binds copies of each of the VARS, then calls FUN
387 ;;; with the argument VALS and the DEFAULTS. Presumably the VALS refer
388 ;;; to the VARS by name. The VALS are passed in the reverse order.
389 ;;;
390 ;;; If any of the copies of the vars are referenced more than once,
391 ;;; then we mark the corresponding var as EVER-USED to inhibit
392 ;;; "defined but not read" warnings for arguments that are only used
393 ;;; by default forms.
394 (defun convert-optional-entry (fun vars vals defaults name)
395   (declare (type clambda fun) (list vars vals defaults))
396   (let* ((fvars (reverse vars))
397          (arg-vars (mapcar (lambda (var)
398                              (make-lambda-var
399                               :%source-name (leaf-source-name var)
400                               :type (leaf-type var)
401                               :where-from (leaf-where-from var)
402                               :specvar (lambda-var-specvar var)))
403                            fvars))
404          (fun (collect ((default-bindings)
405                         (default-vals))
406                 (dolist (default defaults)
407                   (if (sb!xc:constantp default)
408                       (default-vals default)
409                       (let ((var (gensym)))
410                         (default-bindings `(,var ,default))
411                         (default-vals var))))
412                 (let ((bindings (default-bindings))
413                       (call `(%funcall ,fun ,@(reverse vals) ,@(default-vals))))
414                   (ir1-convert-lambda-body (if bindings
415                                                `((let (,@bindings) ,call))
416                                                `(,call))
417                                           arg-vars
418                                           ;; FIXME: Would be nice to
419                                           ;; share these names instead
420                                           ;; of consing up several
421                                           ;; identical ones. Oh well.
422                                           :debug-name (debug-name
423                                                        '&optional-processor
424                                                        name)
425                                           :note-lexical-bindings nil
426                                           :system-lambda t)))))
427     (mapc (lambda (var arg-var)
428             (when (cdr (leaf-refs arg-var))
429               (setf (leaf-ever-used var) t)))
430           fvars arg-vars)
431     fun))
432
433 ;;; This function deals with supplied-p vars in optional arguments. If
434 ;;; the there is no supplied-p arg, then we just call
435 ;;; IR1-CONVERT-HAIRY-ARGS on the remaining arguments, and generate a
436 ;;; optional entry that calls the result. If there is a supplied-p
437 ;;; var, then we add it into the default vars and throw a T into the
438 ;;; entry values. The resulting entry point function is returned.
439 (defun generate-optional-default-entry (res default-vars default-vals
440                                         entry-vars entry-vals
441                                         vars supplied-p-p body
442                                         aux-vars aux-vals
443                                         source-name debug-name
444                                         force post-binding-lexenv
445                                         system-lambda)
446   (declare (type optional-dispatch res)
447            (list default-vars default-vals entry-vars entry-vals vars body
448                  aux-vars aux-vals))
449   (let* ((arg (first vars))
450          (arg-name (leaf-source-name arg))
451          (info (lambda-var-arg-info arg))
452          (default (arg-info-default info))
453          (supplied-p (arg-info-supplied-p info))
454          (force (or force
455                     (not (sb!xc:constantp (arg-info-default info)))))
456          (ep (if supplied-p
457                  (ir1-convert-hairy-args
458                   res
459                   (list* supplied-p arg default-vars)
460                   (list* (leaf-source-name supplied-p) arg-name default-vals)
461                   (cons arg entry-vars)
462                   (list* t arg-name entry-vals)
463                   (rest vars) t body aux-vars aux-vals
464                   source-name debug-name
465                   force post-binding-lexenv system-lambda)
466                  (ir1-convert-hairy-args
467                   res
468                   (cons arg default-vars)
469                   (cons arg-name default-vals)
470                   (cons arg entry-vars)
471                   (cons arg-name entry-vals)
472                   (rest vars) supplied-p-p body aux-vars aux-vals
473                   source-name debug-name
474                   force post-binding-lexenv system-lambda))))
475
476     ;; We want to delay converting the entry, but there exist
477     ;; problems: hidden references should not be established to
478     ;; lambdas of kind NIL should not have (otherwise the compiler
479     ;; might let-convert or delete them) and to variables.
480     (let ((name (or debug-name source-name)))
481       (if (or force
482               supplied-p-p ; this entry will be of kind NIL
483               (and (lambda-p ep) (eq (lambda-kind ep) nil)))
484           (convert-optional-entry ep
485                                   default-vars default-vals
486                                   (if supplied-p (list default nil) (list default))
487                                   name)
488           (let* ((default `',(constant-form-value default))
489                  (defaults (if supplied-p (list default nil) (list default))))
490             ;; DEFAULT can contain a reference to a
491             ;; to-be-optimized-away function/block/tag, so better to
492             ;; reduce code now (but we possibly lose syntax checking
493             ;; in an unreachable code).
494             (delay
495              (register-entry-point
496               (convert-optional-entry (force ep)
497                                       default-vars default-vals
498                                       defaults
499                                       name)
500               res)))))))
501
502 ;;; Create the MORE-ENTRY function for the OPTIONAL-DISPATCH RES.
503 ;;; ENTRY-VARS and ENTRY-VALS describe the fixed arguments. REST is
504 ;;; the var for any &REST arg. KEYS is a list of the &KEY arg vars.
505 ;;;
506 ;;; The most interesting thing that we do is parse keywords. We create
507 ;;; a bunch of temporary variables to hold the result of the parse,
508 ;;; and then loop over the supplied arguments, setting the appropriate
509 ;;; temps for the supplied keyword. Note that it is significant that
510 ;;; we iterate over the keywords in reverse order --- this implements
511 ;;; the CL requirement that (when a keyword appears more than once)
512 ;;; the first value is used.
513 ;;;
514 ;;; If there is no supplied-p var, then we initialize the temp to the
515 ;;; default and just pass the temp into the main entry. Since
516 ;;; non-constant &KEY args are forcibly given a supplied-p var, we
517 ;;; know that the default is constant, and thus safe to evaluate out
518 ;;; of order.
519 ;;;
520 ;;; If there is a supplied-p var, then we create temps for both the
521 ;;; value and the supplied-p, and pass them into the main entry,
522 ;;; letting it worry about defaulting.
523 ;;;
524 ;;; We deal with :ALLOW-OTHER-KEYS by delaying unknown keyword errors
525 ;;; until we have scanned all the keywords.
526 (defun convert-more-entry (res entry-vars entry-vals rest morep keys name)
527   (declare (type optional-dispatch res) (list entry-vars entry-vals keys))
528   (collect ((arg-vars)
529             (arg-vals (reverse entry-vals))
530             (temps)
531             (body))
532
533     (dolist (var (reverse entry-vars))
534       (arg-vars (make-lambda-var :%source-name (leaf-source-name var)
535                                  :type (leaf-type var)
536                                  :where-from (leaf-where-from var))))
537
538     (let* ((n-context (gensym "N-CONTEXT-"))
539            (context-temp (make-lambda-var :%source-name n-context))
540            (n-count (gensym "N-COUNT-"))
541            (count-temp (make-lambda-var :%source-name n-count
542                                         :type (specifier-type 'index))))
543
544       (arg-vars context-temp count-temp)
545
546       (when rest
547         (arg-vals `(%listify-rest-args ,n-context ,n-count)))
548       (when morep
549         (arg-vals n-context)
550         (arg-vals n-count))
551
552       ;; The reason for all the noise with
553       ;; STACK-GROWS-DOWNWARD-NOT-UPWARD is to enable generation of
554       ;; slightly more efficient code on x86oid processors.  (We can
555       ;; hoist the negation of the index outside the main parsing loop
556       ;; and take advantage of the base+index+displacement addressing
557       ;; mode on x86oids.)
558       (when (optional-dispatch-keyp res)
559         (let ((n-index (gensym "N-INDEX-"))
560               (n-key (gensym "N-KEY-"))
561               (n-value-temp (gensym "N-VALUE-TEMP-"))
562               (n-allowp (gensym "N-ALLOWP-"))
563               (n-lose (gensym "N-LOSE-"))
564               (n-losep (gensym "N-LOSEP-"))
565               (allowp (or (optional-dispatch-allowp res)
566                           (policy *lexenv* (zerop safety))))
567               (found-allow-p nil))
568
569           (temps #!-stack-grows-downward-not-upward
570                  `(,n-index (1- ,n-count))
571                  #!+stack-grows-downward-not-upward
572                  `(,n-index (- (1- ,n-count)))
573                  #!-stack-grows-downward-not-upward n-value-temp
574                  #!-stack-grows-downward-not-upward n-key)
575           (body `(declare (fixnum ,n-index)
576                           #!-stack-grows-downward-not-upward
577                           (ignorable ,n-value-temp ,n-key)))
578
579           (collect ((tests))
580             (dolist (key keys)
581               (let* ((info (lambda-var-arg-info key))
582                      (default (arg-info-default info))
583                      (keyword (arg-info-key info))
584                      (supplied-p (arg-info-supplied-p info))
585                      (n-value (gensym "N-VALUE-"))
586                      (clause (cond (supplied-p
587                                     (let ((n-supplied (gensym "N-SUPPLIED-")))
588                                       (temps n-supplied)
589                                       (arg-vals n-value n-supplied)
590                                       `((eq ,n-key ',keyword)
591                                         (setq ,n-supplied t)
592                                         (setq ,n-value ,n-value-temp))))
593                                    (t
594                                     (arg-vals n-value)
595                                     `((eq ,n-key ',keyword)
596                                       (setq ,n-value ,n-value-temp))))))
597                 (when (and (not allowp) (eq keyword :allow-other-keys))
598                   (setq found-allow-p t)
599                   (setq clause
600                         (append clause `((setq ,n-allowp ,n-value-temp)))))
601
602                 (temps `(,n-value ,default))
603                 (tests clause)))
604
605             (unless allowp
606               (temps n-allowp n-lose n-losep)
607               (unless found-allow-p
608                 (tests `((eq ,n-key :allow-other-keys)
609                          (setq ,n-allowp ,n-value-temp))))
610               (tests `(t
611                        (setq ,n-lose ,n-key
612                              ,n-losep t))))
613
614             (body
615              `(when (oddp ,n-count)
616                 (%odd-key-args-error)))
617
618             (body
619              #!-stack-grows-downward-not-upward
620              `(locally
621                 (declare (optimize (safety 0)))
622                 (loop
623                   (when (minusp ,n-index) (return))
624                   (setf ,n-value-temp (%more-arg ,n-context ,n-index))
625                   (decf ,n-index)
626                   (setq ,n-key (%more-arg ,n-context ,n-index))
627                   (decf ,n-index)
628                   (cond ,@(tests))))
629              #!+stack-grows-downward-not-upward
630              `(locally (declare (optimize (safety 0)))
631                 (loop
632                   (when (plusp ,n-index) (return))
633                   (multiple-value-bind (,n-value-temp ,n-key)
634                       (%more-kw-arg ,n-context ,n-index)
635                     (declare (ignorable ,n-value-temp ,n-key))
636                     (incf ,n-index 2)
637                     (cond ,@(tests))))))
638
639             (unless allowp
640               (body `(when (and ,n-losep (not ,n-allowp))
641                        (%unknown-key-arg-error ,n-lose)))))))
642
643       (let ((ep (ir1-convert-lambda-body
644                  `((let ,(temps)
645                      ,@(body)
646                      (%funcall ,(optional-dispatch-main-entry res)
647                                ,@(arg-vals))))
648                  (arg-vars)
649                  :debug-name (debug-name '&more-processor name)
650                  :note-lexical-bindings nil
651                  :system-lambda t)))
652         (setf (optional-dispatch-more-entry res)
653               (register-entry-point ep res)))))
654
655   (values))
656
657 ;;; This is called by IR1-CONVERT-HAIRY-ARGS when we run into a &REST
658 ;;; or &KEY arg. The arguments are similar to that function, but we
659 ;;; split off any &REST arg and pass it in separately. REST is the
660 ;;; &REST arg var, or NIL if there is no &REST arg. KEYS is a list of
661 ;;; the &KEY argument vars.
662 ;;;
663 ;;; When there are &KEY arguments, we introduce temporary gensym
664 ;;; variables to hold the values while keyword defaulting is in
665 ;;; progress to get the required sequential binding semantics.
666 ;;;
667 ;;; This gets interesting mainly when there are &KEY arguments with
668 ;;; supplied-p vars or non-constant defaults. In either case, pass in
669 ;;; a supplied-p var. If the default is non-constant, we introduce an
670 ;;; IF in the main entry that tests the supplied-p var and decides
671 ;;; whether to evaluate the default or not. In this case, the real
672 ;;; incoming value is NIL, so we must union NULL with the declared
673 ;;; type when computing the type for the main entry's argument.
674 (defun ir1-convert-more (res default-vars default-vals entry-vars entry-vals
675                          rest more-context more-count keys supplied-p-p
676                          body aux-vars aux-vals source-name debug-name
677                          post-binding-lexenv system-lambda)
678   (declare (type optional-dispatch res)
679            (list default-vars default-vals entry-vars entry-vals keys body
680                  aux-vars aux-vals))
681   (collect ((main-vars (reverse default-vars))
682             (main-vals default-vals cons)
683             (bind-vars)
684             (bind-vals))
685     (when rest
686       (main-vars rest)
687       (main-vals '())
688       (unless (lambda-var-ignorep rest)
689         ;; Make up two extra variables, and squirrel them away in
690         ;; ARG-INFO-DEFAULT for transforming (VALUES-LIST REST) into
691         ;; (%MORE-ARG-VALUES CONTEXT 0 COUNT) when possible.
692         (let* ((context-name (gensym "REST-CONTEXT"))
693                (context (make-lambda-var :%source-name context-name
694                                          :arg-info (make-arg-info :kind :more-context)))
695                (count-name (gensym "REST-COUNT"))
696                (count (make-lambda-var :%source-name count-name
697                                        :arg-info (make-arg-info :kind :more-count)
698                                        :type (specifier-type 'index))))
699           (setf (arg-info-default (lambda-var-arg-info rest)) (list context count)
700                 (lambda-var-ever-used context) t
701                 (lambda-var-ever-used count) t)
702           (setf more-context context
703                 more-count count))))
704     (when more-context
705       (main-vars more-context)
706       (main-vals nil)
707       (main-vars more-count)
708       (main-vals 0))
709
710     (dolist (key keys)
711       (let* ((info (lambda-var-arg-info key))
712              (default (arg-info-default info))
713              (hairy-default (not (sb!xc:constantp default)))
714              (supplied-p (arg-info-supplied-p info))
715              (n-val (make-symbol (format nil
716                                          "~A-DEFAULTING-TEMP"
717                                          (leaf-source-name key))))
718              (val-temp (make-lambda-var :%source-name n-val)))
719         (main-vars val-temp)
720         (bind-vars key)
721         (cond ((or hairy-default supplied-p)
722                (let* ((n-supplied (gensym "N-SUPPLIED-"))
723                       (supplied-temp (make-lambda-var
724                                       :%source-name n-supplied)))
725                  (unless supplied-p
726                    (setf (arg-info-supplied-p info) supplied-temp))
727                  (when hairy-default
728                    (setf (arg-info-default info) nil))
729                  (main-vars supplied-temp)
730                  (cond (hairy-default
731                         (main-vals nil nil)
732                         (bind-vals `(if ,n-supplied ,n-val ,default)))
733                        (t
734                         (main-vals default nil)
735                         (bind-vals n-val)))
736                  (when supplied-p
737                    (bind-vars supplied-p)
738                    (bind-vals n-supplied))))
739               (t
740                (main-vals (arg-info-default info))
741                (bind-vals n-val)))))
742
743     (let* ((main-entry (ir1-convert-lambda-body
744                         body (main-vars)
745                         :aux-vars (append (bind-vars) aux-vars)
746                         :aux-vals (append (bind-vals) aux-vals)
747                         :post-binding-lexenv post-binding-lexenv
748                         :source-name source-name
749                         :debug-name debug-name
750                         :system-lambda system-lambda))
751            (name (or debug-name source-name))
752            (last-entry (convert-optional-entry main-entry default-vars
753                                                (main-vals) () name)))
754       (setf (optional-dispatch-main-entry res)
755             (register-entry-point main-entry res))
756       (convert-more-entry res entry-vars entry-vals rest more-context keys
757                           name)
758
759       (push (register-entry-point
760              (if supplied-p-p
761                 (convert-optional-entry last-entry entry-vars entry-vals
762                                         () name)
763                 last-entry)
764              res)
765             (optional-dispatch-entry-points res))
766       last-entry)))
767
768 ;;; This function generates the entry point functions for the
769 ;;; OPTIONAL-DISPATCH RES. We accomplish this by recursion on the list
770 ;;; of arguments, analyzing the arglist on the way down and generating
771 ;;; entry points on the way up.
772 ;;;
773 ;;; DEFAULT-VARS is a reversed list of all the argument vars processed
774 ;;; so far, including supplied-p vars. DEFAULT-VALS is a list of the
775 ;;; names of the DEFAULT-VARS.
776 ;;;
777 ;;; ENTRY-VARS is a reversed list of processed argument vars,
778 ;;; excluding supplied-p vars. ENTRY-VALS is a list things that can be
779 ;;; evaluated to get the values for all the vars from the ENTRY-VARS.
780 ;;; It has the var name for each required or optional arg, and has T
781 ;;; for each supplied-p arg.
782 ;;;
783 ;;; VARS is a list of the LAMBDA-VAR structures for arguments that
784 ;;; haven't been processed yet. SUPPLIED-P-P is true if a supplied-p
785 ;;; argument has already been processed; only in this case are the
786 ;;; DEFAULT-XXX and ENTRY-XXX different.
787 ;;;
788 ;;; The result at each point is a lambda which should be called by the
789 ;;; above level to default the remaining arguments and evaluate the
790 ;;; body. We cause the body to be evaluated by converting it and
791 ;;; returning it as the result when the recursion bottoms out.
792 ;;;
793 ;;; Each level in the recursion also adds its entry point function to
794 ;;; the result OPTIONAL-DISPATCH. For most arguments, the defaulting
795 ;;; function and the entry point function will be the same, but when
796 ;;; SUPPLIED-P args are present they may be different.
797 ;;;
798 ;;; When we run into a &REST or &KEY arg, we punt out to
799 ;;; IR1-CONVERT-MORE, which finishes for us in this case.
800 (defun ir1-convert-hairy-args (res default-vars default-vals
801                                entry-vars entry-vals
802                                vars supplied-p-p body aux-vars
803                                aux-vals
804                                source-name debug-name
805                                force post-binding-lexenv
806                                system-lambda)
807   (declare (type optional-dispatch res)
808            (list default-vars default-vals entry-vars entry-vals vars body
809                  aux-vars aux-vals))
810   (aver (or debug-name (neq '.anonymous. source-name)))
811   (cond ((not vars)
812          (if (optional-dispatch-keyp res)
813              ;; Handle &KEY with no keys...
814              (ir1-convert-more res default-vars default-vals
815                                entry-vars entry-vals
816                                nil nil nil vars supplied-p-p body aux-vars
817                                aux-vals source-name debug-name
818                                post-binding-lexenv system-lambda)
819              (let* ((name (or debug-name source-name))
820                     (fun (ir1-convert-lambda-body
821                          body (reverse default-vars)
822                          :aux-vars aux-vars
823                          :aux-vals aux-vals
824                          :post-binding-lexenv post-binding-lexenv
825                          :source-name source-name
826                          :debug-name debug-name
827                          :system-lambda system-lambda)))
828
829                (setf (optional-dispatch-main-entry res) fun)
830                (register-entry-point fun res)
831                (push (if supplied-p-p
832                          (register-entry-point
833                           (convert-optional-entry fun entry-vars entry-vals ()
834                                                   name)
835                           res)
836                           fun)
837                      (optional-dispatch-entry-points res))
838                fun)))
839         ((not (lambda-var-arg-info (first vars)))
840          (let* ((arg (first vars))
841                 (nvars (cons arg default-vars))
842                 (nvals (cons (leaf-source-name arg) default-vals)))
843            (ir1-convert-hairy-args res nvars nvals nvars nvals
844                                    (rest vars) nil body aux-vars aux-vals
845                                    source-name debug-name
846                                    nil post-binding-lexenv system-lambda)))
847         (t
848          (let* ((arg (first vars))
849                 (info (lambda-var-arg-info arg))
850                 (kind (arg-info-kind info)))
851            (ecase kind
852              (:optional
853               (let ((ep (generate-optional-default-entry
854                          res default-vars default-vals
855                          entry-vars entry-vals vars supplied-p-p body
856                          aux-vars aux-vals
857                          source-name debug-name
858                          force post-binding-lexenv
859                          system-lambda)))
860                 ;; See GENERATE-OPTIONAL-DEFAULT-ENTRY.
861                 (push (if (lambda-p ep)
862                           (register-entry-point
863                            (if supplied-p-p
864                                (convert-optional-entry
865                                 ep entry-vars entry-vals nil
866                                 (or debug-name source-name))
867                                ep)
868                            res)
869                           (progn (aver (not supplied-p-p))
870                                  ep))
871                       (optional-dispatch-entry-points res))
872                 ep))
873              (:rest
874               (ir1-convert-more res default-vars default-vals
875                                 entry-vars entry-vals
876                                 arg nil nil (rest vars) supplied-p-p body
877                                 aux-vars aux-vals
878                                 source-name debug-name
879                                 post-binding-lexenv system-lambda))
880              (:more-context
881               (ir1-convert-more res default-vars default-vals
882                                 entry-vars entry-vals
883                                 nil arg (second vars) (cddr vars) supplied-p-p
884                                 body aux-vars aux-vals
885                                 source-name debug-name
886                                 post-binding-lexenv system-lambda))
887              (:keyword
888               (ir1-convert-more res default-vars default-vals
889                                 entry-vars entry-vals
890                                 nil nil nil vars supplied-p-p body aux-vars
891                                 aux-vals source-name debug-name
892                                 post-binding-lexenv system-lambda)))))))
893
894 ;;; This function deals with the case where we have to make an
895 ;;; OPTIONAL-DISPATCH to represent a LAMBDA. We cons up the result and
896 ;;; call IR1-CONVERT-HAIRY-ARGS to do the work. When it is done, we
897 ;;; figure out the MIN-ARGS and MAX-ARGS.
898 (defun ir1-convert-hairy-lambda (body vars keyp allowp aux-vars aux-vals
899                                  &key post-binding-lexenv
900                                  (source-name '.anonymous.)
901                                  debug-name system-lambda)
902   (declare (list body vars aux-vars aux-vals))
903   (aver (or debug-name (neq '.anonymous. source-name)))
904   (let ((res (make-optional-dispatch :arglist vars
905                                      :allowp allowp
906                                      :keyp keyp
907                                      :%source-name source-name
908                                      :%debug-name debug-name
909                                      :plist `(:ir1-environment
910                                               (,*lexenv*
911                                                ,*current-path*))))
912         (min (or (position-if #'lambda-var-arg-info vars) (length vars))))
913     (aver-live-component *current-component*)
914     (push res (component-new-functionals *current-component*))
915     (ir1-convert-hairy-args res () () () () vars nil body aux-vars aux-vals
916                             source-name debug-name nil post-binding-lexenv
917                             system-lambda)
918     (setf (optional-dispatch-min-args res) min)
919     (setf (optional-dispatch-max-args res)
920           (+ (1- (length (optional-dispatch-entry-points res))) min))
921
922     res))
923
924 ;;; Convert a LAMBDA form into a LAMBDA leaf or an OPTIONAL-DISPATCH leaf.
925 (defun ir1-convert-lambda (form &key (source-name '.anonymous.)
926                            debug-name maybe-add-debug-catch
927                            system-lambda)
928   (unless (consp form)
929     (compiler-error "A ~S was found when expecting a lambda expression:~%  ~S"
930                     (type-of form)
931                     form))
932   (unless (eq (car form) 'lambda)
933     (compiler-error "~S was expected but ~S was found:~%  ~S"
934                     'lambda
935                     (car form)
936                     form))
937   (unless (and (consp (cdr form)) (listp (cadr form)))
938     (compiler-error
939      "The lambda expression has a missing or non-list lambda list:~%  ~S"
940      form))
941   (when (and system-lambda maybe-add-debug-catch)
942     (bug "Both SYSTEM-LAMBDA and MAYBE-ADD-DEBUG-CATCH specified"))
943   (unless (or debug-name (neq '.anonymous. source-name))
944     (setf debug-name (name-lambdalike form)))
945   (multiple-value-bind (vars keyp allow-other-keys aux-vars aux-vals)
946       (make-lambda-vars (cadr form))
947     (multiple-value-bind (forms decls doc) (parse-body (cddr form))
948       (binding* (((*lexenv* result-type post-binding-lexenv)
949                   (process-decls decls (append aux-vars vars) nil
950                                  :binding-form-p t))
951                  (debug-catch-p (and maybe-add-debug-catch
952                                      *allow-instrumenting*
953                                      (policy *lexenv*
954                                              (>= insert-debug-catch 2))))
955                  (forms (if debug-catch-p
956                             (wrap-forms-in-debug-catch forms)
957                             forms))
958                  (forms (if (eq result-type *wild-type*)
959                             forms
960                             `((the ,(type-specifier result-type) (progn ,@forms)))))
961                  (*allow-instrumenting* (and (not system-lambda) *allow-instrumenting*))
962                  (res (cond ((or (find-if #'lambda-var-arg-info vars) keyp)
963                              (ir1-convert-hairy-lambda forms vars keyp
964                                                        allow-other-keys
965                                                        aux-vars aux-vals
966                                                        :post-binding-lexenv post-binding-lexenv
967                                                        :source-name source-name
968                                                        :debug-name debug-name
969                                                        :system-lambda system-lambda))
970                             (t
971                              (ir1-convert-lambda-body forms vars
972                                                       :aux-vars aux-vars
973                                                       :aux-vals aux-vals
974                                                       :post-binding-lexenv post-binding-lexenv
975                                                       :source-name source-name
976                                                       :debug-name debug-name
977                                                       :system-lambda system-lambda)))))
978         (setf (functional-inline-expansion res) form)
979         (setf (functional-arg-documentation res) (cadr form))
980         (setf (functional-documentation res) doc)
981         (when (boundp '*lambda-conversions*)
982           ;; KLUDGE: Not counting TL-XEPs is a lie, of course, but
983           ;; keeps things less confusing to users of TIME, where this
984           ;; count gets used.
985           (unless (and (consp debug-name) (eq 'tl-xep (car debug-name)))
986             (incf *lambda-conversions*)))
987         res))))
988
989 (defun wrap-forms-in-debug-catch (forms)
990   #!+unwind-to-frame-and-call-vop
991   `((multiple-value-prog1
992       (progn
993         ,@forms)
994       ;; Just ensure that there won't be any tail-calls, IR2 magic will
995       ;; handle the rest.
996       (values)))
997   #!-unwind-to-frame-and-call-vop
998   `( ;; Normally, we'll return from this block with the below RETURN-FROM.
999     (block
1000         return-value-tag
1001       ;; If DEBUG-CATCH-TAG is thrown (with a thunk as the value) the
1002       ;; RETURN-FROM is elided and we funcall the thunk instead. That
1003       ;; thunk might either return a value (for a RETURN-FROM-FRAME)
1004       ;; or call this same function again (for a RESTART-FRAME).
1005       ;; -- JES, 2007-01-09
1006       (funcall
1007        (the function
1008          ;; Use a constant catch tag instead of consing a new one for every
1009          ;; entry to this block. The uniquencess of the catch tags is
1010          ;; ensured when the tag is throw by the debugger. It'll allocate a
1011          ;; new tag, and modify the reference this tag in the proper
1012          ;; catch-block structure to refer to that new tag. This
1013          ;; significantly decreases the runtime cost of high debug levels.
1014          ;;  -- JES, 2007-01-09
1015          (catch 'debug-catch-tag
1016            (return-from return-value-tag
1017              (progn
1018                ,@forms))))))))
1019
1020 ;;; helper for LAMBDA-like things, to massage them into a form
1021 ;;; suitable for IR1-CONVERT-LAMBDA.
1022 (defun ir1-convert-lambdalike (thing
1023                                &key
1024                                (source-name '.anonymous.)
1025                                debug-name)
1026   (when (and (not debug-name) (eq '.anonymous. source-name))
1027     (setf debug-name (name-lambdalike thing)))
1028   (ecase (car thing)
1029     ((lambda)
1030      (ir1-convert-lambda thing
1031                          :maybe-add-debug-catch t
1032                          :source-name source-name
1033                          :debug-name debug-name))
1034     ((named-lambda)
1035      (let ((name (cadr thing))
1036            (lambda-expression `(lambda ,@(cddr thing))))
1037        (if (and name (legal-fun-name-p name))
1038            (let ((defined-fun-res (get-defined-fun name (second lambda-expression)))
1039                  (res (ir1-convert-lambda lambda-expression
1040                                           :maybe-add-debug-catch t
1041                                           :source-name name)))
1042              (assert-global-function-definition-type name res)
1043              (push res (defined-fun-functionals defined-fun-res))
1044              (unless (eq (defined-fun-inlinep defined-fun-res) :notinline)
1045                (substitute-leaf-if
1046                 (lambda (ref)
1047                   (policy ref (> recognize-self-calls 0)))
1048                 res defined-fun-res))
1049              res)
1050            (ir1-convert-lambda lambda-expression
1051                                :maybe-add-debug-catch t
1052                                :debug-name
1053                                (or name (name-lambdalike thing))))))
1054     ((lambda-with-lexenv)
1055      (ir1-convert-inline-lambda thing
1056                                 :source-name source-name
1057                                 :debug-name debug-name))))
1058 \f
1059 ;;;; defining global functions
1060
1061 ;;; Convert FUN as a lambda in the null environment, but use the
1062 ;;; current compilation policy. Note that FUN may be a
1063 ;;; LAMBDA-WITH-LEXENV, so we may have to augment the environment to
1064 ;;; reflect the state at the definition site.
1065 (defun ir1-convert-inline-lambda (fun
1066                                   &key
1067                                   (source-name '.anonymous.)
1068                                   debug-name
1069                                   system-lambda)
1070   (when (and (not debug-name) (eq '.anonymous. source-name))
1071     (setf debug-name (name-lambdalike fun)))
1072   (destructuring-bind (decls macros symbol-macros &rest body)
1073       (if (eq (car fun) 'lambda-with-lexenv)
1074           (cdr fun)
1075           `(() () () . ,(cdr fun)))
1076     (let* ((*lexenv* (make-lexenv
1077                       :default (process-decls decls nil nil
1078                                               :lexenv (make-null-lexenv))
1079                       :vars (copy-list symbol-macros)
1080                       :funs (mapcar (lambda (x)
1081                                       `(,(car x) .
1082                                          (macro . ,(coerce (cdr x) 'function))))
1083                                     macros)
1084                       ;; Inherit MUFFLE-CONDITIONS from the call-site lexenv
1085                       ;; rather than the definition-site lexenv, since it seems
1086                       ;; like a much more common case.
1087                       :handled-conditions (lexenv-handled-conditions *lexenv*)
1088                       :policy (lexenv-policy *lexenv*)))
1089            (clambda (ir1-convert-lambda `(lambda ,@body)
1090                                         :source-name source-name
1091                                         :debug-name debug-name
1092                                         :system-lambda system-lambda)))
1093       (setf (functional-inline-expanded clambda) t)
1094       clambda)))
1095
1096 ;;; Given a lambda-list, return a FUN-TYPE object representing the signature:
1097 ;;; return type is *, and each individual arguments type is T -- but we get
1098 ;;; the argument counts and keywords.
1099 (defun ftype-from-lambda-list (lambda-list)
1100   (multiple-value-bind (req opt restp rest-name keyp key-list allowp morep)
1101       (parse-lambda-list lambda-list)
1102     (declare (ignore rest-name))
1103     (flet ((t (list)
1104              (mapcar (constantly t) list)))
1105       (let ((reqs (t req))
1106             (opts (when opt (cons '&optional (t opt))))
1107             ;; When it comes to building a type, &REST means pretty much the
1108             ;; same thing as &MORE.
1109             (rest (when (or morep restp) (list '&rest t)))
1110             (keys (when keyp
1111                     (cons '&key (mapcar (lambda (spec)
1112                                           (let ((key/var (if (consp spec)
1113                                                              (car spec)
1114                                                              spec)))
1115                                             (list (if (consp key/var)
1116                                                       (car key/var)
1117                                                       (keywordicate key/var))
1118                                                   t)))
1119                                         key-list))))
1120             (allow (when allowp (list '&allow-other-keys))))
1121         (specifier-type `(function (,@reqs ,@opts ,@rest ,@keys ,@allow) *))))))
1122
1123 ;;; Get a DEFINED-FUN object for a function we are about to define. If
1124 ;;; the function has been forward referenced, then substitute for the
1125 ;;; previous references.
1126 (defun get-defined-fun (name &optional (lambda-list nil lp))
1127   (proclaim-as-fun-name name)
1128   (when (boundp '*free-funs*)
1129     (let ((found (find-free-fun name "shouldn't happen! (defined-fun)")))
1130       (note-name-defined name :function)
1131       (cond ((not (defined-fun-p found))
1132              (aver (not (info :function :inlinep name)))
1133              (let* ((where-from (leaf-where-from found))
1134                     (res (make-defined-fun
1135                           :%source-name name
1136                           :where-from (if (eq where-from :declared)
1137                                           :declared
1138                                           :defined-here)
1139                           :type (if (eq :declared where-from)
1140                                     (leaf-type found)
1141                                     (if lp
1142                                         (ftype-from-lambda-list lambda-list)
1143                                         (specifier-type 'function))))))
1144                (substitute-leaf res found)
1145                (setf (gethash name *free-funs*) res)))
1146             ;; If *FREE-FUNS* has a previously converted definition
1147             ;; for this name, then blow it away and try again.
1148             ((defined-fun-functionals found)
1149              (remhash name *free-funs*)
1150              (get-defined-fun name lambda-list))
1151             (t found)))))
1152
1153 ;;; Check a new global function definition for consistency with
1154 ;;; previous declaration or definition, and assert argument/result
1155 ;;; types if appropriate. This assertion is suppressed by the
1156 ;;; EXPLICIT-CHECK attribute, which is specified on functions that
1157 ;;; check their argument types as a consequence of type dispatching.
1158 ;;; This avoids redundant checks such as NUMBERP on the args to +, etc.
1159 (defun assert-new-definition (var fun)
1160   (let ((type (leaf-type var))
1161         (for-real (eq (leaf-where-from var) :declared))
1162         (info (info :function :info (leaf-source-name var))))
1163     (assert-definition-type
1164      fun type
1165      ;; KLUDGE: Common Lisp is such a dynamic language that in general
1166      ;; all we can do here in general is issue a STYLE-WARNING. It
1167      ;; would be nice to issue a full WARNING in the special case of
1168      ;; of type mismatches within a compilation unit (as in section
1169      ;; 3.2.2.3 of the spec) but at least as of sbcl-0.6.11, we don't
1170      ;; keep track of whether the mismatched data came from the same
1171      ;; compilation unit, so we can't do that. -- WHN 2001-02-11
1172      :lossage-fun #'compiler-style-warn
1173      :unwinnage-fun (cond (info #'compiler-style-warn)
1174                           (for-real #'compiler-notify)
1175                           (t nil))
1176      :really-assert
1177      (and for-real
1178           (not (and info
1179                     (ir1-attributep (fun-info-attributes info)
1180                                     explicit-check))))
1181      :where (if for-real
1182                 "previous declaration"
1183                 "previous definition"))))
1184
1185 ;;; Used for global inline expansion. Earlier something like this was
1186 ;;; used by %DEFUN too. FIXME: And now it's probably worth rethinking
1187 ;;; whether this function is a good idea at all.
1188 (defun ir1-convert-inline-expansion (name expansion var inlinep info)
1189   ;; Unless a :INLINE function, we temporarily clobber the inline
1190   ;; expansion. This prevents recursive inline expansion of
1191   ;; opportunistic pseudo-inlines.
1192   (unless (eq inlinep :inline)
1193     (setf (defined-fun-inline-expansion var) nil))
1194   (let ((fun (ir1-convert-inline-lambda expansion
1195                                         :source-name name
1196                                         ;; prevent instrumentation of
1197                                         ;; known function expansions
1198                                         :system-lambda (and info t))))
1199     (setf (functional-inlinep fun) inlinep)
1200     (assert-new-definition var fun)
1201     (setf (defined-fun-inline-expansion var) expansion)
1202     ;; Associate VAR with the FUN -- and in case of an optional dispatch
1203     ;; with the various entry-points. This allows XREF to know where the
1204     ;; inline CLAMBDA comes from.
1205     (flet ((note-inlining (f)
1206              (typecase f
1207                (functional
1208                 (setf (functional-inline-expanded f) var))
1209                (cons
1210                 ;; Delayed entry-point.
1211                 (if (car f)
1212                     (setf (functional-inline-expanded (cdr f)) var)
1213                     (let ((old-thunk (cdr f)))
1214                       (setf (cdr f) (lambda ()
1215                                       (let ((g (funcall old-thunk)))
1216                                         (setf (functional-inline-expanded g) var)
1217                                         g)))))))))
1218       (note-inlining fun)
1219       (when (optional-dispatch-p fun)
1220         (note-inlining (optional-dispatch-main-entry fun))
1221         (note-inlining (optional-dispatch-more-entry fun))
1222         (mapc #'note-inlining (optional-dispatch-entry-points fun))))
1223     ;; substitute for any old references
1224     (unless (or (not *block-compile*)
1225                 (and info
1226                      (or (fun-info-transforms info)
1227                          (fun-info-templates info)
1228                          (fun-info-ir2-convert info))))
1229       (substitute-leaf fun var))
1230     fun))
1231
1232 (defun %set-inline-expansion (name defined-fun inline-lambda)
1233   (cond (inline-lambda
1234          (setf (info :function :inline-expansion-designator name)
1235                inline-lambda)
1236          (when defined-fun
1237            (setf (defined-fun-inline-expansion defined-fun)
1238                  inline-lambda)))
1239         (t
1240          (clear-info :function :inline-expansion-designator name))))
1241
1242 ;;; the even-at-compile-time part of DEFUN
1243 ;;;
1244 ;;; The INLINE-LAMBDA is a LAMBDA-WITH-LEXENV, or NIL if there is no
1245 ;;; inline expansion.
1246 (defun %compiler-defun (name inline-lambda compile-toplevel)
1247   (let ((defined-fun nil)) ; will be set below if we're in the compiler
1248     (when compile-toplevel
1249       (with-single-package-locked-error
1250           (:symbol name "defining ~S as a function")
1251         (setf defined-fun
1252               (if inline-lambda
1253                   (get-defined-fun name (fifth inline-lambda))
1254                   (get-defined-fun name))))
1255       (when (boundp '*lexenv*)
1256         (remhash name *free-funs*)
1257         (aver (fasl-output-p *compile-object*))
1258         (if (member name *fun-names-in-this-file* :test #'equal)
1259             (warn 'duplicate-definition :name name)
1260             (push name *fun-names-in-this-file*)))
1261       (%set-inline-expansion name defined-fun inline-lambda))
1262
1263     (become-defined-fun-name name)
1264
1265     ;; old CMU CL comment:
1266     ;;   If there is a type from a previous definition, blast it,
1267     ;;   since it is obsolete.
1268     (when (and defined-fun (neq :declared (leaf-where-from defined-fun)))
1269       (setf (leaf-type defined-fun)
1270             ;; FIXME: If this is a block compilation thing, shouldn't
1271             ;; we be setting the type to the full derived type for the
1272             ;; definition, instead of this most general function type?
1273             (specifier-type 'function))))
1274
1275   (values))
1276
1277 \f
1278 ;;; Entry point utilities
1279
1280 ;;; Return a function for the Nth entry point.
1281 (defun optional-dispatch-entry-point-fun (dispatcher n)
1282   (declare (type optional-dispatch dispatcher)
1283            (type unsigned-byte n))
1284   (let* ((env (getf (optional-dispatch-plist dispatcher) :ir1-environment))
1285          (*lexenv* (first env))
1286          (*current-path* (second env)))
1287     (force (nth n (optional-dispatch-entry-points dispatcher)))))