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