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