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