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