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