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