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