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