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