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