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