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