1.0.27.35: minimize the potential for presenting hosts with choices
[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 ;;; Return the LEAF node for a global variable reference to NAME. If
232 ;;; NAME is already entered in *FREE-VARS*, then we just return the
233 ;;; corresponding value. Otherwise, we make a new leaf using
234 ;;; information from the global environment and enter it in
235 ;;; *FREE-VARS*. If the variable is unknown, then we emit a warning.
236 (declaim (ftype (sfunction (t) (or leaf cons heap-alien-info)) find-free-var))
237 (defun find-free-var (name)
238   (unless (symbolp name)
239     (compiler-error "Variable name is not a symbol: ~S." name))
240   (or (gethash name *free-vars*)
241       (let ((kind (info :variable :kind name))
242             (type (info :variable :type name))
243             (where-from (info :variable :where-from name)))
244         (when (and (eq where-from :assumed) (eq kind :global))
245           (note-undefined-reference name :variable))
246         (setf (gethash name *free-vars*)
247               (case kind
248                 (:alien
249                  (info :variable :alien-info name))
250                 ;; FIXME: The return value in this case should really be
251                 ;; of type SB!C::LEAF.  I don't feel too badly about it,
252                 ;; because the MACRO idiom is scattered throughout this
253                 ;; file, but it should be cleaned up so we're not
254                 ;; throwing random conses around.  --njf 2002-03-23
255                 (:macro
256                  (let ((expansion (info :variable :macro-expansion name))
257                        (type (type-specifier (info :variable :type name))))
258                    `(macro . (the ,type ,expansion))))
259                 (:constant
260                  (let ((value (symbol-value name)))
261                    ;; Override the values of standard symbols in XC,
262                    ;; since we can't redefine them.
263                    #+sb-xc-host
264                    (when (eql (find-symbol (symbol-name name) :cl) name)
265                      (multiple-value-bind (xc-value foundp)
266                          (info :variable :xc-constant-value name)
267                        (cond (foundp
268                               (setf value xc-value))
269                              ((not (eq value name))
270                               (compiler-warn
271                                "Using cross-compilation host's definition of ~S: ~A~%"
272                                name (symbol-value name))))))
273                    (find-constant value name)))
274                 (t
275                  (make-global-var :kind kind
276                                   :%source-name name
277                                   :type type
278                                   :where-from where-from)))))))
279 \f
280 ;;; Grovel over CONSTANT checking for any sub-parts that need to be
281 ;;; processed with MAKE-LOAD-FORM. We have to be careful, because
282 ;;; CONSTANT might be circular. We also check that the constant (and
283 ;;; any subparts) are dumpable at all.
284 (defun maybe-emit-make-load-forms (constant &optional (name nil namep))
285   (let ((xset (alloc-xset)))
286     (labels ((trivialp (value)
287                (typep value
288                       '(or
289                         #-sb-xc-host unboxed-array
290                         #+sb-xc-host (simple-array (unsigned-byte 8) (*))
291                         symbol
292                         number
293                         character
294                         string)))
295              (grovel (value)
296                ;; Unless VALUE is an object which which obviously
297                ;; can't contain other objects
298                (unless (trivialp value)
299                  (if (xset-member-p value xset)
300                      (return-from grovel nil)
301                      (add-to-xset value xset))
302                  (typecase value
303                    (cons
304                     (grovel (car value))
305                     (grovel (cdr value)))
306                    (simple-vector
307                     (dotimes (i (length value))
308                       (grovel (svref value i))))
309                    ((vector t)
310                     (dotimes (i (length value))
311                       (grovel (aref value i))))
312                    ((simple-array t)
313                     ;; Even though the (ARRAY T) branch does the exact
314                     ;; same thing as this branch we do this separately
315                     ;; so that the compiler can use faster versions of
316                     ;; array-total-size and row-major-aref.
317                     (dotimes (i (array-total-size value))
318                       (grovel (row-major-aref value i))))
319                    ((array t)
320                     (dotimes (i (array-total-size value))
321                       (grovel (row-major-aref value i))))
322                    (#+sb-xc-host structure!object
323                     #-sb-xc-host instance
324                     ;; In the target SBCL, we can dump any instance, but
325                     ;; in the cross-compilation host, %INSTANCE-FOO
326                     ;; functions don't work on general instances, only on
327                     ;; STRUCTURE!OBJECTs.
328                     ;;
329                     ;; FIXME: What about funcallable instances with
330                     ;; user-defined MAKE-LOAD-FORM methods?
331                     (when (emit-make-load-form value)
332                       (dotimes (i (- (%instance-length value)
333                                      #+sb-xc-host 0
334                                      #-sb-xc-host (layout-n-untagged-slots
335                                                    (%instance-ref value 0))))
336                         (grovel (%instance-ref value i)))))
337                    (t
338                     (compiler-error
339                      "Objects of type ~S can't be dumped into fasl files."
340                      (type-of value)))))))
341       ;; Dump all non-trivial named constants using the name.
342       (if (and namep (not (typep constant '(or symbol character
343                                             ;; FIXME: Cold init breaks if we
344                                             ;; try to reference FP constants
345                                             ;; thru their names.
346                                             #+sb-xc-host number
347                                             #-sb-xc-host fixnum))))
348           (emit-make-load-form constant name)
349           (grovel constant))))
350   (values))
351 \f
352 ;;;; some flow-graph hacking utilities
353
354 ;;; This function sets up the back link between the node and the
355 ;;; ctran which continues at it.
356 (defun link-node-to-previous-ctran (node ctran)
357   (declare (type node node) (type ctran ctran))
358   (aver (not (ctran-next ctran)))
359   (setf (ctran-next ctran) node)
360   (setf (node-prev node) ctran))
361
362 ;;; This function is used to set the ctran for a node, and thus
363 ;;; determine what is evaluated next. If the ctran has no block, then
364 ;;; we make it be in the block that the node is in. If the ctran heads
365 ;;; its block, we end our block and link it to that block.
366 #!-sb-fluid (declaim (inline use-ctran))
367 (defun use-ctran (node ctran)
368   (declare (type node node) (type ctran ctran))
369   (if (eq (ctran-kind ctran) :unused)
370       (let ((node-block (ctran-block (node-prev node))))
371         (setf (ctran-block ctran) node-block)
372         (setf (ctran-kind ctran) :inside-block)
373         (setf (ctran-use ctran) node)
374         (setf (node-next node) ctran))
375       (%use-ctran node ctran)))
376 (defun %use-ctran (node ctran)
377   (declare (type node node) (type ctran ctran) (inline member))
378   (let ((block (ctran-block ctran))
379         (node-block (ctran-block (node-prev node))))
380     (aver (eq (ctran-kind ctran) :block-start))
381     (when (block-last node-block)
382       (error "~S has already ended." node-block))
383     (setf (block-last node-block) node)
384     (when (block-succ node-block)
385       (error "~S already has successors." node-block))
386     (setf (block-succ node-block) (list block))
387     (when (memq node-block (block-pred block))
388       (error "~S is already a predecessor of ~S." node-block block))
389     (push node-block (block-pred block))))
390
391 ;;; Insert NEW before OLD in the flow-graph.
392 (defun insert-node-before (old new)
393   (let ((prev (node-prev old))
394         (temp (make-ctran)))
395     (ensure-block-start prev)
396     (setf (ctran-next prev) nil)
397     (link-node-to-previous-ctran new prev)
398     (use-ctran new temp)
399     (link-node-to-previous-ctran old temp))
400   (values))
401
402 ;;; This function is used to set the ctran for a node, and thus
403 ;;; determine what receives the value.
404 (defun use-lvar (node lvar)
405   (declare (type valued-node node) (type (or lvar null) lvar))
406   (aver (not (node-lvar node)))
407   (when lvar
408     (setf (node-lvar node) lvar)
409     (cond ((null (lvar-uses lvar))
410            (setf (lvar-uses lvar) node))
411           ((listp (lvar-uses lvar))
412            (aver (not (memq node (lvar-uses lvar))))
413            (push node (lvar-uses lvar)))
414           (t
415            (aver (neq node (lvar-uses lvar)))
416            (setf (lvar-uses lvar) (list node (lvar-uses lvar)))))
417     (reoptimize-lvar lvar)))
418
419 #!-sb-fluid(declaim (inline use-continuation))
420 (defun use-continuation (node ctran lvar)
421   (use-ctran node ctran)
422   (use-lvar node lvar))
423 \f
424 ;;;; exported functions
425
426 ;;; This function takes a form and the top level form number for that
427 ;;; form, and returns a lambda representing the translation of that
428 ;;; form in the current global environment. The returned lambda is a
429 ;;; top level lambda that can be called to cause evaluation of the
430 ;;; forms. This lambda is in the initial component. If FOR-VALUE is T,
431 ;;; then the value of the form is returned from the function,
432 ;;; otherwise NIL is returned.
433 ;;;
434 ;;; This function may have arbitrary effects on the global environment
435 ;;; due to processing of EVAL-WHENs. All syntax error checking is
436 ;;; done, with erroneous forms being replaced by a proxy which signals
437 ;;; an error if it is evaluated. Warnings about possibly inconsistent
438 ;;; or illegal changes to the global environment will also be given.
439 ;;;
440 ;;; We make the initial component and convert the form in a PROGN (and
441 ;;; an optional NIL tacked on the end.) We then return the lambda. We
442 ;;; bind all of our state variables here, rather than relying on the
443 ;;; global value (if any) so that IR1 conversion will be reentrant.
444 ;;; This is necessary for EVAL-WHEN processing, etc.
445 ;;;
446 ;;; The hashtables used to hold global namespace info must be
447 ;;; reallocated elsewhere. Note also that *LEXENV* is not bound, so
448 ;;; that local macro definitions can be introduced by enclosing code.
449 (defun ir1-toplevel (form path for-value &optional (allow-instrumenting t))
450   (declare (list path))
451   (let* ((*current-path* path)
452          (component (make-empty-component))
453          (*current-component* component)
454          (*allow-instrumenting* allow-instrumenting))
455     (setf (component-name component) 'initial-component)
456     (setf (component-kind component) :initial)
457     (let* ((forms (if for-value `(,form) `(,form nil)))
458            (res (ir1-convert-lambda-body
459                  forms ()
460                  :debug-name (debug-name 'top-level-form #+sb-xc-host nil #-sb-xc-host form))))
461       (setf (functional-entry-fun res) res
462             (functional-arg-documentation res) ()
463             (functional-kind res) :toplevel)
464       res)))
465
466 ;;; This function is called on freshly read forms to record the
467 ;;; initial location of each form (and subform.) Form is the form to
468 ;;; find the paths in, and TLF-NUM is the top level form number of the
469 ;;; truly top level form.
470 ;;;
471 ;;; This gets a bit interesting when the source code is circular. This
472 ;;; can (reasonably?) happen in the case of circular list constants.
473 (defun find-source-paths (form tlf-num)
474   (declare (type index tlf-num))
475   (let ((*current-form-number* 0))
476     (sub-find-source-paths form (list tlf-num)))
477   (values))
478 (defun sub-find-source-paths (form path)
479   (unless (get-source-path form)
480     (note-source-path form path)
481     (incf *current-form-number*)
482     (let ((pos 0)
483           (subform form)
484           (trail form))
485       (declare (fixnum pos))
486       (macrolet ((frob ()
487                    '(progn
488                       (when (atom subform) (return))
489                       (let ((fm (car subform)))
490                         (if (consp fm)
491                             ;; If it's a cons, recurse
492                             (sub-find-source-paths fm (cons pos path))
493                             ;; Otherwise store the containing form. It's
494                             ;; not perfect, but better than nothing.
495                             (unless (zerop pos)
496                               (note-source-path subform pos path)))
497                         (incf pos))
498                       (setq subform (cdr subform))
499                       (when (eq subform trail) (return)))))
500         (loop
501           (frob)
502           (frob)
503           (setq trail (cdr trail)))))))
504 \f
505 ;;;; IR1-CONVERT, macroexpansion and special form dispatching
506
507 (declaim (ftype (sfunction (ctran ctran (or lvar null) t) (values))
508                 ir1-convert))
509 (macrolet (;; Bind *COMPILER-ERROR-BAILOUT* to a function that throws
510            ;; out of the body and converts a condition signalling form
511            ;; instead. The source form is converted to a string since it
512            ;; may contain arbitrary non-externalizable objects.
513            (ir1-error-bailout ((start next result form) &body body)
514              (with-unique-names (skip condition)
515                `(block ,skip
516                  (let ((,condition (catch 'ir1-error-abort
517                                      (let ((*compiler-error-bailout*
518                                             (lambda (&optional e)
519                                               (throw 'ir1-error-abort e))))
520                                        ,@body
521                                        (return-from ,skip nil)))))
522                    (ir1-convert ,start ,next ,result
523                                 (make-compiler-error-form ,condition
524                                                           ,form)))))))
525
526   ;; Translate FORM into IR1. The code is inserted as the NEXT of the
527   ;; CTRAN START. RESULT is the LVAR which receives the value of the
528   ;; FORM to be translated. The translators call this function
529   ;; recursively to translate their subnodes.
530   ;;
531   ;; As a special hack to make life easier in the compiler, a LEAF
532   ;; IR1-converts into a reference to that LEAF structure. This allows
533   ;; the creation using backquote of forms that contain leaf
534   ;; references, without having to introduce dummy names into the
535   ;; namespace.
536   (defun ir1-convert (start next result form)
537     (ir1-error-bailout (start next result form)
538       (let* ((*current-path* (or (get-source-path form)
539                                  (cons form *current-path*)))
540              (start (instrument-coverage start nil form)))
541         (cond ((atom form)
542                (cond ((and (symbolp form) (not (keywordp form)))
543                       (ir1-convert-var start next result form))
544                      ((leaf-p form)
545                       (reference-leaf start next result form))
546                      (t
547                       (reference-constant start next result form))))
548               (t
549                (ir1-convert-functoid start next result form)))))
550     (values))
551
552   ;; Generate a reference to a manifest constant, creating a new leaf
553   ;; if necessary.
554   (defun reference-constant (start next result value)
555     (declare (type ctran start next)
556              (type (or lvar null) result))
557     (ir1-error-bailout (start next result value)
558       (let* ((leaf (find-constant value))
559              (res (make-ref leaf)))
560         (push res (leaf-refs leaf))
561         (link-node-to-previous-ctran res start)
562         (use-continuation res next result)))
563     (values)))
564
565 ;;; Add FUNCTIONAL to the COMPONENT-REANALYZE-FUNCTIONALS, unless it's
566 ;;; some trivial type for which reanalysis is a trivial no-op, or
567 ;;; unless it doesn't belong in this component at all.
568 ;;;
569 ;;; FUNCTIONAL is returned.
570 (defun maybe-reanalyze-functional (functional)
571
572   (aver (not (eql (functional-kind functional) :deleted))) ; bug 148
573   (aver-live-component *current-component*)
574
575   ;; When FUNCTIONAL is of a type for which reanalysis isn't a trivial
576   ;; no-op
577   (when (typep functional '(or optional-dispatch clambda))
578
579     ;; When FUNCTIONAL knows its component
580     (when (lambda-p functional)
581       (aver (eql (lambda-component functional) *current-component*)))
582
583     (pushnew functional
584              (component-reanalyze-functionals *current-component*)))
585
586   functional)
587
588 ;;; Generate a REF node for LEAF, frobbing the LEAF structure as
589 ;;; needed. If LEAF represents a defined function which has already
590 ;;; been converted, and is not :NOTINLINE, then reference the
591 ;;; functional instead.
592 (defun reference-leaf (start next result leaf &optional (name '.anonymous.))
593   (declare (type ctran start next) (type (or lvar null) result) (type leaf leaf))
594   (when (functional-p leaf)
595     (assure-functional-live-p leaf))
596   (let* ((type (lexenv-find leaf type-restrictions))
597          (leaf (or (and (defined-fun-p leaf)
598                         (not (eq (defined-fun-inlinep leaf)
599                                  :notinline))
600                         (let ((functional (defined-fun-functional leaf)))
601                           (when (and functional
602                                      (not (functional-kind functional))
603                                      ;; Bug MISC.320: ir1-transform
604                                      ;; can create a reference to a
605                                      ;; inline-expanded function,
606                                      ;; defined in another component.
607                                      (not (and (lambda-p functional)
608                                                (neq (lambda-component functional)
609                                                     *current-component*))))
610                             (maybe-reanalyze-functional functional))))
611                    (when (and (lambda-p leaf)
612                               (memq (functional-kind leaf)
613                                     '(nil :optional)))
614                      (maybe-reanalyze-functional leaf))
615                    leaf))
616          (ref (make-ref leaf name)))
617     (push ref (leaf-refs leaf))
618     (setf (leaf-ever-used leaf) t)
619     (link-node-to-previous-ctran ref start)
620     (cond (type (let* ((ref-ctran (make-ctran))
621                        (ref-lvar (make-lvar))
622                        (cast (make-cast ref-lvar
623                                         (make-single-value-type type)
624                                         (lexenv-policy *lexenv*))))
625                   (setf (lvar-dest ref-lvar) cast)
626                   (use-continuation ref ref-ctran ref-lvar)
627                   (link-node-to-previous-ctran cast ref-ctran)
628                   (use-continuation cast next result)))
629           (t (use-continuation ref next result)))))
630
631 ;;; Convert a reference to a symbolic constant or variable. If the
632 ;;; symbol is entered in the LEXENV-VARS we use that definition,
633 ;;; otherwise we find the current global definition. This is also
634 ;;; where we pick off symbol macro and alien variable references.
635 (defun ir1-convert-var (start next result name)
636   (declare (type ctran start next) (type (or lvar null) result) (symbol name))
637   (let ((var (or (lexenv-find name vars) (find-free-var name))))
638     (if (and (global-var-p var) (not result))
639         ;; KLUDGE: If the reference is dead, convert using SYMBOL-VALUE
640         ;; which is not flushable, so that unbound dead variables signal
641         ;; an error (bug 412).
642         (ir1-convert start next result `(symbol-value ',name))
643         (etypecase var
644           (leaf
645            (when (lambda-var-p var)
646              (let ((home (ctran-home-lambda-or-null start)))
647                (when home
648                  (sset-adjoin var (lambda-calls-or-closes home))))
649              (when (lambda-var-ignorep var)
650                ;; (ANSI's specification for the IGNORE declaration requires
651                ;; that this be a STYLE-WARNING, not a full WARNING.)
652                #-sb-xc-host
653                (compiler-style-warn "reading an ignored variable: ~S" name)
654                ;; there's no need for us to accept ANSI's lameness when
655                ;; processing our own code, though.
656                #+sb-xc-host
657                (warn "reading an ignored variable: ~S" name)))
658            (reference-leaf start next result var name))
659           (cons
660            (aver (eq (car var) 'macro))
661            ;; FIXME: [Free] type declarations. -- APD, 2002-01-26
662            (ir1-convert start next result (cdr var)))
663           (heap-alien-info
664            (ir1-convert start next result `(%heap-alien ',var))))))
665   (values))
666
667 ;;; Find a compiler-macro for a form, taking FUNCALL into account.
668 (defun find-compiler-macro (opname form)
669   (if (eq opname 'funcall)
670       (let ((fun-form (cadr form)))
671         (cond ((and (consp fun-form) (eq 'function (car fun-form)))
672                (let ((real-fun (cadr fun-form)))
673                  (if (legal-fun-name-p real-fun)
674                      (values (sb!xc:compiler-macro-function real-fun *lexenv*)
675                              real-fun)
676                      (values nil nil))))
677               ((sb!xc:constantp fun-form *lexenv*)
678                (let ((fun (constant-form-value fun-form *lexenv*)))
679                  (if (legal-fun-name-p fun)
680                      ;; CLHS tells us that local functions must shadow
681                      ;; compiler-macro-functions, but since the call is
682                      ;; through a name, we are obviously interested
683                      ;; in the global function.
684                      (values (sb!xc:compiler-macro-function fun nil) fun)
685                      (values nil nil))))
686               (t
687                (values nil nil))))
688       (if (legal-fun-name-p opname)
689           (values (sb!xc:compiler-macro-function opname *lexenv*) opname)
690           (values nil nil))))
691
692 ;;; Picks of special forms and compiler-macro expansions, and hands
693 ;;; the rest to IR1-CONVERT-COMMON-FUNCTOID
694 (defun ir1-convert-functoid (start next result form)
695   (let* ((op (car form))
696          (translator (and (symbolp op) (info :function :ir1-convert op))))
697     (cond (translator
698            (when (sb!xc:compiler-macro-function op *lexenv*)
699              (compiler-warn "ignoring compiler macro for special form"))
700            (funcall translator start next result form))
701           (t
702            (multiple-value-bind (cmacro-fun cmacro-fun-name)
703                (find-compiler-macro op form)
704              (if (and cmacro-fun
705                       ;; CLHS 3.2.2.1.3 specifies that NOTINLINE
706                       ;; suppresses compiler-macros.
707                       (not (fun-lexically-notinline-p cmacro-fun-name)))
708                  (let ((res (careful-expand-macro cmacro-fun form)))
709                    (if (eq res form)
710                        (ir1-convert-common-functoid start next result form op)
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 ((transform (info :function
1019                                :source-transform
1020                                (leaf-source-name var))))
1021           (if transform
1022               (multiple-value-bind (transformed pass) (funcall transform form)
1023                 (if pass
1024                     (ir1-convert-maybe-predicate start next result form var)
1025                     (ir1-convert start next result transformed)))
1026               (ir1-convert-maybe-predicate start next result form var))))))
1027
1028 ;;; KLUDGE: If we insert a synthetic IF for a function with the PREDICATE
1029 ;;; attribute, don't generate any branch coverage instrumentation for it.
1030 (defvar *instrument-if-for-code-coverage* t)
1031
1032 ;;; If the function has the PREDICATE attribute, and the RESULT's DEST
1033 ;;; isn't an IF, then we convert (IF <form> T NIL), ensuring that a
1034 ;;; predicate always appears in a conditional context.
1035 ;;;
1036 ;;; If the function isn't a predicate, then we call
1037 ;;; IR1-CONVERT-COMBINATION-CHECKING-TYPE.
1038 (defun ir1-convert-maybe-predicate (start next result form var)
1039   (declare (type ctran start next)
1040            (type (or lvar null) result)
1041            (list form)
1042            (type global-var var))
1043   (let ((info (info :function :info (leaf-source-name var))))
1044     (if (and info
1045              (ir1-attributep (fun-info-attributes info) predicate)
1046              (not (if-p (and result (lvar-dest result)))))
1047         (let ((*instrument-if-for-code-coverage* nil))
1048           (ir1-convert start next result `(if ,form t nil)))
1049         (ir1-convert-combination-checking-type start next result form var))))
1050
1051 ;;; Actually really convert a global function call that we are allowed
1052 ;;; to early-bind.
1053 ;;;
1054 ;;; If we know the function type of the function, then we check the
1055 ;;; call for syntactic legality with respect to the declared function
1056 ;;; type. If it is impossible to determine whether the call is correct
1057 ;;; due to non-constant keywords, then we give up, marking the call as
1058 ;;; :FULL to inhibit further error messages. We return true when the
1059 ;;; call is legal.
1060 ;;;
1061 ;;; If the call is legal, we also propagate type assertions from the
1062 ;;; function type to the arg and result lvars. We do this now so that
1063 ;;; IR1 optimize doesn't have to redundantly do the check later so
1064 ;;; that it can do the type propagation.
1065 (defun ir1-convert-combination-checking-type (start next result form var)
1066   (declare (type ctran start next) (type (or lvar null) result)
1067            (list form)
1068            (type leaf var))
1069   (let* ((node (ir1-convert-combination start next result form var))
1070          (fun-lvar (basic-combination-fun node))
1071          (type (leaf-type var))
1072          (defined-type (leaf-defined-type var)))
1073     (when (validate-call-type node type defined-type t)
1074       (setf (lvar-%derived-type fun-lvar)
1075             (make-single-value-type type))
1076       (setf (lvar-reoptimize fun-lvar) nil)))
1077   (values))
1078
1079 ;;; Convert a call to a local function, or if the function has already
1080 ;;; been LET converted, then throw FUNCTIONAL to
1081 ;;; LOCALL-ALREADY-LET-CONVERTED. The THROW should only happen when we
1082 ;;; are converting inline expansions for local functions during
1083 ;;; optimization.
1084 (defun ir1-convert-local-combination (start next result form functional)
1085   (assure-functional-live-p functional)
1086   (ir1-convert-combination start next result
1087                            form
1088                            (maybe-reanalyze-functional functional)))
1089 \f
1090 ;;;; PROCESS-DECLS
1091
1092 ;;; Given a list of LAMBDA-VARs and a variable name, return the
1093 ;;; LAMBDA-VAR for that name, or NIL if it isn't found. We return the
1094 ;;; *last* variable with that name, since LET* bindings may be
1095 ;;; duplicated, and declarations always apply to the last.
1096 (declaim (ftype (sfunction (list symbol) (or lambda-var list))
1097                 find-in-bindings))
1098 (defun find-in-bindings (vars name)
1099   (let ((found nil))
1100     (dolist (var vars)
1101       (cond ((leaf-p var)
1102              (when (eq (leaf-source-name var) name)
1103                (setq found var))
1104              (let ((info (lambda-var-arg-info var)))
1105                (when info
1106                  (let ((supplied-p (arg-info-supplied-p info)))
1107                    (when (and supplied-p
1108                               (eq (leaf-source-name supplied-p) name))
1109                      (setq found supplied-p))))))
1110             ((and (consp var) (eq (car var) name))
1111              (setf found (cdr var)))))
1112     found))
1113
1114 ;;; Called by PROCESS-DECLS to deal with a variable type declaration.
1115 ;;; If a LAMBDA-VAR being bound, we intersect the type with the var's
1116 ;;; type, otherwise we add a type restriction on the var. If a symbol
1117 ;;; macro, we just wrap a THE around the expansion.
1118 (defun process-type-decl (decl res vars context)
1119   (declare (list decl vars) (type lexenv res))
1120   (let ((type (compiler-specifier-type (first decl))))
1121     (collect ((restr nil cons)
1122              (new-vars nil cons))
1123       (dolist (var-name (rest decl))
1124         (when (boundp var-name)
1125           (program-assert-symbol-home-package-unlocked
1126            context var-name "declaring the type of ~A"))
1127         (let* ((bound-var (find-in-bindings vars var-name))
1128                (var (or bound-var
1129                         (lexenv-find var-name vars)
1130                         (find-free-var var-name))))
1131           (etypecase var
1132             (leaf
1133              (flet
1134                  ((process-var (var bound-var)
1135                     (let* ((old-type (or (lexenv-find var type-restrictions)
1136                                          (leaf-type var)))
1137                            (int (if (or (fun-type-p type)
1138                                         (fun-type-p old-type))
1139                                     type
1140                                     (type-approx-intersection2
1141                                      old-type type))))
1142                       (cond ((eq int *empty-type*)
1143                              (unless (policy *lexenv* (= inhibit-warnings 3))
1144                                (warn
1145                                 'type-warning
1146                                 :format-control
1147                                 "The type declarations ~S and ~S for ~S conflict."
1148                                 :format-arguments
1149                                 (list
1150                                  (type-specifier old-type)
1151                                  (type-specifier type)
1152                                  var-name))))
1153                             (bound-var
1154                              (setf (leaf-type bound-var) int
1155                                    (leaf-where-from bound-var) :declared))
1156                             (t
1157                              (restr (cons var int)))))))
1158                (process-var var bound-var)
1159                (awhen (and (lambda-var-p var)
1160                            (lambda-var-specvar var))
1161                       (process-var it nil))))
1162             (cons
1163              ;; FIXME: non-ANSI weirdness
1164              (aver (eq (car var) 'macro))
1165              (new-vars `(,var-name . (macro . (the ,(first decl)
1166                                                 ,(cdr var))))))
1167             (heap-alien-info
1168              (compiler-error
1169               "~S is an alien variable, so its type can't be declared."
1170               var-name)))))
1171
1172       (if (or (restr) (new-vars))
1173           (make-lexenv :default res
1174                        :type-restrictions (restr)
1175                        :vars (new-vars))
1176           res))))
1177
1178 ;;; This is somewhat similar to PROCESS-TYPE-DECL, but handles
1179 ;;; declarations for function variables. In addition to allowing
1180 ;;; declarations for functions being bound, we must also deal with
1181 ;;; declarations that constrain the type of lexically apparent
1182 ;;; functions.
1183 (defun process-ftype-decl (spec res names fvars context)
1184   (declare (type list names fvars)
1185            (type lexenv res))
1186   (let ((type (compiler-specifier-type spec)))
1187     (collect ((res nil cons))
1188       (dolist (name names)
1189         (when (fboundp name)
1190           (program-assert-symbol-home-package-unlocked
1191            context name "declaring the ftype of ~A"))
1192         (let ((found (find name fvars :key #'leaf-source-name :test #'equal)))
1193           (cond
1194            (found
1195             (setf (leaf-type found) type)
1196             (assert-definition-type found type
1197                                     :unwinnage-fun #'compiler-notify
1198                                     :where "FTYPE declaration"))
1199            (t
1200             (res (cons (find-lexically-apparent-fun
1201                         name "in a function type declaration")
1202                        type))))))
1203       (if (res)
1204           (make-lexenv :default res :type-restrictions (res))
1205           res))))
1206
1207 ;;; Process a special declaration, returning a new LEXENV. A non-bound
1208 ;;; special declaration is instantiated by throwing a special variable
1209 ;;; into the variables if BINDING-FORM-P is NIL, or otherwise into
1210 ;;; *POST-BINDING-VARIABLE-LEXENV*.
1211 (defun process-special-decl (spec res vars binding-form-p context)
1212   (declare (list spec vars) (type lexenv res))
1213   (collect ((new-venv nil cons))
1214     (dolist (name (cdr spec))
1215       (program-assert-symbol-home-package-unlocked
1216        context name "declaring ~A special")
1217       (let ((var (find-in-bindings vars name)))
1218         (etypecase var
1219           (cons
1220            (aver (eq (car var) 'macro))
1221            (compiler-error
1222             "~S is a symbol-macro and thus can't be declared special."
1223             name))
1224           (lambda-var
1225            (when (lambda-var-ignorep var)
1226              ;; ANSI's definition for "Declaration IGNORE, IGNORABLE"
1227              ;; requires that this be a STYLE-WARNING, not a full WARNING.
1228              (compiler-style-warn
1229               "The ignored variable ~S is being declared special."
1230               name))
1231            (setf (lambda-var-specvar var)
1232                  (specvar-for-binding name)))
1233           (null
1234            (unless (or (assoc name (new-venv) :test #'eq))
1235              (new-venv (cons name (specvar-for-binding name))))))))
1236     (cond (binding-form-p
1237            (setf *post-binding-variable-lexenv*
1238                  (append (new-venv) *post-binding-variable-lexenv*))
1239            res)
1240           ((new-venv)
1241            (make-lexenv :default res :vars (new-venv)))
1242           (t
1243            res))))
1244
1245 ;;; Return a DEFINED-FUN which copies a GLOBAL-VAR but for its INLINEP
1246 ;;; (and TYPE if notinline), plus type-restrictions from the lexenv.
1247 (defun make-new-inlinep (var inlinep local-type)
1248   (declare (type global-var var) (type inlinep inlinep))
1249   (let* ((type (if (and (eq inlinep :notinline)
1250                         (not (eq (leaf-where-from var) :declared)))
1251                    (specifier-type 'function)
1252                    (leaf-type var)))
1253          (res (make-defined-fun
1254                :%source-name (leaf-source-name var)
1255                :where-from (leaf-where-from var)
1256                :type (if local-type
1257                          (type-intersection local-type type)
1258                          type)
1259                :inlinep inlinep)))
1260     (when (defined-fun-p var)
1261       (setf (defined-fun-inline-expansion res)
1262             (defined-fun-inline-expansion var))
1263       (setf (defined-fun-functionals res)
1264             (defined-fun-functionals var)))
1265     ;; FIXME: Is this really right? Needs we not set the FUNCTIONAL
1266     ;; to the original global-var?
1267     res))
1268
1269 ;;; Parse an inline/notinline declaration. If it's a local function we're
1270 ;;; defining, set its INLINEP. If a global function, add a new FENV entry.
1271 (defun process-inline-decl (spec res fvars)
1272   (let ((sense (cdr (assoc (first spec) *inlinep-translations* :test #'eq)))
1273         (new-fenv ()))
1274     (dolist (name (rest spec))
1275       (let ((fvar (find name fvars :key #'leaf-source-name :test #'equal)))
1276         (if fvar
1277             (setf (functional-inlinep fvar) sense)
1278             (let ((found (find-lexically-apparent-fun
1279                           name "in an inline or notinline declaration")))
1280               (etypecase found
1281                 (functional
1282                  (when (policy *lexenv* (>= speed inhibit-warnings))
1283                    (compiler-notify "ignoring ~A declaration not at ~
1284                                      definition of local function:~%  ~S"
1285                                     sense name)))
1286                 (global-var
1287                  (let ((type
1288                         (cdr (assoc found (lexenv-type-restrictions res)))))
1289                    (push (cons name (make-new-inlinep found sense type))
1290                          new-fenv))))))))
1291     (if new-fenv
1292         (make-lexenv :default res :funs new-fenv)
1293         res)))
1294
1295 ;;; like FIND-IN-BINDINGS, but looks for #'FOO in the FVARS
1296 (defun find-in-bindings-or-fbindings (name vars fvars)
1297   (declare (list vars fvars))
1298   (if (consp name)
1299       (destructuring-bind (wot fn-name) name
1300         (unless (eq wot 'function)
1301           (compiler-error "The function or variable name ~S is unrecognizable."
1302                           name))
1303         (find fn-name fvars :key #'leaf-source-name :test #'equal))
1304       (find-in-bindings vars name)))
1305
1306 ;;; Process an ignore/ignorable declaration, checking for various losing
1307 ;;; conditions.
1308 (defun process-ignore-decl (spec vars fvars)
1309   (declare (list spec vars fvars))
1310   (dolist (name (rest spec))
1311     (let ((var (find-in-bindings-or-fbindings name vars fvars)))
1312       (cond
1313        ((not var)
1314         ;; ANSI's definition for "Declaration IGNORE, IGNORABLE"
1315         ;; requires that this be a STYLE-WARNING, not a full WARNING.
1316         (compiler-style-warn "declaring unknown variable ~S to be ignored"
1317                              name))
1318        ;; FIXME: This special case looks like non-ANSI weirdness.
1319        ((and (consp var) (eq (car var) 'macro))
1320         ;; Just ignore the IGNORE decl.
1321         )
1322        ((functional-p var)
1323         (setf (leaf-ever-used var) t))
1324        ((and (lambda-var-specvar var) (eq (first spec) 'ignore))
1325         ;; ANSI's definition for "Declaration IGNORE, IGNORABLE"
1326         ;; requires that this be a STYLE-WARNING, not a full WARNING.
1327         (compiler-style-warn "declaring special variable ~S to be ignored"
1328                              name))
1329        ((eq (first spec) 'ignorable)
1330         (setf (leaf-ever-used var) t))
1331        (t
1332         (setf (lambda-var-ignorep var) t)))))
1333   (values))
1334
1335 (defun process-dx-decl (names vars fvars kind)
1336   (flet ((maybe-notify (control &rest args)
1337            (when (policy *lexenv* (> speed inhibit-warnings))
1338              (apply #'compiler-notify control args))))
1339     (let ((dx (cond ((eq 'truly-dynamic-extent kind)
1340                      :truly)
1341                     ((and (eq 'dynamic-extent kind)
1342                           *stack-allocate-dynamic-extent*)
1343                      t))))
1344       (if dx
1345           (dolist (name names)
1346             (cond
1347               ((symbolp name)
1348                (let* ((bound-var (find-in-bindings vars name))
1349                       (var (or bound-var
1350                                (lexenv-find name vars)
1351                                (find-free-var name))))
1352                  (etypecase var
1353                    (leaf
1354                     (if bound-var
1355                         (setf (leaf-dynamic-extent var) dx)
1356                         (maybe-notify
1357                          "ignoring DYNAMIC-EXTENT declaration for free ~S"
1358                          name)))
1359                    (cons
1360                     (compiler-error "DYNAMIC-EXTENT on symbol-macro: ~S" name))
1361                    (heap-alien-info
1362                     (compiler-error "DYNAMIC-EXTENT on heap-alien-info: ~S"
1363                                     name)))))
1364               ((and (consp name)
1365                     (eq (car name) 'function)
1366                     (null (cddr name))
1367                     (valid-function-name-p (cadr name)))
1368                (let* ((fname (cadr name))
1369                       (bound-fun (find fname fvars
1370                                        :key #'leaf-source-name
1371                                        :test #'equal)))
1372                  (etypecase bound-fun
1373                    (leaf
1374                     #!+stack-allocatable-closures
1375                     (setf (leaf-dynamic-extent bound-fun) dx)
1376                     #!-stack-allocatable-closures
1377                     (maybe-notify
1378                      "ignoring DYNAMIC-EXTENT declaration on a function ~S ~
1379                     (not supported on this platform)." fname))
1380                    (cons
1381                     (compiler-error "DYNAMIC-EXTENT on macro: ~S" fname))
1382                    (null
1383                     (maybe-notify
1384                      "ignoring DYNAMIC-EXTENT declaration for free ~S"
1385                      fname)))))
1386               (t (compiler-error "DYNAMIC-EXTENT on a weird thing: ~S" name))))
1387           (maybe-notify "ignoring DYNAMIC-EXTENT declarations for ~S" names)))))
1388
1389 ;;; FIXME: This is non-ANSI, so the default should be T, or it should
1390 ;;; go away, I think.
1391 (defvar *suppress-values-declaration* nil
1392   #!+sb-doc
1393   "If true, processing of the VALUES declaration is inhibited.")
1394
1395 ;;; Process a single declaration spec, augmenting the specified LEXENV
1396 ;;; RES. Return RES and result type. VARS and FVARS are as described
1397 ;;; PROCESS-DECLS.
1398 (defun process-1-decl (raw-spec res vars fvars binding-form-p context)
1399   (declare (type list raw-spec vars fvars))
1400   (declare (type lexenv res))
1401   (let ((spec (canonized-decl-spec raw-spec))
1402         (result-type *wild-type*))
1403     (values
1404      (case (first spec)
1405        (special (process-special-decl spec res vars binding-form-p context))
1406        (ftype
1407         (unless (cdr spec)
1408           (compiler-error "no type specified in FTYPE declaration: ~S" spec))
1409         (process-ftype-decl (second spec) res (cddr spec) fvars context))
1410        ((inline notinline maybe-inline)
1411         (process-inline-decl spec res fvars))
1412        ((ignore ignorable)
1413         (process-ignore-decl spec vars fvars)
1414         res)
1415        (optimize
1416         (make-lexenv
1417          :default res
1418          :policy (process-optimize-decl spec (lexenv-policy res))))
1419        (muffle-conditions
1420         (make-lexenv
1421          :default res
1422          :handled-conditions (process-muffle-conditions-decl
1423                               spec (lexenv-handled-conditions res))))
1424        (unmuffle-conditions
1425         (make-lexenv
1426          :default res
1427          :handled-conditions (process-unmuffle-conditions-decl
1428                               spec (lexenv-handled-conditions res))))
1429        (type
1430         (process-type-decl (cdr spec) res vars context))
1431        (values
1432         (unless *suppress-values-declaration*
1433           (let ((types (cdr spec)))
1434             (setq result-type
1435                   (compiler-values-specifier-type
1436                    (if (singleton-p types)
1437                        (car types)
1438                        `(values ,@types)))))
1439           res))
1440        ((dynamic-extent truly-dynamic-extent)
1441         (process-dx-decl (cdr spec) vars fvars (first spec))
1442         res)
1443        ((disable-package-locks enable-package-locks)
1444         (make-lexenv
1445          :default res
1446          :disabled-package-locks (process-package-lock-decl
1447                                   spec (lexenv-disabled-package-locks res))))
1448        (t
1449         (unless (info :declaration :recognized (first spec))
1450           (compiler-warn "unrecognized declaration ~S" raw-spec))
1451         res))
1452      result-type)))
1453
1454 ;;; Use a list of DECLARE forms to annotate the lists of LAMBDA-VAR
1455 ;;; and FUNCTIONAL structures which are being bound. In addition to
1456 ;;; filling in slots in the leaf structures, we return a new LEXENV,
1457 ;;; which reflects pervasive special and function type declarations,
1458 ;;; (NOT)INLINE declarations and OPTIMIZE declarations, and type of
1459 ;;; VALUES declarations. If BINDING-FORM-P is true, the third return
1460 ;;; value is a list of VARs that should not apply to the lexenv of the
1461 ;;; initialization forms for the bindings, but should apply to the body.
1462 ;;;
1463 ;;; This is also called in main.lisp when PROCESS-FORM handles a use
1464 ;;; of LOCALLY.
1465 (defun process-decls (decls vars fvars &key
1466                       (lexenv *lexenv*) (binding-form-p nil) (context :compile))
1467   (declare (list decls vars fvars))
1468   (let ((result-type *wild-type*)
1469         (*post-binding-variable-lexenv* nil))
1470     (dolist (decl decls)
1471       (dolist (spec (rest decl))
1472         (progv
1473             ;; Kludge: EVAL calls this function to deal with LOCALLY.
1474             (when (eq context :compile) (list '*current-path*))
1475             (when (eq context :compile) (list (or (get-source-path spec)
1476                                                   (get-source-path decl)
1477                                                   *current-path*)))
1478           (unless (consp spec)
1479             (compiler-error "malformed declaration specifier ~S in ~S" spec decl))
1480           (multiple-value-bind (new-env new-result-type)
1481               (process-1-decl spec lexenv vars fvars binding-form-p context)
1482             (setq lexenv new-env)
1483             (unless (eq new-result-type *wild-type*)
1484               (setq result-type
1485                     (values-type-intersection result-type new-result-type)))))))
1486     (values lexenv result-type *post-binding-variable-lexenv*)))
1487
1488 (defun %processing-decls (decls vars fvars ctran lvar binding-form-p fun)
1489   (multiple-value-bind (*lexenv* result-type post-binding-lexenv)
1490       (process-decls decls vars fvars :binding-form-p binding-form-p)
1491     (cond ((eq result-type *wild-type*)
1492            (funcall fun ctran lvar post-binding-lexenv))
1493           (t
1494            (let ((value-ctran (make-ctran))
1495                  (value-lvar (make-lvar)))
1496              (multiple-value-prog1
1497                  (funcall fun value-ctran value-lvar post-binding-lexenv)
1498                (let ((cast (make-cast value-lvar result-type
1499                                       (lexenv-policy *lexenv*))))
1500                  (link-node-to-previous-ctran cast value-ctran)
1501                  (setf (lvar-dest value-lvar) cast)
1502                  (use-continuation cast ctran lvar))))))))
1503 (defmacro processing-decls ((decls vars fvars ctran lvar
1504                                    &optional post-binding-lexenv)
1505                             &body forms)
1506   (check-type ctran symbol)
1507   (check-type lvar symbol)
1508   (let ((post-binding-lexenv-p (not (null post-binding-lexenv)))
1509         (post-binding-lexenv (or post-binding-lexenv (sb!xc:gensym "LEXENV"))))
1510     `(%processing-decls ,decls ,vars ,fvars ,ctran ,lvar
1511                         ,post-binding-lexenv-p
1512                         (lambda (,ctran ,lvar ,post-binding-lexenv)
1513                           (declare (ignorable ,post-binding-lexenv))
1514                           ,@forms))))
1515
1516 ;;; Return the SPECVAR for NAME to use when we see a local SPECIAL
1517 ;;; declaration. If there is a global variable of that name, then
1518 ;;; check that it isn't a constant and return it. Otherwise, create an
1519 ;;; anonymous GLOBAL-VAR.
1520 (defun specvar-for-binding (name)
1521   (cond ((not (eq (info :variable :where-from name) :assumed))
1522          (let ((found (find-free-var name)))
1523            (when (heap-alien-info-p found)
1524              (compiler-error
1525               "~S is an alien variable and so can't be declared special."
1526               name))
1527            (unless (global-var-p found)
1528              (compiler-error
1529               "~S is a constant and so can't be declared special."
1530               name))
1531            found))
1532         (t
1533          (make-global-var :kind :special
1534                           :%source-name name
1535                           :where-from :declared))))