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