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