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