02a58f831d4c0d8eec35285567d4ef0d0664c34b
[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 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* nil)
44
45 (defvar *derive-function-types* nil
46   "Should the compiler assume that function types will never change,
47   so that it can use type information inferred from current definitions
48   to optimize code which uses those definitions? Setting this true
49   gives non-ANSI, early-CMU-CL behavior. It can be useful for improving
50   the efficiency of stable code.")
51 \f
52 ;;;; namespace management utilities
53
54 ;;; Return a GLOBAL-VAR structure usable for referencing the global
55 ;;; function NAME.
56 (defun find-free-really-function (name)
57   (unless (info :function :kind name)
58     (setf (info :function :kind name) :function)
59     (setf (info :function :where-from name) :assumed))
60
61   (let ((where (info :function :where-from name)))
62     (when (and (eq where :assumed)
63                ;; In the ordinary target Lisp, it's silly to report
64                ;; undefinedness when the function is defined in the
65                ;; running Lisp. But at cross-compile time, the current
66                ;; definedness of a function is irrelevant to the
67                ;; definedness at runtime, which is what matters.
68                #-sb-xc-host (not (fboundp name)))
69       (note-undefined-reference name :function))
70     (make-global-var :kind :global-function
71                      :name name
72                      :type (if (or *derive-function-types*
73                                    (eq where :declared))
74                                (info :function :type name)
75                                (specifier-type 'function))
76                      :where-from where)))
77
78 ;;; Return a SLOT-ACCESSOR structure usable for referencing the slot
79 ;;; accessor NAME. CLASS is the structure class.
80 (defun find-structure-slot-accessor (class name)
81   (declare (type sb!xc:class class))
82   (let* ((info (layout-info
83                 (or (info :type :compiler-layout (sb!xc:class-name class))
84                     (class-layout class))))
85          (accessor (if (listp name) (cadr name) name))
86          (slot (find accessor (dd-slots info) :key #'sb!kernel:dsd-accessor))
87          (type (dd-name info))
88          (slot-type (dsd-type slot)))
89     (unless slot
90       (error "can't find slot ~S" type))
91     (make-slot-accessor
92      :name name
93      :type (specifier-type
94             (if (listp name)
95                 `(function (,slot-type ,type) ,slot-type)
96                 `(function (,type) ,slot-type)))
97      :for class
98      :slot slot)))
99
100 ;;; If NAME is already entered in *FREE-FUNCTIONS*, then return the
101 ;;; value. Otherwise, make a new GLOBAL-VAR using information from the
102 ;;; global environment and enter it in *FREE-FUNCTIONS*. If NAME names
103 ;;; a macro or special form, then we error out using the supplied
104 ;;; context which indicates what we were trying to do that demanded a
105 ;;; function.
106 (defun find-free-function (name context)
107   (declare (string context))
108   (declare (values global-var))
109   (or (gethash name *free-functions*)
110       (ecase (info :function :kind name)
111         ;; FIXME: The :MACRO and :SPECIAL-FORM cases could be merged.
112         (:macro
113          (compiler-error "The macro name ~S was found ~A." name context))
114         (:special-form
115          (compiler-error "The special form name ~S was found ~A."
116                          name
117                          context))
118         ((:function nil)
119          (check-function-name name)
120          (note-if-setf-function-and-macro name)
121          (let ((expansion (info :function :inline-expansion name))
122                (inlinep (info :function :inlinep name)))
123            (setf (gethash name *free-functions*)
124                  (if (or expansion inlinep)
125                      (make-defined-function
126                       :name name
127                       :inline-expansion expansion
128                       :inlinep inlinep
129                       :where-from (info :function :where-from name)
130                       :type (info :function :type name))
131                      (let ((info (info :function :accessor-for name)))
132                        (etypecase info
133                          (null
134                           (find-free-really-function name))
135                          (sb!xc:structure-class
136                           (find-structure-slot-accessor info name))
137                          (sb!xc:class
138                           (if (typep (layout-info (info :type :compiler-layout
139                                                         (sb!xc:class-name
140                                                          info)))
141                                      'defstruct-description)
142                               (find-structure-slot-accessor info name)
143                               (find-free-really-function name))))))))))))
144
145 ;;; Return the LEAF structure for the lexically apparent function
146 ;;; definition of NAME.
147 (declaim (ftype (function (t string) leaf) find-lexically-apparent-function))
148 (defun find-lexically-apparent-function (name context)
149   (let ((var (lexenv-find name functions :test #'equal)))
150     (cond (var
151            (unless (leaf-p var)
152              (aver (and (consp var) (eq (car var) 'macro)))
153              (compiler-error "found macro name ~S ~A" name context))
154            var)
155           (t
156            (find-free-function name context)))))
157
158 ;;; Return the LEAF node for a global variable reference to NAME. If
159 ;;; NAME is already entered in *FREE-VARIABLES*, then we just return
160 ;;; the corresponding value. Otherwise, we make a new leaf using
161 ;;; information from the global environment and enter it in
162 ;;; *FREE-VARIABLES*. If the variable is unknown, then we emit a
163 ;;; warning.
164 (defun find-free-variable (name)
165   (declare (values (or leaf heap-alien-info)))
166   (unless (symbolp name)
167     (compiler-error "Variable name is not a symbol: ~S." name))
168   (or (gethash name *free-variables*)
169       (let ((kind (info :variable :kind name))
170             (type (info :variable :type name))
171             (where-from (info :variable :where-from name)))
172         (when (and (eq where-from :assumed) (eq kind :global))
173           (note-undefined-reference name :variable))
174
175         (setf (gethash name *free-variables*)
176               (if (eq kind :alien)
177                   (info :variable :alien-info name)
178                   (multiple-value-bind (val valp)
179                       (info :variable :constant-value name)
180                     (if (and (eq kind :constant) valp)
181                         (make-constant :value val
182                                        :name name
183                                        :type (ctype-of val)
184                                        :where-from where-from)
185                         (make-global-var :kind kind
186                                          :name name
187                                          :type type
188                                          :where-from where-from))))))))
189 \f
190 ;;; Grovel over CONSTANT checking for any sub-parts that need to be
191 ;;; processed with MAKE-LOAD-FORM. We have to be careful, because
192 ;;; CONSTANT might be circular. We also check that the constant (and
193 ;;; any subparts) are dumpable at all.
194 (eval-when (:compile-toplevel :load-toplevel :execute)
195   ;; The EVAL-WHEN is necessary for #.(1+ LIST-TO-HASH-TABLE-THRESHOLD) 
196   ;; below. -- AL 20010227
197   (defconstant list-to-hash-table-threshold 32))
198 (defun maybe-emit-make-load-forms (constant)
199   (let ((things-processed nil)
200         (count 0))
201     ;; FIXME: Does this LIST-or-HASH-TABLE messiness give much benefit?
202     (declare (type (or list hash-table) things-processed)
203              (type (integer 0 #.(1+ list-to-hash-table-threshold)) count)
204              (inline member))
205     (labels ((grovel (value)
206                ;; Unless VALUE is an object which which obviously
207                ;; can't contain other objects
208                (unless (typep value
209                               '(or #-sb-xc-host unboxed-array
210                                    symbol
211                                    number
212                                    character
213                                    string))
214                  (etypecase things-processed
215                    (list
216                     (when (member value things-processed :test #'eq)
217                       (return-from grovel nil))
218                     (push value things-processed)
219                     (incf count)
220                     (when (> count list-to-hash-table-threshold)
221                       (let ((things things-processed))
222                         (setf things-processed
223                               (make-hash-table :test 'eq))
224                         (dolist (thing things)
225                           (setf (gethash thing things-processed) t)))))
226                    (hash-table
227                     (when (gethash value things-processed)
228                       (return-from grovel nil))
229                     (setf (gethash value things-processed) t)))
230                  (typecase value
231                    (cons
232                     (grovel (car value))
233                     (grovel (cdr value)))
234                    (simple-vector
235                     (dotimes (i (length value))
236                       (grovel (svref value i))))
237                    ((vector t)
238                     (dotimes (i (length value))
239                       (grovel (aref value i))))
240                    ((simple-array t)
241                     ;; Even though the (ARRAY T) branch does the exact
242                     ;; same thing as this branch we do this separately
243                     ;; so that the compiler can use faster versions of
244                     ;; array-total-size and row-major-aref.
245                     (dotimes (i (array-total-size value))
246                       (grovel (row-major-aref value i))))
247                    ((array t)
248                     (dotimes (i (array-total-size value))
249                       (grovel (row-major-aref value i))))
250                    (;; In the target SBCL, we can dump any instance,
251                     ;; but in the cross-compilation host,
252                     ;; %INSTANCE-FOO functions don't work on general
253                     ;; instances, only on STRUCTURE!OBJECTs.
254                     #+sb-xc-host structure!object
255                     #-sb-xc-host instance
256                     (when (emit-make-load-form value)
257                       (dotimes (i (%instance-length value))
258                         (grovel (%instance-ref value i)))))
259                    (t
260                     (compiler-error
261                      "Objects of type ~S can't be dumped into fasl files."
262                      (type-of value)))))))
263       (grovel constant)))
264   (values))
265 \f
266 ;;;; some flow-graph hacking utilities
267
268 ;;; This function sets up the back link between the node and the
269 ;;; continuation which continues at it.
270 #!-sb-fluid (declaim (inline prev-link))
271 (defun prev-link (node cont)
272   (declare (type node node) (type continuation cont))
273   (aver (not (continuation-next cont)))
274   (setf (continuation-next cont) node)
275   (setf (node-prev node) cont))
276
277 ;;; This function is used to set the continuation for a node, and thus
278 ;;; determine what receives the value and what is evaluated next. If
279 ;;; the continuation has no block, then we make it be in the block
280 ;;; that the node is in. If the continuation heads its block, we end
281 ;;; our block and link it to that block. If the continuation is not
282 ;;; currently used, then we set the derived-type for the continuation
283 ;;; to that of the node, so that a little type propagation gets done.
284 ;;;
285 ;;; We also deal with a bit of THE's semantics here: we weaken the
286 ;;; assertion on CONT to be no stronger than the assertion on CONT in
287 ;;; our scope. See the IR1-CONVERT method for THE.
288 #!-sb-fluid (declaim (inline use-continuation))
289 (defun use-continuation (node cont)
290   (declare (type node node) (type continuation cont))
291   (let ((node-block (continuation-block (node-prev node))))
292     (case (continuation-kind cont)
293       (:unused
294        (setf (continuation-block cont) node-block)
295        (setf (continuation-kind cont) :inside-block)
296        (setf (continuation-use cont) node)
297        (setf (node-cont node) cont))
298       (t
299        (%use-continuation node cont)))))
300 (defun %use-continuation (node cont)
301   (declare (type node node) (type continuation cont) (inline member))
302   (let ((block (continuation-block cont))
303         (node-block (continuation-block (node-prev node))))
304     (aver (eq (continuation-kind cont) :block-start))
305     (when (block-last node-block)
306       (error "~S has already ended." node-block))
307     (setf (block-last node-block) node)
308     (when (block-succ node-block)
309       (error "~S already has successors." node-block))
310     (setf (block-succ node-block) (list block))
311     (when (memq node-block (block-pred block))
312       (error "~S is already a predecessor of ~S." node-block block))
313     (push node-block (block-pred block))
314     (add-continuation-use node cont)
315     (unless (eq (continuation-asserted-type cont) *wild-type*)
316       (let ((new (values-type-union (continuation-asserted-type cont)
317                                     (or (lexenv-find cont type-restrictions)
318                                         *wild-type*))))
319         (when (type/= new (continuation-asserted-type cont))
320           (setf (continuation-asserted-type cont) new)
321           (reoptimize-continuation cont))))))
322 \f
323 ;;;; exported functions
324
325 ;;; This function takes a form and the top-level form number for that
326 ;;; form, and returns a lambda representing the translation of that
327 ;;; form in the current global environment. The lambda is top-level
328 ;;; lambda that can be called to cause evaluation of the forms. This
329 ;;; lambda is in the initial component. If FOR-VALUE is T, then the
330 ;;; value of the form is returned from the function, otherwise NIL is
331 ;;; returned.
332 ;;;
333 ;;; This function may have arbitrary effects on the global environment
334 ;;; due to processing of PROCLAIMs and EVAL-WHENs. All syntax error
335 ;;; checking is done, with erroneous forms being replaced by a proxy
336 ;;; which signals an error if it is evaluated. Warnings about possibly
337 ;;; inconsistent or illegal changes to the global environment will
338 ;;; also be given.
339 ;;;
340 ;;; We make the initial component and convert the form in a PROGN (and
341 ;;; an optional NIL tacked on the end.) We then return the lambda. We
342 ;;; bind all of our state variables here, rather than relying on the
343 ;;; global value (if any) so that IR1 conversion will be reentrant.
344 ;;; This is necessary for EVAL-WHEN processing, etc.
345 ;;;
346 ;;; The hashtables used to hold global namespace info must be
347 ;;; reallocated elsewhere. Note also that *LEXENV* is not bound, so
348 ;;; that local macro definitions can be introduced by enclosing code.
349 (defun ir1-top-level (form path for-value)
350   (declare (list path))
351   (let* ((*current-path* path)
352          (component (make-empty-component))
353          (*current-component* component))
354     (setf (component-name component) "initial component")
355     (setf (component-kind component) :initial)
356     (let* ((forms (if for-value `(,form) `(,form nil)))
357            (res (ir1-convert-lambda-body forms ())))
358       (setf (leaf-name res) "top-level form")
359       (setf (functional-entry-function res) res)
360       (setf (functional-arg-documentation res) ())
361       (setf (functional-kind res) :top-level)
362       res)))
363
364 ;;; *CURRENT-FORM-NUMBER* is used in FIND-SOURCE-PATHS to compute the
365 ;;; form number to associate with a source path. This should be bound
366 ;;; to 0 around the processing of each truly top-level form.
367 (declaim (type index *current-form-number*))
368 (defvar *current-form-number*)
369
370 ;;; This function is called on freshly read forms to record the
371 ;;; initial location of each form (and subform.) Form is the form to
372 ;;; find the paths in, and TLF-NUM is the top-level form number of the
373 ;;; truly top-level form.
374 ;;;
375 ;;; This gets a bit interesting when the source code is circular. This
376 ;;; can (reasonably?) happen in the case of circular list constants.
377 (defun find-source-paths (form tlf-num)
378   (declare (type index tlf-num))
379   (let ((*current-form-number* 0))
380     (sub-find-source-paths form (list tlf-num)))
381   (values))
382 (defun sub-find-source-paths (form path)
383   (unless (gethash form *source-paths*)
384     (setf (gethash form *source-paths*)
385           (list* 'original-source-start *current-form-number* path))
386     (incf *current-form-number*)
387     (let ((pos 0)
388           (subform form)
389           (trail form))
390       (declare (fixnum pos))
391       (macrolet ((frob ()
392                    '(progn
393                       (when (atom subform) (return))
394                       (let ((fm (car subform)))
395                         (when (consp fm)
396                           (sub-find-source-paths fm (cons pos path)))
397                         (incf pos))
398                       (setq subform (cdr subform))
399                       (when (eq subform trail) (return)))))
400         (loop
401           (frob)
402           (frob)
403           (setq trail (cdr trail)))))))
404 \f
405 ;;;; IR1-CONVERT, macroexpansion and special form dispatching
406
407 (macrolet (;; Bind *COMPILER-ERROR-BAILOUT* to a function that throws
408            ;; out of the body and converts a proxy form instead.
409            (ir1-error-bailout ((start
410                                 cont
411                                 form
412                                 &optional
413                                 (proxy ``(error "execution of a form compiled with errors:~% ~S"
414                                                 ',,form)))
415                                &body body)
416                               (let ((skip (gensym "SKIP")))
417                                 `(block ,skip
418                                    (catch 'ir1-error-abort
419                                      (let ((*compiler-error-bailout*
420                                             (lambda ()
421                                               (throw 'ir1-error-abort nil))))
422                                        ,@body
423                                        (return-from ,skip nil)))
424                                    (ir1-convert ,start ,cont ,proxy)))))
425
426   ;; Translate FORM into IR1. The code is inserted as the NEXT of the
427   ;; continuation START. CONT is the continuation which receives the
428   ;; value of the FORM to be translated. The translators call this
429   ;; function recursively to translate their subnodes.
430   ;;
431   ;; As a special hack to make life easier in the compiler, a LEAF
432   ;; IR1-converts into a reference to that LEAF structure. This allows
433   ;; the creation using backquote of forms that contain leaf
434   ;; references, without having to introduce dummy names into the
435   ;; namespace.
436   (declaim (ftype (function (continuation continuation t) (values)) ir1-convert))
437   (defun ir1-convert (start cont form)
438     (ir1-error-bailout (start cont form)
439       (let ((*current-path* (or (gethash form *source-paths*)
440                                 (cons form *current-path*))))
441         (if (atom form)
442             (cond ((and (symbolp form) (not (keywordp form)))
443                    (ir1-convert-variable start cont form))
444                   ((leaf-p form)
445                    (reference-leaf start cont form))
446                   (t
447                    (reference-constant start cont form)))
448             (let ((fun (car form)))
449               (cond
450                ((symbolp fun)
451                 (let ((lexical-def (lexenv-find fun functions)))
452                   (typecase lexical-def
453                     (null (ir1-convert-global-functoid start cont form))
454                     (functional
455                      (ir1-convert-local-combination start
456                                                     cont
457                                                     form
458                                                     lexical-def))
459                     (global-var
460                      (ir1-convert-srctran start cont lexical-def form))
461                     (t
462                      (aver (and (consp lexical-def)
463                                 (eq (car lexical-def) 'macro)))
464                      (ir1-convert start cont
465                                   (careful-expand-macro (cdr lexical-def)
466                                                         form))))))
467                ((or (atom fun) (not (eq (car fun) 'lambda)))
468                 (compiler-error "illegal function call"))
469                (t
470                 (ir1-convert-combination start
471                                          cont
472                                          form
473                                          (ir1-convert-lambda fun))))))))
474     (values))
475
476   ;; Generate a reference to a manifest constant, creating a new leaf
477   ;; if necessary. If we are producing a fasl file, make sure that
478   ;; MAKE-LOAD-FORM gets used on any parts of the constant that it
479   ;; needs to be.
480   (defun reference-constant (start cont value)
481     (declare (type continuation start cont)
482              (inline find-constant))
483     (ir1-error-bailout
484      (start cont value
485             '(error "attempt to reference undumpable constant"))
486      (when (producing-fasl-file)
487        (maybe-emit-make-load-forms value))
488      (let* ((leaf (find-constant value))
489             (res (make-ref (leaf-type leaf) leaf)))
490        (push res (leaf-refs leaf))
491        (prev-link res start)
492        (use-continuation res cont)))
493     (values)))
494
495 ;;; Add Fun to the COMPONENT-REANALYZE-FUNCTIONS. Fun is returned.
496  (defun maybe-reanalyze-function (fun)
497   (declare (type functional fun))
498   (when (typep fun '(or optional-dispatch clambda))
499     (pushnew fun (component-reanalyze-functions *current-component*)))
500   fun)
501
502 ;;; Generate a Ref node for LEAF, frobbing the LEAF structure as
503 ;;; needed. If LEAF represents a defined function which has already
504 ;;; been converted, and is not :NOTINLINE, then reference the
505 ;;; functional instead.
506 (defun reference-leaf (start cont leaf)
507   (declare (type continuation start cont) (type leaf leaf))
508   (let* ((leaf (or (and (defined-function-p leaf)
509                         (not (eq (defined-function-inlinep leaf)
510                                  :notinline))
511                         (let ((fun (defined-function-functional leaf)))
512                           (when (and fun (not (functional-kind fun)))
513                             (maybe-reanalyze-function fun))))
514                    leaf))
515          (res (make-ref (or (lexenv-find leaf type-restrictions)
516                             (leaf-type leaf))
517                         leaf)))
518     (push res (leaf-refs leaf))
519     (setf (leaf-ever-used leaf) t)
520     (prev-link res start)
521     (use-continuation res cont)))
522
523 ;;; Convert a reference to a symbolic constant or variable. If the
524 ;;; symbol is entered in the LEXENV-VARIABLES we use that definition,
525 ;;; otherwise we find the current global definition. This is also
526 ;;; where we pick off symbol macro and Alien variable references.
527 (defun ir1-convert-variable (start cont name)
528   (declare (type continuation start cont) (symbol name))
529   (let ((var (or (lexenv-find name variables) (find-free-variable name))))
530     (etypecase var
531       (leaf
532        (when (and (lambda-var-p var) (lambda-var-ignorep var))
533          ;; (ANSI's specification for the IGNORE declaration requires
534          ;; that this be a STYLE-WARNING, not a full WARNING.)
535          (compiler-style-warning "reading an ignored variable: ~S" name))
536        (reference-leaf start cont var))
537       (cons
538        (aver (eq (car var) 'MACRO))
539        (ir1-convert start cont (cdr var)))
540       (heap-alien-info
541        (ir1-convert start cont `(%heap-alien ',var)))))
542   (values))
543
544 ;;; Convert anything that looks like a special form, global function
545 ;;; or macro call.
546 (defun ir1-convert-global-functoid (start cont form)
547   (declare (type continuation start cont) (list form))
548   (let* ((fun (first form))
549          (translator (info :function :ir1-convert fun))
550          (cmacro (info :function :compiler-macro-function fun)))
551     (cond (translator (funcall translator start cont form))
552           ((and cmacro
553                 (not (eq (info :function :inlinep fun)
554                          :notinline)))
555            (let ((res (careful-expand-macro cmacro form)))
556              (if (eq res form)
557                  (ir1-convert-global-functoid-no-cmacro start cont form fun)
558                  (ir1-convert start cont res))))
559           (t
560            (ir1-convert-global-functoid-no-cmacro start cont form fun)))))
561
562 ;;; Handle the case of where the call was not a compiler macro, or was a
563 ;;; compiler macro and passed.
564 (defun ir1-convert-global-functoid-no-cmacro (start cont form fun)
565   (declare (type continuation start cont) (list form))
566   ;; FIXME: Couldn't all the INFO calls here be converted into
567   ;; standard CL functions, like MACRO-FUNCTION or something?
568   ;; And what happens with lexically-defined (MACROLET) macros
569   ;; here, anyway?
570   (ecase (info :function :kind fun)
571     (:macro
572      (ir1-convert start
573                   cont
574                   (careful-expand-macro (info :function :macro-function fun)
575                                         form)))
576     ((nil :function)
577      (ir1-convert-srctran start cont (find-free-function fun "Eh?") form))))
578
579 (defun muffle-warning-or-die ()
580   (muffle-warning)
581   (error "internal error -- no MUFFLE-WARNING restart"))
582
583 ;;; Expand FORM using the macro whose MACRO-FUNCTION is FUN, trapping
584 ;;; errors which occur during the macroexpansion.
585 (defun careful-expand-macro (fun form)
586   (handler-bind (;; When cross-compiling, we can get style warnings
587                  ;; about e.g. undefined functions. An unhandled
588                  ;; CL:STYLE-WARNING (as opposed to a
589                  ;; SB!C::COMPILER-NOTE) would cause FAILURE-P to be
590                  ;; set on the return from #'SB!XC:COMPILE-FILE, which
591                  ;; would falsely indicate an error sufficiently
592                  ;; serious that we should stop the build process. To
593                  ;; avoid this, we translate CL:STYLE-WARNING
594                  ;; conditions from the host Common Lisp into
595                  ;; cross-compiler SB!C::COMPILER-NOTE calls. (It
596                  ;; might be cleaner to just make Python use
597                  ;; CL:STYLE-WARNING internally, so that the
598                  ;; significance of any host Common Lisp
599                  ;; CL:STYLE-WARNINGs is understood automatically. But
600                  ;; for now I'm not motivated to do this. -- WHN
601                  ;; 19990412)
602                  (style-warning (lambda (c)
603                                   (compiler-note "(during macroexpansion)~%~A"
604                                                  c)
605                                   (muffle-warning-or-die)))
606                  ;; KLUDGE: CMU CL in its wisdom (version 2.4.6 for
607                  ;; Debian Linux, anyway) raises a CL:WARNING
608                  ;; condition (not a CL:STYLE-WARNING) for undefined
609                  ;; symbols when converting interpreted functions,
610                  ;; causing COMPILE-FILE to think the file has a real
611                  ;; problem, causing COMPILE-FILE to return FAILURE-P
612                  ;; set (not just WARNINGS-P set). Since undefined
613                  ;; symbol warnings are often harmless forward
614                  ;; references, and since it'd be inordinately painful
615                  ;; to try to eliminate all such forward references,
616                  ;; these warnings are basically unavoidable. Thus, we
617                  ;; need to coerce the system to work through them,
618                  ;; and this code does so, by crudely suppressing all
619                  ;; warnings in cross-compilation macroexpansion. --
620                  ;; WHN 19990412
621                  #+cmu
622                  (warning (lambda (c)
623                             (compiler-note
624                              "(during macroexpansion)~%~
625                               ~A~%~
626                               (KLUDGE: That was a non-STYLE WARNING.~%~
627                               Ordinarily that would cause compilation to~%~
628                               fail. However, since we're running under~%~
629                               CMU CL, and since CMU CL emits non-STYLE~%~
630                               warnings for safe, hard-to-fix things (e.g.~%~
631                               references to not-yet-defined functions)~%~
632                               we're going to have to ignore it and proceed~%~
633                               anyway. Hopefully we're not ignoring anything~%~
634                               horrible here..)~%"
635                              c)
636                             (muffle-warning-or-die)))
637                  (error (lambda (c)
638                           (compiler-error "(during macroexpansion)~%~A" c))))
639     (funcall sb!xc:*macroexpand-hook*
640              fun
641              form
642              *lexenv*)))
643 \f
644 ;;;; conversion utilities
645
646 ;;; Convert a bunch of forms, discarding all the values except the
647 ;;; last. If there aren't any forms, then translate a NIL.
648 (declaim (ftype (function (continuation continuation list) (values))
649                 ir1-convert-progn-body))
650 (defun ir1-convert-progn-body (start cont body)
651   (if (endp body)
652       (reference-constant start cont nil)
653       (let ((this-start start)
654             (forms body))
655         (loop
656           (let ((form (car forms)))
657             (when (endp (cdr forms))
658               (ir1-convert this-start cont form)
659               (return))
660             (let ((this-cont (make-continuation)))
661               (ir1-convert this-start this-cont form)
662               (setq this-start this-cont  forms (cdr forms)))))))
663   (values))
664 \f
665 ;;;; converting combinations
666
667 ;;; Convert a function call where the function (Fun) is a Leaf. We
668 ;;; return the Combination node so that we can poke at it if we want to.
669 (declaim (ftype (function (continuation continuation list leaf) combination)
670                 ir1-convert-combination))
671 (defun ir1-convert-combination (start cont form fun)
672   (let ((fun-cont (make-continuation)))
673     (reference-leaf start fun-cont fun)
674     (ir1-convert-combination-args fun-cont cont (cdr form))))
675
676 ;;; Convert the arguments to a call and make the Combination node. Fun-Cont
677 ;;; is the continuation which yields the function to call. Form is the source
678 ;;; for the call. Args is the list of arguments for the call, which defaults
679 ;;; to the cdr of source. We return the Combination node.
680 (defun ir1-convert-combination-args (fun-cont cont args)
681   (declare (type continuation fun-cont cont) (list args))
682   (let ((node (make-combination fun-cont)))
683     (setf (continuation-dest fun-cont) node)
684     (assert-continuation-type fun-cont
685                               (specifier-type '(or function symbol)))
686     (collect ((arg-conts))
687       (let ((this-start fun-cont))
688         (dolist (arg args)
689           (let ((this-cont (make-continuation node)))
690             (ir1-convert this-start this-cont arg)
691             (setq this-start this-cont)
692             (arg-conts this-cont)))
693         (prev-link node this-start)
694         (use-continuation node cont)
695         (setf (combination-args node) (arg-conts))))
696     node))
697
698 ;;; Convert a call to a global function. If not :NOTINLINE, then we do
699 ;;; source transforms and try out any inline expansion. If there is no
700 ;;; expansion, but is :INLINE, then give an efficiency note (unless a
701 ;;; known function which will quite possibly be open-coded.) Next, we
702 ;;; go to ok-combination conversion.
703 (defun ir1-convert-srctran (start cont var form)
704   (declare (type continuation start cont) (type global-var var))
705   (let ((inlinep (when (defined-function-p var)
706                    (defined-function-inlinep var))))
707     (if (eq inlinep :notinline)
708         (ir1-convert-combination start cont form var)
709         (let ((transform (info :function :source-transform (leaf-name var))))
710           (if transform
711               (multiple-value-bind (result pass) (funcall transform form)
712                 (if pass
713                     (ir1-convert-maybe-predicate start cont form var)
714                     (ir1-convert start cont result)))
715               (ir1-convert-maybe-predicate start cont form var))))))
716
717 ;;; If the function has the PREDICATE attribute, and the CONT's DEST
718 ;;; isn't an IF, then we convert (IF <form> T NIL), ensuring that a
719 ;;; predicate always appears in a conditional context.
720 ;;;
721 ;;; If the function isn't a predicate, then we call
722 ;;; IR1-CONVERT-COMBINATION-CHECKING-TYPE.
723 (defun ir1-convert-maybe-predicate (start cont form var)
724   (declare (type continuation start cont) (list form) (type global-var var))
725   (let ((info (info :function :info (leaf-name var))))
726     (if (and info
727              (ir1-attributep (function-info-attributes info) predicate)
728              (not (if-p (continuation-dest cont))))
729         (ir1-convert start cont `(if ,form t nil))
730         (ir1-convert-combination-checking-type start cont form var))))
731
732 ;;; Actually really convert a global function call that we are allowed
733 ;;; to early-bind.
734 ;;;
735 ;;; If we know the function type of the function, then we check the
736 ;;; call for syntactic legality with respect to the declared function
737 ;;; type. If it is impossible to determine whether the call is correct
738 ;;; due to non-constant keywords, then we give up, marking the call as
739 ;;; :FULL to inhibit further error messages. We return true when the
740 ;;; call is legal.
741 ;;;
742 ;;; If the call is legal, we also propagate type assertions from the
743 ;;; function type to the arg and result continuations. We do this now
744 ;;; so that IR1 optimize doesn't have to redundantly do the check
745 ;;; later so that it can do the type propagation.
746 (defun ir1-convert-combination-checking-type (start cont form var)
747   (declare (type continuation start cont) (list form) (type leaf var))
748   (let* ((node (ir1-convert-combination start cont form var))
749          (fun-cont (basic-combination-fun node))
750          (type (leaf-type var)))
751     (when (validate-call-type node type t)
752       (setf (continuation-%derived-type fun-cont) type)
753       (setf (continuation-reoptimize fun-cont) nil)
754       (setf (continuation-%type-check fun-cont) nil)))
755
756   (values))
757
758 ;;; Convert a call to a local function. If the function has already
759 ;;; been let converted, then throw FUN to LOCAL-CALL-LOSSAGE. This
760 ;;; should only happen when we are converting inline expansions for
761 ;;; local functions during optimization.
762 (defun ir1-convert-local-combination (start cont form fun)
763   (if (functional-kind fun)
764       (throw 'local-call-lossage fun)
765       (ir1-convert-combination start cont form
766                                (maybe-reanalyze-function fun))))
767 \f
768 ;;;; PROCESS-DECLS
769
770 ;;; Given a list of Lambda-Var structures and a variable name, return
771 ;;; the structure for that name, or NIL if it isn't found. We return
772 ;;; the *last* variable with that name, since LET* bindings may be
773 ;;; duplicated, and declarations always apply to the last.
774 (declaim (ftype (function (list symbol) (or lambda-var list))
775                 find-in-bindings))
776 (defun find-in-bindings (vars name)
777   (let ((found nil))
778     (dolist (var vars)
779       (cond ((leaf-p var)
780              (when (eq (leaf-name var) name)
781                (setq found var))
782              (let ((info (lambda-var-arg-info var)))
783                (when info
784                  (let ((supplied-p (arg-info-supplied-p info)))
785                    (when (and supplied-p
786                               (eq (leaf-name supplied-p) name))
787                      (setq found supplied-p))))))
788             ((and (consp var) (eq (car var) name))
789              (setf found (cdr var)))))
790     found))
791
792 ;;; Called by Process-Decls to deal with a variable type declaration.
793 ;;; If a lambda-var being bound, we intersect the type with the vars
794 ;;; type, otherwise we add a type-restriction on the var. If a symbol
795 ;;; macro, we just wrap a THE around the expansion.
796 (defun process-type-decl (decl res vars)
797   (declare (list decl vars) (type lexenv res))
798   (let ((type (specifier-type (first decl))))
799     (collect ((restr nil cons)
800               (new-vars nil cons))
801       (dolist (var-name (rest decl))
802         (let* ((bound-var (find-in-bindings vars var-name))
803                (var (or bound-var
804                         (lexenv-find var-name variables)
805                         (find-free-variable var-name))))
806           (etypecase var
807             (leaf
808              (let* ((old-type (or (lexenv-find var type-restrictions)
809                                   (leaf-type var)))
810                     (int (if (or (function-type-p type)
811                                  (function-type-p old-type))
812                              type
813                              (type-approx-intersection2 old-type type))))
814                (cond ((eq int *empty-type*)
815                       (unless (policy *lexenv* (= inhibit-warnings 3))
816                         (compiler-warning
817                          "The type declarations ~S and ~S for ~S conflict."
818                          (type-specifier old-type) (type-specifier type)
819                          var-name)))
820                      (bound-var (setf (leaf-type bound-var) int))
821                      (t
822                       (restr (cons var int))))))
823             (cons
824              ;; FIXME: non-ANSI weirdness
825              (aver (eq (car var) 'MACRO))
826              (new-vars `(,var-name . (MACRO . (the ,(first decl)
827                                                    ,(cdr var))))))
828             (heap-alien-info
829              (compiler-error
830               "~S is an alien variable, so its type can't be declared."
831               var-name)))))
832
833       (if (or (restr) (new-vars))
834           (make-lexenv :default res
835                        :type-restrictions (restr)
836                        :variables (new-vars))
837           res))))
838
839 ;;; This is somewhat similar to PROCESS-TYPE-DECL, but handles
840 ;;; declarations for function variables. In addition to allowing
841 ;;; declarations for functions being bound, we must also deal with
842 ;;; declarations that constrain the type of lexically apparent
843 ;;; functions.
844 (defun process-ftype-decl (spec res names fvars)
845   (declare (list spec names fvars) (type lexenv res))
846   (let ((type (specifier-type spec)))
847     (collect ((res nil cons))
848       (dolist (name names)
849         (let ((found (find name fvars :key #'leaf-name :test #'equal)))
850           (cond
851            (found
852             (setf (leaf-type found) type)
853             (assert-definition-type found type
854                                     :warning-function #'compiler-note
855                                     :where "FTYPE declaration"))
856            (t
857             (res (cons (find-lexically-apparent-function
858                         name "in a function type declaration")
859                        type))))))
860       (if (res)
861           (make-lexenv :default res :type-restrictions (res))
862           res))))
863
864 ;;; Process a special declaration, returning a new LEXENV. A non-bound
865 ;;; special declaration is instantiated by throwing a special variable
866 ;;; into the variables.
867 (defun process-special-decl (spec res vars)
868   (declare (list spec vars) (type lexenv res))
869   (collect ((new-venv nil cons))
870     (dolist (name (cdr spec))
871       (let ((var (find-in-bindings vars name)))
872         (etypecase var
873           (cons
874            (aver (eq (car var) 'MACRO))
875            (compiler-error
876             "~S is a symbol-macro and thus can't be declared special."
877             name))
878           (lambda-var
879            (when (lambda-var-ignorep var)
880              ;; ANSI's definition for "Declaration IGNORE, IGNORABLE"
881              ;; requires that this be a STYLE-WARNING, not a full WARNING.
882              (compiler-style-warning
883               "The ignored variable ~S is being declared special."
884               name))
885            (setf (lambda-var-specvar var)
886                  (specvar-for-binding name)))
887           (null
888            (unless (assoc name (new-venv) :test #'eq)
889              (new-venv (cons name (specvar-for-binding name))))))))
890     (if (new-venv)
891         (make-lexenv :default res :variables (new-venv))
892         res)))
893
894 ;;; Return a DEFINED-FUNCTION which copies a global-var but for its inlinep.
895 (defun make-new-inlinep (var inlinep)
896   (declare (type global-var var) (type inlinep inlinep))
897   (let ((res (make-defined-function
898               :name (leaf-name var)
899               :where-from (leaf-where-from var)
900               :type (leaf-type var)
901               :inlinep inlinep)))
902     (when (defined-function-p var)
903       (setf (defined-function-inline-expansion res)
904             (defined-function-inline-expansion var))
905       (setf (defined-function-functional res)
906             (defined-function-functional var)))
907     res))
908
909 ;;; Parse an inline/notinline declaration. If it's a local function we're
910 ;;; defining, set its INLINEP. If a global function, add a new FENV entry.
911 (defun process-inline-decl (spec res fvars)
912   (let ((sense (cdr (assoc (first spec) *inlinep-translations* :test #'eq)))
913         (new-fenv ()))
914     (dolist (name (rest spec))
915       (let ((fvar (find name fvars :key #'leaf-name :test #'equal)))
916         (if fvar
917             (setf (functional-inlinep fvar) sense)
918             (let ((found
919                    (find-lexically-apparent-function
920                     name "in an inline or notinline declaration")))
921               (etypecase found
922                 (functional
923                  (when (policy *lexenv* (>= speed inhibit-warnings))
924                    (compiler-note "ignoring ~A declaration not at ~
925                                    definition of local function:~%  ~S"
926                                   sense name)))
927                 (global-var
928                  (push (cons name (make-new-inlinep found sense))
929                        new-fenv)))))))
930
931     (if new-fenv
932         (make-lexenv :default res :functions new-fenv)
933         res)))
934
935 ;;; Like FIND-IN-BINDINGS, but looks for #'foo in the fvars.
936 (defun find-in-bindings-or-fbindings (name vars fvars)
937   (declare (list vars fvars))
938   (if (consp name)
939       (destructuring-bind (wot fn-name) name
940         (unless (eq wot 'function)
941           (compiler-error "The function or variable name ~S is unrecognizable."
942                           name))
943         (find fn-name fvars :key #'leaf-name :test #'equal))
944       (find-in-bindings vars name)))
945
946 ;;; Process an ignore/ignorable declaration, checking for various losing
947 ;;; conditions.
948 (defun process-ignore-decl (spec vars fvars)
949   (declare (list spec vars fvars))
950   (dolist (name (rest spec))
951     (let ((var (find-in-bindings-or-fbindings name vars fvars)))
952       (cond
953        ((not var)
954         ;; ANSI's definition for "Declaration IGNORE, IGNORABLE"
955         ;; requires that this be a STYLE-WARNING, not a full WARNING.
956         (compiler-style-warning "declaring unknown variable ~S to be ignored"
957                                 name))
958        ;; FIXME: This special case looks like non-ANSI weirdness.
959        ((and (consp var) (consp (cdr var)) (eq (cadr var) 'macro))
960         ;; Just ignore the IGNORE decl.
961         )
962        ((functional-p var)
963         (setf (leaf-ever-used var) t))
964        ((lambda-var-specvar var)
965         ;; ANSI's definition for "Declaration IGNORE, IGNORABLE"
966         ;; requires that this be a STYLE-WARNING, not a full WARNING.
967         (compiler-style-warning "declaring special variable ~S to be ignored"
968                                 name))
969        ((eq (first spec) 'ignorable)
970         (setf (leaf-ever-used var) t))
971        (t
972         (setf (lambda-var-ignorep var) t)))))
973   (values))
974
975 ;;; FIXME: This is non-ANSI, so the default should be T, or it should
976 ;;; go away, I think.
977 (defvar *suppress-values-declaration* nil
978   #!+sb-doc
979   "If true, processing of the VALUES declaration is inhibited.")
980
981 ;;; Process a single declaration spec, augmenting the specified LEXENV
982 ;;; RES and returning it as a result. VARS and FVARS are as described in
983 ;;; PROCESS-DECLS.
984 (defun process-1-decl (raw-spec res vars fvars cont)
985   (declare (type list raw-spec vars fvars))
986   (declare (type lexenv res))
987   (declare (type continuation cont))
988   (let ((spec (canonized-decl-spec raw-spec)))
989     (case (first spec)
990       (special (process-special-decl spec res vars))
991       (ftype
992        (unless (cdr spec)
993          (compiler-error "No type specified in FTYPE declaration: ~S" spec))
994        (process-ftype-decl (second spec) res (cddr spec) fvars))
995       ((inline notinline maybe-inline)
996        (process-inline-decl spec res fvars))
997       ((ignore ignorable)
998        (process-ignore-decl spec vars fvars)
999        res)
1000       (optimize
1001        (make-lexenv
1002         :default res
1003         :policy (process-optimize-decl spec (lexenv-policy res))))
1004       (type
1005        (process-type-decl (cdr spec) res vars))
1006       (values
1007        (if *suppress-values-declaration*
1008            res
1009            (let ((types (cdr spec)))
1010              (do-the-stuff (if (eql (length types) 1)
1011                                (car types)
1012                                `(values ,@types))
1013                            cont res 'values))))
1014       (dynamic-extent
1015        (when (policy *lexenv* (> speed inhibit-warnings))
1016          (compiler-note
1017           "compiler limitation:~
1018            ~%  There's no special support for DYNAMIC-EXTENT (so it's ignored)."))
1019        res)
1020       (t
1021        (unless (info :declaration :recognized (first spec))
1022          (compiler-warning "unrecognized declaration ~S" raw-spec))
1023        res))))
1024
1025 ;;; Use a list of DECLARE forms to annotate the lists of LAMBDA-VAR
1026 ;;; and FUNCTIONAL structures which are being bound. In addition to
1027 ;;; filling in slots in the leaf structures, we return a new LEXENV
1028 ;;; which reflects pervasive special and function type declarations,
1029 ;;; (NOT)INLINE declarations and OPTIMIZE declarations. CONT is the
1030 ;;; continuation affected by VALUES declarations.
1031 ;;;
1032 ;;; This is also called in main.lisp when PROCESS-FORM handles a use
1033 ;;; of LOCALLY.
1034 (defun process-decls (decls vars fvars cont &optional (env *lexenv*))
1035   (declare (list decls vars fvars) (type continuation cont))
1036   (dolist (decl decls)
1037     (dolist (spec (rest decl))
1038       (unless (consp spec)
1039         (compiler-error "malformed declaration specifier ~S in ~S"
1040                         spec
1041                         decl))
1042       (setq env (process-1-decl spec env vars fvars cont))))
1043   env)
1044
1045 ;;; Return the SPECVAR for NAME to use when we see a local SPECIAL
1046 ;;; declaration. If there is a global variable of that name, then
1047 ;;; check that it isn't a constant and return it. Otherwise, create an
1048 ;;; anonymous GLOBAL-VAR.
1049 (defun specvar-for-binding (name)
1050   (cond ((not (eq (info :variable :where-from name) :assumed))
1051          (let ((found (find-free-variable name)))
1052            (when (heap-alien-info-p found)
1053              (compiler-error
1054               "~S is an alien variable and so can't be declared special."
1055               name))
1056            (when (or (not (global-var-p found))
1057                      (eq (global-var-kind found) :constant))
1058              (compiler-error
1059               "~S is a constant and so can't be declared special."
1060               name))
1061            found))
1062         (t
1063          (make-global-var :kind :special
1064                           :name name
1065                           :where-from :declared))))
1066 \f
1067 ;;;; LAMBDA hackery
1068
1069 ;;;; Note: Take a look at the compiler-overview.tex section on "Hairy
1070 ;;;; function representation" before you seriously mess with this
1071 ;;;; stuff.
1072
1073 ;;; Verify that a thing is a legal name for a variable and return a
1074 ;;; Var structure for it, filling in info if it is globally special.
1075 ;;; If it is losing, we punt with a Compiler-Error. Names-So-Far is an
1076 ;;; alist of names which have previously been bound. If the name is in
1077 ;;; this list, then we error out.
1078 (declaim (ftype (function (t list) lambda-var) varify-lambda-arg))
1079 (defun varify-lambda-arg (name names-so-far)
1080   (declare (inline member))
1081   (unless (symbolp name)
1082     (compiler-error "The lambda-variable ~S is not a symbol." name))
1083   (when (member name names-so-far :test #'eq)
1084     (compiler-error "The variable ~S occurs more than once in the lambda-list."
1085                     name))
1086   (let ((kind (info :variable :kind name)))
1087     (when (or (keywordp name) (eq kind :constant))
1088       (compiler-error "The name of the lambda-variable ~S is a constant."
1089                       name))
1090     (cond ((eq kind :special)
1091            (let ((specvar (find-free-variable name)))
1092              (make-lambda-var :name name
1093                               :type (leaf-type specvar)
1094                               :where-from (leaf-where-from specvar)
1095                               :specvar specvar)))
1096           (t
1097            (note-lexical-binding name)
1098            (make-lambda-var :name name)))))
1099
1100 ;;; Make the default keyword for a &KEY arg, checking that the keyword
1101 ;;; isn't already used by one of the VARS. We also check that the
1102 ;;; keyword isn't the magical :ALLOW-OTHER-KEYS.
1103 (declaim (ftype (function (symbol list t) keyword) make-keyword-for-arg))
1104 (defun make-keyword-for-arg (symbol vars keywordify)
1105   (let ((key (if (and keywordify (not (keywordp symbol)))
1106                  (keywordicate symbol)
1107                  symbol)))
1108     (when (eq key :allow-other-keys)
1109       (compiler-error "No &KEY arg can be called :ALLOW-OTHER-KEYS."))
1110     (dolist (var vars)
1111       (let ((info (lambda-var-arg-info var)))
1112         (when (and info
1113                    (eq (arg-info-kind info) :keyword)
1114                    (eq (arg-info-key info) key))
1115           (compiler-error
1116            "The keyword ~S appears more than once in the lambda-list."
1117            key))))
1118     key))
1119
1120 ;;; Parse a lambda-list into a list of VAR structures, stripping off
1121 ;;; any aux bindings. Each arg name is checked for legality, and
1122 ;;; duplicate names are checked for. If an arg is globally special,
1123 ;;; the var is marked as :SPECIAL instead of :LEXICAL. &KEY,
1124 ;;; &OPTIONAL and &REST args are annotated with an ARG-INFO structure
1125 ;;; which contains the extra information. If we hit something losing,
1126 ;;; we bug out with COMPILER-ERROR. These values are returned:
1127 ;;;  1. a list of the var structures for each top-level argument;
1128 ;;;  2. a flag indicating whether &KEY was specified;
1129 ;;;  3. a flag indicating whether other &KEY args are allowed;
1130 ;;;  4. a list of the &AUX variables; and
1131 ;;;  5. a list of the &AUX values.
1132 (declaim (ftype (function (list) (values list boolean boolean list list))
1133                 find-lambda-vars))
1134 (defun find-lambda-vars (list)
1135   (multiple-value-bind (required optional restp rest keyp keys allowp aux
1136                         morep more-context more-count)
1137       (parse-lambda-list list)
1138     (collect ((vars)
1139               (names-so-far)
1140               (aux-vars)
1141               (aux-vals))
1142       (flet (;; PARSE-DEFAULT deals with defaults and supplied-p args
1143              ;; for optionals and keywords args.
1144              (parse-default (spec info)
1145                (when (consp (cdr spec))
1146                  (setf (arg-info-default info) (second spec))
1147                  (when (consp (cddr spec))
1148                    (let* ((supplied-p (third spec))
1149                           (supplied-var (varify-lambda-arg supplied-p
1150                                                            (names-so-far))))
1151                      (setf (arg-info-supplied-p info) supplied-var)
1152                      (names-so-far supplied-p)
1153                      (when (> (length (the list spec)) 3)
1154                        (compiler-error
1155                         "The list ~S is too long to be an arg specifier."
1156                         spec)))))))
1157         
1158         (dolist (name required)
1159           (let ((var (varify-lambda-arg name (names-so-far))))
1160             (vars var)
1161             (names-so-far name)))
1162         
1163         (dolist (spec optional)
1164           (if (atom spec)
1165               (let ((var (varify-lambda-arg spec (names-so-far))))
1166                 (setf (lambda-var-arg-info var) (make-arg-info :kind :optional))
1167                 (vars var)
1168                 (names-so-far spec))
1169               (let* ((name (first spec))
1170                      (var (varify-lambda-arg name (names-so-far)))
1171                      (info (make-arg-info :kind :optional)))
1172                 (setf (lambda-var-arg-info var) info)
1173                 (vars var)
1174                 (names-so-far name)
1175                 (parse-default spec info))))
1176         
1177         (when restp
1178           (let ((var (varify-lambda-arg rest (names-so-far))))
1179             (setf (lambda-var-arg-info var) (make-arg-info :kind :rest))
1180             (vars var)
1181             (names-so-far rest)))
1182
1183         (when morep
1184           (let ((var (varify-lambda-arg more-context (names-so-far))))
1185             (setf (lambda-var-arg-info var)
1186                   (make-arg-info :kind :more-context))
1187             (vars var)
1188             (names-so-far more-context))
1189           (let ((var (varify-lambda-arg more-count (names-so-far))))
1190             (setf (lambda-var-arg-info var)
1191                   (make-arg-info :kind :more-count))
1192             (vars var)
1193             (names-so-far more-count)))
1194         
1195         (dolist (spec keys)
1196           (cond
1197            ((atom spec)
1198             (let ((var (varify-lambda-arg spec (names-so-far))))
1199               (setf (lambda-var-arg-info var)
1200                     (make-arg-info :kind :keyword
1201                                    :key (make-keyword-for-arg spec
1202                                                               (vars)
1203                                                               t)))
1204               (vars var)
1205               (names-so-far spec)))
1206            ((atom (first spec))
1207             (let* ((name (first spec))
1208                    (var (varify-lambda-arg name (names-so-far)))
1209                    (info (make-arg-info
1210                           :kind :keyword
1211                           :key (make-keyword-for-arg name (vars) t))))
1212               (setf (lambda-var-arg-info var) info)
1213               (vars var)
1214               (names-so-far name)
1215               (parse-default spec info)))
1216            (t
1217             (let ((head (first spec)))
1218               (unless (proper-list-of-length-p head 2)
1219                 (error "malformed &KEY argument specifier: ~S" spec))
1220               (let* ((name (second head))
1221                      (var (varify-lambda-arg name (names-so-far)))
1222                      (info (make-arg-info
1223                             :kind :keyword
1224                             :key (make-keyword-for-arg (first head)
1225                                                        (vars)
1226                                                        nil))))
1227                 (setf (lambda-var-arg-info var) info)
1228                 (vars var)
1229                 (names-so-far name)
1230                 (parse-default spec info))))))
1231         
1232         (dolist (spec aux)
1233           (cond ((atom spec)
1234                  (let ((var (varify-lambda-arg spec nil)))
1235                    (aux-vars var)
1236                    (aux-vals nil)
1237                    (names-so-far spec)))
1238                 (t
1239                  (unless (proper-list-of-length-p spec 1 2)
1240                    (compiler-error "malformed &AUX binding specifier: ~S"
1241                                    spec))
1242                  (let* ((name (first spec))
1243                         (var (varify-lambda-arg name nil)))
1244                    (aux-vars var)
1245                    (aux-vals (second spec))
1246                    (names-so-far name)))))
1247
1248         (values (vars) keyp allowp (aux-vars) (aux-vals))))))
1249
1250 ;;; This is similar to IR1-CONVERT-PROGN-BODY except that we
1251 ;;; sequentially bind each AUX-VAR to the corresponding AUX-VAL before
1252 ;;; converting the body. If there are no bindings, just convert the
1253 ;;; body, otherwise do one binding and recurse on the rest.
1254 (defun ir1-convert-aux-bindings (start cont body aux-vars aux-vals)
1255   (declare (type continuation start cont) (list body aux-vars aux-vals))
1256   (if (null aux-vars)
1257       (ir1-convert-progn-body start cont body)
1258       (let ((fun-cont (make-continuation))
1259             (fun (ir1-convert-lambda-body body
1260                                           (list (first aux-vars))
1261                                           :aux-vars (rest aux-vars)
1262                                           :aux-vals (rest aux-vals))))
1263         (reference-leaf start fun-cont fun)
1264         (ir1-convert-combination-args fun-cont cont
1265                                       (list (first aux-vals)))))
1266   (values))
1267
1268 ;;; This is similar to IR1-CONVERT-PROGN-BODY except that code to bind
1269 ;;; the SPECVAR for each SVAR to the value of the variable is wrapped
1270 ;;; around the body. If there are no special bindings, we just convert
1271 ;;; the body, otherwise we do one special binding and recurse on the
1272 ;;; rest.
1273 ;;;
1274 ;;; We make a cleanup and introduce it into the lexical environment.
1275 ;;; If there are multiple special bindings, the cleanup for the blocks
1276 ;;; will end up being the innermost one. We force CONT to start a
1277 ;;; block outside of this cleanup, causing cleanup code to be emitted
1278 ;;; when the scope is exited.
1279 (defun ir1-convert-special-bindings (start cont body aux-vars aux-vals svars)
1280   (declare (type continuation start cont)
1281            (list body aux-vars aux-vals svars))
1282   (cond
1283    ((null svars)
1284     (ir1-convert-aux-bindings start cont body aux-vars aux-vals))
1285    (t
1286     (continuation-starts-block cont)
1287     (let ((cleanup (make-cleanup :kind :special-bind))
1288           (var (first svars))
1289           (next-cont (make-continuation))
1290           (nnext-cont (make-continuation)))
1291       (ir1-convert start next-cont
1292                    `(%special-bind ',(lambda-var-specvar var) ,var))
1293       (setf (cleanup-mess-up cleanup) (continuation-use next-cont))
1294       (let ((*lexenv* (make-lexenv :cleanup cleanup)))
1295         (ir1-convert next-cont nnext-cont '(%cleanup-point))
1296         (ir1-convert-special-bindings nnext-cont cont body aux-vars aux-vals
1297                                       (rest svars))))))
1298   (values))
1299
1300 ;;; Create a lambda node out of some code, returning the result. The
1301 ;;; bindings are specified by the list of VAR structures VARS. We deal
1302 ;;; with adding the names to the LEXENV-VARIABLES for the conversion.
1303 ;;; The result is added to the NEW-FUNCTIONS in the
1304 ;;; *CURRENT-COMPONENT* and linked to the component head and tail.
1305 ;;;
1306 ;;; We detect special bindings here, replacing the original VAR in the
1307 ;;; lambda list with a temporary variable. We then pass a list of the
1308 ;;; special vars to IR1-CONVERT-SPECIAL-BINDINGS, which actually emits
1309 ;;; the special binding code.
1310 ;;;
1311 ;;; We ignore any ARG-INFO in the VARS, trusting that someone else is
1312 ;;; dealing with &nonsense.
1313 ;;;
1314 ;;; AUX-VARS is a list of VAR structures for variables that are to be
1315 ;;; sequentially bound. Each AUX-VAL is a form that is to be evaluated
1316 ;;; to get the initial value for the corresponding AUX-VAR. 
1317 (defun ir1-convert-lambda-body (body vars &key aux-vars aux-vals result)
1318   (declare (list body vars aux-vars aux-vals)
1319            (type (or continuation null) result))
1320   (let* ((bind (make-bind))
1321          (lambda (make-lambda :vars vars :bind bind))
1322          (result (or result (make-continuation))))
1323     (setf (lambda-home lambda) lambda)
1324     (collect ((svars)
1325               (new-venv nil cons))
1326
1327       (dolist (var vars)
1328         (setf (lambda-var-home var) lambda)
1329         (let ((specvar (lambda-var-specvar var)))
1330           (cond (specvar
1331                  (svars var)
1332                  (new-venv (cons (leaf-name specvar) specvar)))
1333                 (t
1334                  (note-lexical-binding (leaf-name var))
1335                  (new-venv (cons (leaf-name var) var))))))
1336
1337       (let ((*lexenv* (make-lexenv :variables (new-venv)
1338                                    :lambda lambda
1339                                    :cleanup nil)))
1340         (setf (bind-lambda bind) lambda)
1341         (setf (node-lexenv bind) *lexenv*)
1342         
1343         (let ((cont1 (make-continuation))
1344               (cont2 (make-continuation)))
1345           (continuation-starts-block cont1)
1346           (prev-link bind cont1)
1347           (use-continuation bind cont2)
1348           (ir1-convert-special-bindings cont2 result body aux-vars aux-vals
1349                                         (svars)))
1350
1351         (let ((block (continuation-block result)))
1352           (when block
1353             (let ((return (make-return :result result :lambda lambda))
1354                   (tail-set (make-tail-set :functions (list lambda)))
1355                   (dummy (make-continuation)))
1356               (setf (lambda-tail-set lambda) tail-set)
1357               (setf (lambda-return lambda) return)
1358               (setf (continuation-dest result) return)
1359               (setf (block-last block) return)
1360               (prev-link return result)
1361               (use-continuation return dummy))
1362             (link-blocks block (component-tail *current-component*))))))
1363
1364     (link-blocks (component-head *current-component*) (node-block bind))
1365     (push lambda (component-new-functions *current-component*))
1366     lambda))
1367
1368 ;;; Create the actual entry-point function for an optional entry
1369 ;;; point. The lambda binds copies of each of the VARS, then calls FUN
1370 ;;; with the argument VALS and the DEFAULTS. Presumably the VALS refer
1371 ;;; to the VARS by name. The VALS are passed in in reverse order.
1372 ;;;
1373 ;;; If any of the copies of the vars are referenced more than once,
1374 ;;; then we mark the corresponding var as EVER-USED to inhibit
1375 ;;; "defined but not read" warnings for arguments that are only used
1376 ;;; by default forms.
1377 (defun convert-optional-entry (fun vars vals defaults)
1378   (declare (type clambda fun) (list vars vals defaults))
1379   (let* ((fvars (reverse vars))
1380          (arg-vars (mapcar (lambda (var)
1381                              (unless (lambda-var-specvar var)
1382                                (note-lexical-binding (leaf-name var)))
1383                              (make-lambda-var
1384                               :name (leaf-name var)
1385                               :type (leaf-type var)
1386                               :where-from (leaf-where-from var)
1387                               :specvar (lambda-var-specvar var)))
1388                            fvars))
1389          (fun
1390           (ir1-convert-lambda-body `((%funcall ,fun
1391                                                ,@(reverse vals)
1392                                                ,@defaults))
1393                                    arg-vars)))
1394     (mapc (lambda (var arg-var)
1395             (when (cdr (leaf-refs arg-var))
1396               (setf (leaf-ever-used var) t)))
1397           fvars arg-vars)
1398     fun))
1399
1400 ;;; This function deals with supplied-p vars in optional arguments. If
1401 ;;; the there is no supplied-p arg, then we just call
1402 ;;; IR1-CONVERT-HAIRY-ARGS on the remaining arguments, and generate a
1403 ;;; optional entry that calls the result. If there is a supplied-p
1404 ;;; var, then we add it into the default vars and throw a T into the
1405 ;;; entry values. The resulting entry point function is returned.
1406 (defun generate-optional-default-entry (res default-vars default-vals
1407                                             entry-vars entry-vals
1408                                             vars supplied-p-p body
1409                                             aux-vars aux-vals cont)
1410   (declare (type optional-dispatch res)
1411            (list default-vars default-vals entry-vars entry-vals vars body
1412                  aux-vars aux-vals)
1413            (type (or continuation null) cont))
1414   (let* ((arg (first vars))
1415          (arg-name (leaf-name arg))
1416          (info (lambda-var-arg-info arg))
1417          (supplied-p (arg-info-supplied-p info))
1418          (ep (if supplied-p
1419                  (ir1-convert-hairy-args
1420                   res
1421                   (list* supplied-p arg default-vars)
1422                   (list* (leaf-name supplied-p) arg-name default-vals)
1423                   (cons arg entry-vars)
1424                   (list* t arg-name entry-vals)
1425                   (rest vars) t body aux-vars aux-vals cont)
1426                  (ir1-convert-hairy-args
1427                   res
1428                   (cons arg default-vars)
1429                   (cons arg-name default-vals)
1430                   (cons arg entry-vars)
1431                   (cons arg-name entry-vals)
1432                   (rest vars) supplied-p-p body aux-vars aux-vals cont))))
1433
1434     (convert-optional-entry ep default-vars default-vals
1435                             (if supplied-p
1436                                 (list (arg-info-default info) nil)
1437                                 (list (arg-info-default info))))))
1438
1439 ;;; Create the MORE-ENTRY function for the OPTIONAL-DISPATCH RES.
1440 ;;; ENTRY-VARS and ENTRY-VALS describe the fixed arguments. REST is
1441 ;;; the var for any &REST arg. KEYS is a list of the &KEY arg vars.
1442 ;;;
1443 ;;; The most interesting thing that we do is parse keywords. We create
1444 ;;; a bunch of temporary variables to hold the result of the parse,
1445 ;;; and then loop over the supplied arguments, setting the appropriate
1446 ;;; temps for the supplied keyword. Note that it is significant that
1447 ;;; we iterate over the keywords in reverse order --- this implements
1448 ;;; the CL requirement that (when a keyword appears more than once)
1449 ;;; the first value is used.
1450 ;;;
1451 ;;; If there is no supplied-p var, then we initialize the temp to the
1452 ;;; default and just pass the temp into the main entry. Since
1453 ;;; non-constant &KEY args are forcibly given a supplied-p var, we
1454 ;;; know that the default is constant, and thus safe to evaluate out
1455 ;;; of order.
1456 ;;;
1457 ;;; If there is a supplied-p var, then we create temps for both the
1458 ;;; value and the supplied-p, and pass them into the main entry,
1459 ;;; letting it worry about defaulting.
1460 ;;;
1461 ;;; We deal with :ALLOW-OTHER-KEYS by delaying unknown keyword errors
1462 ;;; until we have scanned all the keywords.
1463 (defun convert-more-entry (res entry-vars entry-vals rest morep keys)
1464   (declare (type optional-dispatch res) (list entry-vars entry-vals keys))
1465   (collect ((arg-vars)
1466             (arg-vals (reverse entry-vals))
1467             (temps)
1468             (body))
1469
1470     (dolist (var (reverse entry-vars))
1471       (arg-vars (make-lambda-var :name (leaf-name var)
1472                                  :type (leaf-type var)
1473                                  :where-from (leaf-where-from var))))
1474
1475     (let* ((n-context (gensym "N-CONTEXT-"))
1476            (context-temp (make-lambda-var :name n-context))
1477            (n-count (gensym "N-COUNT-"))
1478            (count-temp (make-lambda-var :name n-count
1479                                         :type (specifier-type 'index))))
1480
1481       (arg-vars context-temp count-temp)
1482
1483       (when rest
1484         (arg-vals `(%listify-rest-args ,n-context ,n-count)))
1485       (when morep
1486         (arg-vals n-context)
1487         (arg-vals n-count))
1488
1489       (when (optional-dispatch-keyp res)
1490         (let ((n-index (gensym "N-INDEX-"))
1491               (n-key (gensym "N-KEY-"))
1492               (n-value-temp (gensym "N-VALUE-TEMP-"))
1493               (n-allowp (gensym "N-ALLOWP-"))
1494               (n-losep (gensym "N-LOSEP-"))
1495               (allowp (or (optional-dispatch-allowp res)
1496                           (policy *lexenv* (zerop safety)))))
1497
1498           (temps `(,n-index (1- ,n-count)) n-key n-value-temp)
1499           (body `(declare (fixnum ,n-index) (ignorable ,n-key ,n-value-temp)))
1500
1501           (collect ((tests))
1502             (dolist (key keys)
1503               (let* ((info (lambda-var-arg-info key))
1504                      (default (arg-info-default info))
1505                      (keyword (arg-info-key info))
1506                      (supplied-p (arg-info-supplied-p info))
1507                      (n-value (gensym "N-VALUE-")))
1508                 (temps `(,n-value ,default))
1509                 (cond (supplied-p
1510                        (let ((n-supplied (gensym "N-SUPPLIED-")))
1511                          (temps n-supplied)
1512                          (arg-vals n-value n-supplied)
1513                          (tests `((eq ,n-key ',keyword)
1514                                   (setq ,n-supplied t)
1515                                   (setq ,n-value ,n-value-temp)))))
1516                       (t
1517                        (arg-vals n-value)
1518                        (tests `((eq ,n-key ',keyword)
1519                                 (setq ,n-value ,n-value-temp)))))))
1520
1521             (unless allowp
1522               (temps n-allowp n-losep)
1523               (tests `((eq ,n-key :allow-other-keys)
1524                        (setq ,n-allowp ,n-value-temp)))
1525               (tests `(t
1526                        (setq ,n-losep ,n-key))))
1527
1528             (body
1529              `(when (oddp ,n-count)
1530                 (%odd-key-arguments-error)))
1531
1532             (body
1533              `(locally
1534                 (declare (optimize (safety 0)))
1535                 (loop
1536                   (when (minusp ,n-index) (return))
1537                   (setf ,n-value-temp (%more-arg ,n-context ,n-index))
1538                   (decf ,n-index)
1539                   (setq ,n-key (%more-arg ,n-context ,n-index))
1540                   (decf ,n-index)
1541                   (cond ,@(tests)))))
1542
1543             (unless allowp
1544               (body `(when (and ,n-losep (not ,n-allowp))
1545                        (%unknown-key-argument-error ,n-losep)))))))
1546
1547       (let ((ep (ir1-convert-lambda-body
1548                  `((let ,(temps)
1549                      ,@(body)
1550                      (%funcall ,(optional-dispatch-main-entry res)
1551                                . ,(arg-vals)))) ; FIXME: What is the '.'? ,@?
1552                  (arg-vars))))
1553         (setf (optional-dispatch-more-entry res) ep))))
1554
1555   (values))
1556
1557 ;;; This is called by IR1-CONVERT-HAIRY-ARGS when we run into a &REST
1558 ;;; or &KEY arg. The arguments are similar to that function, but we
1559 ;;; split off any &REST arg and pass it in separately. REST is the
1560 ;;; &REST arg var, or NIL if there is no &REST arg. KEYS is a list of
1561 ;;; the &KEY argument vars.
1562 ;;;
1563 ;;; When there are &KEY arguments, we introduce temporary gensym
1564 ;;; variables to hold the values while keyword defaulting is in
1565 ;;; progress to get the required sequential binding semantics.
1566 ;;;
1567 ;;; This gets interesting mainly when there are &KEY arguments with
1568 ;;; supplied-p vars or non-constant defaults. In either case, pass in
1569 ;;; a supplied-p var. If the default is non-constant, we introduce an
1570 ;;; IF in the main entry that tests the supplied-p var and decides
1571 ;;; whether to evaluate the default or not. In this case, the real
1572 ;;; incoming value is NIL, so we must union NULL with the declared
1573 ;;; type when computing the type for the main entry's argument.
1574 (defun ir1-convert-more (res default-vars default-vals entry-vars entry-vals
1575                              rest more-context more-count keys supplied-p-p
1576                              body aux-vars aux-vals cont)
1577   (declare (type optional-dispatch res)
1578            (list default-vars default-vals entry-vars entry-vals keys body
1579                  aux-vars aux-vals)
1580            (type (or continuation null) cont))
1581   (collect ((main-vars (reverse default-vars))
1582             (main-vals default-vals cons)
1583             (bind-vars)
1584             (bind-vals))
1585     (when rest
1586       (main-vars rest)
1587       (main-vals '()))
1588     (when more-context
1589       (main-vars more-context)
1590       (main-vals nil)
1591       (main-vars more-count)
1592       (main-vals 0))
1593
1594     (dolist (key keys)
1595       (let* ((info (lambda-var-arg-info key))
1596              (default (arg-info-default info))
1597              (hairy-default (not (sb!xc:constantp default)))
1598              (supplied-p (arg-info-supplied-p info))
1599              (n-val (make-symbol (format nil
1600                                          "~A-DEFAULTING-TEMP"
1601                                          (leaf-name key))))
1602              (key-type (leaf-type key))
1603              (val-temp (make-lambda-var
1604                         :name n-val
1605                         :type (if hairy-default
1606                                   (type-union key-type (specifier-type 'null))
1607                                   key-type))))
1608         (main-vars val-temp)
1609         (bind-vars key)
1610         (cond ((or hairy-default supplied-p)
1611                (let* ((n-supplied (gensym "N-SUPPLIED-"))
1612                       (supplied-temp (make-lambda-var :name n-supplied)))
1613                  (unless supplied-p
1614                    (setf (arg-info-supplied-p info) supplied-temp))
1615                  (when hairy-default
1616                    (setf (arg-info-default info) nil))
1617                  (main-vars supplied-temp)
1618                  (cond (hairy-default
1619                         (main-vals nil nil)
1620                         (bind-vals `(if ,n-supplied ,n-val ,default)))
1621                        (t
1622                         (main-vals default nil)
1623                         (bind-vals n-val)))
1624                  (when supplied-p
1625                    (bind-vars supplied-p)
1626                    (bind-vals n-supplied))))
1627               (t
1628                (main-vals (arg-info-default info))
1629                (bind-vals n-val)))))
1630
1631     (let* ((main-entry (ir1-convert-lambda-body
1632                         body (main-vars)
1633                         :aux-vars (append (bind-vars) aux-vars)
1634                         :aux-vals (append (bind-vals) aux-vals)
1635                         :result cont))
1636            (last-entry (convert-optional-entry main-entry default-vars
1637                                                (main-vals) ())))
1638       (setf (optional-dispatch-main-entry res) main-entry)
1639       (convert-more-entry res entry-vars entry-vals rest more-context keys)
1640
1641       (push (if supplied-p-p
1642                 (convert-optional-entry last-entry entry-vars entry-vals ())
1643                 last-entry)
1644             (optional-dispatch-entry-points res))
1645       last-entry)))
1646
1647 ;;; This function generates the entry point functions for the
1648 ;;; optional-dispatch Res. We accomplish this by recursion on the list of
1649 ;;; arguments, analyzing the arglist on the way down and generating entry
1650 ;;; points on the way up.
1651 ;;;
1652 ;;; Default-Vars is a reversed list of all the argument vars processed
1653 ;;; so far, including supplied-p vars. Default-Vals is a list of the
1654 ;;; names of the Default-Vars.
1655 ;;;
1656 ;;; Entry-Vars is a reversed list of processed argument vars,
1657 ;;; excluding supplied-p vars. Entry-Vals is a list things that can be
1658 ;;; evaluated to get the values for all the vars from the Entry-Vars.
1659 ;;; It has the var name for each required or optional arg, and has T
1660 ;;; for each supplied-p arg.
1661 ;;;
1662 ;;; Vars is a list of the Lambda-Var structures for arguments that
1663 ;;; haven't been processed yet. Supplied-p-p is true if a supplied-p
1664 ;;; argument has already been processed; only in this case are the
1665 ;;; Default-XXX and Entry-XXX different.
1666 ;;;
1667 ;;; The result at each point is a lambda which should be called by the
1668 ;;; above level to default the remaining arguments and evaluate the
1669 ;;; body. We cause the body to be evaluated by converting it and
1670 ;;; returning it as the result when the recursion bottoms out.
1671 ;;;
1672 ;;; Each level in the recursion also adds its entry point function to
1673 ;;; the result Optional-Dispatch. For most arguments, the defaulting
1674 ;;; function and the entry point function will be the same, but when
1675 ;;; supplied-p args are present they may be different.
1676 ;;;
1677 ;;; When we run into a &REST or &KEY arg, we punt out to
1678 ;;; IR1-CONVERT-MORE, which finishes for us in this case.
1679 (defun ir1-convert-hairy-args (res default-vars default-vals
1680                                    entry-vars entry-vals
1681                                    vars supplied-p-p body aux-vars
1682                                    aux-vals cont)
1683   (declare (type optional-dispatch res)
1684            (list default-vars default-vals entry-vars entry-vals vars body
1685                  aux-vars aux-vals)
1686            (type (or continuation null) cont))
1687   (cond ((not vars)
1688          (if (optional-dispatch-keyp res)
1689              ;; Handle &KEY with no keys...
1690              (ir1-convert-more res default-vars default-vals
1691                                entry-vars entry-vals
1692                                nil nil nil vars supplied-p-p body aux-vars
1693                                aux-vals cont)
1694              (let ((fun (ir1-convert-lambda-body body (reverse default-vars)
1695                                                  :aux-vars aux-vars
1696                                                  :aux-vals aux-vals
1697                                                  :result cont)))
1698                (setf (optional-dispatch-main-entry res) fun)
1699                (push (if supplied-p-p
1700                          (convert-optional-entry fun entry-vars entry-vals ())
1701                          fun)
1702                      (optional-dispatch-entry-points res))
1703                fun)))
1704         ((not (lambda-var-arg-info (first vars)))
1705          (let* ((arg (first vars))
1706                 (nvars (cons arg default-vars))
1707                 (nvals (cons (leaf-name arg) default-vals)))
1708            (ir1-convert-hairy-args res nvars nvals nvars nvals
1709                                    (rest vars) nil body aux-vars aux-vals
1710                                    cont)))
1711         (t
1712          (let* ((arg (first vars))
1713                 (info (lambda-var-arg-info arg))
1714                 (kind (arg-info-kind info)))
1715            (ecase kind
1716              (:optional
1717               (let ((ep (generate-optional-default-entry
1718                          res default-vars default-vals
1719                          entry-vars entry-vals vars supplied-p-p body
1720                          aux-vars aux-vals cont)))
1721                 (push (if supplied-p-p
1722                           (convert-optional-entry ep entry-vars entry-vals ())
1723                           ep)
1724                       (optional-dispatch-entry-points res))
1725                 ep))
1726              (:rest
1727               (ir1-convert-more res default-vars default-vals
1728                                 entry-vars entry-vals
1729                                 arg nil nil (rest vars) supplied-p-p body
1730                                 aux-vars aux-vals cont))
1731              (:more-context
1732               (ir1-convert-more res default-vars default-vals
1733                                 entry-vars entry-vals
1734                                 nil arg (second vars) (cddr vars) supplied-p-p
1735                                 body aux-vars aux-vals cont))
1736              (:keyword
1737               (ir1-convert-more res default-vars default-vals
1738                                 entry-vars entry-vals
1739                                 nil nil nil vars supplied-p-p body aux-vars
1740                                 aux-vals cont)))))))
1741
1742 ;;; This function deals with the case where we have to make an
1743 ;;; Optional-Dispatch to represent a lambda. We cons up the result and
1744 ;;; call IR1-CONVERT-HAIRY-ARGS to do the work. When it is done, we
1745 ;;; figure out the min-args and max-args.
1746 (defun ir1-convert-hairy-lambda (body vars keyp allowp aux-vars aux-vals cont)
1747   (declare (list body vars aux-vars aux-vals) (type continuation cont))
1748   (let ((res (make-optional-dispatch :arglist vars
1749                                      :allowp allowp
1750                                      :keyp keyp))
1751         (min (or (position-if #'lambda-var-arg-info vars) (length vars))))
1752     (push res (component-new-functions *current-component*))
1753     (ir1-convert-hairy-args res () () () () vars nil body aux-vars aux-vals
1754                             cont)
1755     (setf (optional-dispatch-min-args res) min)
1756     (setf (optional-dispatch-max-args res)
1757           (+ (1- (length (optional-dispatch-entry-points res))) min))
1758
1759     (flet ((frob (ep)
1760              (when ep
1761                (setf (functional-kind ep) :optional)
1762                (setf (leaf-ever-used ep) t)
1763                (setf (lambda-optional-dispatch ep) res))))
1764       (dolist (ep (optional-dispatch-entry-points res)) (frob ep))
1765       (frob (optional-dispatch-more-entry res))
1766       (frob (optional-dispatch-main-entry res)))
1767
1768     res))
1769
1770 ;;; Convert a LAMBDA form into a LAMBDA leaf or an OPTIONAL-DISPATCH leaf.
1771 (defun ir1-convert-lambda (form &optional name)
1772   (unless (consp form)
1773     (compiler-error "A ~S was found when expecting a lambda expression:~%  ~S"
1774                     (type-of form)
1775                     form))
1776   (unless (eq (car form) 'lambda)
1777     (compiler-error "~S was expected but ~S was found:~%  ~S"
1778                     'lambda
1779                     (car form)
1780                     form))
1781   (unless (and (consp (cdr form)) (listp (cadr form)))
1782     (compiler-error
1783      "The lambda expression has a missing or non-list lambda-list:~%  ~S"
1784      form))
1785
1786   (multiple-value-bind (vars keyp allow-other-keys aux-vars aux-vals)
1787       (find-lambda-vars (cadr form))
1788     (multiple-value-bind (forms decls) (sb!sys:parse-body (cddr form))
1789       (let* ((cont (make-continuation))
1790              (*lexenv* (process-decls decls
1791                                       (append aux-vars vars)
1792                                       nil cont))
1793              (res (if (or (find-if #'lambda-var-arg-info vars) keyp)
1794                       (ir1-convert-hairy-lambda forms vars keyp
1795                                                 allow-other-keys
1796                                                 aux-vars aux-vals cont)
1797                       (ir1-convert-lambda-body forms vars
1798                                                :aux-vars aux-vars
1799                                                :aux-vals aux-vals
1800                                                :result cont))))
1801         (setf (functional-inline-expansion res) form)
1802         (setf (functional-arg-documentation res) (cadr form))
1803         (setf (leaf-name res) name)
1804         res))))
1805 \f
1806 ;;; FIXME: This file is rather long, and contains two distinct sections,
1807 ;;; transform machinery above this point and transforms themselves below this
1808 ;;; point. Why not split it in two? (ir1translate.lisp and
1809 ;;; ir1translators.lisp?) Then consider byte-compiling the translators, too.
1810 \f
1811 ;;;; control special forms
1812
1813 (def-ir1-translator progn ((&rest forms) start cont)
1814   #!+sb-doc
1815   "Progn Form*
1816   Evaluates each Form in order, returning the values of the last form. With no
1817   forms, returns NIL."
1818   (ir1-convert-progn-body start cont forms))
1819
1820 (def-ir1-translator if ((test then &optional else) start cont)
1821   #!+sb-doc
1822   "If Predicate Then [Else]
1823   If Predicate evaluates to non-null, evaluate Then and returns its values,
1824   otherwise evaluate Else and return its values. Else defaults to NIL."
1825   (let* ((pred (make-continuation))
1826          (then-cont (make-continuation))
1827          (then-block (continuation-starts-block then-cont))
1828          (else-cont (make-continuation))
1829          (else-block (continuation-starts-block else-cont))
1830          (dummy-cont (make-continuation))
1831          (node (make-if :test pred
1832                         :consequent then-block
1833                         :alternative else-block)))
1834     (setf (continuation-dest pred) node)
1835     (ir1-convert start pred test)
1836     (prev-link node pred)
1837     (use-continuation node dummy-cont)
1838
1839     (let ((start-block (continuation-block pred)))
1840       (setf (block-last start-block) node)
1841       (continuation-starts-block cont)
1842
1843       (link-blocks start-block then-block)
1844       (link-blocks start-block else-block)
1845
1846       (ir1-convert then-cont cont then)
1847       (ir1-convert else-cont cont else))))
1848 \f
1849 ;;;; BLOCK and TAGBODY
1850
1851 ;;;; We make an Entry node to mark the start and a :Entry cleanup to
1852 ;;;; mark its extent. When doing GO or RETURN-FROM, we emit an Exit
1853 ;;;; node.
1854
1855 ;;; Make a :entry cleanup and emit an Entry node, then convert the
1856 ;;; body in the modified environment. We make Cont start a block now,
1857 ;;; since if it was done later, the block would be in the wrong
1858 ;;; environment.
1859 (def-ir1-translator block ((name &rest forms) start cont)
1860   #!+sb-doc
1861   "Block Name Form*
1862   Evaluate the Forms as a PROGN. Within the lexical scope of the body,
1863   (RETURN-FROM Name Value-Form) can be used to exit the form, returning the
1864   result of Value-Form."
1865   (unless (symbolp name)
1866     (compiler-error "The block name ~S is not a symbol." name))
1867   (continuation-starts-block cont)
1868   (let* ((dummy (make-continuation))
1869          (entry (make-entry))
1870          (cleanup (make-cleanup :kind :block
1871                                 :mess-up entry)))
1872     (push entry (lambda-entries (lexenv-lambda *lexenv*)))
1873     (setf (entry-cleanup entry) cleanup)
1874     (prev-link entry start)
1875     (use-continuation entry dummy)
1876     
1877     (let* ((env-entry (list entry cont))
1878            (*lexenv* (make-lexenv :blocks (list (cons name env-entry))
1879                                   :cleanup cleanup)))
1880       (push env-entry (continuation-lexenv-uses cont))
1881       (ir1-convert-progn-body dummy cont forms))))
1882
1883
1884 ;;; We make Cont start a block just so that it will have a block
1885 ;;; assigned. People assume that when they pass a continuation into
1886 ;;; IR1-Convert as Cont, it will have a block when it is done.
1887 (def-ir1-translator return-from ((name &optional value)
1888                                  start cont)
1889   #!+sb-doc
1890   "Return-From Block-Name Value-Form
1891   Evaluate the Value-Form, returning its values from the lexically enclosing
1892   BLOCK Block-Name. This is constrained to be used only within the dynamic
1893   extent of the BLOCK."
1894   (continuation-starts-block cont)
1895   (let* ((found (or (lexenv-find name blocks)
1896                     (compiler-error "return for unknown block: ~S" name)))
1897          (value-cont (make-continuation))
1898          (entry (first found))
1899          (exit (make-exit :entry entry
1900                           :value value-cont)))
1901     (push exit (entry-exits entry))
1902     (setf (continuation-dest value-cont) exit)
1903     (ir1-convert start value-cont value)
1904     (prev-link exit value-cont)
1905     (use-continuation exit (second found))))
1906
1907 ;;; Return a list of the segments of a TAGBODY. Each segment looks
1908 ;;; like (<tag> <form>* (go <next tag>)). That is, we break up the
1909 ;;; tagbody into segments of non-tag statements, and explicitly
1910 ;;; represent the drop-through with a GO. The first segment has a
1911 ;;; dummy NIL tag, since it represents code before the first tag. The
1912 ;;; last segment (which may also be the first segment) ends in NIL
1913 ;;; rather than a GO.
1914 (defun parse-tagbody (body)
1915   (declare (list body))
1916   (collect ((segments))
1917     (let ((current (cons nil body)))
1918       (loop
1919         (let ((tag-pos (position-if (complement #'listp) current :start 1)))
1920           (unless tag-pos
1921             (segments `(,@current nil))
1922             (return))
1923           (let ((tag (elt current tag-pos)))
1924             (when (assoc tag (segments))
1925               (compiler-error
1926                "The tag ~S appears more than once in the tagbody."
1927                tag))
1928             (unless (or (symbolp tag) (integerp tag))
1929               (compiler-error "~S is not a legal tagbody statement." tag))
1930             (segments `(,@(subseq current 0 tag-pos) (go ,tag))))
1931           (setq current (nthcdr tag-pos current)))))
1932     (segments)))
1933
1934 ;;; Set up the cleanup, emitting the entry node. Then make a block for
1935 ;;; each tag, building up the tag list for LEXENV-TAGS as we go.
1936 ;;; Finally, convert each segment with the precomputed Start and Cont
1937 ;;; values.
1938 (def-ir1-translator tagbody ((&rest statements) start cont)
1939   #!+sb-doc
1940   "Tagbody {Tag | Statement}*
1941   Define tags for used with GO. The Statements are evaluated in order
1942   (skipping Tags) and NIL is returned. If a statement contains a GO to a
1943   defined Tag within the lexical scope of the form, then control is transferred
1944   to the next statement following that tag. A Tag must an integer or a
1945   symbol. A statement must be a list. Other objects are illegal within the
1946   body."
1947   (continuation-starts-block cont)
1948   (let* ((dummy (make-continuation))
1949          (entry (make-entry))
1950          (segments (parse-tagbody statements))
1951          (cleanup (make-cleanup :kind :tagbody
1952                                 :mess-up entry)))
1953     (push entry (lambda-entries (lexenv-lambda *lexenv*)))
1954     (setf (entry-cleanup entry) cleanup)
1955     (prev-link entry start)
1956     (use-continuation entry dummy)
1957
1958     (collect ((tags)
1959               (starts)
1960               (conts))
1961       (starts dummy)
1962       (dolist (segment (rest segments))
1963         (let* ((tag-cont (make-continuation))
1964                (tag (list (car segment) entry tag-cont)))          
1965           (conts tag-cont)
1966           (starts tag-cont)
1967           (continuation-starts-block tag-cont)
1968           (tags tag)
1969           (push (cdr tag) (continuation-lexenv-uses tag-cont))))
1970       (conts cont)
1971
1972       (let ((*lexenv* (make-lexenv :cleanup cleanup :tags (tags))))
1973         (mapc (lambda (segment start cont)
1974                 (ir1-convert-progn-body start cont (rest segment)))
1975               segments (starts) (conts))))))
1976
1977 ;;; Emit an EXIT node without any value.
1978 (def-ir1-translator go ((tag) start cont)
1979   #!+sb-doc
1980   "Go Tag
1981   Transfer control to the named Tag in the lexically enclosing TAGBODY. This
1982   is constrained to be used only within the dynamic extent of the TAGBODY."
1983   (continuation-starts-block cont)
1984   (let* ((found (or (lexenv-find tag tags :test #'eql)
1985                     (compiler-error "Go to nonexistent tag: ~S." tag)))
1986          (entry (first found))
1987          (exit (make-exit :entry entry)))
1988     (push exit (entry-exits entry))
1989     (prev-link exit start)
1990     (use-continuation exit (second found))))
1991 \f
1992 ;;;; translators for compiler-magic special forms
1993
1994 ;;; This handles EVAL-WHEN in non-top-level forms. (EVAL-WHENs in
1995 ;;; top-level forms are picked off and handled by PROCESS-TOP-LEVEL-FORM,
1996 ;;; so they're never seen at this level.)
1997 ;;;
1998 ;;; ANSI "3.2.3.1 Processing of Top Level Forms" says that processing
1999 ;;; of non-top-level EVAL-WHENs is very simple:
2000 ;;;   EVAL-WHEN forms cause compile-time evaluation only at top level.
2001 ;;;   Both :COMPILE-TOPLEVEL and :LOAD-TOPLEVEL situation specifications
2002 ;;;   are ignored for non-top-level forms. For non-top-level forms, an
2003 ;;;   eval-when specifying the :EXECUTE situation is treated as an
2004 ;;;   implicit PROGN including the forms in the body of the EVAL-WHEN
2005 ;;;   form; otherwise, the forms in the body are ignored. 
2006 (def-ir1-translator eval-when ((situations &rest forms) start cont)
2007   #!+sb-doc
2008   "EVAL-WHEN (Situation*) Form*
2009   Evaluate the Forms in the specified Situations (any of :COMPILE-TOPLEVEL,
2010   :LOAD-TOPLEVEL, or :EXECUTE, or (deprecated) COMPILE, LOAD, or EVAL)."
2011   (multiple-value-bind (ct lt e) (parse-eval-when-situations situations)
2012     (declare (ignore ct lt))
2013     (when e
2014       (ir1-convert-progn-body start cont forms)))
2015   (values))
2016
2017 ;;; common logic for MACROLET and SYMBOL-MACROLET
2018 ;;;
2019 ;;; Call DEFINITIONIZE-FUN on each element of DEFINITIONS to find its
2020 ;;; in-lexenv representation, stuff the results into *LEXENV*, and
2021 ;;; call FUN (with no arguments).
2022 (defun %funcall-in-foomacrolet-lexenv (definitionize-fun
2023                                        definitionize-keyword
2024                                        definitions
2025                                        fun)
2026   (declare (type function definitionize-fun fun))
2027   (declare (type (member :variables :functions) definitionize-keyword))
2028   (declare (type list definitions))
2029   (unless (= (length definitions)
2030              (length (remove-duplicates definitions :key #'first)))
2031     (compiler-style-warning "duplicate definitions in ~S" definitions))
2032   (let* ((processed-definitions (mapcar definitionize-fun definitions))
2033          (*lexenv* (make-lexenv definitionize-keyword processed-definitions)))
2034     (funcall fun)))
2035
2036 ;;; Tweak *LEXENV* to include the DEFINITIONS from a MACROLET, then
2037 ;;; call FUN (with no arguments).
2038 ;;;
2039 ;;; This is split off from the IR1 convert method so that it can be
2040 ;;; shared by the special-case top-level MACROLET processing code.
2041 (defun funcall-in-macrolet-lexenv (definitions fun)
2042   (%funcall-in-foomacrolet-lexenv
2043    (lambda (definition)
2044      (unless (list-of-length-at-least-p definition 2)
2045        (compiler-error
2046         "The list ~S is too short to be a legal local macro definition."
2047         definition))
2048      (destructuring-bind (name arglist &body body) definition
2049        (unless (symbolp name)
2050          (compiler-error "The local macro name ~S is not a symbol." name))
2051        (let ((whole (gensym "WHOLE"))
2052              (environment (gensym "ENVIRONMENT")))
2053          (multiple-value-bind (body local-decls)
2054              (parse-defmacro arglist whole body name 'macrolet
2055                              :environment environment)
2056            `(,name macro .
2057                    ,(compile nil
2058                              `(lambda (,whole ,environment)
2059                                 ,@local-decls
2060                                 (block ,name ,body))))))))
2061    :functions
2062    definitions
2063    fun))
2064
2065 (def-ir1-translator macrolet ((definitions &rest body) start cont)
2066   #!+sb-doc
2067   "MACROLET ({(Name Lambda-List Form*)}*) Body-Form*
2068   Evaluate the Body-Forms in an environment with the specified local macros
2069   defined. Name is the local macro name, Lambda-List is the DEFMACRO style
2070   destructuring lambda list, and the Forms evaluate to the expansion. The
2071   Forms are evaluated in the null environment."
2072   (funcall-in-macrolet-lexenv definitions
2073                               (lambda ()
2074                                 (ir1-translate-locally body start cont))))
2075
2076 (defun funcall-in-symbol-macrolet-lexenv (definitions fun)
2077   (%funcall-in-foomacrolet-lexenv
2078    (lambda (definition)
2079      (unless (proper-list-of-length-p definition 2)
2080        (compiler-error "malformed symbol/expansion pair: ~S" definition))
2081      (destructuring-bind (name expansion) definition
2082        (unless (symbolp name)
2083          (compiler-error
2084           "The local symbol macro name ~S is not a symbol."
2085           name))
2086        `(,name . (MACRO . ,expansion))))
2087    :variables
2088    definitions
2089    fun))
2090   
2091 (def-ir1-translator symbol-macrolet ((macrobindings &body body) start cont)
2092   #!+sb-doc
2093   "SYMBOL-MACROLET ({(Name Expansion)}*) Decl* Form*
2094   Define the Names as symbol macros with the given Expansions. Within the
2095   body, references to a Name will effectively be replaced with the Expansion."
2096   (funcall-in-symbol-macrolet-lexenv
2097    macrobindings
2098    (lambda ()
2099      (ir1-translate-locally body start cont))))
2100
2101 ;;; not really a special form, but..
2102 (def-ir1-translator declare ((&rest stuff) start cont)
2103   (declare (ignore stuff))
2104   ;; We ignore START and CONT too, but we can't use DECLARE IGNORE to
2105   ;; tell the compiler about it here, because the DEF-IR1-TRANSLATOR
2106   ;; macro would put the DECLARE in the wrong place, so..
2107   start cont
2108   (compiler-error "misplaced declaration"))
2109 \f
2110 ;;;; %PRIMITIVE
2111 ;;;;
2112 ;;;; Uses of %PRIMITIVE are either expanded into Lisp code or turned
2113 ;;;; into a funny function.
2114
2115 ;;; Carefully evaluate a list of forms, returning a list of the results.
2116 (defun eval-info-args (args)
2117   (declare (list args))
2118   (handler-case (mapcar #'eval args)
2119     (error (condition)
2120       (compiler-error "Lisp error during evaluation of info args:~%~A"
2121                       condition))))
2122
2123 ;;; If there is a primitive translator, then we expand the call.
2124 ;;; Otherwise, we convert to the %%PRIMITIVE funny function. The first
2125 ;;; argument is the template, the second is a list of the results of
2126 ;;; any codegen-info args, and the remaining arguments are the runtime
2127 ;;; arguments.
2128 ;;;
2129 ;;; We do a bunch of error checking now so that we don't bomb out with
2130 ;;; a fatal error during IR2 conversion.
2131 ;;;
2132 ;;; KLUDGE: It's confusing having multiple names floating around for
2133 ;;; nearly the same concept: PRIMITIVE, TEMPLATE, VOP. Now that CMU
2134 ;;; CL's *PRIMITIVE-TRANSLATORS* stuff is gone, we could call
2135 ;;; primitives VOPs, rename TEMPLATE to VOP-TEMPLATE, rename
2136 ;;; BACKEND-TEMPLATE-NAMES to BACKEND-VOPS, and rename %PRIMITIVE to
2137 ;;; VOP or %VOP.. -- WHN 2001-06-11
2138 ;;; FIXME: Look at doing this ^, it doesn't look too hard actually.
2139 (def-ir1-translator %primitive ((&whole form name &rest args) start cont)
2140
2141   (unless (symbolp name)
2142     (compiler-error "The primitive name ~S is not a symbol." name))
2143
2144   (let* ((template (or (gethash name *backend-template-names*)
2145                        (compiler-error
2146                         "The primitive name ~A is not defined."
2147                         name)))
2148          (required (length (template-arg-types template)))
2149          (info (template-info-arg-count template))
2150          (min (+ required info))
2151          (nargs (length args)))
2152     (if (template-more-args-type template)
2153         (when (< nargs min)
2154           (compiler-error "Primitive ~A was called with ~R argument~:P, ~
2155                            but wants at least ~R."
2156                           name
2157                           nargs
2158                           min))
2159         (unless (= nargs min)
2160           (compiler-error "Primitive ~A was called with ~R argument~:P, ~
2161                            but wants exactly ~R."
2162                           name
2163                           nargs
2164                           min)))
2165
2166     (when (eq (template-result-types template) :conditional)
2167       (compiler-error
2168        "%PRIMITIVE was used with a conditional template."))
2169
2170     (when (template-more-results-type template)
2171       (compiler-error
2172        "%PRIMITIVE was used with an unknown values template."))
2173
2174     (ir1-convert start
2175                  cont
2176                  `(%%primitive ',template
2177                                ',(eval-info-args
2178                                   (subseq args required min))
2179                                ,@(subseq args 0 required)
2180                                ,@(subseq args min)))))
2181 \f
2182 ;;;; QUOTE and FUNCTION
2183
2184 (def-ir1-translator quote ((thing) start cont)
2185   #!+sb-doc
2186   "QUOTE Value
2187   Return Value without evaluating it."
2188   (reference-constant start cont thing))
2189
2190 (def-ir1-translator function ((thing) start cont)
2191   #!+sb-doc
2192   "FUNCTION Name
2193   Return the lexically apparent definition of the function Name. Name may also
2194   be a lambda."
2195   (if (consp thing)
2196       (case (car thing)
2197         ((lambda)
2198          (reference-leaf start cont (ir1-convert-lambda thing)))
2199         ((setf)
2200          (let ((var (find-lexically-apparent-function
2201                      thing "as the argument to FUNCTION")))
2202            (reference-leaf start cont var)))
2203         ((instance-lambda)
2204          (let ((res (ir1-convert-lambda `(lambda ,@(cdr thing)))))
2205            (setf (getf (functional-plist res) :fin-function) t)
2206            (reference-leaf start cont res)))
2207         (t
2208          (compiler-error "~S is not a legal function name." thing)))
2209       (let ((var (find-lexically-apparent-function
2210                   thing "as the argument to FUNCTION")))
2211         (reference-leaf start cont var))))
2212 \f
2213 ;;;; FUNCALL
2214
2215 ;;; FUNCALL is implemented on %FUNCALL, which can only call functions
2216 ;;; (not symbols). %FUNCALL is used directly in some places where the
2217 ;;; call should always be open-coded even if FUNCALL is :NOTINLINE.
2218 (deftransform funcall ((function &rest args) * * :when :both)
2219   (let ((arg-names (make-gensym-list (length args))))
2220     `(lambda (function ,@arg-names)
2221        (%funcall ,(if (csubtypep (continuation-type function)
2222                                  (specifier-type 'function))
2223                       'function
2224                       '(%coerce-callable-to-function function))
2225                  ,@arg-names))))
2226
2227 (def-ir1-translator %funcall ((function &rest args) start cont)
2228   (let ((fun-cont (make-continuation)))
2229     (ir1-convert start fun-cont function)
2230     (assert-continuation-type fun-cont (specifier-type 'function))
2231     (ir1-convert-combination-args fun-cont cont args)))
2232
2233 ;;; This source transform exists to reduce the amount of work for the
2234 ;;; compiler. If the called function is a FUNCTION form, then convert
2235 ;;; directly to %FUNCALL, instead of waiting around for type
2236 ;;; inference.
2237 (def-source-transform funcall (function &rest args)
2238   (if (and (consp function) (eq (car function) 'function))
2239       `(%funcall ,function ,@args)
2240       (values nil t)))
2241
2242 (deftransform %coerce-callable-to-function ((thing) (function) *
2243                                             :when :both
2244                                             :important t)
2245   "optimize away possible call to FDEFINITION at runtime"
2246   'thing)
2247 \f
2248 ;;; This is a frob that DEFSTRUCT expands into to establish the compiler
2249 ;;; semantics. The other code in the expansion and %%COMPILER-DEFSTRUCT do
2250 ;;; most of the work, we just clear all of the functions out of
2251 ;;; *FREE-FUNCTIONS* to keep things in synch. %%COMPILER-DEFSTRUCT is also
2252 ;;; called at load-time.
2253 (def-ir1-translator %compiler-defstruct ((info) start cont :kind :function)
2254   (let* ((info (eval info)))
2255     (%%compiler-defstruct info)
2256     (dolist (slot (dd-slots info))
2257       (let ((fun (dsd-accessor slot)))
2258         (remhash fun *free-functions*)
2259         (unless (dsd-read-only slot)
2260           (remhash `(setf ,fun) *free-functions*))))
2261     (remhash (dd-predicate info) *free-functions*)
2262     (remhash (dd-copier info) *free-functions*)
2263     (ir1-convert start cont `(%%compiler-defstruct ',info))))
2264
2265 ;;; Return the contents of a quoted form.
2266 (defun unquote (x)
2267   (if (and (consp x)
2268            (= 2 (length x))
2269            (eq 'quote (first x)))
2270     (second x)
2271     (error "not a quoted form")))
2272
2273 ;;; Don't actually compile anything, instead call the function now.
2274 (def-ir1-translator %compiler-only-defstruct
2275                     ((info inherits) start cont :kind :function)
2276   (function-%compiler-only-defstruct (unquote info) (unquote inherits))
2277   (reference-constant start cont nil))
2278 \f
2279 ;;;; LET and LET*
2280 ;;;;
2281 ;;;; (LET and LET* can't be implemented as macros due to the fact that
2282 ;;;; any pervasive declarations also affect the evaluation of the
2283 ;;;; arguments.)
2284
2285 ;;; Given a list of binding specifiers in the style of Let, return:
2286 ;;;  1. The list of var structures for the variables bound.
2287 ;;;  2. The initial value form for each variable.
2288 ;;;
2289 ;;; The variable names are checked for legality and globally special
2290 ;;; variables are marked as such. Context is the name of the form, for
2291 ;;; error reporting purposes.
2292 (declaim (ftype (function (list symbol) (values list list list))
2293                 extract-let-variables))
2294 (defun extract-let-variables (bindings context)
2295   (collect ((vars)
2296             (vals)
2297             (names))
2298     (flet ((get-var (name)
2299              (varify-lambda-arg name
2300                                 (if (eq context 'let*)
2301                                     nil
2302                                     (names)))))
2303       (dolist (spec bindings)
2304         (cond ((atom spec)
2305                (let ((var (get-var spec)))
2306                  (vars var)
2307                  (names (cons spec var))
2308                  (vals nil)))
2309               (t
2310                (unless (proper-list-of-length-p spec 1 2)
2311                  (compiler-error "The ~S binding spec ~S is malformed."
2312                                  context
2313                                  spec))
2314                (let* ((name (first spec))
2315                       (var (get-var name)))
2316                  (vars var)
2317                  (names name)
2318                  (vals (second spec)))))))
2319
2320     (values (vars) (vals) (names))))
2321
2322 (def-ir1-translator let ((bindings &body body)
2323                          start cont)
2324   #!+sb-doc
2325   "LET ({(Var [Value]) | Var}*) Declaration* Form*
2326   During evaluation of the Forms, bind the Vars to the result of evaluating the
2327   Value forms. The variables are bound in parallel after all of the Values are
2328   evaluated."
2329   (multiple-value-bind (forms decls) (sb!sys:parse-body body nil)
2330     (multiple-value-bind (vars values) (extract-let-variables bindings 'let)
2331       (let* ((*lexenv* (process-decls decls vars nil cont))
2332              (fun-cont (make-continuation))
2333              (fun (ir1-convert-lambda-body forms vars)))
2334         (reference-leaf start fun-cont fun)
2335         (ir1-convert-combination-args fun-cont cont values)))))
2336
2337 (def-ir1-translator let* ((bindings &body body)
2338                           start cont)
2339   #!+sb-doc
2340   "LET* ({(Var [Value]) | Var}*) Declaration* Form*
2341   Similar to LET, but the variables are bound sequentially, allowing each Value
2342   form to reference any of the previous Vars."
2343   (multiple-value-bind (forms decls) (sb!sys:parse-body body nil)
2344     (multiple-value-bind (vars values) (extract-let-variables bindings 'let*)
2345       (let ((*lexenv* (process-decls decls vars nil cont)))
2346         (ir1-convert-aux-bindings start cont forms vars values)))))
2347
2348 ;;; logic shared between IR1 translators for LOCALLY, MACROLET,
2349 ;;; and SYMBOL-MACROLET
2350 ;;;
2351 ;;; Note that all these things need to preserve top-level-formness,
2352 ;;; but we don't need to worry about that within an IR1 translator,
2353 ;;; since top-level-formness is picked off by PROCESS-TOP-LEVEL-FOO
2354 ;;; forms before we hit the IR1 transform level.
2355 (defun ir1-translate-locally (body start cont)
2356   (declare (type list body) (type continuation start cont))
2357   (multiple-value-bind (forms decls) (sb!sys:parse-body body nil)
2358     (let ((*lexenv* (process-decls decls nil nil cont)))
2359       (ir1-convert-aux-bindings start cont forms nil nil))))
2360
2361 (def-ir1-translator locally ((&body body) start cont)
2362   #!+sb-doc
2363   "LOCALLY Declaration* Form*
2364   Sequentially evaluate the Forms in a lexical environment where the
2365   the Declarations have effect. If LOCALLY is a top-level form, then
2366   the Forms are also processed as top-level forms."
2367   (ir1-translate-locally body start cont))
2368 \f
2369 ;;;; FLET and LABELS
2370
2371 ;;; Given a list of local function specifications in the style of
2372 ;;; FLET, return lists of the function names and of the lambdas which
2373 ;;; are their definitions.
2374 ;;;
2375 ;;; The function names are checked for legality. CONTEXT is the name
2376 ;;; of the form, for error reporting.
2377 (declaim (ftype (function (list symbol) (values list list))
2378                 extract-flet-variables))
2379 (defun extract-flet-variables (definitions context)
2380   (collect ((names)
2381             (defs))
2382     (dolist (def definitions)
2383       (when (or (atom def) (< (length def) 2))
2384         (compiler-error "The ~S definition spec ~S is malformed." context def))
2385
2386       (let ((name (check-function-name (first def))))
2387         (names name)
2388         (multiple-value-bind (forms decls) (sb!sys:parse-body (cddr def))
2389           (defs `(lambda ,(second def)
2390                    ,@decls
2391                    (block ,(function-name-block-name name)
2392                      . ,forms))))))
2393     (values (names) (defs))))
2394
2395 (def-ir1-translator flet ((definitions &body body)
2396                           start cont)
2397   #!+sb-doc
2398   "FLET ({(Name Lambda-List Declaration* Form*)}*) Declaration* Body-Form*
2399   Evaluate the Body-Forms with some local function definitions. The bindings
2400   do not enclose the definitions; any use of Name in the Forms will refer to
2401   the lexically apparent function definition in the enclosing environment."
2402   (multiple-value-bind (forms decls) (sb!sys:parse-body body nil)
2403     (multiple-value-bind (names defs)
2404         (extract-flet-variables definitions 'flet)
2405       (let* ((fvars (mapcar (lambda (n d)
2406                               (ir1-convert-lambda d n))
2407                             names defs))
2408              (*lexenv* (make-lexenv
2409                         :default (process-decls decls nil fvars cont)
2410                         :functions (pairlis names fvars))))
2411         (ir1-convert-progn-body start cont forms)))))
2412
2413 ;;; For LABELS, we have to create dummy function vars and add them to
2414 ;;; the function namespace while converting the functions. We then
2415 ;;; modify all the references to these leaves so that they point to
2416 ;;; the real functional leaves. We also backpatch the FENV so that if
2417 ;;; the lexical environment is used for inline expansion we will get
2418 ;;; the right functions.
2419 (def-ir1-translator labels ((definitions &body body) start cont)
2420   #!+sb-doc
2421   "LABELS ({(Name Lambda-List Declaration* Form*)}*) Declaration* Body-Form*
2422   Evaluate the Body-Forms with some local function definitions. The bindings
2423   enclose the new definitions, so the defined functions can call themselves or
2424   each other."
2425   (multiple-value-bind (forms decls) (sb!sys:parse-body body nil)
2426     (multiple-value-bind (names defs)
2427         (extract-flet-variables definitions 'labels)
2428       (let* ((new-fenv (loop for name in names
2429                              collect (cons name (make-functional :name name))))
2430              (real-funs
2431               (let ((*lexenv* (make-lexenv :functions new-fenv)))
2432                 (mapcar (lambda (n d)
2433                           (ir1-convert-lambda d n))
2434                         names defs))))
2435
2436         (loop for real in real-funs and env in new-fenv do
2437               (let ((dum (cdr env)))
2438                 (substitute-leaf real dum)
2439                 (setf (cdr env) real)))
2440
2441         (let ((*lexenv* (make-lexenv
2442                          :default (process-decls decls nil real-funs cont)
2443                          :functions (pairlis names real-funs))))
2444           (ir1-convert-progn-body start cont forms))))))
2445 \f
2446 ;;;; THE
2447
2448 ;;; Do stuff to recognize a THE or VALUES declaration. CONT is the
2449 ;;; continuation that the assertion applies to, TYPE is the type
2450 ;;; specifier and Lexenv is the current lexical environment. NAME is
2451 ;;; the name of the declaration we are doing, for use in error
2452 ;;; messages.
2453 ;;;
2454 ;;; This is somewhat involved, since a type assertion may only be made
2455 ;;; on a continuation, not on a node. We can't just set the
2456 ;;; continuation asserted type and let it go at that, since there may
2457 ;;; be parallel THE's for the same continuation, i.e.:
2458 ;;;     (if ...
2459 ;;;      (the foo ...)
2460 ;;;      (the bar ...))
2461 ;;;
2462 ;;; In this case, our representation can do no better than the union
2463 ;;; of these assertions. And if there is a branch with no assertion,
2464 ;;; we have nothing at all. We really need to recognize scoping, since
2465 ;;; we need to be able to discern between parallel assertions (which
2466 ;;; we union) and nested ones (which we intersect).
2467 ;;;
2468 ;;; We represent the scoping by throwing our innermost (intersected)
2469 ;;; assertion on CONT into the TYPE-RESTRICTIONS. As we go down, we
2470 ;;; intersect our assertions together. If CONT has no uses yet, we
2471 ;;; have not yet bottomed out on the first COND branch; in this case
2472 ;;; we optimistically assume that this type will be the one we end up
2473 ;;; with, and set the ASSERTED-TYPE to it. We can never get better
2474 ;;; than the type that we have the first time we bottom out. Later
2475 ;;; THE's (or the absence thereof) can only weaken this result.
2476 ;;;
2477 ;;; We make this work by getting USE-CONTINUATION to do the unioning
2478 ;;; across COND branches. We can't do it here, since we don't know how
2479 ;;; many branches there are going to be.
2480 (defun do-the-stuff (type cont lexenv name)
2481   (declare (type continuation cont) (type lexenv lexenv))
2482   (let* ((ctype (values-specifier-type type))
2483          (old-type (or (lexenv-find cont type-restrictions)
2484                        *wild-type*))
2485          (intersects (values-types-equal-or-intersect old-type ctype))
2486          (int (values-type-intersection old-type ctype))
2487          (new (if intersects int old-type)))
2488     (when (null (find-uses cont))
2489       (setf (continuation-asserted-type cont) new))
2490     (when (and (not intersects)
2491                (not (policy *lexenv*
2492                             (= inhibit-warnings 3)))) ;FIXME: really OK to suppress?
2493       (compiler-warning
2494        "The type ~S in ~S declaration conflicts with an enclosing assertion:~%   ~S"
2495        (type-specifier ctype)
2496        name
2497        (type-specifier old-type)))
2498     (make-lexenv :type-restrictions `((,cont . ,new))
2499                  :default lexenv)))
2500
2501 ;;; Assert that FORM evaluates to the specified type (which may be a
2502 ;;; VALUES type).
2503 ;;;
2504 ;;; FIXME: In a version of CMU CL that I used at Cadabra ca. 20000101,
2505 ;;; this didn't seem to expand into an assertion, at least for ALIEN
2506 ;;; values. Check that SBCL doesn't have this problem.
2507 (def-ir1-translator the ((type value) start cont)
2508   (let ((*lexenv* (do-the-stuff type cont *lexenv* 'the)))
2509     (ir1-convert start cont value)))
2510
2511 ;;; This is like the THE special form, except that it believes
2512 ;;; whatever you tell it. It will never generate a type check, but
2513 ;;; will cause a warning if the compiler can prove the assertion is
2514 ;;; wrong.
2515 ;;;
2516 ;;; Since the CONTINUATION-DERIVED-TYPE is computed as the union of
2517 ;;; its uses's types, setting it won't work. Instead we must intersect
2518 ;;; the type with the uses's DERIVED-TYPE.
2519 (def-ir1-translator truly-the ((type value) start cont)
2520   #!+sb-doc
2521   (declare (inline member))
2522   (let ((type (values-specifier-type type))
2523         (old (find-uses cont)))
2524     (ir1-convert start cont value)
2525     (do-uses (use cont)
2526       (unless (member use old :test #'eq)
2527         (derive-node-type use type)))))
2528 \f
2529 ;;;; SETQ
2530
2531 ;;; If there is a definition in LEXENV-VARIABLES, just set that,
2532 ;;; otherwise look at the global information. If the name is for a
2533 ;;; constant, then error out.
2534 (def-ir1-translator setq ((&whole source &rest things) start cont)
2535   (let ((len (length things)))
2536     (when (oddp len)
2537       (compiler-error "odd number of args to SETQ: ~S" source))
2538     (if (= len 2)
2539         (let* ((name (first things))
2540                (leaf (or (lexenv-find name variables)
2541                          (find-free-variable name))))
2542           (etypecase leaf
2543             (leaf
2544              (when (or (constant-p leaf)
2545                        (and (global-var-p leaf)
2546                             (eq (global-var-kind leaf) :constant)))
2547                (compiler-error "~S is a constant and thus can't be set." name))
2548              (when (and (lambda-var-p leaf)
2549                         (lambda-var-ignorep leaf))
2550                ;; ANSI's definition of "Declaration IGNORE, IGNORABLE"
2551                ;; requires that this be a STYLE-WARNING, not a full warning.
2552                (compiler-style-warning
2553                 "~S is being set even though it was declared to be ignored."
2554                 name))
2555              (set-variable start cont leaf (second things)))
2556             (cons
2557              (aver (eq (car leaf) 'MACRO))
2558              (ir1-convert start cont `(setf ,(cdr leaf) ,(second things))))
2559             (heap-alien-info
2560              (ir1-convert start cont
2561                           `(%set-heap-alien ',leaf ,(second things))))))
2562         (collect ((sets))
2563           (do ((thing things (cddr thing)))
2564               ((endp thing)
2565                (ir1-convert-progn-body start cont (sets)))
2566             (sets `(setq ,(first thing) ,(second thing))))))))
2567
2568 ;;; This is kind of like REFERENCE-LEAF, but we generate a SET node.
2569 ;;; This should only need to be called in SETQ.
2570 (defun set-variable (start cont var value)
2571   (declare (type continuation start cont) (type basic-var var))
2572   (let ((dest (make-continuation)))
2573     (setf (continuation-asserted-type dest) (leaf-type var))
2574     (ir1-convert start dest value)
2575     (let ((res (make-set :var var :value dest)))
2576       (setf (continuation-dest dest) res)
2577       (setf (leaf-ever-used var) t)
2578       (push res (basic-var-sets var))
2579       (prev-link res dest)
2580       (use-continuation res cont))))
2581 \f
2582 ;;;; CATCH, THROW and UNWIND-PROTECT
2583
2584 ;;; We turn THROW into a multiple-value-call of a magical function,
2585 ;;; since as as far as IR1 is concerned, it has no interesting
2586 ;;; properties other than receiving multiple-values.
2587 (def-ir1-translator throw ((tag result) start cont)
2588   #!+sb-doc
2589   "Throw Tag Form
2590   Do a non-local exit, return the values of Form from the CATCH whose tag
2591   evaluates to the same thing as Tag."
2592   (ir1-convert start cont
2593                `(multiple-value-call #'%throw ,tag ,result)))
2594
2595 ;;; This is a special special form used to instantiate a cleanup as
2596 ;;; the current cleanup within the body. KIND is a the kind of cleanup
2597 ;;; to make, and MESS-UP is a form that does the mess-up action. We
2598 ;;; make the MESS-UP be the USE of the MESS-UP form's continuation,
2599 ;;; and introduce the cleanup into the lexical environment. We
2600 ;;; back-patch the ENTRY-CLEANUP for the current cleanup to be the new
2601 ;;; cleanup, since this inner cleanup is the interesting one.
2602 (def-ir1-translator %within-cleanup ((kind mess-up &body body) start cont)
2603   (let ((dummy (make-continuation))
2604         (dummy2 (make-continuation)))
2605     (ir1-convert start dummy mess-up)
2606     (let* ((mess-node (continuation-use dummy))
2607            (cleanup (make-cleanup :kind kind
2608                                   :mess-up mess-node))
2609            (old-cup (lexenv-cleanup *lexenv*))
2610            (*lexenv* (make-lexenv :cleanup cleanup)))
2611       (setf (entry-cleanup (cleanup-mess-up old-cup)) cleanup)
2612       (ir1-convert dummy dummy2 '(%cleanup-point))
2613       (ir1-convert-progn-body dummy2 cont body))))
2614
2615 ;;; This is a special special form that makes an "escape function"
2616 ;;; which returns unknown values from named block. We convert the
2617 ;;; function, set its kind to :ESCAPE, and then reference it. The
2618 ;;; :Escape kind indicates that this function's purpose is to
2619 ;;; represent a non-local control transfer, and that it might not
2620 ;;; actually have to be compiled.
2621 ;;;
2622 ;;; Note that environment analysis replaces references to escape
2623 ;;; functions with references to the corresponding NLX-INFO structure.
2624 (def-ir1-translator %escape-function ((tag) start cont)
2625   (let ((fun (ir1-convert-lambda
2626               `(lambda ()
2627                  (return-from ,tag (%unknown-values))))))
2628     (setf (functional-kind fun) :escape)
2629     (reference-leaf start cont fun)))
2630
2631 ;;; Yet another special special form. This one looks up a local
2632 ;;; function and smashes it to a :CLEANUP function, as well as
2633 ;;; referencing it.
2634 (def-ir1-translator %cleanup-function ((name) start cont)
2635   (let ((fun (lexenv-find name functions)))
2636     (aver (lambda-p fun))
2637     (setf (functional-kind fun) :cleanup)
2638     (reference-leaf start cont fun)))
2639
2640 ;;; We represent the possibility of the control transfer by making an
2641 ;;; "escape function" that does a lexical exit, and instantiate the
2642 ;;; cleanup using %WITHIN-CLEANUP.
2643 (def-ir1-translator catch ((tag &body body) start cont)
2644   #!+sb-doc
2645   "Catch Tag Form*
2646   Evaluates Tag and instantiates it as a catcher while the body forms are
2647   evaluated in an implicit PROGN. If a THROW is done to Tag within the dynamic
2648   scope of the body, then control will be transferred to the end of the body
2649   and the thrown values will be returned."
2650   (ir1-convert
2651    start cont
2652    (let ((exit-block (gensym "EXIT-BLOCK-")))
2653      `(block ,exit-block
2654         (%within-cleanup
2655             :catch
2656             (%catch (%escape-function ,exit-block) ,tag)
2657           ,@body)))))
2658
2659 ;;; UNWIND-PROTECT is similar to CATCH, but more hairy. We make the
2660 ;;; cleanup forms into a local function so that they can be referenced
2661 ;;; both in the case where we are unwound and in any local exits. We
2662 ;;; use %CLEANUP-FUNCTION on this to indicate that reference by
2663 ;;; %UNWIND-PROTECT ISN'T "real", and thus doesn't cause creation of
2664 ;;; an XEP.
2665 (def-ir1-translator unwind-protect ((protected &body cleanup) start cont)
2666   #!+sb-doc
2667   "Unwind-Protect Protected Cleanup*
2668   Evaluate the form Protected, returning its values. The cleanup forms are
2669   evaluated whenever the dynamic scope of the Protected form is exited (either
2670   due to normal completion or a non-local exit such as THROW)."
2671   (ir1-convert
2672    start cont
2673    (let ((cleanup-fun (gensym "CLEANUP-FUN-"))
2674          (drop-thru-tag (gensym "DROP-THRU-TAG-"))
2675          (exit-tag (gensym "EXIT-TAG-"))
2676          (next (gensym "NEXT"))
2677          (start (gensym "START"))
2678          (count (gensym "COUNT")))
2679      `(flet ((,cleanup-fun () ,@cleanup nil))
2680         ;; FIXME: If we ever get DYNAMIC-EXTENT working, then
2681         ;; ,CLEANUP-FUN should probably be declared DYNAMIC-EXTENT,
2682         ;; and something can be done to make %ESCAPE-FUNCTION have
2683         ;; dynamic extent too.
2684         (block ,drop-thru-tag
2685           (multiple-value-bind (,next ,start ,count)
2686               (block ,exit-tag
2687                 (%within-cleanup
2688                     :unwind-protect
2689                     (%unwind-protect (%escape-function ,exit-tag)
2690                                      (%cleanup-function ,cleanup-fun))
2691                   (return-from ,drop-thru-tag ,protected)))
2692             (,cleanup-fun)
2693             (%continue-unwind ,next ,start ,count)))))))
2694 \f
2695 ;;;; multiple-value stuff
2696
2697 ;;; If there are arguments, MULTIPLE-VALUE-CALL turns into an
2698 ;;; MV-COMBINATION.
2699 ;;;
2700 ;;; If there are no arguments, then we convert to a normal
2701 ;;; combination, ensuring that a MV-COMBINATION always has at least
2702 ;;; one argument. This can be regarded as an optimization, but it is
2703 ;;; more important for simplifying compilation of MV-COMBINATIONS.
2704 (def-ir1-translator multiple-value-call ((fun &rest args) start cont)
2705   #!+sb-doc
2706   "MULTIPLE-VALUE-CALL Function Values-Form*
2707   Call Function, passing all the values of each Values-Form as arguments,
2708   values from the first Values-Form making up the first argument, etc."
2709   (let* ((fun-cont (make-continuation))
2710          (node (if args
2711                    (make-mv-combination fun-cont)
2712                    (make-combination fun-cont))))
2713     (ir1-convert start fun-cont
2714                  (if (and (consp fun) (eq (car fun) 'function))
2715                      fun
2716                      `(%coerce-callable-to-function ,fun)))
2717     (setf (continuation-dest fun-cont) node)
2718     (assert-continuation-type fun-cont
2719                               (specifier-type '(or function symbol)))
2720     (collect ((arg-conts))
2721       (let ((this-start fun-cont))
2722         (dolist (arg args)
2723           (let ((this-cont (make-continuation node)))
2724             (ir1-convert this-start this-cont arg)
2725             (setq this-start this-cont)
2726             (arg-conts this-cont)))
2727         (prev-link node this-start)
2728         (use-continuation node cont)
2729         (setf (basic-combination-args node) (arg-conts))))))
2730
2731 ;;; MULTIPLE-VALUE-PROG1 is represented implicitly in IR1 by having a
2732 ;;; the result code use result continuation (CONT), but transfer
2733 ;;; control to the evaluation of the body. In other words, the result
2734 ;;; continuation isn't IMMEDIATELY-USED-P by the nodes that compute
2735 ;;; the result.
2736 ;;;
2737 ;;; In order to get the control flow right, we convert the result with
2738 ;;; a dummy result continuation, then convert all the uses of the
2739 ;;; dummy to be uses of CONT. If a use is an EXIT, then we also
2740 ;;; substitute CONT for the dummy in the corresponding ENTRY node so
2741 ;;; that they are consistent. Note that this doesn't amount to
2742 ;;; changing the exit target, since the control destination of an exit
2743 ;;; is determined by the block successor; we are just indicating the
2744 ;;; continuation that the result is delivered to.
2745 ;;;
2746 ;;; We then convert the body, using another dummy continuation in its
2747 ;;; own block as the result. After we are done converting the body, we
2748 ;;; move all predecessors of the dummy end block to CONT's block.
2749 ;;;
2750 ;;; Note that we both exploit and maintain the invariant that the CONT
2751 ;;; to an IR1 convert method either has no block or starts the block
2752 ;;; that control should transfer to after completion for the form.
2753 ;;; Nested MV-PROG1's work because during conversion of the result
2754 ;;; form, we use dummy continuation whose block is the true control
2755 ;;; destination.
2756 (def-ir1-translator multiple-value-prog1 ((result &rest forms) start cont)
2757   #!+sb-doc
2758   "MULTIPLE-VALUE-PROG1 Values-Form Form*
2759   Evaluate Values-Form and then the Forms, but return all the values of
2760   Values-Form."
2761   (continuation-starts-block cont)
2762   (let* ((dummy-result (make-continuation))
2763          (dummy-start (make-continuation))
2764          (cont-block (continuation-block cont)))
2765     (continuation-starts-block dummy-start)
2766     (ir1-convert start dummy-start result)
2767
2768     (substitute-continuation-uses cont dummy-start)
2769
2770     (continuation-starts-block dummy-result)
2771     (ir1-convert-progn-body dummy-start dummy-result forms)
2772     (let ((end-block (continuation-block dummy-result)))
2773       (dolist (pred (block-pred end-block))
2774         (unlink-blocks pred end-block)
2775         (link-blocks pred cont-block))
2776       (aver (not (continuation-dest dummy-result)))
2777       (delete-continuation dummy-result)
2778       (remove-from-dfo end-block))))
2779 \f
2780 ;;;; interface to defining macros
2781
2782 ;;;; FIXME:
2783 ;;;;   classic CMU CL comment:
2784 ;;;;     DEFMACRO and DEFUN expand into calls to %DEFxxx functions
2785 ;;;;     so that we get a chance to see what is going on. We define
2786 ;;;;     IR1 translators for these functions which look at the
2787 ;;;;     definition and then generate a call to the %%DEFxxx function.
2788 ;;;; Alas, this implementation doesn't do the right thing for
2789 ;;;; non-toplevel uses of these forms, so this should probably
2790 ;;;; be changed to use EVAL-WHEN instead.
2791
2792 ;;; Return a new source path with any stuff intervening between the
2793 ;;; current path and the first form beginning with NAME stripped off.
2794 ;;; This is used to hide the guts of DEFmumble macros to prevent
2795 ;;; annoying error messages.
2796 (defun revert-source-path (name)
2797   (do ((path *current-path* (cdr path)))
2798       ((null path) *current-path*)
2799     (let ((first (first path)))
2800       (when (or (eq first name)
2801                 (eq first 'original-source-start))
2802         (return path)))))
2803
2804 ;;; Warn about incompatible or illegal definitions and add the macro
2805 ;;; to the compiler environment.
2806 ;;;
2807 ;;; Someday we could check for macro arguments being incompatibly
2808 ;;; redefined. Doing this right will involve finding the old macro
2809 ;;; lambda-list and comparing it with the new one.
2810 (def-ir1-translator %defmacro ((qname qdef lambda-list doc) start cont
2811                                :kind :function)
2812   (let (;; QNAME is typically a quoted name. I think the idea is to let
2813         ;; %DEFMACRO work as an ordinary function when interpreting. Whatever
2814         ;; the reason it's there, we don't want it any more. -- WHN 19990603
2815         (name (eval qname))
2816         ;; QDEF should be a sharp-quoted definition. We don't want to make a
2817         ;; function of it just yet, so we just drop the sharp-quote.
2818         (def (progn
2819                (aver (eq 'function (first qdef)))
2820                (aver (proper-list-of-length-p qdef 2))
2821                (second qdef))))
2822
2823     (/show "doing IR1 translator for %DEFMACRO" name)
2824
2825     (unless (symbolp name)
2826       (compiler-error "The macro name ~S is not a symbol." name))
2827
2828     (ecase (info :function :kind name)
2829       ((nil))
2830       (:function
2831        (remhash name *free-functions*)
2832        (undefine-function-name name)
2833        (compiler-warning
2834         "~S is being redefined as a macro when it was ~
2835          previously ~(~A~) to be a function."
2836         name
2837         (info :function :where-from name)))
2838       (:macro)
2839       (:special-form
2840        (compiler-error "The special form ~S can't be redefined as a macro."
2841                        name)))
2842
2843     (setf (info :function :kind name) :macro
2844           (info :function :where-from name) :defined
2845           (info :function :macro-function name) (coerce def 'function))
2846
2847     (let* ((*current-path* (revert-source-path 'defmacro))
2848            (fun (ir1-convert-lambda def name)))
2849       (setf (leaf-name fun)
2850             (concatenate 'string "DEFMACRO " (symbol-name name)))
2851       (setf (functional-arg-documentation fun) (eval lambda-list))
2852
2853       (ir1-convert start cont `(%%defmacro ',name ,fun ,doc)))
2854
2855     (when sb!xc:*compile-print*
2856       ;; FIXME: It would be nice to convert this, and the other places
2857       ;; which create compiler diagnostic output prefixed by
2858       ;; semicolons, to use some common utility which automatically
2859       ;; prefixes all its output with semicolons. (The addition of
2860       ;; semicolon prefixes was introduced ca. sbcl-0.6.8.10 as the
2861       ;; "MNA compiler message patch", and implemented by modifying a
2862       ;; bunch of output statements on a case-by-case basis, which
2863       ;; seems unnecessarily error-prone and unclear, scattering
2864       ;; implicit information about output style throughout the
2865       ;; system.) Starting by rewriting COMPILER-MUMBLE to add
2866       ;; semicolon prefixes would be a good start, and perhaps also:
2867       ;;   * Add semicolon prefixes for "FOO assembled" messages emitted 
2868       ;;     when e.g. src/assembly/x86/assem-rtns.lisp is processed.
2869       ;;   * At least some debugger output messages deserve semicolon
2870       ;;     prefixes too:
2871       ;;     ** restarts table
2872       ;;     ** "Within the debugger, you can type HELP for help."
2873       (compiler-mumble "~&; converted ~S~%" name))))
2874
2875 (def-ir1-translator %define-compiler-macro ((name def lambda-list doc)
2876                                             start cont
2877                                             :kind :function)
2878   (let ((name (eval name))
2879         (def (second def))) ; We don't want to make a function just yet...
2880
2881     (when (eq (info :function :kind name) :special-form)
2882       (compiler-error "attempt to define a compiler-macro for special form ~S"
2883                       name))
2884
2885     (setf (info :function :compiler-macro-function name)
2886           (coerce def 'function))
2887
2888     (let* ((*current-path* (revert-source-path 'define-compiler-macro))
2889            (fun (ir1-convert-lambda def name)))
2890       (setf (leaf-name fun)
2891             (let ((*print-case* :upcase))
2892               (format nil "DEFINE-COMPILER-MACRO ~S" name)))
2893       (setf (functional-arg-documentation fun) (eval lambda-list))
2894
2895       (ir1-convert start cont `(%%define-compiler-macro ',name ,fun ,doc)))
2896
2897     (when sb!xc:*compile-print*
2898       (compiler-mumble "~&; converted ~S~%" name))))
2899 \f
2900 ;;;; defining global functions
2901
2902 ;;; Convert FUN as a lambda in the null environment, but use the
2903 ;;; current compilation policy. Note that FUN may be a
2904 ;;; LAMBDA-WITH-ENVIRONMENT, so we may have to augment the environment
2905 ;;; to reflect the state at the definition site.
2906 (defun ir1-convert-inline-lambda (fun &optional name)
2907   (destructuring-bind (decls macros symbol-macros &rest body)
2908                       (if (eq (car fun) 'lambda-with-environment)
2909                           (cdr fun)
2910                           `(() () () . ,(cdr fun)))
2911     (let ((*lexenv* (make-lexenv
2912                      :default (process-decls decls nil nil
2913                                              (make-continuation)
2914                                              (make-null-lexenv))
2915                      :variables (copy-list symbol-macros)
2916                      :functions
2917                      (mapcar (lambda (x)
2918                                `(,(car x) .
2919                                  (macro . ,(coerce (cdr x) 'function))))
2920                              macros)
2921                      :policy (lexenv-policy *lexenv*))))
2922       (ir1-convert-lambda `(lambda ,@body) name))))
2923
2924 ;;; Return a lambda that has been "closed" with respect to ENV,
2925 ;;; returning a LAMBDA-WITH-ENVIRONMENT if there are interesting
2926 ;;; macros or declarations. If there is something too complex (like a
2927 ;;; lexical variable) in the environment, then we return NIL.
2928 (defun inline-syntactic-closure-lambda (lambda &optional (env *lexenv*))
2929   (let ((variables (lexenv-variables env))
2930         (functions (lexenv-functions env))
2931         (decls ())
2932         (symmacs ())
2933         (macros ()))
2934     (cond ((or (lexenv-blocks env) (lexenv-tags env)) nil)
2935           ((and (null variables) (null functions))
2936            lambda)
2937           ((dolist (x variables nil)
2938              (let ((name (car x))
2939                    (what (cdr x)))
2940                (when (eq x (assoc name variables :test #'eq))
2941                  (typecase what
2942                    (cons
2943                     (aver (eq (car what) 'macro))
2944                     (push x symmacs))
2945                    (global-var
2946                     (aver (eq (global-var-kind what) :special))
2947                     (push `(special ,name) decls))
2948                    (t (return t))))))
2949            nil)
2950           ((dolist (x functions nil)
2951              (let ((name (car x))
2952                    (what (cdr x)))
2953                (when (eq x (assoc name functions :test #'equal))
2954                  (typecase what
2955                    (cons
2956                     (push (cons name
2957                                 (function-lambda-expression (cdr what)))
2958                           macros))
2959                    (global-var
2960                     (when (defined-function-p what)
2961                       (push `(,(car (rassoc (defined-function-inlinep what)
2962                                             *inlinep-translations*))
2963                               ,name)
2964                             decls)))
2965                    (t (return t))))))
2966            nil)
2967           (t
2968            `(lambda-with-environment ,decls
2969                                      ,macros
2970                                      ,symmacs
2971                                      . ,(rest lambda))))))
2972
2973 ;;; Get a DEFINED-FUNCTION object for a function we are about to
2974 ;;; define. If the function has been forward referenced, then
2975 ;;; substitute for the previous references.
2976 (defun get-defined-function (name)
2977   (let* ((name (proclaim-as-function-name name))
2978          (found (find-free-function name "Eh?")))
2979     (note-name-defined name :function)
2980     (cond ((not (defined-function-p found))
2981            (aver (not (info :function :inlinep name)))
2982            (let* ((where-from (leaf-where-from found))
2983                   (res (make-defined-function
2984                         :name name
2985                         :where-from (if (eq where-from :declared)
2986                                         :declared :defined)
2987                         :type (leaf-type found))))
2988              (substitute-leaf res found)
2989              (setf (gethash name *free-functions*) res)))
2990           ;; If *FREE-FUNCTIONS* has a previously converted definition for this
2991           ;; name, then blow it away and try again.
2992           ((defined-function-functional found)
2993            (remhash name *free-functions*)
2994            (get-defined-function name))
2995           (t found))))
2996
2997 ;;; Check a new global function definition for consistency with
2998 ;;; previous declaration or definition, and assert argument/result
2999 ;;; types if appropriate. This assertion is suppressed by the
3000 ;;; EXPLICIT-CHECK attribute, which is specified on functions that
3001 ;;; check their argument types as a consequence of type dispatching.
3002 ;;; This avoids redundant checks such as NUMBERP on the args to +,
3003 ;;; etc.
3004 (defun assert-new-definition (var fun)
3005   (let ((type (leaf-type var))
3006         (for-real (eq (leaf-where-from var) :declared))
3007         (info (info :function :info (leaf-name var))))
3008     (assert-definition-type
3009      fun type
3010      ;; KLUDGE: Common Lisp is such a dynamic language that in general
3011      ;; all we can do here in general is issue a STYLE-WARNING. It
3012      ;; would be nice to issue a full WARNING in the special case of
3013      ;; of type mismatches within a compilation unit (as in section
3014      ;; 3.2.2.3 of the spec) but at least as of sbcl-0.6.11, we don't
3015      ;; keep track of whether the mismatched data came from the same
3016      ;; compilation unit, so we can't do that. -- WHN 2001-02-11
3017      :error-function #'compiler-style-warning
3018      :warning-function (cond (info #'compiler-style-warning)
3019                              (for-real #'compiler-note)
3020                              (t nil))
3021      :really-assert
3022      (and for-real
3023           (not (and info
3024                     (ir1-attributep (function-info-attributes info)
3025                                     explicit-check))))
3026      :where (if for-real
3027                 "previous declaration"
3028                 "previous definition"))))
3029
3030 ;;; Convert a lambda doing all the basic stuff we would do if we were
3031 ;;; converting a DEFUN. This is used both by the %DEFUN translator and
3032 ;;; for global inline expansion.
3033 ;;;
3034 ;;; Unless a :INLINE function, we temporarily clobber the inline
3035 ;;; expansion. This prevents recursive inline expansion of
3036 ;;; opportunistic pseudo-inlines.
3037 (defun ir1-convert-lambda-for-defun (lambda var expansion converter)
3038   (declare (cons lambda) (function converter) (type defined-function var))
3039   (let ((var-expansion (defined-function-inline-expansion var)))
3040     (unless (eq (defined-function-inlinep var) :inline)
3041       (setf (defined-function-inline-expansion var) nil))
3042     (let* ((name (leaf-name var))
3043            (fun (funcall converter lambda name))
3044            (function-info (info :function :info name)))
3045       (setf (functional-inlinep fun) (defined-function-inlinep var))
3046       (assert-new-definition var fun)
3047       (setf (defined-function-inline-expansion var) var-expansion)
3048       ;; If definitely not an interpreter stub, then substitute for any
3049       ;; old references.
3050       (unless (or (eq (defined-function-inlinep var) :notinline)
3051                   (not *block-compile*)
3052                   (and function-info
3053                        (or (function-info-transforms function-info)
3054                            (function-info-templates function-info)
3055                            (function-info-ir2-convert function-info))))
3056         (substitute-leaf fun var)
3057         ;; If in a simple environment, then we can allow backward
3058         ;; references to this function from following top-level forms.
3059         (when expansion (setf (defined-function-functional var) fun)))
3060       fun)))
3061
3062 ;;; Convert the definition and install it in the global environment
3063 ;;; with a LABELS-like effect. If the lexical environment is not null,
3064 ;;; then we only install the definition during the processing of this
3065 ;;; DEFUN, ensuring that the function cannot be called outside of the
3066 ;;; correct environment. If the function is globally NOTINLINE, then
3067 ;;; that inhibits even local substitution. Also, emit top-level code
3068 ;;; to install the definition.
3069 ;;;
3070 ;;; This is one of the major places where the semantics of block
3071 ;;; compilation is handled. Substitution for global names is totally
3072 ;;; inhibited if *BLOCK-COMPILE* is NIL. And if *BLOCK-COMPILE* is
3073 ;;; true and entry points are specified, then we don't install global
3074 ;;; definitions for non-entry functions (effectively turning them into
3075 ;;; local lexical functions.)
3076 (def-ir1-translator %defun ((name def doc source) start cont
3077                             :kind :function)
3078   (declare (ignore source))
3079   (let* ((name (eval name))
3080          (lambda (second def))
3081          (*current-path* (revert-source-path 'defun))
3082          (expansion (unless (eq (info :function :inlinep name) :notinline)
3083                       (inline-syntactic-closure-lambda lambda))))
3084     ;; If not in a simple environment or NOTINLINE, then discard any
3085     ;; forward references to this function.
3086     (unless expansion (remhash name *free-functions*))
3087
3088     (let* ((var (get-defined-function name))
3089            (save-expansion (and (member (defined-function-inlinep var)
3090                                         '(:inline :maybe-inline))
3091                                 expansion)))
3092       (setf (defined-function-inline-expansion var) expansion)
3093       (setf (info :function :inline-expansion name) save-expansion)
3094       ;; If there is a type from a previous definition, blast it,
3095       ;; since it is obsolete.
3096       (when (eq (leaf-where-from var) :defined)
3097         (setf (leaf-type var) (specifier-type 'function)))
3098
3099       (let ((fun (ir1-convert-lambda-for-defun lambda
3100                                                var
3101                                                expansion
3102                                                #'ir1-convert-lambda)))
3103         (ir1-convert
3104          start cont
3105          (if (and *block-compile* *entry-points*
3106                   (not (member name *entry-points* :test #'equal)))
3107              `',name
3108              `(%%defun ',name ,fun ,doc
3109                        ,@(when save-expansion `(',save-expansion)))))
3110
3111         (when sb!xc:*compile-print*
3112           (compiler-mumble "~&; converted ~S~%" name))))))