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