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