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