0.7.13.26:
[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 (ir1-convert-lambda-body `((%funcall ,fun
1539                                                    ,@(reverse vals)
1540                                                    ,@defaults))
1541                                        arg-vars
1542                                        :debug-name "&OPTIONAL processor"
1543                                        :note-lexical-bindings nil)))
1544     (mapc (lambda (var arg-var)
1545             (when (cdr (leaf-refs arg-var))
1546               (setf (leaf-ever-used var) t)))
1547           fvars arg-vars)
1548     fun))
1549
1550 ;;; This function deals with supplied-p vars in optional arguments. If
1551 ;;; the there is no supplied-p arg, then we just call
1552 ;;; IR1-CONVERT-HAIRY-ARGS on the remaining arguments, and generate a
1553 ;;; optional entry that calls the result. If there is a supplied-p
1554 ;;; var, then we add it into the default vars and throw a T into the
1555 ;;; entry values. The resulting entry point function is returned.
1556 (defun generate-optional-default-entry (res default-vars default-vals
1557                                             entry-vars entry-vals
1558                                             vars supplied-p-p body
1559                                             aux-vars aux-vals cont
1560                                             source-name debug-name)
1561   (declare (type optional-dispatch res)
1562            (list default-vars default-vals entry-vars entry-vals vars body
1563                  aux-vars aux-vals)
1564            (type (or continuation null) cont))
1565   (let* ((arg (first vars))
1566          (arg-name (leaf-source-name arg))
1567          (info (lambda-var-arg-info arg))
1568          (supplied-p (arg-info-supplied-p info))
1569          (ep (if supplied-p
1570                  (ir1-convert-hairy-args
1571                   res
1572                   (list* supplied-p arg default-vars)
1573                   (list* (leaf-source-name supplied-p) arg-name default-vals)
1574                   (cons arg entry-vars)
1575                   (list* t arg-name entry-vals)
1576                   (rest vars) t body aux-vars aux-vals cont
1577                   source-name debug-name)
1578                  (ir1-convert-hairy-args
1579                   res
1580                   (cons arg default-vars)
1581                   (cons arg-name default-vals)
1582                   (cons arg entry-vars)
1583                   (cons arg-name entry-vals)
1584                   (rest vars) supplied-p-p body aux-vars aux-vals cont
1585                   source-name debug-name))))
1586
1587     (convert-optional-entry ep default-vars default-vals
1588                             (if supplied-p
1589                                 (list (arg-info-default info) nil)
1590                                 (list (arg-info-default info))))))
1591
1592 ;;; Create the MORE-ENTRY function for the OPTIONAL-DISPATCH RES.
1593 ;;; ENTRY-VARS and ENTRY-VALS describe the fixed arguments. REST is
1594 ;;; the var for any &REST arg. KEYS is a list of the &KEY arg vars.
1595 ;;;
1596 ;;; The most interesting thing that we do is parse keywords. We create
1597 ;;; a bunch of temporary variables to hold the result of the parse,
1598 ;;; and then loop over the supplied arguments, setting the appropriate
1599 ;;; temps for the supplied keyword. Note that it is significant that
1600 ;;; we iterate over the keywords in reverse order --- this implements
1601 ;;; the CL requirement that (when a keyword appears more than once)
1602 ;;; the first value is used.
1603 ;;;
1604 ;;; If there is no supplied-p var, then we initialize the temp to the
1605 ;;; default and just pass the temp into the main entry. Since
1606 ;;; non-constant &KEY args are forcibly given a supplied-p var, we
1607 ;;; know that the default is constant, and thus safe to evaluate out
1608 ;;; of order.
1609 ;;;
1610 ;;; If there is a supplied-p var, then we create temps for both the
1611 ;;; value and the supplied-p, and pass them into the main entry,
1612 ;;; letting it worry about defaulting.
1613 ;;;
1614 ;;; We deal with :ALLOW-OTHER-KEYS by delaying unknown keyword errors
1615 ;;; until we have scanned all the keywords.
1616 (defun convert-more-entry (res entry-vars entry-vals rest morep keys)
1617   (declare (type optional-dispatch res) (list entry-vars entry-vals keys))
1618   (collect ((arg-vars)
1619             (arg-vals (reverse entry-vals))
1620             (temps)
1621             (body))
1622
1623     (dolist (var (reverse entry-vars))
1624       (arg-vars (make-lambda-var :%source-name (leaf-source-name var)
1625                                  :type (leaf-type var)
1626                                  :where-from (leaf-where-from var))))
1627
1628     (let* ((n-context (gensym "N-CONTEXT-"))
1629            (context-temp (make-lambda-var :%source-name n-context))
1630            (n-count (gensym "N-COUNT-"))
1631            (count-temp (make-lambda-var :%source-name n-count
1632                                         :type (specifier-type 'index))))
1633
1634       (arg-vars context-temp count-temp)
1635
1636       (when rest
1637         (arg-vals `(%listify-rest-args ,n-context ,n-count)))
1638       (when morep
1639         (arg-vals n-context)
1640         (arg-vals n-count))
1641
1642       (when (optional-dispatch-keyp res)
1643         (let ((n-index (gensym "N-INDEX-"))
1644               (n-key (gensym "N-KEY-"))
1645               (n-value-temp (gensym "N-VALUE-TEMP-"))
1646               (n-allowp (gensym "N-ALLOWP-"))
1647               (n-losep (gensym "N-LOSEP-"))
1648               (allowp (or (optional-dispatch-allowp res)
1649                           (policy *lexenv* (zerop safety))))
1650               (found-allow-p nil))
1651
1652           (temps `(,n-index (1- ,n-count)) n-key n-value-temp)
1653           (body `(declare (fixnum ,n-index) (ignorable ,n-key ,n-value-temp)))
1654
1655           (collect ((tests))
1656             (dolist (key keys)
1657               (let* ((info (lambda-var-arg-info key))
1658                      (default (arg-info-default info))
1659                      (keyword (arg-info-key info))
1660                      (supplied-p (arg-info-supplied-p info))
1661                      (n-value (gensym "N-VALUE-"))
1662                      (clause (cond (supplied-p
1663                                     (let ((n-supplied (gensym "N-SUPPLIED-")))
1664                                       (temps n-supplied)
1665                                       (arg-vals n-value n-supplied)
1666                                       `((eq ,n-key ',keyword)
1667                                         (setq ,n-supplied t)
1668                                         (setq ,n-value ,n-value-temp))))
1669                                    (t
1670                                     (arg-vals n-value)
1671                                     `((eq ,n-key ',keyword)
1672                                       (setq ,n-value ,n-value-temp))))))
1673                 (when (and (not allowp) (eq keyword :allow-other-keys))
1674                   (setq found-allow-p t)
1675                   (setq clause
1676                         (append clause `((setq ,n-allowp ,n-value-temp)))))
1677
1678                 (temps `(,n-value ,default))
1679                 (tests clause)))
1680
1681             (unless allowp
1682               (temps n-allowp n-losep)
1683               (unless found-allow-p
1684                 (tests `((eq ,n-key :allow-other-keys)
1685                          (setq ,n-allowp ,n-value-temp))))
1686               (tests `(t
1687                        (setq ,n-losep ,n-key))))
1688
1689             (body
1690              `(when (oddp ,n-count)
1691                 (%odd-key-args-error)))
1692
1693             (body
1694              `(locally
1695                 (declare (optimize (safety 0)))
1696                 (loop
1697                   (when (minusp ,n-index) (return))
1698                   (setf ,n-value-temp (%more-arg ,n-context ,n-index))
1699                   (decf ,n-index)
1700                   (setq ,n-key (%more-arg ,n-context ,n-index))
1701                   (decf ,n-index)
1702                   (cond ,@(tests)))))
1703
1704             (unless allowp
1705               (body `(when (and ,n-losep (not ,n-allowp))
1706                        (%unknown-key-arg-error ,n-losep)))))))
1707
1708       (let ((ep (ir1-convert-lambda-body
1709                  `((let ,(temps)
1710                      ,@(body)
1711                      (%funcall ,(optional-dispatch-main-entry res)
1712                                ,@(arg-vals))))
1713                  (arg-vars)
1714                  :debug-name (debug-namify "~S processing" '&more)
1715                  :note-lexical-bindings nil)))
1716         (setf (optional-dispatch-more-entry res) ep))))
1717
1718   (values))
1719
1720 ;;; This is called by IR1-CONVERT-HAIRY-ARGS when we run into a &REST
1721 ;;; or &KEY arg. The arguments are similar to that function, but we
1722 ;;; split off any &REST arg and pass it in separately. REST is the
1723 ;;; &REST arg var, or NIL if there is no &REST arg. KEYS is a list of
1724 ;;; the &KEY argument vars.
1725 ;;;
1726 ;;; When there are &KEY arguments, we introduce temporary gensym
1727 ;;; variables to hold the values while keyword defaulting is in
1728 ;;; progress to get the required sequential binding semantics.
1729 ;;;
1730 ;;; This gets interesting mainly when there are &KEY arguments with
1731 ;;; supplied-p vars or non-constant defaults. In either case, pass in
1732 ;;; a supplied-p var. If the default is non-constant, we introduce an
1733 ;;; IF in the main entry that tests the supplied-p var and decides
1734 ;;; whether to evaluate the default or not. In this case, the real
1735 ;;; incoming value is NIL, so we must union NULL with the declared
1736 ;;; type when computing the type for the main entry's argument.
1737 (defun ir1-convert-more (res default-vars default-vals entry-vars entry-vals
1738                              rest more-context more-count keys supplied-p-p
1739                              body aux-vars aux-vals cont
1740                              source-name debug-name)
1741   (declare (type optional-dispatch res)
1742            (list default-vars default-vals entry-vars entry-vals keys body
1743                  aux-vars aux-vals)
1744            (type (or continuation null) cont))
1745   (collect ((main-vars (reverse default-vars))
1746             (main-vals default-vals cons)
1747             (bind-vars)
1748             (bind-vals))
1749     (when rest
1750       (main-vars rest)
1751       (main-vals '()))
1752     (when more-context
1753       (main-vars more-context)
1754       (main-vals nil)
1755       (main-vars more-count)
1756       (main-vals 0))
1757
1758     (dolist (key keys)
1759       (let* ((info (lambda-var-arg-info key))
1760              (default (arg-info-default info))
1761              (hairy-default (not (sb!xc:constantp default)))
1762              (supplied-p (arg-info-supplied-p info))
1763              (n-val (make-symbol (format nil
1764                                          "~A-DEFAULTING-TEMP"
1765                                          (leaf-source-name key))))
1766              (key-type (leaf-type key))
1767              (val-temp (make-lambda-var
1768                         :%source-name n-val
1769                         :type (if hairy-default
1770                                   (type-union key-type (specifier-type 'null))
1771                                   key-type))))
1772         (main-vars val-temp)
1773         (bind-vars key)
1774         (cond ((or hairy-default supplied-p)
1775                (let* ((n-supplied (gensym "N-SUPPLIED-"))
1776                       (supplied-temp (make-lambda-var
1777                                       :%source-name n-supplied)))
1778                  (unless supplied-p
1779                    (setf (arg-info-supplied-p info) supplied-temp))
1780                  (when hairy-default
1781                    (setf (arg-info-default info) nil))
1782                  (main-vars supplied-temp)
1783                  (cond (hairy-default
1784                         (main-vals nil nil)
1785                         (bind-vals `(if ,n-supplied ,n-val ,default)))
1786                        (t
1787                         (main-vals default nil)
1788                         (bind-vals n-val)))
1789                  (when supplied-p
1790                    (bind-vars supplied-p)
1791                    (bind-vals n-supplied))))
1792               (t
1793                (main-vals (arg-info-default info))
1794                (bind-vals n-val)))))
1795
1796     (let* ((main-entry (ir1-convert-lambda-body
1797                         body (main-vars)
1798                         :aux-vars (append (bind-vars) aux-vars)
1799                         :aux-vals (append (bind-vals) aux-vals)
1800                         :result cont
1801                         :debug-name (debug-namify "varargs entry for ~A"
1802                                                   (as-debug-name source-name
1803                                                                  debug-name))))
1804            (last-entry (convert-optional-entry main-entry default-vars
1805                                                (main-vals) ())))
1806       (setf (optional-dispatch-main-entry res) main-entry)
1807       (convert-more-entry res entry-vars entry-vals rest more-context keys)
1808
1809       (push (if supplied-p-p
1810                 (convert-optional-entry last-entry entry-vars entry-vals ())
1811                 last-entry)
1812             (optional-dispatch-entry-points res))
1813       last-entry)))
1814
1815 ;;; This function generates the entry point functions for the
1816 ;;; OPTIONAL-DISPATCH RES. We accomplish this by recursion on the list
1817 ;;; of arguments, analyzing the arglist on the way down and generating
1818 ;;; entry points on the way up.
1819 ;;;
1820 ;;; DEFAULT-VARS is a reversed list of all the argument vars processed
1821 ;;; so far, including supplied-p vars. DEFAULT-VALS is a list of the
1822 ;;; names of the DEFAULT-VARS.
1823 ;;;
1824 ;;; ENTRY-VARS is a reversed list of processed argument vars,
1825 ;;; excluding supplied-p vars. ENTRY-VALS is a list things that can be
1826 ;;; evaluated to get the values for all the vars from the ENTRY-VARS.
1827 ;;; It has the var name for each required or optional arg, and has T
1828 ;;; for each supplied-p arg.
1829 ;;;
1830 ;;; VARS is a list of the LAMBDA-VAR structures for arguments that
1831 ;;; haven't been processed yet. SUPPLIED-P-P is true if a supplied-p
1832 ;;; argument has already been processed; only in this case are the
1833 ;;; DEFAULT-XXX and ENTRY-XXX different.
1834 ;;;
1835 ;;; The result at each point is a lambda which should be called by the
1836 ;;; above level to default the remaining arguments and evaluate the
1837 ;;; body. We cause the body to be evaluated by converting it and
1838 ;;; returning it as the result when the recursion bottoms out.
1839 ;;;
1840 ;;; Each level in the recursion also adds its entry point function to
1841 ;;; the result OPTIONAL-DISPATCH. For most arguments, the defaulting
1842 ;;; function and the entry point function will be the same, but when
1843 ;;; SUPPLIED-P args are present they may be different.
1844 ;;;
1845 ;;; When we run into a &REST or &KEY arg, we punt out to
1846 ;;; IR1-CONVERT-MORE, which finishes for us in this case.
1847 (defun ir1-convert-hairy-args (res default-vars default-vals
1848                                    entry-vars entry-vals
1849                                    vars supplied-p-p body aux-vars
1850                                    aux-vals cont
1851                                    source-name debug-name)
1852   (declare (type optional-dispatch res)
1853            (list default-vars default-vals entry-vars entry-vals vars body
1854                  aux-vars aux-vals)
1855            (type (or continuation null) cont))
1856   (cond ((not vars)
1857          (if (optional-dispatch-keyp res)
1858              ;; Handle &KEY with no keys...
1859              (ir1-convert-more res default-vars default-vals
1860                                entry-vars entry-vals
1861                                nil nil nil vars supplied-p-p body aux-vars
1862                                aux-vals cont source-name debug-name)
1863              (let ((fun (ir1-convert-lambda-body
1864                          body (reverse default-vars)
1865                          :aux-vars aux-vars
1866                          :aux-vals aux-vals
1867                          :result cont
1868                          :debug-name (debug-namify
1869                                       "hairy arg processor for ~A"
1870                                       (as-debug-name source-name
1871                                                      debug-name)))))
1872                (setf (optional-dispatch-main-entry res) fun)
1873                (push (if supplied-p-p
1874                          (convert-optional-entry fun entry-vars entry-vals ())
1875                          fun)
1876                      (optional-dispatch-entry-points res))
1877                fun)))
1878         ((not (lambda-var-arg-info (first vars)))
1879          (let* ((arg (first vars))
1880                 (nvars (cons arg default-vars))
1881                 (nvals (cons (leaf-source-name arg) default-vals)))
1882            (ir1-convert-hairy-args res nvars nvals nvars nvals
1883                                    (rest vars) nil body aux-vars aux-vals
1884                                    cont
1885                                    source-name debug-name)))
1886         (t
1887          (let* ((arg (first vars))
1888                 (info (lambda-var-arg-info arg))
1889                 (kind (arg-info-kind info)))
1890            (ecase kind
1891              (:optional
1892               (let ((ep (generate-optional-default-entry
1893                          res default-vars default-vals
1894                          entry-vars entry-vals vars supplied-p-p body
1895                          aux-vars aux-vals cont
1896                          source-name debug-name)))
1897                 (push (if supplied-p-p
1898                           (convert-optional-entry ep entry-vars entry-vals ())
1899                           ep)
1900                       (optional-dispatch-entry-points res))
1901                 ep))
1902              (:rest
1903               (ir1-convert-more res default-vars default-vals
1904                                 entry-vars entry-vals
1905                                 arg nil nil (rest vars) supplied-p-p body
1906                                 aux-vars aux-vals cont
1907                                 source-name debug-name))
1908              (:more-context
1909               (ir1-convert-more res default-vars default-vals
1910                                 entry-vars entry-vals
1911                                 nil arg (second vars) (cddr vars) supplied-p-p
1912                                 body aux-vars aux-vals cont
1913                                 source-name debug-name))
1914              (:keyword
1915               (ir1-convert-more res default-vars default-vals
1916                                 entry-vars entry-vals
1917                                 nil nil nil vars supplied-p-p body aux-vars
1918                                 aux-vals cont source-name debug-name)))))))
1919
1920 ;;; This function deals with the case where we have to make an
1921 ;;; OPTIONAL-DISPATCH to represent a LAMBDA. We cons up the result and
1922 ;;; call IR1-CONVERT-HAIRY-ARGS to do the work. When it is done, we
1923 ;;; figure out the MIN-ARGS and MAX-ARGS.
1924 (defun ir1-convert-hairy-lambda (body vars keyp allowp aux-vars aux-vals cont
1925                                       &key
1926                                       (source-name '.anonymous.)
1927                                       (debug-name (debug-namify
1928                                                    "OPTIONAL-DISPATCH ~S"
1929                                                    vars)))
1930   (declare (list body vars aux-vars aux-vals) (type continuation cont))
1931   (let ((res (make-optional-dispatch :arglist vars
1932                                      :allowp allowp
1933                                      :keyp keyp
1934                                      :%source-name source-name
1935                                      :%debug-name debug-name))
1936         (min (or (position-if #'lambda-var-arg-info vars) (length vars))))
1937     (aver-live-component *current-component*)
1938     (push res (component-new-functionals *current-component*))
1939     (ir1-convert-hairy-args res () () () () vars nil body aux-vars aux-vals
1940                             cont source-name debug-name)
1941     (setf (optional-dispatch-min-args res) min)
1942     (setf (optional-dispatch-max-args res)
1943           (+ (1- (length (optional-dispatch-entry-points res))) min))
1944
1945     (flet ((frob (ep)
1946              (when ep
1947                (setf (functional-kind ep) :optional)
1948                (setf (leaf-ever-used ep) t)
1949                (setf (lambda-optional-dispatch ep) res))))
1950       (dolist (ep (optional-dispatch-entry-points res)) (frob ep))
1951       (frob (optional-dispatch-more-entry res))
1952       (frob (optional-dispatch-main-entry res)))
1953
1954     res))
1955
1956 ;;; Convert a LAMBDA form into a LAMBDA leaf or an OPTIONAL-DISPATCH leaf.
1957 (defun ir1-convert-lambda (form &key (source-name '.anonymous.)
1958                                      debug-name
1959                                      allow-debug-catch-tag)
1960
1961   (unless (consp form)
1962     (compiler-error "A ~S was found when expecting a lambda expression:~%  ~S"
1963                     (type-of form)
1964                     form))
1965   (unless (eq (car form) 'lambda)
1966     (compiler-error "~S was expected but ~S was found:~%  ~S"
1967                     'lambda
1968                     (car form)
1969                     form))
1970   (unless (and (consp (cdr form)) (listp (cadr form)))
1971     (compiler-error
1972      "The lambda expression has a missing or non-list lambda list:~%  ~S"
1973      form))
1974
1975   (let ((*allow-debug-catch-tag* (and *allow-debug-catch-tag* allow-debug-catch-tag)))
1976     (multiple-value-bind (vars keyp allow-other-keys aux-vars aux-vals)
1977         (make-lambda-vars (cadr form))
1978       (multiple-value-bind (forms decls) (parse-body (cddr form))
1979         (let* ((result-cont (make-continuation))
1980                (*lexenv* (process-decls decls
1981                                         (append aux-vars vars)
1982                                         nil result-cont))
1983                (forms (if (and *allow-debug-catch-tag*
1984                                (policy *lexenv* (> debug (max speed space))))
1985                           `((catch (make-symbol "SB-DEBUG-CATCH-TAG")
1986                               ,@forms))
1987                           forms))
1988                (res (if (or (find-if #'lambda-var-arg-info vars) keyp)
1989                         (ir1-convert-hairy-lambda forms vars keyp
1990                                                   allow-other-keys
1991                                                   aux-vars aux-vals result-cont
1992                                                   :source-name source-name
1993                                                   :debug-name debug-name)
1994                         (ir1-convert-lambda-body forms vars
1995                                                  :aux-vars aux-vars
1996                                                  :aux-vals aux-vals
1997                                                  :result result-cont
1998                                                  :source-name source-name
1999                                                  :debug-name debug-name))))
2000           (setf (functional-inline-expansion res) form)
2001           (setf (functional-arg-documentation res) (cadr form))
2002           res)))))
2003
2004 ;;; helper for LAMBDA-like things, to massage them into a form
2005 ;;; suitable for IR1-CONVERT-LAMBDA.
2006 ;;;
2007 ;;; KLUDGE: We cons up a &REST list here, maybe for no particularly
2008 ;;; good reason.  It's probably lost in the noise of all the other
2009 ;;; consing, but it's still inelegant.  And we force our called
2010 ;;; functions to do full runtime keyword parsing, ugh.  -- CSR,
2011 ;;; 2003-01-25
2012 (defun ir1-convert-lambdalike (thing &rest args
2013                                &key (source-name '.anonymous.)
2014                                debug-name allow-debug-catch-tag)
2015   (ecase (car thing)
2016     ((lambda) (apply #'ir1-convert-lambda thing args))
2017     ((instance-lambda)
2018      (let ((res (apply #'ir1-convert-lambda
2019                        `(lambda ,@(cdr thing)) args)))
2020        (setf (getf (functional-plist res) :fin-function) t)
2021        res))
2022     ((named-lambda)
2023      (let ((name (cadr thing)))
2024        (if (legal-fun-name-p name)
2025            (let ((res (apply #'ir1-convert-lambda `(lambda ,@(cddr thing))
2026                              :source-name name
2027                              :debug-name nil
2028                              args)))
2029              (assert-global-function-definition-type name res)
2030              res)
2031            (apply #'ir1-convert-lambda `(lambda ,@(cddr thing))
2032                   :debug-name name args))))
2033     ((lambda-with-lexenv) (apply #'ir1-convert-inline-lambda thing args))))
2034 \f
2035 ;;;; defining global functions
2036
2037 ;;; Convert FUN as a lambda in the null environment, but use the
2038 ;;; current compilation policy. Note that FUN may be a
2039 ;;; LAMBDA-WITH-LEXENV, so we may have to augment the environment to
2040 ;;; reflect the state at the definition site.
2041 (defun ir1-convert-inline-lambda (fun &key
2042                                       (source-name '.anonymous.)
2043                                       debug-name
2044                                       allow-debug-catch-tag)
2045   (destructuring-bind (decls macros symbol-macros &rest body)
2046                       (if (eq (car fun) 'lambda-with-lexenv)
2047                           (cdr fun)
2048                           `(() () () . ,(cdr fun)))
2049     (let ((*lexenv* (make-lexenv
2050                      :default (process-decls decls nil nil
2051                                              (make-continuation)
2052                                              (make-null-lexenv))
2053                      :vars (copy-list symbol-macros)
2054                      :funs (mapcar (lambda (x)
2055                                      `(,(car x) .
2056                                        (macro . ,(coerce (cdr x) 'function))))
2057                                    macros)
2058                      :policy (lexenv-policy *lexenv*))))
2059       (ir1-convert-lambda `(lambda ,@body)
2060                           :source-name source-name
2061                           :debug-name debug-name
2062                           :allow-debug-catch-tag nil))))
2063
2064 ;;; Get a DEFINED-FUN object for a function we are about to define. If
2065 ;;; the function has been forward referenced, then substitute for the
2066 ;;; previous references.
2067 (defun get-defined-fun (name)
2068   (proclaim-as-fun-name name)
2069   (let ((found (find-free-fun name "shouldn't happen! (defined-fun)")))
2070     (note-name-defined name :function)
2071     (cond ((not (defined-fun-p found))
2072            (aver (not (info :function :inlinep name)))
2073            (let* ((where-from (leaf-where-from found))
2074                   (res (make-defined-fun
2075                         :%source-name name
2076                         :where-from (if (eq where-from :declared)
2077                                         :declared :defined)
2078                         :type (leaf-type found))))
2079              (substitute-leaf res found)
2080              (setf (gethash name *free-funs*) res)))
2081           ;; If *FREE-FUNS* has a previously converted definition
2082           ;; for this name, then blow it away and try again.
2083           ((defined-fun-functional found)
2084            (remhash name *free-funs*)
2085            (get-defined-fun name))
2086           (t found))))
2087
2088 ;;; Check a new global function definition for consistency with
2089 ;;; previous declaration or definition, and assert argument/result
2090 ;;; types if appropriate. This assertion is suppressed by the
2091 ;;; EXPLICIT-CHECK attribute, which is specified on functions that
2092 ;;; check their argument types as a consequence of type dispatching.
2093 ;;; This avoids redundant checks such as NUMBERP on the args to +, etc.
2094 (defun assert-new-definition (var fun)
2095   (let ((type (leaf-type var))
2096         (for-real (eq (leaf-where-from var) :declared))
2097         (info (info :function :info (leaf-source-name var))))
2098     (assert-definition-type
2099      fun type
2100      ;; KLUDGE: Common Lisp is such a dynamic language that in general
2101      ;; all we can do here in general is issue a STYLE-WARNING. It
2102      ;; would be nice to issue a full WARNING in the special case of
2103      ;; of type mismatches within a compilation unit (as in section
2104      ;; 3.2.2.3 of the spec) but at least as of sbcl-0.6.11, we don't
2105      ;; keep track of whether the mismatched data came from the same
2106      ;; compilation unit, so we can't do that. -- WHN 2001-02-11
2107      :lossage-fun #'compiler-style-warn
2108      :unwinnage-fun (cond (info #'compiler-style-warn)
2109                           (for-real #'compiler-note)
2110                           (t nil))
2111      :really-assert
2112      (and for-real
2113           (not (and info
2114                     (ir1-attributep (fun-info-attributes info)
2115                                     explicit-check))))
2116      :where (if for-real
2117                 "previous declaration"
2118                 "previous definition"))))
2119
2120 ;;; Convert a lambda doing all the basic stuff we would do if we were
2121 ;;; converting a DEFUN. In the old CMU CL system, this was used both
2122 ;;; by the %DEFUN translator and for global inline expansion, but
2123 ;;; since sbcl-0.pre7.something %DEFUN does things differently.
2124 ;;; FIXME: And now it's probably worth rethinking whether this
2125 ;;; function is a good idea.
2126 ;;;
2127 ;;; Unless a :INLINE function, we temporarily clobber the inline
2128 ;;; expansion. This prevents recursive inline expansion of
2129 ;;; opportunistic pseudo-inlines.
2130 (defun ir1-convert-lambda-for-defun (lambda var expansion converter)
2131   (declare (cons lambda) (function converter) (type defined-fun var))
2132   (let ((var-expansion (defined-fun-inline-expansion var)))
2133     (unless (eq (defined-fun-inlinep var) :inline)
2134       (setf (defined-fun-inline-expansion var) nil))
2135     (let* ((name (leaf-source-name var))
2136            (fun (funcall converter lambda
2137                          :source-name name))
2138            (fun-info (info :function :info name)))
2139       (setf (functional-inlinep fun) (defined-fun-inlinep var))
2140       (assert-new-definition var fun)
2141       (setf (defined-fun-inline-expansion var) var-expansion)
2142       ;; If definitely not an interpreter stub, then substitute for
2143       ;; any old references.
2144       (unless (or (eq (defined-fun-inlinep var) :notinline)
2145                   (not *block-compile*)
2146                   (and fun-info
2147                        (or (fun-info-transforms fun-info)
2148                            (fun-info-templates fun-info)
2149                            (fun-info-ir2-convert fun-info))))
2150         (substitute-leaf fun var)
2151         ;; If in a simple environment, then we can allow backward
2152         ;; references to this function from following top level forms.
2153         (when expansion (setf (defined-fun-functional var) fun)))
2154       fun)))
2155
2156 ;;; the even-at-compile-time part of DEFUN
2157 ;;;
2158 ;;; The INLINE-EXPANSION is a LAMBDA-WITH-LEXENV, or NIL if there is
2159 ;;; no inline expansion.
2160 (defun %compiler-defun (name lambda-with-lexenv)
2161
2162   (let ((defined-fun nil)) ; will be set below if we're in the compiler
2163     
2164     (when (boundp '*lexenv*) ; when in the compiler
2165       (when sb!xc:*compile-print*
2166         (compiler-mumble "~&; recognizing DEFUN ~S~%" name))
2167       (remhash name *free-funs*)
2168       (setf defined-fun (get-defined-fun name)))
2169
2170     (become-defined-fun-name name)
2171
2172     (cond (lambda-with-lexenv
2173            (setf (info :function :inline-expansion-designator name)
2174                  lambda-with-lexenv)
2175            (when defined-fun 
2176              (setf (defined-fun-inline-expansion defined-fun)
2177                    lambda-with-lexenv)))
2178           (t
2179            (clear-info :function :inline-expansion-designator name)))
2180
2181     ;; old CMU CL comment:
2182     ;;   If there is a type from a previous definition, blast it,
2183     ;;   since it is obsolete.
2184     (when (and defined-fun
2185                (eq (leaf-where-from defined-fun) :defined))
2186       (setf (leaf-type defined-fun)
2187             ;; FIXME: If this is a block compilation thing, shouldn't
2188             ;; we be setting the type to the full derived type for the
2189             ;; definition, instead of this most general function type?
2190             (specifier-type 'function))))
2191
2192   (values))