1.0.23.11: Typecheck late-bound calls too
[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 ;;; *CURRENT-FORM-NUMBER* is used in FIND-SOURCE-PATHS to compute the
18 ;;; form number to associate with a source path. This should be bound
19 ;;; to an initial value of 0 before the processing of each truly
20 ;;; top level form.
21 (declaim (type index *current-form-number*))
22 (defvar *current-form-number*)
23
24 ;;; *SOURCE-PATHS* is a hashtable from source code forms to the path
25 ;;; taken through the source to reach the form. This provides a way to
26 ;;; keep track of the location of original source forms, even when
27 ;;; macroexpansions and other arbitary permutations of the code
28 ;;; happen. This table is initialized by calling FIND-SOURCE-PATHS on
29 ;;; the original source.
30 ;;;
31 ;;; It is fairly useless to store symbols, characters, or fixnums in
32 ;;; this table, as 42 is EQ to 42 no matter where in the source it
33 ;;; appears. GET-SOURCE-PATH and NOTE-SOURCE-PATH functions should be
34 ;;; always used to access this table.
35 (declaim (hash-table *source-paths*))
36 (defvar *source-paths*)
37
38 (declaim (inline source-form-has-path-p))
39 (defun source-form-has-path-p (form)
40   (not (typep form '(or symbol fixnum character))))
41
42 (defun get-source-path (form)
43   (when (source-form-has-path-p form)
44     (gethash form *source-paths*)))
45
46 (defun note-source-path (form &rest arguments)
47   (when (source-form-has-path-p form)
48     (setf (gethash form *source-paths*)
49           (apply #'list* 'original-source-start *current-form-number* arguments))))
50
51 ;;; *CURRENT-COMPONENT* is the COMPONENT structure which we link
52 ;;; blocks into as we generate them. This just serves to glue the
53 ;;; emitted blocks together until local call analysis and flow graph
54 ;;; canonicalization figure out what is really going on. We need to
55 ;;; keep track of all the blocks generated so that we can delete them
56 ;;; if they turn out to be unreachable.
57 ;;;
58 ;;; FIXME: It's confusing having one variable named *CURRENT-COMPONENT*
59 ;;; and another named *COMPONENT-BEING-COMPILED*. (In CMU CL they
60 ;;; were called *CURRENT-COMPONENT* and *COMPILE-COMPONENT* respectively,
61 ;;; which was also confusing.)
62 (declaim (type (or component null) *current-component*))
63 (defvar *current-component*)
64
65 ;;; *CURRENT-PATH* is the source path of the form we are currently
66 ;;; translating. See NODE-SOURCE-PATH in the NODE structure.
67 (declaim (list *current-path*))
68 (defvar *current-path*)
69
70 (defvar *derive-function-types* nil
71   "Should the compiler assume that function types will never change,
72   so that it can use type information inferred from current definitions
73   to optimize code which uses those definitions? Setting this true
74   gives non-ANSI, early-CMU-CL behavior. It can be useful for improving
75   the efficiency of stable code.")
76
77 (defvar *fun-names-in-this-file* nil)
78
79 (defvar *post-binding-variable-lexenv* nil)
80 \f
81 ;;;; namespace management utilities
82
83 (defun fun-lexically-notinline-p (name)
84   (let ((fun (lexenv-find name funs :test #'equal)))
85     ;; a declaration will trump a proclamation
86     (if (and fun (defined-fun-p fun))
87         (eq (defined-fun-inlinep fun) :notinline)
88         (eq (info :function :inlinep name) :notinline))))
89
90 ;; This will get redefined in PCL boot.
91 (declaim (notinline update-info-for-gf))
92 (defun maybe-update-info-for-gf (name)
93   (declare (ignorable name))
94   (values))
95
96 ;;; Return a GLOBAL-VAR structure usable for referencing the global
97 ;;; function NAME.
98 (defun find-global-fun (name latep)
99   (unless (info :function :kind name)
100     (setf (info :function :kind name) :function)
101     (setf (info :function :where-from name) :assumed))
102   (let ((where (info :function :where-from name)))
103     (when (and (eq where :assumed)
104                ;; In the ordinary target Lisp, it's silly to report
105                ;; undefinedness when the function is defined in the
106                ;; running Lisp. But at cross-compile time, the current
107                ;; definedness of a function is irrelevant to the
108                ;; definedness at runtime, which is what matters.
109                #-sb-xc-host (not (fboundp name))
110                ;; LATEP is true when the user has indicated that
111                ;; late-late binding is desired by using eg. a quoted
112                ;; symbol -- in which case it makes little sense to
113                ;; complain about undefined functions.
114                (not latep))
115       (note-undefined-reference name :function))
116     (make-global-var
117      :kind :global-function
118      :%source-name name
119      :type (if (or (eq where :declared)
120                    (and (not latep)
121                         (or *derive-function-types*
122                             (eq where :defined-method)
123                             (and (not (fun-lexically-notinline-p name))
124                                  (member name *fun-names-in-this-file*
125                                          :test #'equal)))))
126                (progn
127                  (maybe-update-info-for-gf name)
128                  (info :function :type name))
129                (specifier-type 'function))
130      :defined-type (if (eq where :defined)
131                        (info :function :type name)
132                        *universal-type*)
133      :where-from where)))
134
135 ;;; Has the *FREE-FUNS* entry FREE-FUN become invalid?
136 ;;;
137 ;;; In CMU CL, the answer was implicitly always true, so this
138 ;;; predicate didn't exist.
139 ;;;
140 ;;; This predicate was added to fix bug 138 in SBCL. In some obscure
141 ;;; circumstances, it was possible for a *FREE-FUNS* entry to contain a
142 ;;; DEFINED-FUN whose DEFINED-FUN-FUNCTIONAL object contained IR1
143 ;;; stuff (NODEs, BLOCKs...) referring to an already compiled (aka
144 ;;; "dead") component. When this IR1 stuff was reused in a new
145 ;;; component, under further obscure circumstances it could be used by
146 ;;; WITH-IR1-ENVIRONMENT-FROM-NODE to generate a binding for
147 ;;; *CURRENT-COMPONENT*. At that point things got all confused, since
148 ;;; IR1 conversion was sending code to a component which had already
149 ;;; been compiled and would never be compiled again.
150 (defun invalid-free-fun-p (free-fun)
151   ;; There might be other reasons that *FREE-FUN* entries could
152   ;; become invalid, but the only one we've been bitten by so far
153   ;; (sbcl-0.pre7.118) is this one:
154   (and (defined-fun-p free-fun)
155        (let ((functional (defined-fun-functional free-fun)))
156          (or (and functional
157                   (eql (functional-kind functional) :deleted))
158              (and (lambda-p functional)
159                   (or
160                    ;; (The main reason for this first test is to bail
161                    ;; out early in cases where the LAMBDA-COMPONENT
162                    ;; call in the second test would fail because links
163                    ;; it needs are uninitialized or invalid.)
164                    ;;
165                    ;; If the BIND node for this LAMBDA is null, then
166                    ;; according to the slot comments, the LAMBDA has
167                    ;; been deleted or its call has been deleted. In
168                    ;; that case, it seems rather questionable to reuse
169                    ;; it, and certainly it shouldn't be necessary to
170                    ;; reuse it, so we cheerfully declare it invalid.
171                    (null (lambda-bind functional))
172                    ;; If this IR1 stuff belongs to a dead component,
173                    ;; then we can't reuse it without getting into
174                    ;; bizarre confusion.
175                    (eql (component-info (lambda-component functional))
176                         :dead)))))))
177
178 ;;; If NAME already has a valid entry in *FREE-FUNS*, then return
179 ;;; the value. Otherwise, make a new GLOBAL-VAR using information from
180 ;;; the global environment and enter it in *FREE-FUNS*. If NAME
181 ;;; names a macro or special form, then we error out using the
182 ;;; supplied context which indicates what we were trying to do that
183 ;;; demanded a function.
184 (declaim (ftype (sfunction (t string) global-var) find-free-fun))
185 (defun find-free-fun (name context)
186   (or (let ((old-free-fun (gethash name *free-funs*)))
187         (and (not (invalid-free-fun-p old-free-fun))
188              old-free-fun))
189       (ecase (info :function :kind name)
190         ;; FIXME: The :MACRO and :SPECIAL-FORM cases could be merged.
191         (:macro
192          (compiler-error "The macro name ~S was found ~A." name context))
193         (:special-form
194          (compiler-error "The special form name ~S was found ~A."
195                          name
196                          context))
197         ((:function nil)
198          (check-fun-name name)
199          (note-if-setf-fun-and-macro name)
200          (let ((expansion (fun-name-inline-expansion name))
201                (inlinep (info :function :inlinep name)))
202            (setf (gethash name *free-funs*)
203                  (if (or expansion inlinep)
204                      (make-defined-fun
205                       :%source-name name
206                       :inline-expansion expansion
207                       :inlinep inlinep
208                       :where-from (info :function :where-from name)
209                       :type (if (eq inlinep :notinline)
210                                 (specifier-type 'function)
211                                 (info :function :type name)))
212                      (find-global-fun name nil))))))))
213
214 ;;; Return the LEAF structure for the lexically apparent function
215 ;;; definition of NAME.
216 (declaim (ftype (sfunction (t string) leaf) find-lexically-apparent-fun))
217 (defun find-lexically-apparent-fun (name context)
218   (let ((var (lexenv-find name funs :test #'equal)))
219     (cond (var
220            (unless (leaf-p var)
221              (aver (and (consp var) (eq (car var) 'macro)))
222              (compiler-error "found macro name ~S ~A" name context))
223            var)
224           (t
225            (find-free-fun name context)))))
226
227 ;;; Return the LEAF node for a global variable reference to NAME. If
228 ;;; NAME is already entered in *FREE-VARS*, then we just return the
229 ;;; corresponding value. Otherwise, we make a new leaf using
230 ;;; information from the global environment and enter it in
231 ;;; *FREE-VARS*. If the variable is unknown, then we emit a warning.
232 (declaim (ftype (sfunction (t) (or leaf cons heap-alien-info)) find-free-var))
233 (defun find-free-var (name)
234   (unless (symbolp name)
235     (compiler-error "Variable name is not a symbol: ~S." name))
236   (or (gethash name *free-vars*)
237       (let ((kind (info :variable :kind name))
238             (type (info :variable :type name))
239             (where-from (info :variable :where-from name)))
240         (when (and (eq where-from :assumed) (eq kind :global))
241           (note-undefined-reference name :variable))
242         (setf (gethash name *free-vars*)
243               (case kind
244                 (:alien
245                  (info :variable :alien-info name))
246                 ;; FIXME: The return value in this case should really be
247                 ;; of type SB!C::LEAF.  I don't feel too badly about it,
248                 ;; because the MACRO idiom is scattered throughout this
249                 ;; file, but it should be cleaned up so we're not
250                 ;; throwing random conses around.  --njf 2002-03-23
251                 (:macro
252                  (let ((expansion (info :variable :macro-expansion name))
253                        (type (type-specifier (info :variable :type name))))
254                    `(macro . (the ,type ,expansion))))
255                 (:constant
256                  (let ((value (symbol-value name)))
257                    ;; Override the values of standard symbols in XC,
258                    ;; since we can't redefine them.
259                    #+sb-xc-host
260                    (when (eql (find-symbol (symbol-name name) :cl) name)
261                      (multiple-value-bind (xc-value foundp)
262                          (info :variable :xc-constant-value name)
263                        (cond (foundp
264                               (setf value xc-value))
265                              ((not (eq value name))
266                               (compiler-warn
267                                "Using cross-compilation host's definition of ~S: ~A~%"
268                                name (symbol-value name))))))
269                    (find-constant value name)))
270                 (t
271                  (make-global-var :kind kind
272                                   :%source-name name
273                                   :type type
274                                   :where-from where-from)))))))
275 \f
276 ;;; Grovel over CONSTANT checking for any sub-parts that need to be
277 ;;; processed with MAKE-LOAD-FORM. We have to be careful, because
278 ;;; CONSTANT might be circular. We also check that the constant (and
279 ;;; any subparts) are dumpable at all.
280 (defun maybe-emit-make-load-forms (constant &optional (name nil namep))
281   (let ((xset (alloc-xset)))
282     (labels ((trivialp (value)
283                (typep value
284                       '(or
285                         #-sb-xc-host unboxed-array
286                         #+sb-xc-host (simple-array (unsigned-byte 8) (*))
287                         symbol
288                         number
289                         character
290                         string)))
291              (grovel (value)
292                ;; Unless VALUE is an object which which obviously
293                ;; can't contain other objects
294                (unless (trivialp value)
295                  (if (xset-member-p value xset)
296                      (return-from grovel nil)
297                      (add-to-xset value xset))
298                  (typecase value
299                    (cons
300                     (grovel (car value))
301                     (grovel (cdr value)))
302                    (simple-vector
303                     (dotimes (i (length value))
304                       (grovel (svref value i))))
305                    ((vector t)
306                     (dotimes (i (length value))
307                       (grovel (aref value i))))
308                    ((simple-array t)
309                     ;; Even though the (ARRAY T) branch does the exact
310                     ;; same thing as this branch we do this separately
311                     ;; so that the compiler can use faster versions of
312                     ;; array-total-size and row-major-aref.
313                     (dotimes (i (array-total-size value))
314                       (grovel (row-major-aref value i))))
315                    ((array t)
316                     (dotimes (i (array-total-size value))
317                       (grovel (row-major-aref value i))))
318                    (#+sb-xc-host structure!object
319                     #-sb-xc-host instance
320                     ;; In the target SBCL, we can dump any instance, but
321                     ;; in the cross-compilation host, %INSTANCE-FOO
322                     ;; functions don't work on general instances, only on
323                     ;; STRUCTURE!OBJECTs.
324                     ;;
325                     ;; FIXME: What about funcallable instances with
326                     ;; user-defined MAKE-LOAD-FORM methods?
327                     (when (emit-make-load-form value)
328                       (dotimes (i (- (%instance-length value)
329                                      #+sb-xc-host 0
330                                      #-sb-xc-host (layout-n-untagged-slots
331                                                    (%instance-ref value 0))))
332                         (grovel (%instance-ref value i)))))
333                    (t
334                     (compiler-error
335                      "Objects of type ~S can't be dumped into fasl files."
336                      (type-of value)))))))
337       ;; Dump all non-trivial named constants using the name.
338       (if (and namep (not (typep constant '(or symbol character
339                                             ;; FIXME: Cold init breaks if we
340                                             ;; try to reference FP constants
341                                             ;; thru their names.
342                                             #+sb-xc-host number
343                                             #-sb-xc-host fixnum))))
344           (emit-make-load-form constant name)
345           (grovel constant))))
346   (values))
347 \f
348 ;;;; some flow-graph hacking utilities
349
350 ;;; This function sets up the back link between the node and the
351 ;;; ctran which continues at it.
352 (defun link-node-to-previous-ctran (node ctran)
353   (declare (type node node) (type ctran ctran))
354   (aver (not (ctran-next ctran)))
355   (setf (ctran-next ctran) node)
356   (setf (node-prev node) ctran))
357
358 ;;; This function is used to set the ctran for a node, and thus
359 ;;; determine what is evaluated next. If the ctran has no block, then
360 ;;; we make it be in the block that the node is in. If the ctran heads
361 ;;; its block, we end our block and link it to that block.
362 #!-sb-fluid (declaim (inline use-ctran))
363 (defun use-ctran (node ctran)
364   (declare (type node node) (type ctran ctran))
365   (if (eq (ctran-kind ctran) :unused)
366       (let ((node-block (ctran-block (node-prev node))))
367         (setf (ctran-block ctran) node-block)
368         (setf (ctran-kind ctran) :inside-block)
369         (setf (ctran-use ctran) node)
370         (setf (node-next node) ctran))
371       (%use-ctran node ctran)))
372 (defun %use-ctran (node ctran)
373   (declare (type node node) (type ctran ctran) (inline member))
374   (let ((block (ctran-block ctran))
375         (node-block (ctran-block (node-prev node))))
376     (aver (eq (ctran-kind ctran) :block-start))
377     (when (block-last node-block)
378       (error "~S has already ended." node-block))
379     (setf (block-last node-block) node)
380     (when (block-succ node-block)
381       (error "~S already has successors." node-block))
382     (setf (block-succ node-block) (list block))
383     (when (memq node-block (block-pred block))
384       (error "~S is already a predecessor of ~S." node-block block))
385     (push node-block (block-pred block))))
386
387 ;;; Insert NEW before OLD in the flow-graph.
388 (defun insert-node-before (old new)
389   (let ((prev (node-prev old))
390         (temp (make-ctran)))
391     (ensure-block-start prev)
392     (setf (ctran-next prev) nil)
393     (link-node-to-previous-ctran new prev)
394     (use-ctran new temp)
395     (link-node-to-previous-ctran old temp))
396   (values))
397
398 ;;; This function is used to set the ctran for a node, and thus
399 ;;; determine what receives the value.
400 (defun use-lvar (node lvar)
401   (declare (type valued-node node) (type (or lvar null) lvar))
402   (aver (not (node-lvar node)))
403   (when lvar
404     (setf (node-lvar node) lvar)
405     (cond ((null (lvar-uses lvar))
406            (setf (lvar-uses lvar) node))
407           ((listp (lvar-uses lvar))
408            (aver (not (memq node (lvar-uses lvar))))
409            (push node (lvar-uses lvar)))
410           (t
411            (aver (neq node (lvar-uses lvar)))
412            (setf (lvar-uses lvar) (list node (lvar-uses lvar)))))
413     (reoptimize-lvar lvar)))
414
415 #!-sb-fluid(declaim (inline use-continuation))
416 (defun use-continuation (node ctran lvar)
417   (use-ctran node ctran)
418   (use-lvar node lvar))
419 \f
420 ;;;; exported functions
421
422 ;;; This function takes a form and the top level form number for that
423 ;;; form, and returns a lambda representing the translation of that
424 ;;; form in the current global environment. The returned lambda is a
425 ;;; top level lambda that can be called to cause evaluation of the
426 ;;; forms. This lambda is in the initial component. If FOR-VALUE is T,
427 ;;; then the value of the form is returned from the function,
428 ;;; otherwise NIL is returned.
429 ;;;
430 ;;; This function may have arbitrary effects on the global environment
431 ;;; due to processing of EVAL-WHENs. All syntax error checking is
432 ;;; done, with erroneous forms being replaced by a proxy which signals
433 ;;; an error if it is evaluated. Warnings about possibly inconsistent
434 ;;; or illegal changes to the global environment will also be given.
435 ;;;
436 ;;; We make the initial component and convert the form in a PROGN (and
437 ;;; an optional NIL tacked on the end.) We then return the lambda. We
438 ;;; bind all of our state variables here, rather than relying on the
439 ;;; global value (if any) so that IR1 conversion will be reentrant.
440 ;;; This is necessary for EVAL-WHEN processing, etc.
441 ;;;
442 ;;; The hashtables used to hold global namespace info must be
443 ;;; reallocated elsewhere. Note also that *LEXENV* is not bound, so
444 ;;; that local macro definitions can be introduced by enclosing code.
445 (defun ir1-toplevel (form path for-value &optional (allow-instrumenting t))
446   (declare (list path))
447   (let* ((*current-path* path)
448          (component (make-empty-component))
449          (*current-component* component)
450          (*allow-instrumenting* allow-instrumenting))
451     (setf (component-name component) 'initial-component)
452     (setf (component-kind component) :initial)
453     (let* ((forms (if for-value `(,form) `(,form nil)))
454            (res (ir1-convert-lambda-body
455                  forms ()
456                  :debug-name (debug-name 'top-level-form form))))
457       (setf (functional-entry-fun res) res
458             (functional-arg-documentation res) ()
459             (functional-kind res) :toplevel)
460       res)))
461
462 ;;; This function is called on freshly read forms to record the
463 ;;; initial location of each form (and subform.) Form is the form to
464 ;;; find the paths in, and TLF-NUM is the top level form number of the
465 ;;; truly top level form.
466 ;;;
467 ;;; This gets a bit interesting when the source code is circular. This
468 ;;; can (reasonably?) happen in the case of circular list constants.
469 (defun find-source-paths (form tlf-num)
470   (declare (type index tlf-num))
471   (let ((*current-form-number* 0))
472     (sub-find-source-paths form (list tlf-num)))
473   (values))
474 (defun sub-find-source-paths (form path)
475   (unless (get-source-path form)
476     (note-source-path form path)
477     (incf *current-form-number*)
478     (let ((pos 0)
479           (subform form)
480           (trail form))
481       (declare (fixnum pos))
482       (macrolet ((frob ()
483                    '(progn
484                       (when (atom subform) (return))
485                       (let ((fm (car subform)))
486                         (if (consp fm)
487                             ;; If it's a cons, recurse
488                             (sub-find-source-paths fm (cons pos path))
489                             ;; Otherwise store the containing form. It's
490                             ;; not perfect, but better than nothing.
491                             (unless (zerop pos)
492                               (note-source-path subform pos path)))
493                         (incf pos))
494                       (setq subform (cdr subform))
495                       (when (eq subform trail) (return)))))
496         (loop
497           (frob)
498           (frob)
499           (setq trail (cdr trail)))))))
500 \f
501 ;;;; IR1-CONVERT, macroexpansion and special form dispatching
502
503 (declaim (ftype (sfunction (ctran ctran (or lvar null) t) (values))
504                 ir1-convert))
505 (macrolet (;; Bind *COMPILER-ERROR-BAILOUT* to a function that throws
506            ;; out of the body and converts a condition signalling form
507            ;; instead. The source form is converted to a string since it
508            ;; may contain arbitrary non-externalizable objects.
509            (ir1-error-bailout ((start next result form) &body body)
510              (with-unique-names (skip condition)
511                `(block ,skip
512                  (let ((,condition (catch 'ir1-error-abort
513                                      (let ((*compiler-error-bailout*
514                                             (lambda (&optional e)
515                                               (throw 'ir1-error-abort e))))
516                                        ,@body
517                                        (return-from ,skip nil)))))
518                    (ir1-convert ,start ,next ,result
519                                 (make-compiler-error-form ,condition
520                                                           ,form)))))))
521
522   ;; Translate FORM into IR1. The code is inserted as the NEXT of the
523   ;; CTRAN START. RESULT is the LVAR which receives the value of the
524   ;; FORM to be translated. The translators call this function
525   ;; recursively to translate their subnodes.
526   ;;
527   ;; As a special hack to make life easier in the compiler, a LEAF
528   ;; IR1-converts into a reference to that LEAF structure. This allows
529   ;; the creation using backquote of forms that contain leaf
530   ;; references, without having to introduce dummy names into the
531   ;; namespace.
532   (defun ir1-convert (start next result form)
533     (ir1-error-bailout (start next result form)
534       (let* ((*current-path* (or (get-source-path form)
535                                  (cons form *current-path*)))
536              (start (instrument-coverage start nil form)))
537         (cond ((atom form)
538                (cond ((and (symbolp form) (not (keywordp form)))
539                       (ir1-convert-var start next result form))
540                      ((leaf-p form)
541                       (reference-leaf start next result form))
542                      (t
543                       (reference-constant start next result form))))
544               (t
545                (ir1-convert-functoid start next result form)))))
546     (values))
547
548   ;; Generate a reference to a manifest constant, creating a new leaf
549   ;; if necessary.
550   (defun reference-constant (start next result value)
551     (declare (type ctran start next)
552              (type (or lvar null) result))
553     (ir1-error-bailout (start next result value)
554       (let* ((leaf (find-constant value))
555              (res (make-ref leaf)))
556         (push res (leaf-refs leaf))
557         (link-node-to-previous-ctran res start)
558         (use-continuation res next result)))
559     (values)))
560
561 ;;; Add FUNCTIONAL to the COMPONENT-REANALYZE-FUNCTIONALS, unless it's
562 ;;; some trivial type for which reanalysis is a trivial no-op, or
563 ;;; unless it doesn't belong in this component at all.
564 ;;;
565 ;;; FUNCTIONAL is returned.
566 (defun maybe-reanalyze-functional (functional)
567
568   (aver (not (eql (functional-kind functional) :deleted))) ; bug 148
569   (aver-live-component *current-component*)
570
571   ;; When FUNCTIONAL is of a type for which reanalysis isn't a trivial
572   ;; no-op
573   (when (typep functional '(or optional-dispatch clambda))
574
575     ;; When FUNCTIONAL knows its component
576     (when (lambda-p functional)
577       (aver (eql (lambda-component functional) *current-component*)))
578
579     (pushnew functional
580              (component-reanalyze-functionals *current-component*)))
581
582   functional)
583
584 ;;; Generate a REF node for LEAF, frobbing the LEAF structure as
585 ;;; needed. If LEAF represents a defined function which has already
586 ;;; been converted, and is not :NOTINLINE, then reference the
587 ;;; functional instead.
588 (defun reference-leaf (start next result leaf &optional (name '.anonymous.))
589   (declare (type ctran start next) (type (or lvar null) result) (type leaf leaf))
590   (when (functional-p leaf)
591     (assure-functional-live-p leaf))
592   (let* ((type (lexenv-find leaf type-restrictions))
593          (leaf (or (and (defined-fun-p leaf)
594                         (not (eq (defined-fun-inlinep leaf)
595                                  :notinline))
596                         (let ((functional (defined-fun-functional leaf)))
597                           (when (and functional
598                                      (not (functional-kind functional))
599                                      ;; Bug MISC.320: ir1-transform
600                                      ;; can create a reference to a
601                                      ;; inline-expanded function,
602                                      ;; defined in another component.
603                                      (not (and (lambda-p functional)
604                                                (neq (lambda-component functional)
605                                                     *current-component*))))
606                             (maybe-reanalyze-functional functional))))
607                    (when (and (lambda-p leaf)
608                               (memq (functional-kind leaf)
609                                     '(nil :optional)))
610                      (maybe-reanalyze-functional leaf))
611                    leaf))
612          (ref (make-ref leaf name)))
613     (push ref (leaf-refs leaf))
614     (setf (leaf-ever-used leaf) t)
615     (link-node-to-previous-ctran ref start)
616     (cond (type (let* ((ref-ctran (make-ctran))
617                        (ref-lvar (make-lvar))
618                        (cast (make-cast ref-lvar
619                                         (make-single-value-type type)
620                                         (lexenv-policy *lexenv*))))
621                   (setf (lvar-dest ref-lvar) cast)
622                   (use-continuation ref ref-ctran ref-lvar)
623                   (link-node-to-previous-ctran cast ref-ctran)
624                   (use-continuation cast next result)))
625           (t (use-continuation ref next result)))))
626
627 ;;; Convert a reference to a symbolic constant or variable. If the
628 ;;; symbol is entered in the LEXENV-VARS we use that definition,
629 ;;; otherwise we find the current global definition. This is also
630 ;;; where we pick off symbol macro and alien variable references.
631 (defun ir1-convert-var (start next result name)
632   (declare (type ctran start next) (type (or lvar null) result) (symbol name))
633   (let ((var (or (lexenv-find name vars) (find-free-var name))))
634     (if (and (global-var-p var) (not result))
635         ;; KLUDGE: If the reference is dead, convert using SYMBOL-VALUE
636         ;; which is not flushable, so that unbound dead variables signal
637         ;; an error (bug 412).
638         (ir1-convert start next result `(symbol-value ',name))
639         (etypecase var
640           (leaf
641            (when (lambda-var-p var)
642              (let ((home (ctran-home-lambda-or-null start)))
643                (when home
644                  (sset-adjoin var (lambda-calls-or-closes home))))
645              (when (lambda-var-ignorep var)
646                ;; (ANSI's specification for the IGNORE declaration requires
647                ;; that this be a STYLE-WARNING, not a full WARNING.)
648                #-sb-xc-host
649                (compiler-style-warn "reading an ignored variable: ~S" name)
650                ;; there's no need for us to accept ANSI's lameness when
651                ;; processing our own code, though.
652                #+sb-xc-host
653                (warn "reading an ignored variable: ~S" name)))
654            (reference-leaf start next result var name))
655           (cons
656            (aver (eq (car var) 'macro))
657            ;; FIXME: [Free] type declarations. -- APD, 2002-01-26
658            (ir1-convert start next result (cdr var)))
659           (heap-alien-info
660            (ir1-convert start next result `(%heap-alien ',var))))))
661   (values))
662
663 ;;; Find a compiler-macro for a form, taking FUNCALL into account.
664 (defun find-compiler-macro (opname form)
665   (if (eq opname 'funcall)
666       (let ((fun-form (cadr form)))
667         (cond ((and (consp fun-form) (eq 'function (car fun-form)))
668                (let ((real-fun (cadr fun-form)))
669                  (if (legal-fun-name-p real-fun)
670                      (values (sb!xc:compiler-macro-function real-fun *lexenv*)
671                              real-fun)
672                      (values nil nil))))
673               ((sb!xc:constantp fun-form *lexenv*)
674                (let ((fun (constant-form-value fun-form *lexenv*)))
675                  (if (legal-fun-name-p fun)
676                      ;; CLHS tells us that local functions must shadow
677                      ;; compiler-macro-functions, but since the call is
678                      ;; through a name, we are obviously interested
679                      ;; in the global function.
680                      (values (sb!xc:compiler-macro-function fun nil) fun)
681                      (values nil nil))))
682               (t
683                (values nil nil))))
684       (if (legal-fun-name-p opname)
685           (values (sb!xc:compiler-macro-function opname *lexenv*) opname)
686           (values nil nil))))
687
688 ;;; Picks of special forms and compiler-macro expansions, and hands
689 ;;; the rest to IR1-CONVERT-COMMON-FUNCTOID
690 (defun ir1-convert-functoid (start next result form)
691   (let* ((op (car form))
692          (translator (and (symbolp op) (info :function :ir1-convert op))))
693     (cond (translator
694            (when (sb!xc:compiler-macro-function op *lexenv*)
695              (compiler-warn "ignoring compiler macro for special form"))
696            (funcall translator start next result form))
697           (t
698            (multiple-value-bind (cmacro-fun cmacro-fun-name)
699                (find-compiler-macro op form)
700              (if (and cmacro-fun
701                       ;; CLHS 3.2.2.1.3 specifies that NOTINLINE
702                       ;; suppresses compiler-macros.
703                       (not (fun-lexically-notinline-p cmacro-fun-name)))
704                  (let ((res (careful-expand-macro cmacro-fun form)))
705                    (if (eq res form)
706                        (ir1-convert-common-functoid start next result form
707                                                     op)
708                        (ir1-convert start next result res)))
709                  (ir1-convert-common-functoid start next result form op)))))))
710
711 ;;; Handles the "common" cases: any other forms except special forms
712 ;;; and compiler-macros.
713 (defun ir1-convert-common-functoid (start next result form op)
714   (cond ((or (symbolp op) (leaf-p op))
715          (let ((lexical-def (if (leaf-p op) op (lexenv-find op funs))))
716            (typecase lexical-def
717              (null
718               (ir1-convert-global-functoid start next result form op))
719              (functional
720               (ir1-convert-local-combination start next result form
721                                              lexical-def))
722              (global-var
723               (ir1-convert-srctran start next result lexical-def form))
724              (t
725               (aver (and (consp lexical-def) (eq (car lexical-def) 'macro)))
726               (ir1-convert start next result
727                            (careful-expand-macro (cdr lexical-def) form))))))
728         ((or (atom op) (not (eq (car op) 'lambda)))
729          (compiler-error "illegal function call"))
730         (t
731          ;; implicitly (LAMBDA ..) because the LAMBDA expression is
732          ;; the CAR of an executed form.
733          (ir1-convert-combination
734           start next result form
735           (ir1-convert-lambda op
736                               :debug-name (debug-name 'inline-lambda op))))))
737
738 ;;; Convert anything that looks like a global function call.
739 (defun ir1-convert-global-functoid (start next result form fun)
740   (declare (type ctran start next) (type (or lvar null) result)
741            (list form))
742   ;; FIXME: Couldn't all the INFO calls here be converted into
743   ;; standard CL functions, like MACRO-FUNCTION or something? And what
744   ;; happens with lexically-defined (MACROLET) macros here, anyway?
745   (ecase (info :function :kind fun)
746     (:macro
747      (ir1-convert start next result
748                   (careful-expand-macro (info :function :macro-function fun)
749                                         form))
750      (unless (policy *lexenv* (zerop store-xref-data))
751        (record-macroexpansion fun (ctran-block start) *current-path*)))
752     ((nil :function)
753      (ir1-convert-srctran start next result
754                           (find-free-fun fun "shouldn't happen! (no-cmacro)")
755                           form))))
756
757 (defun muffle-warning-or-die ()
758   (muffle-warning)
759   (bug "no MUFFLE-WARNING restart"))
760
761 ;;; Expand FORM using the macro whose MACRO-FUNCTION is FUN, trapping
762 ;;; errors which occur during the macroexpansion.
763 (defun careful-expand-macro (fun form)
764   (let (;; a hint I (WHN) wish I'd known earlier
765         (hint "(hint: For more precise location, try *BREAK-ON-SIGNALS*.)"))
766     (flet (;; Return a string to use as a prefix in error reporting,
767            ;; telling something about which form caused the problem.
768            (wherestring ()
769              (let ((*print-pretty* nil)
770                    ;; We rely on the printer to abbreviate FORM.
771                    (*print-length* 3)
772                    (*print-level* 3))
773                (format
774                 nil
775                 #-sb-xc-host "(in macroexpansion of ~S)"
776                 ;; longer message to avoid ambiguity "Was it the xc host
777                 ;; or the cross-compiler which encountered the problem?"
778                 #+sb-xc-host "(in cross-compiler macroexpansion of ~S)"
779                 form))))
780       (handler-bind ((style-warning (lambda (c)
781                                       (compiler-style-warn
782                                        "~@<~A~:@_~A~@:_~A~:>"
783                                        (wherestring) hint c)
784                                       (muffle-warning-or-die)))
785                      ;; KLUDGE: CMU CL in its wisdom (version 2.4.6 for
786                      ;; Debian Linux, anyway) raises a CL:WARNING
787                      ;; condition (not a CL:STYLE-WARNING) for undefined
788                      ;; symbols when converting interpreted functions,
789                      ;; causing COMPILE-FILE to think the file has a real
790                      ;; problem, causing COMPILE-FILE to return FAILURE-P
791                      ;; set (not just WARNINGS-P set). Since undefined
792                      ;; symbol warnings are often harmless forward
793                      ;; references, and since it'd be inordinately painful
794                      ;; to try to eliminate all such forward references,
795                      ;; these warnings are basically unavoidable. Thus, we
796                      ;; need to coerce the system to work through them,
797                      ;; and this code does so, by crudely suppressing all
798                      ;; warnings in cross-compilation macroexpansion. --
799                      ;; WHN 19990412
800                      #+(and cmu sb-xc-host)
801                      (warning (lambda (c)
802                                 (compiler-notify
803                                  "~@<~A~:@_~
804                                   ~A~:@_~
805                                   ~@<(KLUDGE: That was a non-STYLE WARNING. ~
806                                   Ordinarily that would cause compilation to ~
807                                   fail. However, since we're running under ~
808                                   CMU CL, and since CMU CL emits non-STYLE ~
809                                   warnings for safe, hard-to-fix things (e.g. ~
810                                   references to not-yet-defined functions) ~
811                                   we're going to have to ignore it and ~
812                                   proceed anyway. Hopefully we're not ~
813                                   ignoring anything  horrible here..)~:@>~:>"
814                                  (wherestring)
815                                  c)
816                                 (muffle-warning-or-die)))
817                      #-(and cmu sb-xc-host)
818                      (warning (lambda (c)
819                                 (warn "~@<~A~:@_~A~@:_~A~:>"
820                                       (wherestring) hint c)
821                                 (muffle-warning-or-die)))
822                      (error (lambda (c)
823                               (compiler-error "~@<~A~:@_~A~@:_~A~:>"
824                                               (wherestring) hint c))))
825         (funcall sb!xc:*macroexpand-hook* fun form *lexenv*)))))
826 \f
827 ;;;; conversion utilities
828
829 ;;; Convert a bunch of forms, discarding all the values except the
830 ;;; last. If there aren't any forms, then translate a NIL.
831 (declaim (ftype (sfunction (ctran ctran (or lvar null) list) (values))
832                 ir1-convert-progn-body))
833 (defun ir1-convert-progn-body (start next result body)
834   (if (endp body)
835       (reference-constant start next result nil)
836       (let ((this-start start)
837             (forms body))
838         (loop
839           (let ((form (car forms)))
840             (setf this-start
841                   (maybe-instrument-progn-like this-start forms form))
842             (when (endp (cdr forms))
843               (ir1-convert this-start next result form)
844               (return))
845             (let ((this-ctran (make-ctran)))
846               (ir1-convert this-start this-ctran nil form)
847               (setq this-start this-ctran
848                     forms (cdr forms)))))))
849   (values))
850
851 \f
852 ;;;; code coverage
853
854 ;;; Check the policy for whether we should generate code coverage
855 ;;; instrumentation. If not, just return the original START
856 ;;; ctran. Otherwise insert code coverage instrumentation after
857 ;;; START, and return the new ctran.
858 (defun instrument-coverage (start mode form)
859   ;; We don't actually use FORM for anything, it's just convenient to
860   ;; have around when debugging the instrumentation.
861   (declare (ignore form))
862   (if (and (policy *lexenv* (> store-coverage-data 0))
863            *code-coverage-records*
864            *allow-instrumenting*)
865       (let ((path (source-path-original-source *current-path*)))
866         (when mode
867           (push mode path))
868         (if (member (ctran-block start)
869                     (gethash path *code-coverage-blocks*))
870             ;; If this source path has already been instrumented in
871             ;; this block, don't instrument it again.
872             start
873             (let ((store
874                    ;; Get an interned record cons for the path. A cons
875                    ;; with the same object identity must be used for
876                    ;; each instrument for the same block.
877                    (or (gethash path *code-coverage-records*)
878                        (setf (gethash path *code-coverage-records*)
879                              (cons path +code-coverage-unmarked+))))
880                   (next (make-ctran))
881                   (*allow-instrumenting* nil))
882               (push (ctran-block start)
883                     (gethash path *code-coverage-blocks*))
884               (let ((*allow-instrumenting* nil))
885                 (ir1-convert start next nil
886                              `(locally
887                                   (declare (optimize speed
888                                                      (safety 0)
889                                                      (debug 0)
890                                                      (check-constant-modification 0)))
891                                 ;; We're being naughty here, and
892                                 ;; modifying constant data. That's ok,
893                                 ;; we know what we're doing.
894                                 (%rplacd ',store t))))
895               next)))
896       start))
897
898 ;;; In contexts where we don't have a source location for FORM
899 ;;; e.g. due to it not being a cons, but where we have a source
900 ;;; location for the enclosing cons, use the latter source location if
901 ;;; available. This works pretty well in practice, since many PROGNish
902 ;;; macroexpansions will just directly splice a block of forms into
903 ;;; some enclosing form with `(progn ,@body), thus retaining the
904 ;;; EQness of the conses.
905 (defun maybe-instrument-progn-like (start forms form)
906   (or (when (and *allow-instrumenting*
907                  (not (get-source-path form)))
908         (let ((*current-path* (get-source-path forms)))
909           (when *current-path*
910             (instrument-coverage start nil form))))
911       start))
912
913 (defun record-code-coverage (info cc)
914   (setf (gethash info *code-coverage-info*) cc))
915
916 (defun clear-code-coverage ()
917   (clrhash *code-coverage-info*))
918
919 (defun reset-code-coverage ()
920   (maphash (lambda (info cc)
921              (declare (ignore info))
922              (dolist (cc-entry cc)
923                (setf (cdr cc-entry) +code-coverage-unmarked+)))
924            *code-coverage-info*))
925
926 (defun code-coverage-record-marked (record)
927   (aver (consp record))
928   (ecase (cdr record)
929     ((#.+code-coverage-unmarked+) nil)
930     ((t) t)))
931
932 \f
933 ;;;; converting combinations
934
935 ;;; Does this form look like something that we should add single-stepping
936 ;;; instrumentation for?
937 (defun step-form-p (form)
938   (flet ((step-symbol-p (symbol)
939            (not (member (symbol-package symbol)
940                         (load-time-value
941                          ;; KLUDGE: packages we're not interested in
942                          ;; stepping.
943                          (mapcar #'find-package '(sb!c sb!int sb!impl
944                                                   sb!kernel sb!pcl)))))))
945     (and *allow-instrumenting*
946          (policy *lexenv* (= insert-step-conditions 3))
947          (listp form)
948          (symbolp (car form))
949          (step-symbol-p (car form)))))
950
951 ;;; Convert a function call where the function FUN is a LEAF. FORM is
952 ;;; the source for the call. We return the COMBINATION node so that
953 ;;; the caller can poke at it if it wants to.
954 (declaim (ftype (sfunction (ctran ctran (or lvar null) list leaf) combination)
955                 ir1-convert-combination))
956 (defun ir1-convert-combination (start next result form fun)
957   (let ((ctran (make-ctran))
958         (fun-lvar (make-lvar)))
959     (ir1-convert start ctran fun-lvar `(the (or function symbol) ,fun))
960     (let ((combination
961            (ir1-convert-combination-args fun-lvar ctran next result
962                                          (cdr form))))
963       (when (step-form-p form)
964         ;; Store a string representation of the form in the
965         ;; combination node. This will let the IR2 translator know
966         ;; that we want stepper instrumentation for this node. The
967         ;; string will be stored in the debug-info by DUMP-1-LOCATION.
968         (setf (combination-step-info combination)
969               (let ((*print-pretty* t)
970                     (*print-circle* t)
971                     (*print-readably* nil))
972                 (prin1-to-string form))))
973       combination)))
974
975 ;;; Convert the arguments to a call and make the COMBINATION
976 ;;; node. FUN-LVAR yields the function to call. ARGS is the list of
977 ;;; arguments for the call, which defaults to the cdr of source. We
978 ;;; return the COMBINATION node.
979 (defun ir1-convert-combination-args (fun-lvar start next result args)
980   (declare (type ctran start next)
981            (type lvar fun-lvar)
982            (type (or lvar null) result)
983            (list args))
984   (let ((node (make-combination fun-lvar)))
985     (setf (lvar-dest fun-lvar) node)
986     (collect ((arg-lvars))
987       (let ((this-start start)
988             (forms args))
989         (dolist (arg args)
990           (setf this-start
991                 (maybe-instrument-progn-like this-start forms arg))
992           (setf forms (cdr forms))
993           (let ((this-ctran (make-ctran))
994                 (this-lvar (make-lvar node)))
995             (ir1-convert this-start this-ctran this-lvar arg)
996             (setq this-start this-ctran)
997             (arg-lvars this-lvar)))
998         (link-node-to-previous-ctran node this-start)
999         (use-continuation node next result)
1000         (setf (combination-args node) (arg-lvars))))
1001     node))
1002
1003 ;;; Convert a call to a global function. If not :NOTINLINE, then we do
1004 ;;; source transforms and try out any inline expansion. If there is no
1005 ;;; expansion, but is :INLINE, then give an efficiency note (unless a
1006 ;;; known function which will quite possibly be open-coded.) Next, we
1007 ;;; go to ok-combination conversion.
1008 (defun ir1-convert-srctran (start next result var form)
1009   (declare (type ctran start next) (type (or lvar null) result)
1010            (type global-var var))
1011   (let ((inlinep (when (defined-fun-p var)
1012                    (defined-fun-inlinep var))))
1013     (if (eq inlinep :notinline)
1014         (ir1-convert-combination start next result form var)
1015         (let ((transform (info :function
1016                                :source-transform
1017                                (leaf-source-name var))))
1018           (if transform
1019               (multiple-value-bind (transformed pass) (funcall transform form)
1020                 (if pass
1021                     (ir1-convert-maybe-predicate start next result form var)
1022                     (ir1-convert start next result transformed)))
1023               (ir1-convert-maybe-predicate start next result form var))))))
1024
1025 ;;; KLUDGE: If we insert a synthetic IF for a function with the PREDICATE
1026 ;;; attribute, don't generate any branch coverage instrumentation for it.
1027 (defvar *instrument-if-for-code-coverage* t)
1028
1029 ;;; If the function has the PREDICATE attribute, and the RESULT's DEST
1030 ;;; isn't an IF, then we convert (IF <form> T NIL), ensuring that a
1031 ;;; predicate always appears in a conditional context.
1032 ;;;
1033 ;;; If the function isn't a predicate, then we call
1034 ;;; IR1-CONVERT-COMBINATION-CHECKING-TYPE.
1035 (defun ir1-convert-maybe-predicate (start next result form var)
1036   (declare (type ctran start next)
1037            (type (or lvar null) result)
1038            (list form)
1039            (type global-var var))
1040   (let ((info (info :function :info (leaf-source-name var))))
1041     (if (and info
1042              (ir1-attributep (fun-info-attributes info) predicate)
1043              (not (if-p (and result (lvar-dest result)))))
1044         (let ((*instrument-if-for-code-coverage* nil))
1045           (ir1-convert start next result `(if ,form t nil)))
1046         (ir1-convert-combination-checking-type start next result form var))))
1047
1048 ;;; Actually really convert a global function call that we are allowed
1049 ;;; to early-bind.
1050 ;;;
1051 ;;; If we know the function type of the function, then we check the
1052 ;;; call for syntactic legality with respect to the declared function
1053 ;;; type. If it is impossible to determine whether the call is correct
1054 ;;; due to non-constant keywords, then we give up, marking the call as
1055 ;;; :FULL to inhibit further error messages. We return true when the
1056 ;;; call is legal.
1057 ;;;
1058 ;;; If the call is legal, we also propagate type assertions from the
1059 ;;; function type to the arg and result lvars. We do this now so that
1060 ;;; IR1 optimize doesn't have to redundantly do the check later so
1061 ;;; that it can do the type propagation.
1062 (defun ir1-convert-combination-checking-type (start next result form var)
1063   (declare (type ctran start next) (type (or lvar null) result)
1064            (list form)
1065            (type leaf var))
1066   (let* ((node (ir1-convert-combination start next result form var))
1067          (fun-lvar (basic-combination-fun node))
1068          (type (leaf-type var))
1069          (defined-type (leaf-defined-type var)))
1070     (when (validate-call-type node type defined-type t)
1071       (setf (lvar-%derived-type fun-lvar)
1072             (make-single-value-type type))
1073       (setf (lvar-reoptimize fun-lvar) nil)))
1074   (values))
1075
1076 ;;; Convert a call to a local function, or if the function has already
1077 ;;; been LET converted, then throw FUNCTIONAL to
1078 ;;; LOCALL-ALREADY-LET-CONVERTED. The THROW should only happen when we
1079 ;;; are converting inline expansions for local functions during
1080 ;;; optimization.
1081 (defun ir1-convert-local-combination (start next result form functional)
1082   (assure-functional-live-p functional)
1083   (ir1-convert-combination start next result
1084                            form
1085                            (maybe-reanalyze-functional functional)))
1086 \f
1087 ;;;; PROCESS-DECLS
1088
1089 ;;; Given a list of LAMBDA-VARs and a variable name, return the
1090 ;;; LAMBDA-VAR for that name, or NIL if it isn't found. We return the
1091 ;;; *last* variable with that name, since LET* bindings may be
1092 ;;; duplicated, and declarations always apply to the last.
1093 (declaim (ftype (sfunction (list symbol) (or lambda-var list))
1094                 find-in-bindings))
1095 (defun find-in-bindings (vars name)
1096   (let ((found nil))
1097     (dolist (var vars)
1098       (cond ((leaf-p var)
1099              (when (eq (leaf-source-name var) name)
1100                (setq found var))
1101              (let ((info (lambda-var-arg-info var)))
1102                (when info
1103                  (let ((supplied-p (arg-info-supplied-p info)))
1104                    (when (and supplied-p
1105                               (eq (leaf-source-name supplied-p) name))
1106                      (setq found supplied-p))))))
1107             ((and (consp var) (eq (car var) name))
1108              (setf found (cdr var)))))
1109     found))
1110
1111 ;;; Called by PROCESS-DECLS to deal with a variable type declaration.
1112 ;;; If a LAMBDA-VAR being bound, we intersect the type with the var's
1113 ;;; type, otherwise we add a type restriction on the var. If a symbol
1114 ;;; macro, we just wrap a THE around the expansion.
1115 (defun process-type-decl (decl res vars context)
1116   (declare (list decl vars) (type lexenv res))
1117   (let ((type (compiler-specifier-type (first decl))))
1118     (collect ((restr nil cons)
1119              (new-vars nil cons))
1120       (dolist (var-name (rest decl))
1121         (when (boundp var-name)
1122           (program-assert-symbol-home-package-unlocked
1123            context var-name "declaring the type of ~A"))
1124         (let* ((bound-var (find-in-bindings vars var-name))
1125                (var (or bound-var
1126                         (lexenv-find var-name vars)
1127                         (find-free-var var-name))))
1128           (etypecase var
1129             (leaf
1130              (flet
1131                  ((process-var (var bound-var)
1132                     (let* ((old-type (or (lexenv-find var type-restrictions)
1133                                          (leaf-type var)))
1134                            (int (if (or (fun-type-p type)
1135                                         (fun-type-p old-type))
1136                                     type
1137                                     (type-approx-intersection2
1138                                      old-type type))))
1139                       (cond ((eq int *empty-type*)
1140                              (unless (policy *lexenv* (= inhibit-warnings 3))
1141                                (warn
1142                                 'type-warning
1143                                 :format-control
1144                                 "The type declarations ~S and ~S for ~S conflict."
1145                                 :format-arguments
1146                                 (list
1147                                  (type-specifier old-type)
1148                                  (type-specifier type)
1149                                  var-name))))
1150                             (bound-var
1151                              (setf (leaf-type bound-var) int
1152                                    (leaf-where-from bound-var) :declared))
1153                             (t
1154                              (restr (cons var int)))))))
1155                (process-var var bound-var)
1156                (awhen (and (lambda-var-p var)
1157                            (lambda-var-specvar var))
1158                       (process-var it nil))))
1159             (cons
1160              ;; FIXME: non-ANSI weirdness
1161              (aver (eq (car var) 'macro))
1162              (new-vars `(,var-name . (macro . (the ,(first decl)
1163                                                 ,(cdr var))))))
1164             (heap-alien-info
1165              (compiler-error
1166               "~S is an alien variable, so its type can't be declared."
1167               var-name)))))
1168
1169       (if (or (restr) (new-vars))
1170           (make-lexenv :default res
1171                        :type-restrictions (restr)
1172                        :vars (new-vars))
1173           res))))
1174
1175 ;;; This is somewhat similar to PROCESS-TYPE-DECL, but handles
1176 ;;; declarations for function variables. In addition to allowing
1177 ;;; declarations for functions being bound, we must also deal with
1178 ;;; declarations that constrain the type of lexically apparent
1179 ;;; functions.
1180 (defun process-ftype-decl (spec res names fvars context)
1181   (declare (type list names fvars)
1182            (type lexenv res))
1183   (let ((type (compiler-specifier-type spec)))
1184     (collect ((res nil cons))
1185       (dolist (name names)
1186         (when (fboundp name)
1187           (program-assert-symbol-home-package-unlocked
1188            context name "declaring the ftype of ~A"))
1189         (let ((found (find name fvars :key #'leaf-source-name :test #'equal)))
1190           (cond
1191            (found
1192             (setf (leaf-type found) type)
1193             (assert-definition-type found type
1194                                     :unwinnage-fun #'compiler-notify
1195                                     :where "FTYPE declaration"))
1196            (t
1197             (res (cons (find-lexically-apparent-fun
1198                         name "in a function type declaration")
1199                        type))))))
1200       (if (res)
1201           (make-lexenv :default res :type-restrictions (res))
1202           res))))
1203
1204 ;;; Process a special declaration, returning a new LEXENV. A non-bound
1205 ;;; special declaration is instantiated by throwing a special variable
1206 ;;; into the variables if BINDING-FORM-P is NIL, or otherwise into
1207 ;;; *POST-BINDING-VARIABLE-LEXENV*.
1208 (defun process-special-decl (spec res vars binding-form-p context)
1209   (declare (list spec vars) (type lexenv res))
1210   (collect ((new-venv nil cons))
1211     (dolist (name (cdr spec))
1212       (program-assert-symbol-home-package-unlocked
1213        context name "declaring ~A special")
1214       (let ((var (find-in-bindings vars name)))
1215         (etypecase var
1216           (cons
1217            (aver (eq (car var) 'macro))
1218            (compiler-error
1219             "~S is a symbol-macro and thus can't be declared special."
1220             name))
1221           (lambda-var
1222            (when (lambda-var-ignorep var)
1223              ;; ANSI's definition for "Declaration IGNORE, IGNORABLE"
1224              ;; requires that this be a STYLE-WARNING, not a full WARNING.
1225              (compiler-style-warn
1226               "The ignored variable ~S is being declared special."
1227               name))
1228            (setf (lambda-var-specvar var)
1229                  (specvar-for-binding name)))
1230           (null
1231            (unless (or (assoc name (new-venv) :test #'eq))
1232              (new-venv (cons name (specvar-for-binding name))))))))
1233     (cond (binding-form-p
1234            (setf *post-binding-variable-lexenv*
1235                  (append (new-venv) *post-binding-variable-lexenv*))
1236            res)
1237           ((new-venv)
1238            (make-lexenv :default res :vars (new-venv)))
1239           (t
1240            res))))
1241
1242 ;;; Return a DEFINED-FUN which copies a GLOBAL-VAR but for its INLINEP
1243 ;;; (and TYPE if notinline), plus type-restrictions from the lexenv.
1244 (defun make-new-inlinep (var inlinep local-type)
1245   (declare (type global-var var) (type inlinep inlinep))
1246   (let* ((type (if (and (eq inlinep :notinline)
1247                         (not (eq (leaf-where-from var) :declared)))
1248                    (specifier-type 'function)
1249                    (leaf-type var)))
1250          (res (make-defined-fun
1251                :%source-name (leaf-source-name var)
1252                :where-from (leaf-where-from var)
1253                :type (if local-type
1254                          (type-intersection local-type type)
1255                          type)
1256                :inlinep inlinep)))
1257     (when (defined-fun-p var)
1258       (setf (defined-fun-inline-expansion res)
1259             (defined-fun-inline-expansion var))
1260       (setf (defined-fun-functional res)
1261             (defined-fun-functional var)))
1262     ;; FIXME: Is this really right? Needs we not set the FUNCTIONAL
1263     ;; to the original global-var?
1264     res))
1265
1266 ;;; Parse an inline/notinline declaration. If it's a local function we're
1267 ;;; defining, set its INLINEP. If a global function, add a new FENV entry.
1268 (defun process-inline-decl (spec res fvars)
1269   (let ((sense (cdr (assoc (first spec) *inlinep-translations* :test #'eq)))
1270         (new-fenv ()))
1271     (dolist (name (rest spec))
1272       (let ((fvar (find name fvars :key #'leaf-source-name :test #'equal)))
1273         (if fvar
1274             (setf (functional-inlinep fvar) sense)
1275             (let ((found (find-lexically-apparent-fun
1276                           name "in an inline or notinline declaration")))
1277               (etypecase found
1278                 (functional
1279                  (when (policy *lexenv* (>= speed inhibit-warnings))
1280                    (compiler-notify "ignoring ~A declaration not at ~
1281                                      definition of local function:~%  ~S"
1282                                     sense name)))
1283                 (global-var
1284                  (let ((type
1285                         (cdr (assoc found (lexenv-type-restrictions res)))))
1286                    (push (cons name (make-new-inlinep found sense type))
1287                          new-fenv))))))))
1288     (if new-fenv
1289         (make-lexenv :default res :funs new-fenv)
1290         res)))
1291
1292 ;;; like FIND-IN-BINDINGS, but looks for #'FOO in the FVARS
1293 (defun find-in-bindings-or-fbindings (name vars fvars)
1294   (declare (list vars fvars))
1295   (if (consp name)
1296       (destructuring-bind (wot fn-name) name
1297         (unless (eq wot 'function)
1298           (compiler-error "The function or variable name ~S is unrecognizable."
1299                           name))
1300         (find fn-name fvars :key #'leaf-source-name :test #'equal))
1301       (find-in-bindings vars name)))
1302
1303 ;;; Process an ignore/ignorable declaration, checking for various losing
1304 ;;; conditions.
1305 (defun process-ignore-decl (spec vars fvars)
1306   (declare (list spec vars fvars))
1307   (dolist (name (rest spec))
1308     (let ((var (find-in-bindings-or-fbindings name vars fvars)))
1309       (cond
1310        ((not var)
1311         ;; ANSI's definition for "Declaration IGNORE, IGNORABLE"
1312         ;; requires that this be a STYLE-WARNING, not a full WARNING.
1313         (compiler-style-warn "declaring unknown variable ~S to be ignored"
1314                              name))
1315        ;; FIXME: This special case looks like non-ANSI weirdness.
1316        ((and (consp var) (eq (car var) 'macro))
1317         ;; Just ignore the IGNORE decl.
1318         )
1319        ((functional-p var)
1320         (setf (leaf-ever-used var) t))
1321        ((and (lambda-var-specvar var) (eq (first spec) 'ignore))
1322         ;; ANSI's definition for "Declaration IGNORE, IGNORABLE"
1323         ;; requires that this be a STYLE-WARNING, not a full WARNING.
1324         (compiler-style-warn "declaring special variable ~S to be ignored"
1325                              name))
1326        ((eq (first spec) 'ignorable)
1327         (setf (leaf-ever-used var) t))
1328        (t
1329         (setf (lambda-var-ignorep var) t)))))
1330   (values))
1331
1332 (defun process-dx-decl (names vars fvars kind)
1333   (flet ((maybe-notify (control &rest args)
1334            (when (policy *lexenv* (> speed inhibit-warnings))
1335              (apply #'compiler-notify control args))))
1336     (let ((dx (cond ((eq 'truly-dynamic-extent kind)
1337                      :truly)
1338                     ((and (eq 'dynamic-extent kind)
1339                           *stack-allocate-dynamic-extent*)
1340                      t))))
1341       (if dx
1342           (dolist (name names)
1343             (cond
1344               ((symbolp name)
1345                (let* ((bound-var (find-in-bindings vars name))
1346                       (var (or bound-var
1347                                (lexenv-find name vars)
1348                                (find-free-var name))))
1349                  (etypecase var
1350                    (leaf
1351                     (if bound-var
1352                         (setf (leaf-dynamic-extent var) dx)
1353                         (maybe-notify
1354                          "ignoring DYNAMIC-EXTENT declaration for free ~S"
1355                          name)))
1356                    (cons
1357                     (compiler-error "DYNAMIC-EXTENT on symbol-macro: ~S" name))
1358                    (heap-alien-info
1359                     (compiler-error "DYNAMIC-EXTENT on heap-alien-info: ~S"
1360                                     name)))))
1361               ((and (consp name)
1362                     (eq (car name) 'function)
1363                     (null (cddr name))
1364                     (valid-function-name-p (cadr name)))
1365                (let* ((fname (cadr name))
1366                       (bound-fun (find fname fvars
1367                                        :key #'leaf-source-name
1368                                        :test #'equal)))
1369                  (etypecase bound-fun
1370                    (leaf
1371                     #!+stack-allocatable-closures
1372                     (setf (leaf-dynamic-extent bound-fun) dx)
1373                     #!-stack-allocatable-closures
1374                     (maybe-notify
1375                      "ignoring DYNAMIC-EXTENT declaration on a function ~S ~
1376                     (not supported on this platform)." fname))
1377                    (cons
1378                     (compiler-error "DYNAMIC-EXTENT on macro: ~S" fname))
1379                    (null
1380                     (maybe-notify
1381                      "ignoring DYNAMIC-EXTENT declaration for free ~S"
1382                      fname)))))
1383               (t (compiler-error "DYNAMIC-EXTENT on a weird thing: ~S" name))))
1384           (maybe-notify "ignoring DYNAMIC-EXTENT declarations for ~S" names)))))
1385
1386 ;;; FIXME: This is non-ANSI, so the default should be T, or it should
1387 ;;; go away, I think.
1388 (defvar *suppress-values-declaration* nil
1389   #!+sb-doc
1390   "If true, processing of the VALUES declaration is inhibited.")
1391
1392 ;;; Process a single declaration spec, augmenting the specified LEXENV
1393 ;;; RES. Return RES and result type. VARS and FVARS are as described
1394 ;;; PROCESS-DECLS.
1395 (defun process-1-decl (raw-spec res vars fvars binding-form-p context)
1396   (declare (type list raw-spec vars fvars))
1397   (declare (type lexenv res))
1398   (let ((spec (canonized-decl-spec raw-spec))
1399         (result-type *wild-type*))
1400     (values
1401      (case (first spec)
1402        (special (process-special-decl spec res vars binding-form-p context))
1403        (ftype
1404         (unless (cdr spec)
1405           (compiler-error "no type specified in FTYPE declaration: ~S" spec))
1406         (process-ftype-decl (second spec) res (cddr spec) fvars context))
1407        ((inline notinline maybe-inline)
1408         (process-inline-decl spec res fvars))
1409        ((ignore ignorable)
1410         (process-ignore-decl spec vars fvars)
1411         res)
1412        (optimize
1413         (make-lexenv
1414          :default res
1415          :policy (process-optimize-decl spec (lexenv-policy res))))
1416        (muffle-conditions
1417         (make-lexenv
1418          :default res
1419          :handled-conditions (process-muffle-conditions-decl
1420                               spec (lexenv-handled-conditions res))))
1421        (unmuffle-conditions
1422         (make-lexenv
1423          :default res
1424          :handled-conditions (process-unmuffle-conditions-decl
1425                               spec (lexenv-handled-conditions res))))
1426        (type
1427         (process-type-decl (cdr spec) res vars context))
1428        (values
1429         (unless *suppress-values-declaration*
1430           (let ((types (cdr spec)))
1431             (setq result-type
1432                   (compiler-values-specifier-type
1433                    (if (singleton-p types)
1434                        (car types)
1435                        `(values ,@types)))))
1436           res))
1437        ((dynamic-extent truly-dynamic-extent)
1438         (process-dx-decl (cdr spec) vars fvars (first spec))
1439         res)
1440        ((disable-package-locks enable-package-locks)
1441         (make-lexenv
1442          :default res
1443          :disabled-package-locks (process-package-lock-decl
1444                                   spec (lexenv-disabled-package-locks res))))
1445        (t
1446         (unless (info :declaration :recognized (first spec))
1447           (compiler-warn "unrecognized declaration ~S" raw-spec))
1448         res))
1449      result-type)))
1450
1451 ;;; Use a list of DECLARE forms to annotate the lists of LAMBDA-VAR
1452 ;;; and FUNCTIONAL structures which are being bound. In addition to
1453 ;;; filling in slots in the leaf structures, we return a new LEXENV,
1454 ;;; which reflects pervasive special and function type declarations,
1455 ;;; (NOT)INLINE declarations and OPTIMIZE declarations, and type of
1456 ;;; VALUES declarations. If BINDING-FORM-P is true, the third return
1457 ;;; value is a list of VARs that should not apply to the lexenv of the
1458 ;;; initialization forms for the bindings, but should apply to the body.
1459 ;;;
1460 ;;; This is also called in main.lisp when PROCESS-FORM handles a use
1461 ;;; of LOCALLY.
1462 (defun process-decls (decls vars fvars &key
1463                       (lexenv *lexenv*) (binding-form-p nil) (context :compile))
1464   (declare (list decls vars fvars))
1465   (let ((result-type *wild-type*)
1466         (*post-binding-variable-lexenv* nil))
1467     (dolist (decl decls)
1468       (dolist (spec (rest decl))
1469         (unless (consp spec)
1470           (compiler-error "malformed declaration specifier ~S in ~S" spec decl))
1471         (multiple-value-bind (new-env new-result-type)
1472             (process-1-decl spec lexenv vars fvars binding-form-p context)
1473           (setq lexenv new-env)
1474           (unless (eq new-result-type *wild-type*)
1475             (setq result-type
1476                   (values-type-intersection result-type new-result-type))))))
1477     (values lexenv result-type *post-binding-variable-lexenv*)))
1478
1479 (defun %processing-decls (decls vars fvars ctran lvar binding-form-p fun)
1480   (multiple-value-bind (*lexenv* result-type post-binding-lexenv)
1481       (process-decls decls vars fvars :binding-form-p binding-form-p)
1482     (cond ((eq result-type *wild-type*)
1483            (funcall fun ctran lvar post-binding-lexenv))
1484           (t
1485            (let ((value-ctran (make-ctran))
1486                  (value-lvar (make-lvar)))
1487              (multiple-value-prog1
1488                  (funcall fun value-ctran value-lvar post-binding-lexenv)
1489                (let ((cast (make-cast value-lvar result-type
1490                                       (lexenv-policy *lexenv*))))
1491                  (link-node-to-previous-ctran cast value-ctran)
1492                  (setf (lvar-dest value-lvar) cast)
1493                  (use-continuation cast ctran lvar))))))))
1494 (defmacro processing-decls ((decls vars fvars ctran lvar
1495                                    &optional post-binding-lexenv)
1496                             &body forms)
1497   (check-type ctran symbol)
1498   (check-type lvar symbol)
1499   (let ((post-binding-lexenv-p (not (null post-binding-lexenv)))
1500         (post-binding-lexenv (or post-binding-lexenv (gensym))))
1501     `(%processing-decls ,decls ,vars ,fvars ,ctran ,lvar
1502                         ,post-binding-lexenv-p
1503                         (lambda (,ctran ,lvar ,post-binding-lexenv)
1504                           (declare (ignorable ,post-binding-lexenv))
1505                           ,@forms))))
1506
1507 ;;; Return the SPECVAR for NAME to use when we see a local SPECIAL
1508 ;;; declaration. If there is a global variable of that name, then
1509 ;;; check that it isn't a constant and return it. Otherwise, create an
1510 ;;; anonymous GLOBAL-VAR.
1511 (defun specvar-for-binding (name)
1512   (cond ((not (eq (info :variable :where-from name) :assumed))
1513          (let ((found (find-free-var name)))
1514            (when (heap-alien-info-p found)
1515              (compiler-error
1516               "~S is an alien variable and so can't be declared special."
1517               name))
1518            (unless (global-var-p found)
1519              (compiler-error
1520               "~S is a constant and so can't be declared special."
1521               name))
1522            found))
1523         (t
1524          (make-global-var :kind :special
1525                           :%source-name name
1526                           :where-from :declared))))