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