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