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