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