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