0.pre7.117:
[sbcl.git] / src / compiler / ir1tran.lisp
1 ;;;; This file contains code which does the translation from Lisp code
2 ;;;; to the first intermediate representation (IR1).
3
4 ;;;; This software is part of the SBCL system. See the README file for
5 ;;;; more information.
6 ;;;;
7 ;;;; This software is derived from the CMU CL system, which was
8 ;;;; written at Carnegie Mellon University and released into the
9 ;;;; public domain. The software is in the public domain and is
10 ;;;; provided with absolutely no warranty. See the COPYING and CREDITS
11 ;;;; files for more information.
12
13 (in-package "SB!C")
14
15 (declaim (special *compiler-error-bailout*))
16
17 ;;; *SOURCE-PATHS* is a hashtable from source code forms to the path
18 ;;; taken through the source to reach the form. This provides a way to
19 ;;; keep track of the location of original source forms, even when
20 ;;; macroexpansions and other arbitary permutations of the code
21 ;;; happen. This table is initialized by calling FIND-SOURCE-PATHS on
22 ;;; the original source.
23 (declaim (hash-table *source-paths*))
24 (defvar *source-paths*)
25
26 ;;; *CURRENT-COMPONENT* is the COMPONENT structure which we link
27 ;;; blocks into as we generate them. This just serves to glue the
28 ;;; emitted blocks together until local call analysis and flow graph
29 ;;; canonicalization figure out what is really going on. We need to
30 ;;; keep track of all the blocks generated so that we can delete them
31 ;;; if they turn out to be unreachable.
32 ;;;
33 ;;; FIXME: It's confusing having one variable named *CURRENT-COMPONENT*
34 ;;; and another named *COMPONENT-BEING-COMPILED*. (In CMU CL they
35 ;;; were called *CURRENT-COMPONENT* and *COMPILE-COMPONENT* respectively,
36 ;;; which was also confusing.)
37 (declaim (type (or component null) *current-component*))
38 (defvar *current-component*)
39
40 ;;; *CURRENT-PATH* is the source path of the form we are currently
41 ;;; translating. See NODE-SOURCE-PATH in the NODE structure.
42 (declaim (list *current-path*))
43 (defvar *current-path*)
44
45 (defvar *derive-function-types* nil
46   "Should the compiler assume that function types will never change,
47   so that it can use type information inferred from current definitions
48   to optimize code which uses those definitions? Setting this true
49   gives non-ANSI, early-CMU-CL behavior. It can be useful for improving
50   the efficiency of stable code.")
51 \f
52 ;;;; namespace management utilities
53
54 ;;; Return a GLOBAL-VAR structure usable for referencing the global
55 ;;; function NAME.
56 (defun find-free-really-function (name)
57   (unless (info :function :kind name)
58     (setf (info :function :kind name) :function)
59     (setf (info :function :where-from name) :assumed))
60
61   (let ((where (info :function :where-from name)))
62     (when (and (eq where :assumed)
63                ;; In the ordinary target Lisp, it's silly to report
64                ;; undefinedness when the function is defined in the
65                ;; running Lisp. But at cross-compile time, the current
66                ;; definedness of a function is irrelevant to the
67                ;; definedness at runtime, which is what matters.
68                #-sb-xc-host (not (fboundp name)))
69       (note-undefined-reference name :function))
70     (make-global-var :kind :global-function
71                      :%source-name name
72                      :type (if (or *derive-function-types*
73                                    (eq where :declared))
74                                (info :function :type name)
75                                (specifier-type 'function))
76                      :where-from where)))
77
78 ;;; Return a SLOT-ACCESSOR structure usable for referencing the slot
79 ;;; accessor NAME. CLASS is the structure class.
80 (defun find-structure-slot-accessor (class name)
81   (declare (type sb!xc:class class))
82   (let* ((info (layout-info
83                 (or (info :type :compiler-layout (sb!xc:class-name class))
84                     (class-layout class))))
85          (accessor-name (if (listp name) (cadr name) name))
86          (slot (find accessor-name (dd-slots info)
87                      :key #'sb!kernel:dsd-accessor-name))
88          (type (dd-name info))
89          (slot-type (dsd-type slot)))
90     (unless slot
91       (error "can't find slot ~S" type))
92     (make-slot-accessor
93      :%source-name name
94      :type (specifier-type
95             (if (listp name)
96                 `(function (,slot-type ,type) ,slot-type)
97                 `(function (,type) ,slot-type)))
98      :for class
99      :slot slot)))
100
101 ;;; If NAME is already entered in *FREE-FUNCTIONS*, then return the
102 ;;; value. Otherwise, make a new GLOBAL-VAR using information from the
103 ;;; global environment and enter it in *FREE-FUNCTIONS*. If NAME names
104 ;;; a macro or special form, then we error out using the supplied
105 ;;; context which indicates what we were trying to do that demanded a
106 ;;; function.
107 (defun find-free-function (name context)
108   (declare (string context))
109   (declare (values global-var))
110   (or (gethash name *free-functions*)
111       (ecase (info :function :kind name)
112         ;; FIXME: The :MACRO and :SPECIAL-FORM cases could be merged.
113         (:macro
114          (compiler-error "The macro name ~S was found ~A." name context))
115         (:special-form
116          (compiler-error "The special form name ~S was found ~A."
117                          name
118                          context))
119         ((:function nil)
120          (check-fun-name name)
121          (note-if-setf-function-and-macro name)
122          (let ((expansion (fun-name-inline-expansion name))
123                (inlinep (info :function :inlinep name)))
124            (setf (gethash name *free-functions*)
125                  (if (or expansion inlinep)
126                      (make-defined-fun
127                       :%source-name name
128                       :inline-expansion expansion
129                       :inlinep inlinep
130                       :where-from (info :function :where-from name)
131                       :type (info :function :type name))
132                      (find-free-really-function name))))))))
133
134 ;;; Return the LEAF structure for the lexically apparent function
135 ;;; definition of NAME.
136 (declaim (ftype (function (t string) leaf) find-lexically-apparent-function))
137 (defun find-lexically-apparent-function (name context)
138   (let ((var (lexenv-find name functions :test #'equal)))
139     (cond (var
140            (unless (leaf-p var)
141              (aver (and (consp var) (eq (car var) 'macro)))
142              (compiler-error "found macro name ~S ~A" name context))
143            var)
144           (t
145            (find-free-function name context)))))
146
147 ;;; Return the LEAF node for a global variable reference to NAME. If
148 ;;; NAME is already entered in *FREE-VARIABLES*, then we just return
149 ;;; the corresponding value. Otherwise, we make a new leaf using
150 ;;; information from the global environment and enter it in
151 ;;; *FREE-VARIABLES*. If the variable is unknown, then we emit a
152 ;;; warning.
153 (defun find-free-variable (name)
154   (declare (values (or leaf heap-alien-info)))
155   (unless (symbolp name)
156     (compiler-error "Variable name is not a symbol: ~S." name))
157   (or (gethash name *free-variables*)
158       (let ((kind (info :variable :kind name))
159             (type (info :variable :type name))
160             (where-from (info :variable :where-from name)))
161         (when (and (eq where-from :assumed) (eq kind :global))
162           (note-undefined-reference name :variable))
163         (setf (gethash name *free-variables*)
164               (case kind
165                 (:alien
166                  (info :variable :alien-info name))
167                 (:constant
168                  (let ((value (info :variable :constant-value name)))
169                    (make-constant :value value
170                                   :%source-name name
171                                   :type (ctype-of value)
172                                   :where-from where-from)))
173                 (t
174                  (make-global-var :kind kind
175                                   :%source-name name
176                                   :type type
177                                   :where-from where-from)))))))
178 \f
179 ;;; Grovel over CONSTANT checking for any sub-parts that need to be
180 ;;; processed with MAKE-LOAD-FORM. We have to be careful, because
181 ;;; CONSTANT might be circular. We also check that the constant (and
182 ;;; any subparts) are dumpable at all.
183 (eval-when (:compile-toplevel :load-toplevel :execute)
184   ;; The EVAL-WHEN is necessary for #.(1+ LIST-TO-HASH-TABLE-THRESHOLD) 
185   ;; below. -- AL 20010227
186   (defconstant list-to-hash-table-threshold 32))
187 (defun maybe-emit-make-load-forms (constant)
188   (let ((things-processed nil)
189         (count 0))
190     ;; FIXME: Does this LIST-or-HASH-TABLE messiness give much benefit?
191     (declare (type (or list hash-table) things-processed)
192              (type (integer 0 #.(1+ list-to-hash-table-threshold)) count)
193              (inline member))
194     (labels ((grovel (value)
195                ;; Unless VALUE is an object which which obviously
196                ;; can't contain other objects
197                (unless (typep value
198                               '(or #-sb-xc-host unboxed-array
199                                    symbol
200                                    number
201                                    character
202                                    string))
203                  (etypecase things-processed
204                    (list
205                     (when (member value things-processed :test #'eq)
206                       (return-from grovel nil))
207                     (push value things-processed)
208                     (incf count)
209                     (when (> count list-to-hash-table-threshold)
210                       (let ((things things-processed))
211                         (setf things-processed
212                               (make-hash-table :test 'eq))
213                         (dolist (thing things)
214                           (setf (gethash thing things-processed) t)))))
215                    (hash-table
216                     (when (gethash value things-processed)
217                       (return-from grovel nil))
218                     (setf (gethash value things-processed) t)))
219                  (typecase value
220                    (cons
221                     (grovel (car value))
222                     (grovel (cdr value)))
223                    (simple-vector
224                     (dotimes (i (length value))
225                       (grovel (svref value i))))
226                    ((vector t)
227                     (dotimes (i (length value))
228                       (grovel (aref value i))))
229                    ((simple-array t)
230                     ;; Even though the (ARRAY T) branch does the exact
231                     ;; same thing as this branch we do this separately
232                     ;; so that the compiler can use faster versions of
233                     ;; array-total-size and row-major-aref.
234                     (dotimes (i (array-total-size value))
235                       (grovel (row-major-aref value i))))
236                    ((array t)
237                     (dotimes (i (array-total-size value))
238                       (grovel (row-major-aref value i))))
239                    (;; In the target SBCL, we can dump any instance,
240                     ;; but in the cross-compilation host,
241                     ;; %INSTANCE-FOO functions don't work on general
242                     ;; instances, only on STRUCTURE!OBJECTs.
243                     #+sb-xc-host structure!object
244                     #-sb-xc-host instance
245                     (when (emit-make-load-form value)
246                       (dotimes (i (%instance-length value))
247                         (grovel (%instance-ref value i)))))
248                    (t
249                     (compiler-error
250                      "Objects of type ~S can't be dumped into fasl files."
251                      (type-of value)))))))
252       (grovel constant)))
253   (values))
254 \f
255 ;;;; some flow-graph hacking utilities
256
257 ;;; This function sets up the back link between the node and the
258 ;;; continuation which continues at it.
259 (defun link-node-to-previous-continuation (node cont)
260   (declare (type node node) (type continuation cont))
261   (aver (not (continuation-next cont)))
262   (setf (continuation-next cont) node)
263   (setf (node-prev node) cont))
264
265 ;;; This function is used to set the continuation for a node, and thus
266 ;;; determine what receives the value and what is evaluated next. If
267 ;;; the continuation has no block, then we make it be in the block
268 ;;; that the node is in. If the continuation heads its block, we end
269 ;;; our block and link it to that block. If the continuation is not
270 ;;; currently used, then we set the DERIVED-TYPE for the continuation
271 ;;; to that of the node, so that a little type propagation gets done.
272 ;;;
273 ;;; We also deal with a bit of THE's semantics here: we weaken the
274 ;;; assertion on CONT to be no stronger than the assertion on CONT in
275 ;;; our scope. See the IR1-CONVERT method for THE.
276 #!-sb-fluid (declaim (inline use-continuation))
277 (defun use-continuation (node cont)
278   (declare (type node node) (type continuation cont))
279   (let ((node-block (continuation-block (node-prev node))))
280     (case (continuation-kind cont)
281       (:unused
282        (setf (continuation-block cont) node-block)
283        (setf (continuation-kind cont) :inside-block)
284        (setf (continuation-use cont) node)
285        (setf (node-cont node) cont))
286       (t
287        (%use-continuation node cont)))))
288 (defun %use-continuation (node cont)
289   (declare (type node node) (type continuation cont) (inline member))
290   (let ((block (continuation-block cont))
291         (node-block (continuation-block (node-prev node))))
292     (aver (eq (continuation-kind cont) :block-start))
293     (when (block-last node-block)
294       (error "~S has already ended." node-block))
295     (setf (block-last node-block) node)
296     (when (block-succ node-block)
297       (error "~S already has successors." node-block))
298     (setf (block-succ node-block) (list block))
299     (when (memq node-block (block-pred block))
300       (error "~S is already a predecessor of ~S." node-block block))
301     (push node-block (block-pred block))
302     (add-continuation-use node cont)
303     (unless (eq (continuation-asserted-type cont) *wild-type*)
304       (let ((new (values-type-union (continuation-asserted-type cont)
305                                     (or (lexenv-find cont type-restrictions)
306                                         *wild-type*))))
307         (when (type/= new (continuation-asserted-type cont))
308           (setf (continuation-asserted-type cont) new)
309           (reoptimize-continuation cont))))))
310 \f
311 ;;;; exported functions
312
313 ;;; This function takes a form and the top level form number for that
314 ;;; form, and returns a lambda representing the translation of that
315 ;;; form in the current global environment. The returned lambda is a
316 ;;; top level lambda that can be called to cause evaluation of the
317 ;;; forms. This lambda is in the initial component. If FOR-VALUE is T,
318 ;;; then the value of the form is returned from the function,
319 ;;; otherwise NIL is returned.
320 ;;;
321 ;;; This function may have arbitrary effects on the global environment
322 ;;; due to processing of EVAL-WHENs. All syntax error checking is
323 ;;; done, with erroneous forms being replaced by a proxy which signals
324 ;;; an error if it is evaluated. Warnings about possibly inconsistent
325 ;;; or illegal changes to the global environment will also be given.
326 ;;;
327 ;;; We make the initial component and convert the form in a PROGN (and
328 ;;; an optional NIL tacked on the end.) We then return the lambda. We
329 ;;; bind all of our state variables here, rather than relying on the
330 ;;; global value (if any) so that IR1 conversion will be reentrant.
331 ;;; This is necessary for EVAL-WHEN processing, etc.
332 ;;;
333 ;;; The hashtables used to hold global namespace info must be
334 ;;; reallocated elsewhere. Note also that *LEXENV* is not bound, so
335 ;;; that local macro definitions can be introduced by enclosing code.
336 (defun ir1-toplevel (form path for-value)
337   (declare (list path))
338   (let* ((*current-path* path)
339          (component (make-empty-component))
340          (*current-component* component))
341     (setf (component-name component) "initial component")
342     (setf (component-kind component) :initial)
343     (let* ((forms (if for-value `(,form) `(,form nil)))
344            (res (ir1-convert-lambda-body
345                  forms ()
346                  :debug-name (debug-namify "top level form ~S" form))))
347       (setf (functional-entry-fun res) res
348             (functional-arg-documentation res) ()
349             (functional-kind res) :toplevel)
350       res)))
351
352 ;;; *CURRENT-FORM-NUMBER* is used in FIND-SOURCE-PATHS to compute the
353 ;;; form number to associate with a source path. This should be bound
354 ;;; to an initial value of 0 before the processing of each truly
355 ;;; top level form.
356 (declaim (type index *current-form-number*))
357 (defvar *current-form-number*)
358
359 ;;; This function is called on freshly read forms to record the
360 ;;; initial location of each form (and subform.) Form is the form to
361 ;;; find the paths in, and TLF-NUM is the top level form number of the
362 ;;; truly top level form.
363 ;;;
364 ;;; This gets a bit interesting when the source code is circular. This
365 ;;; can (reasonably?) happen in the case of circular list constants.
366 (defun find-source-paths (form tlf-num)
367   (declare (type index tlf-num))
368   (let ((*current-form-number* 0))
369     (sub-find-source-paths form (list tlf-num)))
370   (values))
371 (defun sub-find-source-paths (form path)
372   (unless (gethash form *source-paths*)
373     (setf (gethash form *source-paths*)
374           (list* 'original-source-start *current-form-number* path))
375     (incf *current-form-number*)
376     (let ((pos 0)
377           (subform form)
378           (trail form))
379       (declare (fixnum pos))
380       (macrolet ((frob ()
381                    '(progn
382                       (when (atom subform) (return))
383                       (let ((fm (car subform)))
384                         (when (consp fm)
385                           (sub-find-source-paths fm (cons pos path)))
386                         (incf pos))
387                       (setq subform (cdr subform))
388                       (when (eq subform trail) (return)))))
389         (loop
390           (frob)
391           (frob)
392           (setq trail (cdr trail)))))))
393 \f
394 ;;;; IR1-CONVERT, macroexpansion and special form dispatching
395
396 (macrolet (;; Bind *COMPILER-ERROR-BAILOUT* to a function that throws
397            ;; out of the body and converts a proxy form instead.
398            (ir1-error-bailout ((start
399                                 cont
400                                 form
401                                 &optional
402                                 (proxy ``(error "execution of a form compiled with errors:~% ~S"
403                                                 ',,form)))
404                                &body body)
405                               (let ((skip (gensym "SKIP")))
406                                 `(block ,skip
407                                    (catch 'ir1-error-abort
408                                      (let ((*compiler-error-bailout*
409                                             (lambda ()
410                                               (throw 'ir1-error-abort nil))))
411                                        ,@body
412                                        (return-from ,skip nil)))
413                                    (ir1-convert ,start ,cont ,proxy)))))
414
415   ;; Translate FORM into IR1. The code is inserted as the NEXT of the
416   ;; continuation START. CONT is the continuation which receives the
417   ;; value of the FORM to be translated. The translators call this
418   ;; function recursively to translate their subnodes.
419   ;;
420   ;; As a special hack to make life easier in the compiler, a LEAF
421   ;; IR1-converts into a reference to that LEAF structure. This allows
422   ;; the creation using backquote of forms that contain leaf
423   ;; references, without having to introduce dummy names into the
424   ;; namespace.
425   (declaim (ftype (function (continuation continuation t) (values)) ir1-convert))
426   (defun ir1-convert (start cont form)
427     (ir1-error-bailout (start cont form)
428       (let ((*current-path* (or (gethash form *source-paths*)
429                                 (cons form *current-path*))))
430         (if (atom form)
431             (cond ((and (symbolp form) (not (keywordp form)))
432                    (ir1-convert-variable start cont form))
433                   ((leaf-p form)
434                    (reference-leaf start cont form))
435                   (t
436                    (reference-constant start cont form)))
437             (let ((opname (car form)))
438               (cond ((symbolp opname)
439                      (let ((lexical-def (lexenv-find opname functions)))
440                        (typecase lexical-def
441                          (null (ir1-convert-global-functoid start cont form))
442                          (functional
443                           (ir1-convert-local-combination start
444                                                          cont
445                                                          form
446                                                          lexical-def))
447                          (global-var
448                           (ir1-convert-srctran start cont lexical-def form))
449                          (t
450                           (aver (and (consp lexical-def)
451                                      (eq (car lexical-def) 'macro)))
452                           (ir1-convert start cont
453                                        (careful-expand-macro (cdr lexical-def)
454                                                              form))))))
455                     ((or (atom opname) (not (eq (car opname) 'lambda)))
456                      (compiler-error "illegal function call"))
457                     (t
458                      ;; implicitly #'(LAMBDA ..) because the LAMBDA
459                      ;; expression is the CAR of an executed form
460                      (ir1-convert-combination start
461                                               cont
462                                               form
463                                               (ir1-convert-lambda
464                                                opname
465                                                :debug-name (debug-namify
466                                                             "LAMBDA CAR ~S"
467                                                             opname)))))))))
468     (values))
469
470   ;; Generate a reference to a manifest constant, creating a new leaf
471   ;; if necessary. If we are producing a fasl file, make sure that
472   ;; MAKE-LOAD-FORM gets used on any parts of the constant that it
473   ;; needs to be.
474   (defun reference-constant (start cont value)
475     (declare (type continuation start cont)
476              (inline find-constant))
477     (ir1-error-bailout
478      (start cont value '(error "attempt to reference undumpable constant"))
479      (when (producing-fasl-file)
480        (maybe-emit-make-load-forms value))
481      (let* ((leaf (find-constant value))
482             (res (make-ref (leaf-type leaf) leaf)))
483        (push res (leaf-refs leaf))
484        (link-node-to-previous-continuation res start)
485        (use-continuation res cont)))
486     (values)))
487
488 ;;; Add FUN to the COMPONENT-REANALYZE-FUNS, unless it's some
489 ;;; trivial type for which reanalysis is a trivial no-op. FUN is returned.
490 (defun maybe-reanalyze-fun (fun)
491   (declare (type functional fun))
492
493   (aver-live-component *current-component*)
494   (when (lambda-p fun) ; when it's easy to ask FUN its COMPONENT
495     ;; general sanity check, specifically related to bug 138
496     (aver (eql (lambda-component fun) *current-component*)))
497
498   ;; I *think* this means "unless FUN is of some type for which
499   ;; reanalysis is a no-op". -- WHN 2001-01-06
500   (when (typep fun '(or optional-dispatch clambda))
501     (pushnew fun (component-reanalyze-funs *current-component*)))
502
503   fun)
504
505 ;;; Generate a REF node for LEAF, frobbing the LEAF structure as
506 ;;; needed. If LEAF represents a defined function which has already
507 ;;; been converted, and is not :NOTINLINE, then reference the
508 ;;; functional instead.
509 (defun reference-leaf (start cont leaf)
510   (declare (type continuation start cont) (type leaf leaf))
511   (let* ((leaf (or (and (defined-fun-p leaf)
512                         (not (eq (defined-fun-inlinep leaf)
513                                  :notinline))
514                         (let ((fun (defined-fun-functional leaf)))
515                           (when (and fun (not (functional-kind fun)))
516                             (maybe-reanalyze-fun fun))))
517                    leaf))
518          (res (make-ref (or (lexenv-find leaf type-restrictions)
519                             (leaf-type leaf))
520                         leaf)))
521     (push res (leaf-refs leaf))
522     (setf (leaf-ever-used leaf) t)
523     (link-node-to-previous-continuation res start)
524     (use-continuation res cont)))
525
526 ;;; Convert a reference to a symbolic constant or variable. If the
527 ;;; symbol is entered in the LEXENV-VARIABLES we use that definition,
528 ;;; otherwise we find the current global definition. This is also
529 ;;; where we pick off symbol macro and alien variable references.
530 (defun ir1-convert-variable (start cont name)
531   (declare (type continuation start cont) (symbol name))
532   (let ((var (or (lexenv-find name variables) (find-free-variable name))))
533     (etypecase var
534       (leaf
535        (when (lambda-var-p var)
536          (let ((home (continuation-home-lambda-or-null start)))
537            (when home
538              (pushnew var (lambda-calls-or-closes home))))
539          (when (lambda-var-ignorep var)
540            ;; (ANSI's specification for the IGNORE declaration requires
541            ;; that this be a STYLE-WARNING, not a full WARNING.)
542            (compiler-style-warning "reading an ignored variable: ~S" name)))
543        (reference-leaf start cont var))
544       (cons
545        (aver (eq (car var) 'MACRO))
546        (ir1-convert start cont (cdr var)))
547       (heap-alien-info
548        (ir1-convert start cont `(%heap-alien ',var)))))
549   (values))
550
551 ;;; Convert anything that looks like a special form, global function
552 ;;; or macro call.
553 (defun ir1-convert-global-functoid (start cont form)
554   (declare (type continuation start cont) (list form))
555   (let* ((fun (first form))
556          (translator (info :function :ir1-convert fun))
557          (cmacro (info :function :compiler-macro-function fun)))
558     (cond (translator (funcall translator start cont form))
559           ((and cmacro
560                 (not (eq (info :function :inlinep fun)
561                          :notinline)))
562            (let ((res (careful-expand-macro cmacro form)))
563              (if (eq res form)
564                  (ir1-convert-global-functoid-no-cmacro start cont form fun)
565                  (ir1-convert start cont res))))
566           (t
567            (ir1-convert-global-functoid-no-cmacro start cont form fun)))))
568
569 ;;; Handle the case of where the call was not a compiler macro, or was
570 ;;; a compiler macro and passed.
571 (defun ir1-convert-global-functoid-no-cmacro (start cont form fun)
572   (declare (type continuation start cont) (list form))
573   ;; FIXME: Couldn't all the INFO calls here be converted into
574   ;; standard CL functions, like MACRO-FUNCTION or something?
575   ;; And what happens with lexically-defined (MACROLET) macros
576   ;; here, anyway?
577   (ecase (info :function :kind fun)
578     (:macro
579      (ir1-convert start
580                   cont
581                   (careful-expand-macro (info :function :macro-function fun)
582                                         form)))
583     ((nil :function)
584      (ir1-convert-srctran start
585                           cont
586                           (find-free-function fun
587                                               "shouldn't happen! (no-cmacro)")
588                           form))))
589
590 (defun muffle-warning-or-die ()
591   (muffle-warning)
592   (error "internal error -- no MUFFLE-WARNING restart"))
593
594 ;;; Expand FORM using the macro whose MACRO-FUNCTION is FUN, trapping
595 ;;; errors which occur during the macroexpansion.
596 (defun careful-expand-macro (fun form)
597   (let (;; a hint I (WHN) wish I'd known earlier
598         (hint "(hint: For more precise location, try *BREAK-ON-SIGNALS*.)"))
599     (flet (;; Return a string to use as a prefix in error reporting,
600            ;; telling something about which form caused the problem.
601            (wherestring ()
602              (let ((*print-pretty* nil)
603                    ;; We rely on the printer to abbreviate FORM. 
604                    (*print-length* 3)
605                    (*print-level* 1))
606                (format
607                 nil
608                 #-sb-xc-host "(in macroexpansion of ~S)"
609                 ;; longer message to avoid ambiguity "Was it the xc host
610                 ;; or the cross-compiler which encountered the problem?"
611                 #+sb-xc-host "(in cross-compiler macroexpansion of ~S)"
612                 form))))
613       (handler-bind (;; When cross-compiling, we can get style warnings
614                      ;; about e.g. undefined functions. An unhandled
615                      ;; CL:STYLE-WARNING (as opposed to a
616                      ;; SB!C::COMPILER-NOTE) would cause FAILURE-P to be
617                      ;; set on the return from #'SB!XC:COMPILE-FILE, which
618                      ;; would falsely indicate an error sufficiently
619                      ;; serious that we should stop the build process. To
620                      ;; avoid this, we translate CL:STYLE-WARNING
621                      ;; conditions from the host Common Lisp into
622                      ;; cross-compiler SB!C::COMPILER-NOTE calls. (It
623                      ;; might be cleaner to just make Python use
624                      ;; CL:STYLE-WARNING internally, so that the
625                      ;; significance of any host Common Lisp
626                      ;; CL:STYLE-WARNINGs is understood automatically. But
627                      ;; for now I'm not motivated to do this. -- WHN
628                      ;; 19990412)
629                      (style-warning (lambda (c)
630                                       (compiler-note "~@<~A~:@_~A~:@_~A~:>"
631                                                      (wherestring) hint c)
632                                       (muffle-warning-or-die)))
633                      ;; KLUDGE: CMU CL in its wisdom (version 2.4.6 for
634                      ;; Debian Linux, anyway) raises a CL:WARNING
635                      ;; condition (not a CL:STYLE-WARNING) for undefined
636                      ;; symbols when converting interpreted functions,
637                      ;; causing COMPILE-FILE to think the file has a real
638                      ;; problem, causing COMPILE-FILE to return FAILURE-P
639                      ;; set (not just WARNINGS-P set). Since undefined
640                      ;; symbol warnings are often harmless forward
641                      ;; references, and since it'd be inordinately painful
642                      ;; to try to eliminate all such forward references,
643                      ;; these warnings are basically unavoidable. Thus, we
644                      ;; need to coerce the system to work through them,
645                      ;; and this code does so, by crudely suppressing all
646                      ;; warnings in cross-compilation macroexpansion. --
647                      ;; WHN 19990412
648                      #+cmu
649                      (warning (lambda (c)
650                                 (compiler-note
651                                  "~@<~A~:@_~
652                                   ~A~:@_~
653                                   ~@<(KLUDGE: That was a non-STYLE WARNING. ~
654                                   Ordinarily that would cause compilation to ~
655                                   fail. However, since we're running under ~
656                                   CMU CL, and since CMU CL emits non-STYLE ~
657                                   warnings for safe, hard-to-fix things (e.g. ~
658                                   references to not-yet-defined functions) ~
659                                   we're going to have to ignore it and ~
660                                   proceed anyway. Hopefully we're not ~
661                                   ignoring anything  horrible here..)~:@>~:>"
662                                  (wherestring)
663                                  c)
664                                 (muffle-warning-or-die)))
665                      (error (lambda (c)
666                               (compiler-error "~@<~A~:@_~A~@:_~A~:>"
667                                               (wherestring) hint c))))
668         (funcall sb!xc:*macroexpand-hook* fun form *lexenv*)))))
669 \f
670 ;;;; conversion utilities
671
672 ;;; Convert a bunch of forms, discarding all the values except the
673 ;;; last. If there aren't any forms, then translate a NIL.
674 (declaim (ftype (function (continuation continuation list) (values))
675                 ir1-convert-progn-body))
676 (defun ir1-convert-progn-body (start cont body)
677   (if (endp body)
678       (reference-constant start cont nil)
679       (let ((this-start start)
680             (forms body))
681         (loop
682           (let ((form (car forms)))
683             (when (endp (cdr forms))
684               (ir1-convert this-start cont form)
685               (return))
686             (let ((this-cont (make-continuation)))
687               (ir1-convert this-start this-cont form)
688               (setq this-start this-cont
689                     forms (cdr forms)))))))
690   (values))
691 \f
692 ;;;; converting combinations
693
694 ;;; Convert a function call where the function (i.e. the FUN argument)
695 ;;; is a LEAF. We return the COMBINATION node so that the caller can
696 ;;; poke at it if it wants to.
697 (declaim (ftype (function (continuation continuation list leaf) combination)
698                 ir1-convert-combination))
699 (defun ir1-convert-combination (start cont form fun)
700   (let ((fun-cont (make-continuation)))
701     (reference-leaf start fun-cont fun)
702     (ir1-convert-combination-args fun-cont cont (cdr form))))
703
704 ;;; Convert the arguments to a call and make the COMBINATION node.
705 ;;; FUN-CONT is the continuation which yields the function to call.
706 ;;; FORM is the source for the call. ARGS is the list of arguments for
707 ;;; the call, which defaults to the cdr of source. We return the
708 ;;; COMBINATION node.
709 (defun ir1-convert-combination-args (fun-cont cont args)
710   (declare (type continuation fun-cont cont) (list args))
711   (let ((node (make-combination fun-cont)))
712     (setf (continuation-dest fun-cont) node)
713     (assert-continuation-type fun-cont
714                               (specifier-type '(or function symbol)))
715     (collect ((arg-conts))
716       (let ((this-start fun-cont))
717         (dolist (arg args)
718           (let ((this-cont (make-continuation node)))
719             (ir1-convert this-start this-cont arg)
720             (setq this-start this-cont)
721             (arg-conts this-cont)))
722         (link-node-to-previous-continuation node this-start)
723         (use-continuation node cont)
724         (setf (combination-args node) (arg-conts))))
725     node))
726
727 ;;; Convert a call to a global function. If not :NOTINLINE, then we do
728 ;;; source transforms and try out any inline expansion. If there is no
729 ;;; expansion, but is :INLINE, then give an efficiency note (unless a
730 ;;; known function which will quite possibly be open-coded.) Next, we
731 ;;; go to ok-combination conversion.
732 (defun ir1-convert-srctran (start cont var form)
733   (declare (type continuation start cont) (type global-var var))
734   (let ((inlinep (when (defined-fun-p var)
735                    (defined-fun-inlinep var))))
736     (if (eq inlinep :notinline)
737         (ir1-convert-combination start cont form var)
738         (let ((transform (info :function
739                                :source-transform
740                                (leaf-source-name var))))
741           (if transform
742               (multiple-value-bind (result pass) (funcall transform form)
743                 (if pass
744                     (ir1-convert-maybe-predicate start cont form var)
745                     (ir1-convert start cont result)))
746               (ir1-convert-maybe-predicate start cont form var))))))
747
748 ;;; If the function has the PREDICATE attribute, and the CONT's DEST
749 ;;; isn't an IF, then we convert (IF <form> T NIL), ensuring that a
750 ;;; predicate always appears in a conditional context.
751 ;;;
752 ;;; If the function isn't a predicate, then we call
753 ;;; IR1-CONVERT-COMBINATION-CHECKING-TYPE.
754 (defun ir1-convert-maybe-predicate (start cont form var)
755   (declare (type continuation start cont) (list form) (type global-var var))
756   (let ((info (info :function :info (leaf-source-name var))))
757     (if (and info
758              (ir1-attributep (function-info-attributes info) predicate)
759              (not (if-p (continuation-dest cont))))
760         (ir1-convert start cont `(if ,form t nil))
761         (ir1-convert-combination-checking-type start cont form var))))
762
763 ;;; Actually really convert a global function call that we are allowed
764 ;;; to early-bind.
765 ;;;
766 ;;; If we know the function type of the function, then we check the
767 ;;; call for syntactic legality with respect to the declared function
768 ;;; type. If it is impossible to determine whether the call is correct
769 ;;; due to non-constant keywords, then we give up, marking the call as
770 ;;; :FULL to inhibit further error messages. We return true when the
771 ;;; call is legal.
772 ;;;
773 ;;; If the call is legal, we also propagate type assertions from the
774 ;;; function type to the arg and result continuations. We do this now
775 ;;; so that IR1 optimize doesn't have to redundantly do the check
776 ;;; later so that it can do the type propagation.
777 (defun ir1-convert-combination-checking-type (start cont form var)
778   (declare (type continuation start cont) (list form) (type leaf var))
779   (let* ((node (ir1-convert-combination start cont form var))
780          (fun-cont (basic-combination-fun node))
781          (type (leaf-type var)))
782     (when (validate-call-type node type t)
783       (setf (continuation-%derived-type fun-cont) type)
784       (setf (continuation-reoptimize fun-cont) nil)
785       (setf (continuation-%type-check fun-cont) nil)))
786   (values))
787
788 ;;; Convert a call to a local function. If the function has already
789 ;;; been LET converted, then throw FUN to LOCAL-CALL-LOSSAGE. This
790 ;;; should only happen when we are converting inline expansions for
791 ;;; local functions during optimization.
792 (defun ir1-convert-local-combination (start cont form fun)
793   (if (functional-kind fun)
794       (throw 'local-call-lossage fun)
795       (ir1-convert-combination start cont form
796                                (maybe-reanalyze-fun fun))))
797 \f
798 ;;;; PROCESS-DECLS
799
800 ;;; Given a list of LAMBDA-VARs and a variable name, return the
801 ;;; LAMBDA-VAR for that name, or NIL if it isn't found. We return the
802 ;;; *last* variable with that name, since LET* bindings may be
803 ;;; duplicated, and declarations always apply to the last.
804 (declaim (ftype (function (list symbol) (or lambda-var list))
805                 find-in-bindings))
806 (defun find-in-bindings (vars name)
807   (let ((found nil))
808     (dolist (var vars)
809       (cond ((leaf-p var)
810              (when (eq (leaf-source-name var) name)
811                (setq found var))
812              (let ((info (lambda-var-arg-info var)))
813                (when info
814                  (let ((supplied-p (arg-info-supplied-p info)))
815                    (when (and supplied-p
816                               (eq (leaf-source-name supplied-p) name))
817                      (setq found supplied-p))))))
818             ((and (consp var) (eq (car var) name))
819              (setf found (cdr var)))))
820     found))
821
822 ;;; Called by Process-Decls to deal with a variable type declaration.
823 ;;; If a lambda-var being bound, we intersect the type with the vars
824 ;;; type, otherwise we add a type-restriction on the var. If a symbol
825 ;;; macro, we just wrap a THE around the expansion.
826 (defun process-type-decl (decl res vars)
827   (declare (list decl vars) (type lexenv res))
828   (let ((type (specifier-type (first decl))))
829     (collect ((restr nil cons)
830               (new-vars nil cons))
831       (dolist (var-name (rest decl))
832         (let* ((bound-var (find-in-bindings vars var-name))
833                (var (or bound-var
834                         (lexenv-find var-name variables)
835                         (find-free-variable var-name))))
836           (etypecase var
837             (leaf
838              (let* ((old-type (or (lexenv-find var type-restrictions)
839                                   (leaf-type var)))
840                     (int (if (or (fun-type-p type)
841                                  (fun-type-p old-type))
842                              type
843                              (type-approx-intersection2 old-type type))))
844                (cond ((eq int *empty-type*)
845                       (unless (policy *lexenv* (= inhibit-warnings 3))
846                         (compiler-warning
847                          "The type declarations ~S and ~S for ~S conflict."
848                          (type-specifier old-type) (type-specifier type)
849                          var-name)))
850                      (bound-var (setf (leaf-type bound-var) int))
851                      (t
852                       (restr (cons var int))))))
853             (cons
854              ;; FIXME: non-ANSI weirdness
855              (aver (eq (car var) 'MACRO))
856              (new-vars `(,var-name . (MACRO . (the ,(first decl)
857                                                    ,(cdr var))))))
858             (heap-alien-info
859              (compiler-error
860               "~S is an alien variable, so its type can't be declared."
861               var-name)))))
862
863       (if (or (restr) (new-vars))
864           (make-lexenv :default res
865                        :type-restrictions (restr)
866                        :variables (new-vars))
867           res))))
868
869 ;;; This is somewhat similar to PROCESS-TYPE-DECL, but handles
870 ;;; declarations for function variables. In addition to allowing
871 ;;; declarations for functions being bound, we must also deal with
872 ;;; declarations that constrain the type of lexically apparent
873 ;;; functions.
874 (defun process-ftype-decl (spec res names fvars)
875   (declare (list spec names fvars) (type lexenv res))
876   (let ((type (specifier-type spec)))
877     (collect ((res nil cons))
878       (dolist (name names)
879         (let ((found (find name fvars
880                            :key #'leaf-source-name
881                            :test #'equal)))
882           (cond
883            (found
884             (setf (leaf-type found) type)
885             (assert-definition-type found type
886                                     :warning-function #'compiler-note
887                                     :where "FTYPE declaration"))
888            (t
889             (res (cons (find-lexically-apparent-function
890                         name "in a function type declaration")
891                        type))))))
892       (if (res)
893           (make-lexenv :default res :type-restrictions (res))
894           res))))
895
896 ;;; Process a special declaration, returning a new LEXENV. A non-bound
897 ;;; special declaration is instantiated by throwing a special variable
898 ;;; into the variables.
899 (defun process-special-decl (spec res vars)
900   (declare (list spec vars) (type lexenv res))
901   (collect ((new-venv nil cons))
902     (dolist (name (cdr spec))
903       (let ((var (find-in-bindings vars name)))
904         (etypecase var
905           (cons
906            (aver (eq (car var) 'MACRO))
907            (compiler-error
908             "~S is a symbol-macro and thus can't be declared special."
909             name))
910           (lambda-var
911            (when (lambda-var-ignorep var)
912              ;; ANSI's definition for "Declaration IGNORE, IGNORABLE"
913              ;; requires that this be a STYLE-WARNING, not a full WARNING.
914              (compiler-style-warning
915               "The ignored variable ~S is being declared special."
916               name))
917            (setf (lambda-var-specvar var)
918                  (specvar-for-binding name)))
919           (null
920            (unless (assoc name (new-venv) :test #'eq)
921              (new-venv (cons name (specvar-for-binding name))))))))
922     (if (new-venv)
923         (make-lexenv :default res :variables (new-venv))
924         res)))
925
926 ;;; Return a DEFINED-FUN which copies a GLOBAL-VAR but for its INLINEP.
927 (defun make-new-inlinep (var inlinep)
928   (declare (type global-var var) (type inlinep inlinep))
929   (let ((res (make-defined-fun
930               :%source-name (leaf-source-name var)
931               :where-from (leaf-where-from var)
932               :type (leaf-type var)
933               :inlinep inlinep)))
934     (when (defined-fun-p var)
935       (setf (defined-fun-inline-expansion res)
936             (defined-fun-inline-expansion var))
937       (setf (defined-fun-functional res)
938             (defined-fun-functional var)))
939     res))
940
941 ;;; Parse an inline/notinline declaration. If it's a local function we're
942 ;;; defining, set its INLINEP. If a global function, add a new FENV entry.
943 (defun process-inline-decl (spec res fvars)
944   (let ((sense (cdr (assoc (first spec) *inlinep-translations* :test #'eq)))
945         (new-fenv ()))
946     (dolist (name (rest spec))
947       (let ((fvar (find name fvars
948                         :key #'leaf-source-name
949                         :test #'equal)))
950         (if fvar
951             (setf (functional-inlinep fvar) sense)
952             (let ((found
953                    (find-lexically-apparent-function
954                     name "in an inline or notinline declaration")))
955               (etypecase found
956                 (functional
957                  (when (policy *lexenv* (>= speed inhibit-warnings))
958                    (compiler-note "ignoring ~A declaration not at ~
959                                    definition of local function:~%  ~S"
960                                   sense name)))
961                 (global-var
962                  (push (cons name (make-new-inlinep found sense))
963                        new-fenv)))))))
964
965     (if new-fenv
966         (make-lexenv :default res :functions new-fenv)
967         res)))
968
969 ;;; Like FIND-IN-BINDINGS, but looks for #'foo in the fvars.
970 (defun find-in-bindings-or-fbindings (name vars fvars)
971   (declare (list vars fvars))
972   (if (consp name)
973       (destructuring-bind (wot fn-name) name
974         (unless (eq wot 'function)
975           (compiler-error "The function or variable name ~S is unrecognizable."
976                           name))
977         (find fn-name fvars :key #'leaf-source-name :test #'equal))
978       (find-in-bindings vars name)))
979
980 ;;; Process an ignore/ignorable declaration, checking for various losing
981 ;;; conditions.
982 (defun process-ignore-decl (spec vars fvars)
983   (declare (list spec vars fvars))
984   (dolist (name (rest spec))
985     (let ((var (find-in-bindings-or-fbindings name vars fvars)))
986       (cond
987        ((not var)
988         ;; ANSI's definition for "Declaration IGNORE, IGNORABLE"
989         ;; requires that this be a STYLE-WARNING, not a full WARNING.
990         (compiler-style-warning "declaring unknown variable ~S to be ignored"
991                                 name))
992        ;; FIXME: This special case looks like non-ANSI weirdness.
993        ((and (consp var) (consp (cdr var)) (eq (cadr var) 'macro))
994         ;; Just ignore the IGNORE decl.
995         )
996        ((functional-p var)
997         (setf (leaf-ever-used var) t))
998        ((lambda-var-specvar var)
999         ;; ANSI's definition for "Declaration IGNORE, IGNORABLE"
1000         ;; requires that this be a STYLE-WARNING, not a full WARNING.
1001         (compiler-style-warning "declaring special variable ~S to be ignored"
1002                                 name))
1003        ((eq (first spec) 'ignorable)
1004         (setf (leaf-ever-used var) t))
1005        (t
1006         (setf (lambda-var-ignorep var) t)))))
1007   (values))
1008
1009 ;;; FIXME: This is non-ANSI, so the default should be T, or it should
1010 ;;; go away, I think.
1011 (defvar *suppress-values-declaration* nil
1012   #!+sb-doc
1013   "If true, processing of the VALUES declaration is inhibited.")
1014
1015 ;;; Process a single declaration spec, augmenting the specified LEXENV
1016 ;;; RES and returning it as a result. VARS and FVARS are as described in
1017 ;;; PROCESS-DECLS.
1018 (defun process-1-decl (raw-spec res vars fvars cont)
1019   (declare (type list raw-spec vars fvars))
1020   (declare (type lexenv res))
1021   (declare (type continuation cont))
1022   (let ((spec (canonized-decl-spec raw-spec)))
1023     (case (first spec)
1024       (special (process-special-decl spec res vars))
1025       (ftype
1026        (unless (cdr spec)
1027          (compiler-error "No type specified in FTYPE declaration: ~S" spec))
1028        (process-ftype-decl (second spec) res (cddr spec) fvars))
1029       ((inline notinline maybe-inline)
1030        (process-inline-decl spec res fvars))
1031       ((ignore ignorable)
1032        (process-ignore-decl spec vars fvars)
1033        res)
1034       (optimize
1035        (make-lexenv
1036         :default res
1037         :policy (process-optimize-decl spec (lexenv-policy res))))
1038       (type
1039        (process-type-decl (cdr spec) res vars))
1040       (values
1041        (if *suppress-values-declaration*
1042            res
1043            (let ((types (cdr spec)))
1044              (do-the-stuff (if (eql (length types) 1)
1045                                (car types)
1046                                `(values ,@types))
1047                            cont res 'values))))
1048       (dynamic-extent
1049        (when (policy *lexenv* (> speed inhibit-warnings))
1050          (compiler-note
1051           "compiler limitation:~
1052            ~%  There's no special support for DYNAMIC-EXTENT (so it's ignored)."))
1053        res)
1054       (t
1055        (unless (info :declaration :recognized (first spec))
1056          (compiler-warning "unrecognized declaration ~S" raw-spec))
1057        res))))
1058
1059 ;;; Use a list of DECLARE forms to annotate the lists of LAMBDA-VAR
1060 ;;; and FUNCTIONAL structures which are being bound. In addition to
1061 ;;; filling in slots in the leaf structures, we return a new LEXENV
1062 ;;; which reflects pervasive special and function type declarations,
1063 ;;; (NOT)INLINE declarations and OPTIMIZE declarations. CONT is the
1064 ;;; continuation affected by VALUES declarations.
1065 ;;;
1066 ;;; This is also called in main.lisp when PROCESS-FORM handles a use
1067 ;;; of LOCALLY.
1068 (defun process-decls (decls vars fvars cont &optional (env *lexenv*))
1069   (declare (list decls vars fvars) (type continuation cont))
1070   (dolist (decl decls)
1071     (dolist (spec (rest decl))
1072       (unless (consp spec)
1073         (compiler-error "malformed declaration specifier ~S in ~S"
1074                         spec
1075                         decl))
1076       (setq env (process-1-decl spec env vars fvars cont))))
1077   env)
1078
1079 ;;; Return the SPECVAR for NAME to use when we see a local SPECIAL
1080 ;;; declaration. If there is a global variable of that name, then
1081 ;;; check that it isn't a constant and return it. Otherwise, create an
1082 ;;; anonymous GLOBAL-VAR.
1083 (defun specvar-for-binding (name)
1084   (cond ((not (eq (info :variable :where-from name) :assumed))
1085          (let ((found (find-free-variable name)))
1086            (when (heap-alien-info-p found)
1087              (compiler-error
1088               "~S is an alien variable and so can't be declared special."
1089               name))
1090            (unless (global-var-p found)
1091              (compiler-error
1092               "~S is a constant and so can't be declared special."
1093               name))
1094            found))
1095         (t
1096          (make-global-var :kind :special
1097                           :%source-name name
1098                           :where-from :declared))))
1099 \f
1100 ;;;; LAMBDA hackery
1101
1102 ;;;; Note: Take a look at the compiler-overview.tex section on "Hairy
1103 ;;;; function representation" before you seriously mess with this
1104 ;;;; stuff.
1105
1106 ;;; Verify that a thing is a legal name for a variable and return a
1107 ;;; Var structure for it, filling in info if it is globally special.
1108 ;;; If it is losing, we punt with a Compiler-Error. Names-So-Far is an
1109 ;;; alist of names which have previously been bound. If the name is in
1110 ;;; this list, then we error out.
1111 (declaim (ftype (function (t list) lambda-var) varify-lambda-arg))
1112 (defun varify-lambda-arg (name names-so-far)
1113   (declare (inline member))
1114   (unless (symbolp name)
1115     (compiler-error "The lambda-variable ~S is not a symbol." name))
1116   (when (member name names-so-far :test #'eq)
1117     (compiler-error "The variable ~S occurs more than once in the lambda-list."
1118                     name))
1119   (let ((kind (info :variable :kind name)))
1120     (when (or (keywordp name) (eq kind :constant))
1121       (compiler-error "The name of the lambda-variable ~S is a constant."
1122                       name))
1123     (cond ((eq kind :special)
1124            (let ((specvar (find-free-variable name)))
1125              (make-lambda-var :%source-name name
1126                               :type (leaf-type specvar)
1127                               :where-from (leaf-where-from specvar)
1128                               :specvar specvar)))
1129           (t
1130            (note-lexical-binding name)
1131            (make-lambda-var :%source-name name)))))
1132
1133 ;;; Make the default keyword for a &KEY arg, checking that the keyword
1134 ;;; isn't already used by one of the VARS. We also check that the
1135 ;;; keyword isn't the magical :ALLOW-OTHER-KEYS.
1136 (declaim (ftype (function (symbol list t) keyword) make-keyword-for-arg))
1137 (defun make-keyword-for-arg (symbol vars keywordify)
1138   (let ((key (if (and keywordify (not (keywordp symbol)))
1139                  (keywordicate symbol)
1140                  symbol)))
1141     (when (eq key :allow-other-keys)
1142       (compiler-error "No &KEY arg can be called :ALLOW-OTHER-KEYS."))
1143     (dolist (var vars)
1144       (let ((info (lambda-var-arg-info var)))
1145         (when (and info
1146                    (eq (arg-info-kind info) :keyword)
1147                    (eq (arg-info-key info) key))
1148           (compiler-error
1149            "The keyword ~S appears more than once in the lambda-list."
1150            key))))
1151     key))
1152
1153 ;;; Parse a lambda list into a list of VAR structures, stripping off
1154 ;;; any &AUX bindings. Each arg name is checked for legality, and
1155 ;;; duplicate names are checked for. If an arg is globally special,
1156 ;;; the var is marked as :SPECIAL instead of :LEXICAL. &KEY,
1157 ;;; &OPTIONAL and &REST args are annotated with an ARG-INFO structure
1158 ;;; which contains the extra information. If we hit something losing,
1159 ;;; we bug out with COMPILER-ERROR. These values are returned:
1160 ;;;  1. a list of the var structures for each top level argument;
1161 ;;;  2. a flag indicating whether &KEY was specified;
1162 ;;;  3. a flag indicating whether other &KEY args are allowed;
1163 ;;;  4. a list of the &AUX variables; and
1164 ;;;  5. a list of the &AUX values.
1165 (declaim (ftype (function (list) (values list boolean boolean list list))
1166                 make-lambda-vars))
1167 (defun make-lambda-vars (list)
1168   (multiple-value-bind (required optional restp rest keyp keys allowp aux
1169                         morep more-context more-count)
1170       (parse-lambda-list list)
1171     (collect ((vars)
1172               (names-so-far)
1173               (aux-vars)
1174               (aux-vals))
1175       (flet (;; PARSE-DEFAULT deals with defaults and supplied-p args
1176              ;; for optionals and keywords args.
1177              (parse-default (spec info)
1178                (when (consp (cdr spec))
1179                  (setf (arg-info-default info) (second spec))
1180                  (when (consp (cddr spec))
1181                    (let* ((supplied-p (third spec))
1182                           (supplied-var (varify-lambda-arg supplied-p
1183                                                            (names-so-far))))
1184                      (setf (arg-info-supplied-p info) supplied-var)
1185                      (names-so-far supplied-p)
1186                      (when (> (length (the list spec)) 3)
1187                        (compiler-error
1188                         "The list ~S is too long to be an arg specifier."
1189                         spec)))))))
1190         
1191         (dolist (name required)
1192           (let ((var (varify-lambda-arg name (names-so-far))))
1193             (vars var)
1194             (names-so-far name)))
1195         
1196         (dolist (spec optional)
1197           (if (atom spec)
1198               (let ((var (varify-lambda-arg spec (names-so-far))))
1199                 (setf (lambda-var-arg-info var) (make-arg-info :kind :optional))
1200                 (vars var)
1201                 (names-so-far spec))
1202               (let* ((name (first spec))
1203                      (var (varify-lambda-arg name (names-so-far)))
1204                      (info (make-arg-info :kind :optional)))
1205                 (setf (lambda-var-arg-info var) info)
1206                 (vars var)
1207                 (names-so-far name)
1208                 (parse-default spec info))))
1209         
1210         (when restp
1211           (let ((var (varify-lambda-arg rest (names-so-far))))
1212             (setf (lambda-var-arg-info var) (make-arg-info :kind :rest))
1213             (vars var)
1214             (names-so-far rest)))
1215
1216         (when morep
1217           (let ((var (varify-lambda-arg more-context (names-so-far))))
1218             (setf (lambda-var-arg-info var)
1219                   (make-arg-info :kind :more-context))
1220             (vars var)
1221             (names-so-far more-context))
1222           (let ((var (varify-lambda-arg more-count (names-so-far))))
1223             (setf (lambda-var-arg-info var)
1224                   (make-arg-info :kind :more-count))
1225             (vars var)
1226             (names-so-far more-count)))
1227         
1228         (dolist (spec keys)
1229           (cond
1230            ((atom spec)
1231             (let ((var (varify-lambda-arg spec (names-so-far))))
1232               (setf (lambda-var-arg-info var)
1233                     (make-arg-info :kind :keyword
1234                                    :key (make-keyword-for-arg spec
1235                                                               (vars)
1236                                                               t)))
1237               (vars var)
1238               (names-so-far spec)))
1239            ((atom (first spec))
1240             (let* ((name (first spec))
1241                    (var (varify-lambda-arg name (names-so-far)))
1242                    (info (make-arg-info
1243                           :kind :keyword
1244                           :key (make-keyword-for-arg name (vars) t))))
1245               (setf (lambda-var-arg-info var) info)
1246               (vars var)
1247               (names-so-far name)
1248               (parse-default spec info)))
1249            (t
1250             (let ((head (first spec)))
1251               (unless (proper-list-of-length-p head 2)
1252                 (error "malformed &KEY argument specifier: ~S" spec))
1253               (let* ((name (second head))
1254                      (var (varify-lambda-arg name (names-so-far)))
1255                      (info (make-arg-info
1256                             :kind :keyword
1257                             :key (make-keyword-for-arg (first head)
1258                                                        (vars)
1259                                                        nil))))
1260                 (setf (lambda-var-arg-info var) info)
1261                 (vars var)
1262                 (names-so-far name)
1263                 (parse-default spec info))))))
1264         
1265         (dolist (spec aux)
1266           (cond ((atom spec)
1267                  (let ((var (varify-lambda-arg spec nil)))
1268                    (aux-vars var)
1269                    (aux-vals nil)
1270                    (names-so-far spec)))
1271                 (t
1272                  (unless (proper-list-of-length-p spec 1 2)
1273                    (compiler-error "malformed &AUX binding specifier: ~S"
1274                                    spec))
1275                  (let* ((name (first spec))
1276                         (var (varify-lambda-arg name nil)))
1277                    (aux-vars var)
1278                    (aux-vals (second spec))
1279                    (names-so-far name)))))
1280
1281         (values (vars) keyp allowp (aux-vars) (aux-vals))))))
1282
1283 ;;; This is similar to IR1-CONVERT-PROGN-BODY except that we
1284 ;;; sequentially bind each AUX-VAR to the corresponding AUX-VAL before
1285 ;;; converting the body. If there are no bindings, just convert the
1286 ;;; body, otherwise do one binding and recurse on the rest.
1287 ;;;
1288 ;;; FIXME: This could and probably should be converted to use
1289 ;;; SOURCE-NAME and DEBUG-NAME. But I (WHN) don't use &AUX bindings,
1290 ;;; so I'm not motivated. Patches will be accepted...
1291 (defun ir1-convert-aux-bindings (start cont body aux-vars aux-vals)
1292   (declare (type continuation start cont) (list body aux-vars aux-vals))
1293   (if (null aux-vars)
1294       (ir1-convert-progn-body start cont body)
1295       (let ((fun-cont (make-continuation))
1296             (fun (ir1-convert-lambda-body body
1297                                           (list (first aux-vars))
1298                                           :aux-vars (rest aux-vars)
1299                                           :aux-vals (rest aux-vals)
1300                                           :debug-name (debug-namify
1301                                                        "&AUX bindings ~S"
1302                                                        aux-vars))))
1303         (reference-leaf start fun-cont fun)
1304         (ir1-convert-combination-args fun-cont cont
1305                                       (list (first aux-vals)))))
1306   (values))
1307
1308 ;;; This is similar to IR1-CONVERT-PROGN-BODY except that code to bind
1309 ;;; the SPECVAR for each SVAR to the value of the variable is wrapped
1310 ;;; around the body. If there are no special bindings, we just convert
1311 ;;; the body, otherwise we do one special binding and recurse on the
1312 ;;; rest.
1313 ;;;
1314 ;;; We make a cleanup and introduce it into the lexical environment.
1315 ;;; If there are multiple special bindings, the cleanup for the blocks
1316 ;;; will end up being the innermost one. We force CONT to start a
1317 ;;; block outside of this cleanup, causing cleanup code to be emitted
1318 ;;; when the scope is exited.
1319 (defun ir1-convert-special-bindings (start cont body aux-vars aux-vals svars)
1320   (declare (type continuation start cont)
1321            (list body aux-vars aux-vals svars))
1322   (cond
1323    ((null svars)
1324     (ir1-convert-aux-bindings start cont body aux-vars aux-vals))
1325    (t
1326     (continuation-starts-block cont)
1327     (let ((cleanup (make-cleanup :kind :special-bind))
1328           (var (first svars))
1329           (next-cont (make-continuation))
1330           (nnext-cont (make-continuation)))
1331       (ir1-convert start next-cont
1332                    `(%special-bind ',(lambda-var-specvar var) ,var))
1333       (setf (cleanup-mess-up cleanup) (continuation-use next-cont))
1334       (let ((*lexenv* (make-lexenv :cleanup cleanup)))
1335         (ir1-convert next-cont nnext-cont '(%cleanup-point))
1336         (ir1-convert-special-bindings nnext-cont cont body aux-vars aux-vals
1337                                       (rest svars))))))
1338   (values))
1339
1340 ;;; Create a lambda node out of some code, returning the result. The
1341 ;;; bindings are specified by the list of VAR structures VARS. We deal
1342 ;;; with adding the names to the LEXENV-VARIABLES for the conversion.
1343 ;;; The result is added to the NEW-FUNS in the *CURRENT-COMPONENT* and
1344 ;;; linked to the component head and tail.
1345 ;;;
1346 ;;; We detect special bindings here, replacing the original VAR in the
1347 ;;; lambda list with a temporary variable. We then pass a list of the
1348 ;;; special vars to IR1-CONVERT-SPECIAL-BINDINGS, which actually emits
1349 ;;; the special binding code.
1350 ;;;
1351 ;;; We ignore any ARG-INFO in the VARS, trusting that someone else is
1352 ;;; dealing with &nonsense.
1353 ;;;
1354 ;;; AUX-VARS is a list of VAR structures for variables that are to be
1355 ;;; sequentially bound. Each AUX-VAL is a form that is to be evaluated
1356 ;;; to get the initial value for the corresponding AUX-VAR. 
1357 (defun ir1-convert-lambda-body (body
1358                                 vars
1359                                 &key
1360                                 aux-vars
1361                                 aux-vals
1362                                 result
1363                                 (source-name '.anonymous.)
1364                                 debug-name)
1365   (declare (list body vars aux-vars aux-vals)
1366            (type (or continuation null) result))
1367
1368   ;; We're about to try to put new blocks into *CURRENT-COMPONENT*.
1369   (aver-live-component *current-component*)
1370
1371   (let* ((bind (make-bind))
1372          (lambda (make-lambda :vars vars
1373                               :bind bind
1374                               :%source-name source-name
1375                               :%debug-name debug-name))
1376          (result (or result (make-continuation))))
1377
1378     ;; just to check: This function should fail internal assertions if
1379     ;; we didn't set up a valid debug name above.
1380     ;;
1381     ;; (In SBCL we try to make everything have a debug name, since we
1382     ;; lack the omniscient perspective the original implementors used
1383     ;; to decide which things didn't need one.)
1384     (functional-debug-name lambda)
1385
1386     (setf (lambda-home lambda) lambda)
1387     (collect ((svars)
1388               (new-venv nil cons))
1389
1390       (dolist (var vars)
1391         ;; As far as I can see, LAMBDA-VAR-HOME should never have
1392         ;; been set before. Let's make sure. -- WHN 2001-09-29
1393         (aver (null (lambda-var-home var)))
1394         (setf (lambda-var-home var) lambda)
1395         (let ((specvar (lambda-var-specvar var)))
1396           (cond (specvar
1397                  (svars var)
1398                  (new-venv (cons (leaf-source-name specvar) specvar)))
1399                 (t
1400                  (note-lexical-binding (leaf-source-name var))
1401                  (new-venv (cons (leaf-source-name var) var))))))
1402
1403       (let ((*lexenv* (make-lexenv :variables (new-venv)
1404                                    :lambda lambda
1405                                    :cleanup nil)))
1406         (setf (bind-lambda bind) lambda)
1407         (setf (node-lexenv bind) *lexenv*)
1408         
1409         (let ((cont1 (make-continuation))
1410               (cont2 (make-continuation)))
1411           (continuation-starts-block cont1)
1412           (link-node-to-previous-continuation bind cont1)
1413           (use-continuation bind cont2)
1414           (ir1-convert-special-bindings cont2 result body aux-vars aux-vals
1415                                         (svars)))
1416
1417         (let ((block (continuation-block result)))
1418           (when block
1419             (let ((return (make-return :result result :lambda lambda))
1420                   (tail-set (make-tail-set :funs (list lambda)))
1421                   (dummy (make-continuation)))
1422               (setf (lambda-tail-set lambda) tail-set)
1423               (setf (lambda-return lambda) return)
1424               (setf (continuation-dest result) return)
1425               (setf (block-last block) return)
1426               (link-node-to-previous-continuation return result)
1427               (use-continuation return dummy))
1428             (link-blocks block (component-tail *current-component*))))))
1429
1430     (link-blocks (component-head *current-component*) (node-block bind))
1431     (push lambda (component-new-funs *current-component*))
1432
1433     lambda))
1434
1435 ;;; Create the actual entry-point function for an optional entry
1436 ;;; point. The lambda binds copies of each of the VARS, then calls FUN
1437 ;;; with the argument VALS and the DEFAULTS. Presumably the VALS refer
1438 ;;; to the VARS by name. The VALS are passed in in reverse order.
1439 ;;;
1440 ;;; If any of the copies of the vars are referenced more than once,
1441 ;;; then we mark the corresponding var as EVER-USED to inhibit
1442 ;;; "defined but not read" warnings for arguments that are only used
1443 ;;; by default forms.
1444 (defun convert-optional-entry (fun vars vals defaults)
1445   (declare (type clambda fun) (list vars vals defaults))
1446   (let* ((fvars (reverse vars))
1447          (arg-vars (mapcar (lambda (var)
1448                              (unless (lambda-var-specvar var)
1449                                (note-lexical-binding (leaf-source-name var)))
1450                              (make-lambda-var
1451                               :%source-name (leaf-source-name var)
1452                               :type (leaf-type var)
1453                               :where-from (leaf-where-from var)
1454                               :specvar (lambda-var-specvar var)))
1455                            fvars))
1456          (fun (ir1-convert-lambda-body `((%funcall ,fun
1457                                                    ,@(reverse vals)
1458                                                    ,@defaults))
1459                                        arg-vars
1460                                        :debug-name "&OPTIONAL processor")))
1461     (mapc (lambda (var arg-var)
1462             (when (cdr (leaf-refs arg-var))
1463               (setf (leaf-ever-used var) t)))
1464           fvars arg-vars)
1465     fun))
1466
1467 ;;; This function deals with supplied-p vars in optional arguments. If
1468 ;;; the there is no supplied-p arg, then we just call
1469 ;;; IR1-CONVERT-HAIRY-ARGS on the remaining arguments, and generate a
1470 ;;; optional entry that calls the result. If there is a supplied-p
1471 ;;; var, then we add it into the default vars and throw a T into the
1472 ;;; entry values. The resulting entry point function is returned.
1473 (defun generate-optional-default-entry (res default-vars default-vals
1474                                             entry-vars entry-vals
1475                                             vars supplied-p-p body
1476                                             aux-vars aux-vals cont
1477                                             source-name debug-name)
1478   (declare (type optional-dispatch res)
1479            (list default-vars default-vals entry-vars entry-vals vars body
1480                  aux-vars aux-vals)
1481            (type (or continuation null) cont))
1482   (let* ((arg (first vars))
1483          (arg-name (leaf-source-name arg))
1484          (info (lambda-var-arg-info arg))
1485          (supplied-p (arg-info-supplied-p info))
1486          (ep (if supplied-p
1487                  (ir1-convert-hairy-args
1488                   res
1489                   (list* supplied-p arg default-vars)
1490                   (list* (leaf-source-name supplied-p) arg-name default-vals)
1491                   (cons arg entry-vars)
1492                   (list* t arg-name entry-vals)
1493                   (rest vars) t body aux-vars aux-vals cont
1494                   source-name debug-name)
1495                  (ir1-convert-hairy-args
1496                   res
1497                   (cons arg default-vars)
1498                   (cons arg-name default-vals)
1499                   (cons arg entry-vars)
1500                   (cons arg-name entry-vals)
1501                   (rest vars) supplied-p-p body aux-vars aux-vals cont
1502                   source-name debug-name))))
1503
1504     (convert-optional-entry ep default-vars default-vals
1505                             (if supplied-p
1506                                 (list (arg-info-default info) nil)
1507                                 (list (arg-info-default info))))))
1508
1509 ;;; Create the MORE-ENTRY function for the OPTIONAL-DISPATCH RES.
1510 ;;; ENTRY-VARS and ENTRY-VALS describe the fixed arguments. REST is
1511 ;;; the var for any &REST arg. KEYS is a list of the &KEY arg vars.
1512 ;;;
1513 ;;; The most interesting thing that we do is parse keywords. We create
1514 ;;; a bunch of temporary variables to hold the result of the parse,
1515 ;;; and then loop over the supplied arguments, setting the appropriate
1516 ;;; temps for the supplied keyword. Note that it is significant that
1517 ;;; we iterate over the keywords in reverse order --- this implements
1518 ;;; the CL requirement that (when a keyword appears more than once)
1519 ;;; the first value is used.
1520 ;;;
1521 ;;; If there is no supplied-p var, then we initialize the temp to the
1522 ;;; default and just pass the temp into the main entry. Since
1523 ;;; non-constant &KEY args are forcibly given a supplied-p var, we
1524 ;;; know that the default is constant, and thus safe to evaluate out
1525 ;;; of order.
1526 ;;;
1527 ;;; If there is a supplied-p var, then we create temps for both the
1528 ;;; value and the supplied-p, and pass them into the main entry,
1529 ;;; letting it worry about defaulting.
1530 ;;;
1531 ;;; We deal with :ALLOW-OTHER-KEYS by delaying unknown keyword errors
1532 ;;; until we have scanned all the keywords.
1533 (defun convert-more-entry (res entry-vars entry-vals rest morep keys)
1534   (declare (type optional-dispatch res) (list entry-vars entry-vals keys))
1535   (collect ((arg-vars)
1536             (arg-vals (reverse entry-vals))
1537             (temps)
1538             (body))
1539
1540     (dolist (var (reverse entry-vars))
1541       (arg-vars (make-lambda-var :%source-name (leaf-source-name var)
1542                                  :type (leaf-type var)
1543                                  :where-from (leaf-where-from var))))
1544
1545     (let* ((n-context (gensym "N-CONTEXT-"))
1546            (context-temp (make-lambda-var :%source-name n-context))
1547            (n-count (gensym "N-COUNT-"))
1548            (count-temp (make-lambda-var :%source-name n-count
1549                                         :type (specifier-type 'index))))
1550
1551       (arg-vars context-temp count-temp)
1552
1553       (when rest
1554         (arg-vals `(%listify-rest-args ,n-context ,n-count)))
1555       (when morep
1556         (arg-vals n-context)
1557         (arg-vals n-count))
1558
1559       (when (optional-dispatch-keyp res)
1560         (let ((n-index (gensym "N-INDEX-"))
1561               (n-key (gensym "N-KEY-"))
1562               (n-value-temp (gensym "N-VALUE-TEMP-"))
1563               (n-allowp (gensym "N-ALLOWP-"))
1564               (n-losep (gensym "N-LOSEP-"))
1565               (allowp (or (optional-dispatch-allowp res)
1566                           (policy *lexenv* (zerop safety)))))
1567
1568           (temps `(,n-index (1- ,n-count)) n-key n-value-temp)
1569           (body `(declare (fixnum ,n-index) (ignorable ,n-key ,n-value-temp)))
1570
1571           (collect ((tests))
1572             (dolist (key keys)
1573               (let* ((info (lambda-var-arg-info key))
1574                      (default (arg-info-default info))
1575                      (keyword (arg-info-key info))
1576                      (supplied-p (arg-info-supplied-p info))
1577                      (n-value (gensym "N-VALUE-")))
1578                 (temps `(,n-value ,default))
1579                 (cond (supplied-p
1580                        (let ((n-supplied (gensym "N-SUPPLIED-")))
1581                          (temps n-supplied)
1582                          (arg-vals n-value n-supplied)
1583                          (tests `((eq ,n-key ',keyword)
1584                                   (setq ,n-supplied t)
1585                                   (setq ,n-value ,n-value-temp)))))
1586                       (t
1587                        (arg-vals n-value)
1588                        (tests `((eq ,n-key ',keyword)
1589                                 (setq ,n-value ,n-value-temp)))))))
1590
1591             (unless allowp
1592               (temps n-allowp n-losep)
1593               (tests `((eq ,n-key :allow-other-keys)
1594                        (setq ,n-allowp ,n-value-temp)))
1595               (tests `(t
1596                        (setq ,n-losep ,n-key))))
1597
1598             (body
1599              `(when (oddp ,n-count)
1600                 (%odd-key-arguments-error)))
1601
1602             (body
1603              `(locally
1604                 (declare (optimize (safety 0)))
1605                 (loop
1606                   (when (minusp ,n-index) (return))
1607                   (setf ,n-value-temp (%more-arg ,n-context ,n-index))
1608                   (decf ,n-index)
1609                   (setq ,n-key (%more-arg ,n-context ,n-index))
1610                   (decf ,n-index)
1611                   (cond ,@(tests)))))
1612
1613             (unless allowp
1614               (body `(when (and ,n-losep (not ,n-allowp))
1615                        (%unknown-key-argument-error ,n-losep)))))))
1616
1617       (let ((ep (ir1-convert-lambda-body
1618                  `((let ,(temps)
1619                      ,@(body)
1620                      (%funcall ,(optional-dispatch-main-entry res)
1621                                . ,(arg-vals)))) ; FIXME: What is the '.'? ,@?
1622                  (arg-vars)
1623                  :debug-name (debug-namify "~S processing" '&more))))
1624         (setf (optional-dispatch-more-entry res) ep))))
1625
1626   (values))
1627
1628 ;;; This is called by IR1-CONVERT-HAIRY-ARGS when we run into a &REST
1629 ;;; or &KEY arg. The arguments are similar to that function, but we
1630 ;;; split off any &REST arg and pass it in separately. REST is the
1631 ;;; &REST arg var, or NIL if there is no &REST arg. KEYS is a list of
1632 ;;; the &KEY argument vars.
1633 ;;;
1634 ;;; When there are &KEY arguments, we introduce temporary gensym
1635 ;;; variables to hold the values while keyword defaulting is in
1636 ;;; progress to get the required sequential binding semantics.
1637 ;;;
1638 ;;; This gets interesting mainly when there are &KEY arguments with
1639 ;;; supplied-p vars or non-constant defaults. In either case, pass in
1640 ;;; a supplied-p var. If the default is non-constant, we introduce an
1641 ;;; IF in the main entry that tests the supplied-p var and decides
1642 ;;; whether to evaluate the default or not. In this case, the real
1643 ;;; incoming value is NIL, so we must union NULL with the declared
1644 ;;; type when computing the type for the main entry's argument.
1645 (defun ir1-convert-more (res default-vars default-vals entry-vars entry-vals
1646                              rest more-context more-count keys supplied-p-p
1647                              body aux-vars aux-vals cont
1648                              source-name debug-name)
1649   (declare (type optional-dispatch res)
1650            (list default-vars default-vals entry-vars entry-vals keys body
1651                  aux-vars aux-vals)
1652            (type (or continuation null) cont))
1653   (collect ((main-vars (reverse default-vars))
1654             (main-vals default-vals cons)
1655             (bind-vars)
1656             (bind-vals))
1657     (when rest
1658       (main-vars rest)
1659       (main-vals '()))
1660     (when more-context
1661       (main-vars more-context)
1662       (main-vals nil)
1663       (main-vars more-count)
1664       (main-vals 0))
1665
1666     (dolist (key keys)
1667       (let* ((info (lambda-var-arg-info key))
1668              (default (arg-info-default info))
1669              (hairy-default (not (sb!xc:constantp default)))
1670              (supplied-p (arg-info-supplied-p info))
1671              (n-val (make-symbol (format nil
1672                                          "~A-DEFAULTING-TEMP"
1673                                          (leaf-source-name key))))
1674              (key-type (leaf-type key))
1675              (val-temp (make-lambda-var
1676                         :%source-name n-val
1677                         :type (if hairy-default
1678                                   (type-union key-type (specifier-type 'null))
1679                                   key-type))))
1680         (main-vars val-temp)
1681         (bind-vars key)
1682         (cond ((or hairy-default supplied-p)
1683                (let* ((n-supplied (gensym "N-SUPPLIED-"))
1684                       (supplied-temp (make-lambda-var
1685                                       :%source-name n-supplied)))
1686                  (unless supplied-p
1687                    (setf (arg-info-supplied-p info) supplied-temp))
1688                  (when hairy-default
1689                    (setf (arg-info-default info) nil))
1690                  (main-vars supplied-temp)
1691                  (cond (hairy-default
1692                         (main-vals nil nil)
1693                         (bind-vals `(if ,n-supplied ,n-val ,default)))
1694                        (t
1695                         (main-vals default nil)
1696                         (bind-vals n-val)))
1697                  (when supplied-p
1698                    (bind-vars supplied-p)
1699                    (bind-vals n-supplied))))
1700               (t
1701                (main-vals (arg-info-default info))
1702                (bind-vals n-val)))))
1703
1704     (let* ((main-entry (ir1-convert-lambda-body
1705                         body (main-vars)
1706                         :aux-vars (append (bind-vars) aux-vars)
1707                         :aux-vals (append (bind-vals) aux-vals)
1708                         :result cont
1709                         :debug-name (debug-namify "varargs entry point for ~A"
1710                                                   (as-debug-name source-name
1711                                                                  debug-name))))
1712            (last-entry (convert-optional-entry main-entry default-vars
1713                                                (main-vals) ())))
1714       (setf (optional-dispatch-main-entry res) main-entry)
1715       (convert-more-entry res entry-vars entry-vals rest more-context keys)
1716
1717       (push (if supplied-p-p
1718                 (convert-optional-entry last-entry entry-vars entry-vals ())
1719                 last-entry)
1720             (optional-dispatch-entry-points res))
1721       last-entry)))
1722
1723 ;;; This function generates the entry point functions for the
1724 ;;; OPTIONAL-DISPATCH RES. We accomplish this by recursion on the list
1725 ;;; of arguments, analyzing the arglist on the way down and generating
1726 ;;; entry points on the way up.
1727 ;;;
1728 ;;; DEFAULT-VARS is a reversed list of all the argument vars processed
1729 ;;; so far, including supplied-p vars. DEFAULT-VALS is a list of the
1730 ;;; names of the DEFAULT-VARS.
1731 ;;;
1732 ;;; ENTRY-VARS is a reversed list of processed argument vars,
1733 ;;; excluding supplied-p vars. ENTRY-VALS is a list things that can be
1734 ;;; evaluated to get the values for all the vars from the ENTRY-VARS.
1735 ;;; It has the var name for each required or optional arg, and has T
1736 ;;; for each supplied-p arg.
1737 ;;;
1738 ;;; VARS is a list of the LAMBDA-VAR structures for arguments that
1739 ;;; haven't been processed yet. SUPPLIED-P-P is true if a supplied-p
1740 ;;; argument has already been processed; only in this case are the
1741 ;;; DEFAULT-XXX and ENTRY-XXX different.
1742 ;;;
1743 ;;; The result at each point is a lambda which should be called by the
1744 ;;; above level to default the remaining arguments and evaluate the
1745 ;;; body. We cause the body to be evaluated by converting it and
1746 ;;; returning it as the result when the recursion bottoms out.
1747 ;;;
1748 ;;; Each level in the recursion also adds its entry point function to
1749 ;;; the result OPTIONAL-DISPATCH. For most arguments, the defaulting
1750 ;;; function and the entry point function will be the same, but when
1751 ;;; SUPPLIED-P args are present they may be different.
1752 ;;;
1753 ;;; When we run into a &REST or &KEY arg, we punt out to
1754 ;;; IR1-CONVERT-MORE, which finishes for us in this case.
1755 (defun ir1-convert-hairy-args (res default-vars default-vals
1756                                    entry-vars entry-vals
1757                                    vars supplied-p-p body aux-vars
1758                                    aux-vals cont
1759                                    source-name debug-name)
1760   (declare (type optional-dispatch res)
1761            (list default-vars default-vals entry-vars entry-vals vars body
1762                  aux-vars aux-vals)
1763            (type (or continuation null) cont))
1764   (cond ((not vars)
1765          (if (optional-dispatch-keyp res)
1766              ;; Handle &KEY with no keys...
1767              (ir1-convert-more res default-vars default-vals
1768                                entry-vars entry-vals
1769                                nil nil nil vars supplied-p-p body aux-vars
1770                                aux-vals cont source-name debug-name)
1771              (let ((fun (ir1-convert-lambda-body
1772                          body (reverse default-vars)
1773                          :aux-vars aux-vars
1774                          :aux-vals aux-vals
1775                          :result cont
1776                          :debug-name (debug-namify
1777                                       "hairy arg processor for ~A"
1778                                       (as-debug-name source-name
1779                                                      debug-name)))))
1780                (setf (optional-dispatch-main-entry res) fun)
1781                (push (if supplied-p-p
1782                          (convert-optional-entry fun entry-vars entry-vals ())
1783                          fun)
1784                      (optional-dispatch-entry-points res))
1785                fun)))
1786         ((not (lambda-var-arg-info (first vars)))
1787          (let* ((arg (first vars))
1788                 (nvars (cons arg default-vars))
1789                 (nvals (cons (leaf-source-name arg) default-vals)))
1790            (ir1-convert-hairy-args res nvars nvals nvars nvals
1791                                    (rest vars) nil body aux-vars aux-vals
1792                                    cont
1793                                    source-name debug-name)))
1794         (t
1795          (let* ((arg (first vars))
1796                 (info (lambda-var-arg-info arg))
1797                 (kind (arg-info-kind info)))
1798            (ecase kind
1799              (:optional
1800               (let ((ep (generate-optional-default-entry
1801                          res default-vars default-vals
1802                          entry-vars entry-vals vars supplied-p-p body
1803                          aux-vars aux-vals cont
1804                          source-name debug-name)))
1805                 (push (if supplied-p-p
1806                           (convert-optional-entry ep entry-vars entry-vals ())
1807                           ep)
1808                       (optional-dispatch-entry-points res))
1809                 ep))
1810              (:rest
1811               (ir1-convert-more res default-vars default-vals
1812                                 entry-vars entry-vals
1813                                 arg nil nil (rest vars) supplied-p-p body
1814                                 aux-vars aux-vals cont
1815                                 source-name debug-name))
1816              (:more-context
1817               (ir1-convert-more res default-vars default-vals
1818                                 entry-vars entry-vals
1819                                 nil arg (second vars) (cddr vars) supplied-p-p
1820                                 body aux-vars aux-vals cont
1821                                 source-name debug-name))
1822              (:keyword
1823               (ir1-convert-more res default-vars default-vals
1824                                 entry-vars entry-vals
1825                                 nil nil nil vars supplied-p-p body aux-vars
1826                                 aux-vals cont source-name debug-name)))))))
1827
1828 ;;; This function deals with the case where we have to make an
1829 ;;; OPTIONAL-DISPATCH to represent a LAMBDA. We cons up the result and
1830 ;;; call IR1-CONVERT-HAIRY-ARGS to do the work. When it is done, we
1831 ;;; figure out the MIN-ARGS and MAX-ARGS.
1832 (defun ir1-convert-hairy-lambda (body vars keyp allowp aux-vars aux-vals cont
1833                                       &key
1834                                       (source-name '.anonymous.)
1835                                       (debug-name (debug-namify
1836                                                    "OPTIONAL-DISPATCH ~S"
1837                                                    vars)))
1838   (declare (list body vars aux-vars aux-vals) (type continuation cont))
1839   (let ((res (make-optional-dispatch :arglist vars
1840                                      :allowp allowp
1841                                      :keyp keyp
1842                                      :%source-name source-name
1843                                      :%debug-name debug-name))
1844         (min (or (position-if #'lambda-var-arg-info vars) (length vars))))
1845     (aver-live-component *current-component*)
1846     (push res (component-new-funs *current-component*))
1847     (ir1-convert-hairy-args res () () () () vars nil body aux-vars aux-vals
1848                             cont source-name debug-name)
1849     (setf (optional-dispatch-min-args res) min)
1850     (setf (optional-dispatch-max-args res)
1851           (+ (1- (length (optional-dispatch-entry-points res))) min))
1852
1853     (flet ((frob (ep)
1854              (when ep
1855                (setf (functional-kind ep) :optional)
1856                (setf (leaf-ever-used ep) t)
1857                (setf (lambda-optional-dispatch ep) res))))
1858       (dolist (ep (optional-dispatch-entry-points res)) (frob ep))
1859       (frob (optional-dispatch-more-entry res))
1860       (frob (optional-dispatch-main-entry res)))
1861
1862     res))
1863
1864 ;;; Convert a LAMBDA form into a LAMBDA leaf or an OPTIONAL-DISPATCH leaf.
1865 (defun ir1-convert-lambda (form &key (source-name '.anonymous.) debug-name)
1866
1867   (unless (consp form)
1868     (compiler-error "A ~S was found when expecting a lambda expression:~%  ~S"
1869                     (type-of form)
1870                     form))
1871   (unless (eq (car form) 'lambda)
1872     (compiler-error "~S was expected but ~S was found:~%  ~S"
1873                     'lambda
1874                     (car form)
1875                     form))
1876   (unless (and (consp (cdr form)) (listp (cadr form)))
1877     (compiler-error
1878      "The lambda expression has a missing or non-list lambda list:~%  ~S"
1879      form))
1880
1881   (multiple-value-bind (vars keyp allow-other-keys aux-vars aux-vals)
1882       (make-lambda-vars (cadr form))
1883     (multiple-value-bind (forms decls) (sb!sys:parse-body (cddr form))
1884       (let* ((result-cont (make-continuation))
1885              (*lexenv* (process-decls decls
1886                                       (append aux-vars vars)
1887                                       nil result-cont))
1888              (res (if (or (find-if #'lambda-var-arg-info vars) keyp)
1889                       (ir1-convert-hairy-lambda forms vars keyp
1890                                                 allow-other-keys
1891                                                 aux-vars aux-vals result-cont
1892                                                 :source-name source-name
1893                                                 :debug-name debug-name)
1894                       (ir1-convert-lambda-body forms vars
1895                                                :aux-vars aux-vars
1896                                                :aux-vals aux-vals
1897                                                :result result-cont
1898                                                :source-name source-name
1899                                                :debug-name debug-name))))
1900         (setf (functional-inline-expansion res) form)
1901         (setf (functional-arg-documentation res) (cadr form))
1902         res))))
1903 \f
1904 ;;;; defining global functions
1905
1906 ;;; Convert FUN as a lambda in the null environment, but use the
1907 ;;; current compilation policy. Note that FUN may be a
1908 ;;; LAMBDA-WITH-LEXENV, so we may have to augment the environment to
1909 ;;; reflect the state at the definition site.
1910 (defun ir1-convert-inline-lambda (fun &key
1911                                       (source-name '.anonymous.)
1912                                       debug-name)
1913   (destructuring-bind (decls macros symbol-macros &rest body)
1914                       (if (eq (car fun) 'lambda-with-lexenv)
1915                           (cdr fun)
1916                           `(() () () . ,(cdr fun)))
1917     (let ((*lexenv* (make-lexenv
1918                      :default (process-decls decls nil nil
1919                                              (make-continuation)
1920                                              (make-null-lexenv))
1921                      :variables (copy-list symbol-macros)
1922                      :functions
1923                      (mapcar (lambda (x)
1924                                `(,(car x) .
1925                                  (macro . ,(coerce (cdr x) 'function))))
1926                              macros)
1927                      :policy (lexenv-policy *lexenv*))))
1928       (ir1-convert-lambda `(lambda ,@body)
1929                           :source-name source-name
1930                           :debug-name debug-name))))
1931
1932 ;;; Get a DEFINED-FUN object for a function we are about to
1933 ;;; define. If the function has been forward referenced, then
1934 ;;; substitute for the previous references.
1935 (defun get-defined-fun (name)
1936   (proclaim-as-fun-name name)
1937   (let ((found (find-free-function name "shouldn't happen! (defined-fun)")))
1938     (note-name-defined name :function)
1939     (cond ((not (defined-fun-p found))
1940            (aver (not (info :function :inlinep name)))
1941            (let* ((where-from (leaf-where-from found))
1942                   (res (make-defined-fun
1943                         :%source-name name
1944                         :where-from (if (eq where-from :declared)
1945                                         :declared :defined)
1946                         :type (leaf-type found))))
1947              (substitute-leaf res found)
1948              (setf (gethash name *free-functions*) res)))
1949           ;; If *FREE-FUNCTIONS* has a previously converted definition
1950           ;; for this name, then blow it away and try again.
1951           ((defined-fun-functional found)
1952            (remhash name *free-functions*)
1953            (get-defined-fun name))
1954           (t found))))
1955
1956 ;;; Check a new global function definition for consistency with
1957 ;;; previous declaration or definition, and assert argument/result
1958 ;;; types if appropriate. This assertion is suppressed by the
1959 ;;; EXPLICIT-CHECK attribute, which is specified on functions that
1960 ;;; check their argument types as a consequence of type dispatching.
1961 ;;; This avoids redundant checks such as NUMBERP on the args to +, etc.
1962 (defun assert-new-definition (var fun)
1963   (let ((type (leaf-type var))
1964         (for-real (eq (leaf-where-from var) :declared))
1965         (info (info :function :info (leaf-source-name var))))
1966     (assert-definition-type
1967      fun type
1968      ;; KLUDGE: Common Lisp is such a dynamic language that in general
1969      ;; all we can do here in general is issue a STYLE-WARNING. It
1970      ;; would be nice to issue a full WARNING in the special case of
1971      ;; of type mismatches within a compilation unit (as in section
1972      ;; 3.2.2.3 of the spec) but at least as of sbcl-0.6.11, we don't
1973      ;; keep track of whether the mismatched data came from the same
1974      ;; compilation unit, so we can't do that. -- WHN 2001-02-11
1975      :error-function #'compiler-style-warning
1976      :warning-function (cond (info #'compiler-style-warning)
1977                              (for-real #'compiler-note)
1978                              (t nil))
1979      :really-assert
1980      (and for-real
1981           (not (and info
1982                     (ir1-attributep (function-info-attributes info)
1983                                     explicit-check))))
1984      :where (if for-real
1985                 "previous declaration"
1986                 "previous definition"))))
1987
1988 ;;; Convert a lambda doing all the basic stuff we would do if we were
1989 ;;; converting a DEFUN. In the old CMU CL system, this was used both
1990 ;;; by the %DEFUN translator and for global inline expansion, but
1991 ;;; since sbcl-0.pre7.something %DEFUN does things differently.
1992 ;;; FIXME: And now it's probably worth rethinking whether this
1993 ;;; function is a good idea.
1994 ;;;
1995 ;;; Unless a :INLINE function, we temporarily clobber the inline
1996 ;;; expansion. This prevents recursive inline expansion of
1997 ;;; opportunistic pseudo-inlines.
1998 (defun ir1-convert-lambda-for-defun (lambda var expansion converter)
1999   (declare (cons lambda) (function converter) (type defined-fun var))
2000   (let ((var-expansion (defined-fun-inline-expansion var)))
2001     (unless (eq (defined-fun-inlinep var) :inline)
2002       (setf (defined-fun-inline-expansion var) nil))
2003     (let* ((name (leaf-source-name var))
2004            (fun (funcall converter lambda :source-name name))
2005            (function-info (info :function :info name)))
2006       (setf (functional-inlinep fun) (defined-fun-inlinep var))
2007       (assert-new-definition var fun)
2008       (setf (defined-fun-inline-expansion var) var-expansion)
2009       ;; If definitely not an interpreter stub, then substitute for any
2010       ;; old references.
2011       (unless (or (eq (defined-fun-inlinep var) :notinline)
2012                   (not *block-compile*)
2013                   (and function-info
2014                        (or (function-info-transforms function-info)
2015                            (function-info-templates function-info)
2016                            (function-info-ir2-convert function-info))))
2017         (substitute-leaf fun var)
2018         ;; If in a simple environment, then we can allow backward
2019         ;; references to this function from following top level forms.
2020         (when expansion (setf (defined-fun-functional var) fun)))
2021       fun)))
2022
2023 ;;; the even-at-compile-time part of DEFUN
2024 ;;;
2025 ;;; The INLINE-EXPANSION is a LAMBDA-WITH-LEXENV, or NIL if there is
2026 ;;; no inline expansion.
2027 (defun %compiler-defun (name lambda-with-lexenv)
2028
2029   (let ((defined-fun nil)) ; will be set below if we're in the compiler
2030     
2031     (when (boundp '*lexenv*) ; when in the compiler
2032       (when sb!xc:*compile-print*
2033         (compiler-mumble "~&; recognizing DEFUN ~S~%" name))
2034       (remhash name *free-functions*)
2035       (setf defined-fun (get-defined-fun name)))
2036
2037     (become-defined-fun-name name)
2038
2039     (cond (lambda-with-lexenv
2040            (setf (info :function :inline-expansion-designator name)
2041                  lambda-with-lexenv)
2042            (when defined-fun 
2043              (setf (defined-fun-inline-expansion defined-fun)
2044                    lambda-with-lexenv)))
2045           (t
2046            (clear-info :function :inline-expansion-designator name)))
2047
2048     ;; old CMU CL comment:
2049     ;;   If there is a type from a previous definition, blast it,
2050     ;;   since it is obsolete.
2051     (when (and defined-fun
2052                (eq (leaf-where-from defined-fun) :defined))
2053       (setf (leaf-type defined-fun)
2054             ;; FIXME: If this is a block compilation thing, shouldn't
2055             ;; we be setting the type to the full derived type for the
2056             ;; definition, instead of this most general function type?
2057             (specifier-type 'function))))
2058
2059   (values))