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