0.8.21.12: compiler message fixes
[sbcl.git] / src / compiler / main.lisp
1 ;;;; the top level interfaces to the compiler, plus some other
2 ;;;; compiler-related stuff (e.g. CL:CALL-ARGUMENTS-LIMIT) which
3 ;;;; doesn't obviously belong anywhere else
4
5 ;;;; This software is part of the SBCL system. See the README file for
6 ;;;; more information.
7 ;;;;
8 ;;;; This software is derived from the CMU CL system, which was
9 ;;;; written at Carnegie Mellon University and released into the
10 ;;;; public domain. The software is in the public domain and is
11 ;;;; provided with absolutely no warranty. See the COPYING and CREDITS
12 ;;;; files for more information.
13
14 (in-package "SB!C")
15
16 ;;; FIXME: Doesn't this belong somewhere else, like early-c.lisp?
17 (declaim (special *constants* *free-vars* *component-being-compiled*
18                   *code-vector* *next-location* *result-fixups*
19                   *free-funs* *source-paths*
20                   *seen-blocks* *seen-funs* *list-conflicts-table*
21                   *continuation-number* *continuation-numbers*
22                   *number-continuations* *tn-id* *tn-ids* *id-tns*
23                   *label-ids* *label-id* *id-labels*
24                   *undefined-warnings* *compiler-error-count*
25                   *compiler-warning-count* *compiler-style-warning-count*
26                   *compiler-note-count*
27                   *compiler-error-bailout*
28                   #!+sb-show *compiler-trace-output*
29                   *last-source-context* *last-original-source*
30                   *last-source-form* *last-format-string* *last-format-args*
31                   *last-message-count* *lexenv* *fun-names-in-this-file*
32                   *allow-instrumenting*))
33
34 ;;; Whether call of a function which cannot be defined causes a full
35 ;;; warning.
36 (defvar *flame-on-necessarily-undefined-function* nil)
37
38 (defvar *check-consistency* nil)
39 (defvar *all-components*)
40
41 ;;; Set to NIL to disable loop analysis for register allocation. 
42 (defvar *loop-analyze* t)
43
44 ;;; Bind this to a stream to capture various internal debugging output.
45 (defvar *compiler-trace-output* nil)
46
47 ;;; The current block compilation state. These are initialized to the
48 ;;; :BLOCK-COMPILE and :ENTRY-POINTS arguments that COMPILE-FILE was
49 ;;; called with.
50 ;;;
51 ;;; *BLOCK-COMPILE-ARG* holds the original value of the :BLOCK-COMPILE
52 ;;; argument, which overrides any internal declarations.
53 (defvar *block-compile*)
54 (defvar *block-compile-arg*)
55 (declaim (type (member nil t :specified) *block-compile* *block-compile-arg*))
56 (defvar *entry-points*)
57 (declaim (list *entry-points*))
58
59 ;;; When block compiling, used by PROCESS-FORM to accumulate top level
60 ;;; lambdas resulting from compiling subforms. (In reverse order.)
61 (defvar *toplevel-lambdas*)
62 (declaim (list *toplevel-lambdas*))
63
64 ;;; The current non-macroexpanded toplevel form as printed when
65 ;;; *compile-print* is true.
66 (defvar *top-level-form-noted* nil)
67
68 (defvar sb!xc:*compile-verbose* t
69   #!+sb-doc
70   "The default for the :VERBOSE argument to COMPILE-FILE.")
71 (defvar sb!xc:*compile-print* t
72   #!+sb-doc
73   "The default for the :PRINT argument to COMPILE-FILE.")
74 (defvar *compile-progress* nil
75   #!+sb-doc
76   "When this is true, the compiler prints to *STANDARD-OUTPUT* progress
77   information about the phases of compilation of each function. (This
78   is useful mainly in large block compilations.)")
79
80 (defvar sb!xc:*compile-file-pathname* nil
81   #!+sb-doc
82   "The defaulted pathname of the file currently being compiled, or NIL if not
83   compiling.")
84 (defvar sb!xc:*compile-file-truename* nil
85   #!+sb-doc
86   "The TRUENAME of the file currently being compiled, or NIL if not
87   compiling.")
88
89 (declaim (type (or pathname null)
90                sb!xc:*compile-file-pathname*
91                sb!xc:*compile-file-truename*))
92
93 ;;; the SOURCE-INFO structure for the current compilation. This is
94 ;;; null globally to indicate that we aren't currently in any
95 ;;; identifiable compilation.
96 (defvar *source-info* nil)
97
98 ;;; This is true if we are within a WITH-COMPILATION-UNIT form (which
99 ;;; normally causes nested uses to be no-ops).
100 (defvar *in-compilation-unit* nil)
101
102 ;;; Count of the number of compilation units dynamically enclosed by
103 ;;; the current active WITH-COMPILATION-UNIT that were unwound out of.
104 (defvar *aborted-compilation-unit-count*)
105
106 ;;; Mumble conditional on *COMPILE-PROGRESS*.
107 (defun maybe-mumble (&rest foo)
108   (when *compile-progress*
109     (compiler-mumble "~&")
110     (pprint-logical-block (*standard-output* nil :per-line-prefix "; ")
111        (apply #'compiler-mumble foo))))
112
113 (deftype object () '(or fasl-output core-object null))
114
115 (defvar *compile-object* nil)
116 (declaim (type object *compile-object*))
117 \f
118 ;;;; WITH-COMPILATION-UNIT and WITH-COMPILATION-VALUES
119
120 (defmacro sb!xc:with-compilation-unit (options &body body)
121   #!+sb-doc
122   "WITH-COMPILATION-UNIT ({Key Value}*) Form*
123   This form affects compilations that take place within its dynamic extent. It
124   is intended to be wrapped around the compilation of all files in the same
125   system. These keywords are defined:
126     :OVERRIDE Boolean-Form
127         One of the effects of this form is to delay undefined warnings
128         until the end of the form, instead of giving them at the end of each
129         compilation. If OVERRIDE is NIL (the default), then the outermost
130         WITH-COMPILATION-UNIT form grabs the undefined warnings. Specifying
131         OVERRIDE true causes that form to grab any enclosed warnings, even if
132         it is enclosed by another WITH-COMPILATION-UNIT."
133   `(%with-compilation-unit (lambda () ,@body) ,@options))
134
135 (defun %with-compilation-unit (fn &key override)
136   (declare (type function fn))
137   (let ((succeeded-p nil))
138     (if (and *in-compilation-unit* (not override))
139         ;; Inside another WITH-COMPILATION-UNIT, a WITH-COMPILATION-UNIT is
140         ;; ordinarily (unless OVERRIDE) basically a no-op.
141         (unwind-protect
142              (multiple-value-prog1 (funcall fn) (setf succeeded-p t))
143           (unless succeeded-p
144             (incf *aborted-compilation-unit-count*)))
145         (let ((*aborted-compilation-unit-count* 0)
146               (*compiler-error-count* 0)
147               (*compiler-warning-count* 0)
148               (*compiler-style-warning-count* 0)
149               (*compiler-note-count* 0)
150               (*undefined-warnings* nil)
151               (*in-compilation-unit* t))
152           (sb!thread:with-recursive-lock (*big-compiler-lock*)
153             (handler-bind ((parse-unknown-type
154                             (lambda (c)
155                               (note-undefined-reference
156                                (parse-unknown-type-specifier c)
157                                :type))))
158               (unwind-protect
159                    (multiple-value-prog1 (funcall fn) (setf succeeded-p t))
160                 (unless succeeded-p
161                   (incf *aborted-compilation-unit-count*))
162                 (summarize-compilation-unit (not succeeded-p)))))))))
163
164 ;;; Is FUN-NAME something that no conforming program can rely on
165 ;;; defining as a function?
166 (defun fun-name-reserved-by-ansi-p (fun-name)
167   (eq (symbol-package (fun-name-block-name fun-name))
168       *cl-package*))
169
170 ;;; This is to be called at the end of a compilation unit. It signals
171 ;;; any residual warnings about unknown stuff, then prints the total
172 ;;; error counts. ABORT-P should be true when the compilation unit was
173 ;;; aborted by throwing out. ABORT-COUNT is the number of dynamically
174 ;;; enclosed nested compilation units that were aborted.
175 (defun summarize-compilation-unit (abort-p)
176   (unless abort-p
177     (handler-bind ((style-warning #'compiler-style-warning-handler)
178                    (warning #'compiler-warning-handler))
179
180       (let ((undefs (sort *undefined-warnings* #'string<
181                           :key (lambda (x)
182                                  (let ((x (undefined-warning-name x)))
183                                    (if (symbolp x)
184                                        (symbol-name x)
185                                        (prin1-to-string x)))))))
186         (dolist (undef undefs)
187           (let ((name (undefined-warning-name undef))
188                 (kind (undefined-warning-kind undef))
189                 (warnings (undefined-warning-warnings undef))
190                 (undefined-warning-count (undefined-warning-count undef)))
191             (dolist (*compiler-error-context* warnings)
192               (if #-sb-xc-host (and (eq kind :function)
193                                     (fun-name-reserved-by-ansi-p name)
194                                     *flame-on-necessarily-undefined-function*)
195                   #+sb-xc-host nil
196                   (case name
197                     ((declare)
198                      (compiler-warn
199                       "~@<There is no function named ~S. References to ~S in ~
200                        some contexts (like starts of blocks) have special ~
201                        meaning, but here it would have to be a function, ~
202                        and that shouldn't be right.~:@>"
203                       name name))
204                     (t
205                      (compiler-warn
206                       "~@<The ~(~A~) ~S is undefined, and its name is ~
207                        reserved by ANSI CL so that even if it were ~
208                        defined later, the code doing so would not be ~
209                        portable.~:@>"
210                       kind name)))
211                   (if (eq kind :variable)
212                       (compiler-warn "undefined ~(~A~): ~S" kind name)
213                       (compiler-style-warn "undefined ~(~A~): ~S" kind name))))
214             (let ((warn-count (length warnings)))
215               (when (and warnings (> undefined-warning-count warn-count))
216                 (let ((more (- undefined-warning-count warn-count)))
217                   (if (eq kind :variable)
218                       (compiler-warn
219                        "~W more use~:P of undefined ~(~A~) ~S"
220                        more kind name)
221                       (compiler-style-warn
222                        "~W more use~:P of undefined ~(~A~) ~S"
223                        more kind name)))))))
224
225         (dolist (kind '(:variable :function :type))
226           (let ((summary (mapcar #'undefined-warning-name
227                                  (remove kind undefs :test #'neq
228                                          :key #'undefined-warning-kind))))
229             (when summary
230               (if (eq kind :variable)
231                   (compiler-warn
232                    "~:[This ~(~A~) is~;These ~(~A~)s are~] undefined:~
233                     ~%  ~{~<~%  ~1:;~S~>~^ ~}"
234                    (cdr summary) kind summary)
235                   (compiler-style-warn
236                    "~:[This ~(~A~) is~;These ~(~A~)s are~] undefined:~
237                    ~%  ~{~<~%  ~1:;~S~>~^ ~}"
238                    (cdr summary) kind summary))))))))
239
240   (unless (and (not abort-p)
241                (zerop *aborted-compilation-unit-count*)
242                (zerop *compiler-error-count*)
243                (zerop *compiler-warning-count*)
244                (zerop *compiler-style-warning-count*)
245                (zerop *compiler-note-count*))
246     (pprint-logical-block (*error-output* nil :per-line-prefix "; ")
247       (format *error-output* "~&compilation unit ~:[finished~;aborted~]~
248                              ~[~:;~:*~&  caught ~W fatal ERROR condition~:P~]~
249                              ~[~:;~:*~&  caught ~W ERROR condition~:P~]~
250                              ~[~:;~:*~&  caught ~W WARNING condition~:P~]~
251                              ~[~:;~:*~&  caught ~W STYLE-WARNING condition~:P~]~
252                              ~[~:;~:*~&  printed ~W note~:P~]~%"
253               abort-p
254               *aborted-compilation-unit-count*
255               *compiler-error-count*
256               *compiler-warning-count*
257               *compiler-style-warning-count*
258               *compiler-note-count*))
259     (force-output *error-output*)))
260
261 ;;; Evaluate BODY, then return (VALUES BODY-VALUE WARNINGS-P
262 ;;; FAILURE-P), where BODY-VALUE is the first value of the body, and
263 ;;; WARNINGS-P and FAILURE-P are as in CL:COMPILE or CL:COMPILE-FILE.
264 ;;; This also wraps up WITH-IR1-NAMESPACE functionality.
265 (defmacro with-compilation-values (&body body)
266   `(with-ir1-namespace
267     (let ((*warnings-p* nil)
268           (*failure-p* nil))
269       (values (progn ,@body)
270               *warnings-p*
271               *failure-p*))))
272 \f
273 ;;;; component compilation
274
275 (defparameter *max-optimize-iterations* 3 ; ARB
276   #!+sb-doc
277   "The upper limit on the number of times that we will consecutively do IR1
278   optimization that doesn't introduce any new code. A finite limit is
279   necessary, since type inference may take arbitrarily long to converge.")
280
281 (defevent ir1-optimize-until-done "IR1-OPTIMIZE-UNTIL-DONE called")
282 (defevent ir1-optimize-maxed-out "hit *MAX-OPTIMIZE-ITERATIONS* limit")
283
284 ;;; Repeatedly optimize COMPONENT until no further optimizations can
285 ;;; be found or we hit our iteration limit. When we hit the limit, we
286 ;;; clear the component and block REOPTIMIZE flags to discourage the
287 ;;; next optimization attempt from pounding on the same code.
288 (defun ir1-optimize-until-done (component)
289   (declare (type component component))
290   (maybe-mumble "opt")
291   (event ir1-optimize-until-done)
292   (let ((count 0)
293         (cleared-reanalyze nil)
294         (fastp nil))
295     (loop
296       (when (component-reanalyze component)
297         (setq count 0)
298         (setq cleared-reanalyze t)
299         (setf (component-reanalyze component) nil))
300       (setf (component-reoptimize component) nil)
301       (ir1-optimize component fastp)
302       (cond ((component-reoptimize component)
303              (incf count)
304              (when (and (>= count *max-optimize-iterations*)
305                         (not (component-reanalyze component))
306                         (eq (component-reoptimize component) :maybe))
307                (maybe-mumble "*")
308                (cond ((retry-delayed-ir1-transforms :optimize)
309                       (maybe-mumble "+")
310                       (setq count 0))
311                      (t
312                       (event ir1-optimize-maxed-out)
313                       (setf (component-reoptimize component) nil)
314                       (do-blocks (block component)
315                         (setf (block-reoptimize block) nil))
316                       (return)))))
317             ((retry-delayed-ir1-transforms :optimize)
318              (setf count 0)
319              (maybe-mumble "+"))
320             (t
321              (maybe-mumble " ")
322              (return)))
323       (setq fastp (>= count *max-optimize-iterations*))
324       (maybe-mumble (if fastp "-" ".")))
325     (when cleared-reanalyze
326       (setf (component-reanalyze component) t)))
327   (values))
328
329 (defparameter *constraint-propagate* t)
330
331 ;;; KLUDGE: This was bumped from 5 to 10 in a DTC patch ported by MNA
332 ;;; from CMU CL into sbcl-0.6.11.44, the same one which allowed IR1
333 ;;; transforms to be delayed. Either DTC or MNA or both didn't explain
334 ;;; why, and I don't know what the rationale was. -- WHN 2001-04-28
335 ;;;
336 ;;; FIXME: It would be good to document why it's important to have a
337 ;;; large value here, and what the drawbacks of an excessively large
338 ;;; value are; and it might also be good to make it depend on
339 ;;; optimization policy.
340 (defparameter *reoptimize-after-type-check-max* 10)
341
342 (defevent reoptimize-maxed-out
343   "*REOPTIMIZE-AFTER-TYPE-CHECK-MAX* exceeded.")
344
345 ;;; Iterate doing FIND-DFO until no new dead code is discovered.
346 (defun dfo-as-needed (component)
347   (declare (type component component))
348   (when (component-reanalyze component)
349     (maybe-mumble "DFO")
350     (loop
351       (find-dfo component)
352       (unless (component-reanalyze component)
353         (maybe-mumble " ")
354         (return))
355       (maybe-mumble ".")))
356   (values))
357
358 ;;; Do all the IR1 phases for a non-top-level component.
359 (defun ir1-phases (component)
360   (declare (type component component))
361   (aver-live-component component)
362   (let ((*constraint-number* 0)
363         (loop-count 1)
364         (*delayed-ir1-transforms* nil))
365     (declare (special *constraint-number* *delayed-ir1-transforms*))
366     (loop
367       (ir1-optimize-until-done component)
368       (when (or (component-new-functionals component)
369                 (component-reanalyze-functionals component))
370         (maybe-mumble "locall ")
371         (locall-analyze-component component))
372       (dfo-as-needed component)
373       (when *constraint-propagate*
374         (maybe-mumble "constraint ")
375         (constraint-propagate component))
376       (when (retry-delayed-ir1-transforms :constraint)
377         (maybe-mumble "Rtran "))
378       (flet ((want-reoptimization-p ()
379                (or (component-reoptimize component)
380                    (component-reanalyze component)
381                    (component-new-functionals component)
382                    (component-reanalyze-functionals component))))
383         (unless (and (want-reoptimization-p)
384                      ;; We delay the generation of type checks until
385                      ;; the type constraints have had time to
386                      ;; propagate, else the compiler can confuse itself.
387                      (< loop-count (- *reoptimize-after-type-check-max* 4)))
388           (maybe-mumble "type ")
389           (generate-type-checks component)
390           (unless (want-reoptimization-p)
391             (return))))
392       (when (>= loop-count *reoptimize-after-type-check-max*)
393         (maybe-mumble "[reoptimize limit]")
394         (event reoptimize-maxed-out)
395         (return))
396       (incf loop-count)))
397
398   (ir1-finalize component)
399   (values))
400
401 (defun %compile-component (component)
402   (let ((*code-segment* nil)
403         (*elsewhere* nil))
404     (maybe-mumble "GTN ")
405     (gtn-analyze component)
406     (maybe-mumble "LTN ")
407     (ltn-analyze component)
408     (dfo-as-needed component)
409     (maybe-mumble "control ")
410     (control-analyze component #'make-ir2-block)
411
412     (when (or (ir2-component-values-receivers (component-info component))
413               (component-dx-lvars component))
414       (maybe-mumble "stack ")
415       (stack-analyze component)
416       ;; Assign BLOCK-NUMBER for any cleanup blocks introduced by
417       ;; stack analysis. There shouldn't be any unreachable code after
418       ;; control, so this won't delete anything.
419       (dfo-as-needed component))
420
421     (unwind-protect
422         (progn
423           (maybe-mumble "IR2tran ")
424           (init-assembler)
425           (entry-analyze component)
426           (ir2-convert component)
427
428           (when (policy *lexenv* (>= speed compilation-speed))
429             (maybe-mumble "copy ")
430             (copy-propagate component))
431
432           (select-representations component)
433
434           (when *check-consistency*
435             (maybe-mumble "check2 ")
436             (check-ir2-consistency component))
437
438           (delete-unreferenced-tns component)
439
440           (maybe-mumble "life ")
441           (lifetime-analyze component)
442
443           (when *compile-progress*
444             (compiler-mumble "") ; Sync before doing more output.
445             (pre-pack-tn-stats component *standard-output*))
446
447           (when *check-consistency*
448             (maybe-mumble "check-life ")
449             (check-life-consistency component))
450
451           (maybe-mumble "pack ")
452           (pack component)
453
454           (when *check-consistency*
455             (maybe-mumble "check-pack ")
456             (check-pack-consistency component))
457
458           (when *compiler-trace-output*
459             (describe-component component *compiler-trace-output*)
460             (describe-ir2-component component *compiler-trace-output*))
461
462           (maybe-mumble "code ")
463           (multiple-value-bind (code-length trace-table fixup-notes)
464               (generate-code component)
465
466             #-sb-xc-host
467             (when *compiler-trace-output*
468               (format *compiler-trace-output*
469                       "~|~%disassembly of code for ~S~2%" component)
470               (sb!disassem:disassemble-assem-segment *code-segment*
471                                                      *compiler-trace-output*))
472
473             (etypecase *compile-object*
474               (fasl-output
475                (maybe-mumble "fasl")
476                (fasl-dump-component component
477                                     *code-segment*
478                                     code-length
479                                     trace-table
480                                     fixup-notes
481                                     *compile-object*))
482               (core-object
483                (maybe-mumble "core")
484                (make-core-component component
485                                     *code-segment*
486                                     code-length
487                                     trace-table
488                                     fixup-notes
489                                     *compile-object*))
490               (null))))))
491
492   ;; We're done, so don't bother keeping anything around.
493   (setf (component-info component) :dead)
494
495   (values))
496
497 ;;; Delete components with no external entry points before we try to
498 ;;; generate code. Unreachable closures can cause IR2 conversion to
499 ;;; puke on itself, since it is the reference to the closure which
500 ;;; normally causes the components to be combined.
501 (defun delete-if-no-entries (component)
502   (dolist (fun (component-lambdas component) (delete-component component))
503     (when (functional-has-external-references-p fun)
504       (return))
505     (case (functional-kind fun)
506       (:toplevel (return))
507       (:external
508        (unless (every (lambda (ref)
509                         (eq (node-component ref) component))
510                       (leaf-refs fun))
511          (return))))))
512
513 (defun compile-component (component)
514
515   ;; miscellaneous sanity checks
516   ;;
517   ;; FIXME: These are basically pretty wimpy compared to the checks done
518   ;; by the old CHECK-IR1-CONSISTENCY code. It would be really nice to
519   ;; make those internal consistency checks work again and use them.
520   (aver-live-component component)
521   (do-blocks (block component)
522     (aver (eql (block-component block) component)))
523   (dolist (lambda (component-lambdas component))
524     ;; sanity check to prevent weirdness from propagating insidiously as
525     ;; far from its root cause as it did in bug 138: Make sure that
526     ;; thing-to-COMPONENT links are consistent.
527     (aver (eql (lambda-component lambda) component))
528     (aver (eql (node-component (lambda-bind lambda)) component)))
529
530   (let* ((*component-being-compiled* component))
531
532     (ir1-phases component)
533
534     (when *loop-analyze*
535       (dfo-as-needed component)
536       (find-dominators component)
537       (loop-analyze component))
538
539     #|
540     (when (and *loop-analyze* *compiler-trace-output*)
541       (labels ((print-blocks (block)
542                  (format *compiler-trace-output* "    ~A~%" block)
543                  (when (block-loop-next block)
544                    (print-blocks (block-loop-next block))))
545                (print-loop (loop)
546                  (format *compiler-trace-output* "loop=~A~%" loop)
547                  (print-blocks (loop-blocks loop))
548                  (dolist (l (loop-inferiors loop))
549                    (print-loop l))))
550         (print-loop (component-outer-loop component))))
551     |#
552     
553     ;; FIXME: What is MAYBE-MUMBLE for? Do we need it any more?
554     (maybe-mumble "env ")
555     (physenv-analyze component)
556     (dfo-as-needed component)
557
558     (delete-if-no-entries component)
559
560     (unless (eq (block-next (component-head component))
561                 (component-tail component))
562       (%compile-component component)))
563
564   (clear-constant-info)
565   
566   (values))
567 \f
568 ;;;; clearing global data structures
569 ;;;;
570 ;;;; FIXME: Is it possible to get rid of this stuff, getting rid of
571 ;;;; global data structures entirely when possible and consing up the
572 ;;;; others from scratch instead of clearing and reusing them?
573
574 ;;; Clear the INFO in constants in the *FREE-VARS*, etc. In
575 ;;; addition to allowing stuff to be reclaimed, this is required for
576 ;;; correct assignment of constant offsets, since we need to assign a
577 ;;; new offset for each component. We don't clear the FUNCTIONAL-INFO
578 ;;; slots, since they are used to keep track of functions across
579 ;;; component boundaries.
580 (defun clear-constant-info ()
581   (maphash (lambda (k v)
582              (declare (ignore k))
583              (setf (leaf-info v) nil))
584            *constants*)
585   (maphash (lambda (k v)
586              (declare (ignore k))
587              (when (constant-p v)
588                (setf (leaf-info v) nil)))
589            *free-vars*)
590   (values))
591
592 ;;; Blow away the REFS for all global variables, and let COMPONENT
593 ;;; be recycled.
594 (defun clear-ir1-info (component)
595   (declare (type component component))
596   (labels ((blast (x)
597              (maphash (lambda (k v)
598                         (declare (ignore k))
599                         (when (leaf-p v)
600                           (setf (leaf-refs v)
601                                 (delete-if #'here-p (leaf-refs v)))
602                           (when (basic-var-p v)
603                             (setf (basic-var-sets v)
604                                   (delete-if #'here-p (basic-var-sets v))))))
605                       x))
606            (here-p (x)
607              (eq (node-component x) component)))
608     (blast *free-vars*)
609     (blast *free-funs*)
610     (blast *constants*))
611   (values))
612
613 ;;; Clear global variables used by the compiler.
614 ;;;
615 ;;; FIXME: It seems kinda nasty and unmaintainable to have to do this,
616 ;;; and it adds overhead even when people aren't using the compiler.
617 ;;; Perhaps we could make these global vars unbound except when
618 ;;; actually in use, so that this function could go away.
619 (defun clear-stuff (&optional (debug-too t))
620
621   ;; Clear global tables.
622   (when (boundp '*free-funs*)
623     (clrhash *free-funs*)
624     (clrhash *free-vars*)
625     (clrhash *constants*))
626
627   ;; Clear debug counters and tables.
628   (clrhash *seen-blocks*)
629   (clrhash *seen-funs*)
630   (clrhash *list-conflicts-table*)
631
632   (when debug-too
633     (clrhash *continuation-numbers*)
634     (clrhash *number-continuations*)
635     (setq *continuation-number* 0)
636     (clrhash *tn-ids*)
637     (clrhash *id-tns*)
638     (setq *tn-id* 0)
639     (clrhash *label-ids*)
640     (clrhash *id-labels*)
641     (setq *label-id* 0))
642
643   ;; (Note: The CMU CL code used to set CL::*GENSYM-COUNTER* to zero here.
644   ;; Superficially, this seemed harmful -- the user could reasonably be
645   ;; surprised if *GENSYM-COUNTER* turned back to zero when something was
646   ;; compiled. A closer inspection showed that this actually turned out to be
647   ;; harmless in practice, because CLEAR-STUFF was only called from within
648   ;; forms which bound CL::*GENSYM-COUNTER* to zero. However, this means that
649   ;; even though zeroing CL::*GENSYM-COUNTER* here turned out to be harmless in
650   ;; practice, it was also useless in practice. So we don't do it any more.)
651
652   (values))
653 \f
654 ;;;; trace output
655
656 ;;; Print out some useful info about COMPONENT to STREAM.
657 (defun describe-component (component *standard-output*)
658   (declare (type component component))
659   (format t "~|~%;;;; component: ~S~2%" (component-name component))
660   (print-all-blocks component)
661   (values))
662
663 (defun describe-ir2-component (component *standard-output*)
664   (format t "~%~|~%;;;; IR2 component: ~S~2%" (component-name component))
665   (format t "entries:~%")
666   (dolist (entry (ir2-component-entries (component-info component)))
667     (format t "~4TL~D: ~S~:[~; [closure]~]~%"
668             (label-id (entry-info-offset entry))
669             (entry-info-name entry)
670             (entry-info-closure-tn entry)))
671   (terpri)
672   (pre-pack-tn-stats component *standard-output*)
673   (terpri)
674   (print-ir2-blocks component)
675   (terpri)
676   (values))
677 \f
678 ;;;; file reading
679 ;;;;
680 ;;;; When reading from a file, we have to keep track of some source
681 ;;;; information. We also exploit our ability to back up for printing
682 ;;;; the error context and for recovering from errors.
683 ;;;;
684 ;;;; The interface we provide to this stuff is the stream-oid
685 ;;;; SOURCE-INFO structure. The bookkeeping is done as a side effect
686 ;;;; of getting the next source form.
687
688 ;;; A FILE-INFO structure holds all the source information for a
689 ;;; given file.
690 (def!struct (file-info (:copier nil))
691   ;; If a file, the truename of the corresponding source file. If from
692   ;; a Lisp form, :LISP. If from a stream, :STREAM.
693   (name (missing-arg) :type (or pathname (member :lisp :stream)))
694   ;; the external format that we'll call OPEN with, if NAME is a file.
695   (external-format nil)
696   ;; the defaulted, but not necessarily absolute file name (i.e. prior
697   ;; to TRUENAME call.) Null if not a file. This is used to set
698   ;; *COMPILE-FILE-PATHNAME*, and if absolute, is dumped in the
699   ;; debug-info.
700   (untruename nil :type (or pathname null))
701   ;; the file's write date (if relevant)
702   (write-date nil :type (or unsigned-byte null))
703   ;; the source path root number of the first form in this file (i.e.
704   ;; the total number of forms converted previously in this
705   ;; compilation)
706   (source-root 0 :type unsigned-byte)
707   ;; parallel vectors containing the forms read out of the file and
708   ;; the file positions that reading of each form started at (i.e. the
709   ;; end of the previous form)
710   (forms (make-array 10 :fill-pointer 0 :adjustable t) :type (vector t))
711   (positions (make-array 10 :fill-pointer 0 :adjustable t) :type (vector t)))
712
713 ;;; The SOURCE-INFO structure provides a handle on all the source
714 ;;; information for an entire compilation.
715 (def!struct (source-info
716              #-no-ansi-print-object
717              (:print-object (lambda (s stream)
718                               (print-unreadable-object (s stream :type t))))
719              (:copier nil))
720   ;; the UT that compilation started at
721   (start-time (get-universal-time) :type unsigned-byte)
722   ;; the FILE-INFO structure for this compilation
723   (file-info nil :type (or file-info null))
724   ;; the stream that we are using to read the FILE-INFO, or NIL if
725   ;; no stream has been opened yet
726   (stream nil :type (or stream null)))
727
728 ;;; Given a pathname, return a SOURCE-INFO structure.
729 (defun make-file-source-info (file external-format)
730   (let ((file-info (make-file-info :name (truename file)
731                                    :untruename file
732                                    :external-format external-format
733                                    :write-date (file-write-date file))))
734
735     (make-source-info :file-info file-info)))
736
737 ;;; Return a SOURCE-INFO to describe the incremental compilation of FORM. 
738 (defun make-lisp-source-info (form)
739   (make-source-info :start-time (get-universal-time)
740                     :file-info (make-file-info :name :lisp
741                                                :forms (vector form)
742                                                :positions '#(0))))
743
744 ;;; Return a SOURCE-INFO which will read from STREAM.
745 (defun make-stream-source-info (stream)
746   (let ((file-info (make-file-info :name :stream)))
747     (make-source-info :file-info file-info
748                       :stream stream)))
749
750 ;;; Return a form read from STREAM; or for EOF use the trick,
751 ;;; popularized by Kent Pitman, of returning STREAM itself. If an
752 ;;; error happens, then convert it to standard abort-the-compilation
753 ;;; error condition (possibly recording some extra location
754 ;;; information).
755 (defun read-for-compile-file (stream position)
756   (handler-case (read stream nil stream)
757     (reader-error (condition)
758      (error 'input-error-in-compile-file
759             :condition condition
760             ;; We don't need to supply :POSITION here because
761             ;; READER-ERRORs already know their position in the file.
762             ))
763     ;; ANSI, in its wisdom, says that READ should return END-OF-FILE
764     ;; (and that this is not a READER-ERROR) when it encounters end of
765     ;; file in the middle of something it's trying to read.
766     (end-of-file (condition)
767      (error 'input-error-in-compile-file
768             :condition condition
769             ;; We need to supply :POSITION here because the END-OF-FILE
770             ;; condition doesn't carry the position that the user
771             ;; probably cares about, where the failed READ began.
772             :position position))))
773
774 ;;; If STREAM is present, return it, otherwise open a stream to the
775 ;;; current file. There must be a current file.
776 ;;;
777 ;;; FIXME: This is probably an unnecessarily roundabout way to do
778 ;;; things now that we process a single file in COMPILE-FILE (unlike
779 ;;; the old CMU CL code, which accepted multiple files). Also, the old
780 ;;; comment said
781 ;;;   When we open a new file, we also reset *PACKAGE* and policy.
782 ;;;   This gives the effect of rebinding around each file.
783 ;;; which doesn't seem to be true now. Check to make sure that if
784 ;;; such rebinding is necessary, it's still done somewhere.
785 (defun get-source-stream (info)
786   (declare (type source-info info))
787   (or (source-info-stream info)
788       (let* ((file-info (source-info-file-info info))
789              (name (file-info-name file-info))
790              (external-format (file-info-external-format file-info)))
791         (setf sb!xc:*compile-file-truename* name
792               sb!xc:*compile-file-pathname* (file-info-untruename file-info)
793               (source-info-stream info)
794               (open name :direction :input
795                     :external-format external-format)))))
796
797 ;;; Close the stream in INFO if it is open.
798 (defun close-source-info (info)
799   (declare (type source-info info))
800   (let ((stream (source-info-stream info)))
801     (when stream (close stream)))
802   (setf (source-info-stream info) nil)
803   (values))
804
805 ;;; Read and compile the source file.
806 (defun sub-sub-compile-file (info)
807   (let* ((file-info (source-info-file-info info))
808          (stream (get-source-stream info)))
809     (loop
810      (let* ((pos (file-position stream))
811             (form (read-for-compile-file stream pos)))
812        (if (eq form stream) ; i.e., if EOF
813            (return)
814            (let* ((forms (file-info-forms file-info))
815                   (current-idx (+ (fill-pointer forms)
816                                   (file-info-source-root file-info))))
817              (vector-push-extend form forms)
818              (vector-push-extend pos (file-info-positions file-info))
819              (find-source-paths form current-idx)
820              (process-toplevel-form form
821                                     `(original-source-start 0 ,current-idx)
822                                     nil)))))))
823
824 ;;; Return the INDEX'th source form read from INFO and the position
825 ;;; where it was read.
826 (defun find-source-root (index info)
827   (declare (type index index) (type source-info info))
828   (let ((file-info (source-info-file-info info)))
829     (values (aref (file-info-forms file-info) index)
830             (aref (file-info-positions file-info) index))))
831 \f
832 ;;;; processing of top level forms
833
834 ;;; This is called by top level form processing when we are ready to
835 ;;; actually compile something. If *BLOCK-COMPILE* is T, then we still
836 ;;; convert the form, but delay compilation, pushing the result on
837 ;;; *TOPLEVEL-LAMBDAS* instead.
838 (defun convert-and-maybe-compile (form path)
839   (declare (list path))
840   (let* ((*top-level-form-noted* (note-top-level-form form t))
841          (*lexenv* (make-lexenv 
842                     :policy *policy*
843                     :handled-conditions *handled-conditions*
844                     :disabled-package-locks *disabled-package-locks*))
845          (tll (ir1-toplevel form path nil)))
846     (if (eq *block-compile* t) 
847         (push tll *toplevel-lambdas*)
848         (compile-toplevel (list tll) nil))
849     nil))
850
851 ;;; Macroexpand FORM in the current environment with an error handler.
852 ;;; We only expand one level, so that we retain all the intervening
853 ;;; forms in the source path.
854 (defun preprocessor-macroexpand-1 (form)
855   (handler-case (sb!xc:macroexpand-1 form *lexenv*)
856     (error (condition)
857       (compiler-error "(during macroexpansion of ~A)~%~A"
858                       (let ((*print-level* 2)
859                             (*print-length* 2))
860                         (format nil "~S" form))
861                       condition))))
862
863 ;;; Process a PROGN-like portion of a top level form. FORMS is a list of
864 ;;; the forms, and PATH is the source path of the FORM they came out of.
865 ;;; COMPILE-TIME-TOO is as in ANSI "3.2.3.1 Processing of Top Level Forms".
866 (defun process-toplevel-progn (forms path compile-time-too)
867   (declare (list forms) (list path))
868   (dolist (form forms)
869     (process-toplevel-form form path compile-time-too)))
870
871 ;;; Process a top level use of LOCALLY, or anything else (e.g.
872 ;;; MACROLET) at top level which has declarations and ordinary forms.
873 ;;; We parse declarations and then recursively process the body.
874 (defun process-toplevel-locally (body path compile-time-too &key vars funs)
875   (declare (list path))
876   (multiple-value-bind (forms decls)
877       (parse-body body :doc-string-allowed nil :toplevel t)
878     (let* ((*lexenv* (process-decls decls vars funs))
879            ;; FIXME: VALUES declaration
880            ;;
881            ;; Binding *POLICY* is pretty much of a hack, since it
882            ;; causes LOCALLY to "capture" enclosed proclamations. It
883            ;; is necessary because CONVERT-AND-MAYBE-COMPILE uses the
884            ;; value of *POLICY* as the policy. The need for this hack
885            ;; is due to the quirk that there is no way to represent in
886            ;; a POLICY that an optimize quality came from the default.
887            ;;
888            ;; FIXME: Ideally, something should be done so that DECLAIM
889            ;; inside LOCALLY works OK. Failing that, at least we could
890            ;; issue a warning instead of silently screwing up.
891            (*policy* (lexenv-policy *lexenv*))
892            ;; This is probably also a hack
893            (*handled-conditions* (lexenv-handled-conditions *lexenv*))
894            ;; ditto
895            (*disabled-package-locks* (lexenv-disabled-package-locks *lexenv*)))
896       (process-toplevel-progn forms path compile-time-too))))
897
898 ;;; Parse an EVAL-WHEN situations list, returning three flags,
899 ;;; (VALUES COMPILE-TOPLEVEL LOAD-TOPLEVEL EXECUTE), indicating
900 ;;; the types of situations present in the list.
901 (defun parse-eval-when-situations (situations)
902   (when (or (not (listp situations))
903             (set-difference situations
904                             '(:compile-toplevel
905                               compile
906                               :load-toplevel
907                               load
908                               :execute
909                               eval)))
910     (compiler-error "bad EVAL-WHEN situation list: ~S" situations))
911   (let ((deprecated-names (intersection situations '(compile load eval))))
912     (when deprecated-names
913       (style-warn "using deprecated EVAL-WHEN situation names~{ ~S~}"
914                   deprecated-names)))
915   (values (intersection '(:compile-toplevel compile)
916                         situations)
917           (intersection '(:load-toplevel load) situations)
918           (intersection '(:execute eval) situations)))
919
920
921 ;;; utilities for extracting COMPONENTs of FUNCTIONALs
922 (defun functional-components (f)
923   (declare (type functional f))
924   (etypecase f
925     (clambda (list (lambda-component f)))
926     (optional-dispatch (let ((result nil))
927                          (flet ((maybe-frob (maybe-clambda)
928                                   (when (and maybe-clambda
929                                              (promise-ready-p maybe-clambda))
930                                     (pushnew (lambda-component
931                                               (force maybe-clambda))
932                                              result))))
933                            (map nil #'maybe-frob (optional-dispatch-entry-points f))
934                            (maybe-frob (optional-dispatch-more-entry f))
935                            (maybe-frob (optional-dispatch-main-entry f)))
936                          result))))
937
938 (defun make-functional-from-toplevel-lambda (definition
939                                              &key
940                                              name
941                                              (path
942                                               ;; I'd thought NIL should
943                                               ;; work, but it doesn't.
944                                               ;; -- WHN 2001-09-20
945                                               (missing-arg)))
946   (let* ((*current-path* path)
947          (component (make-empty-component))
948          (*current-component* component))
949     (setf (component-name component)
950           (debug-name 'initial-component name))
951     (setf (component-kind component) :initial)
952     (let* ((locall-fun (let ((*allow-instrumenting* t))
953                          (apply #'ir1-convert-lambdalike 
954                                 definition
955                                 (list :source-name name))))
956            (fun (ir1-convert-lambda (make-xep-lambda-expression locall-fun)
957                                     :source-name (or name '.anonymous.)
958                                     :debug-name (debug-name 'tl-xep  name))))
959       (when name
960         (assert-global-function-definition-type name locall-fun))
961       (setf (functional-entry-fun fun) locall-fun
962             (functional-kind fun) :external
963             (functional-has-external-references-p fun) t)
964       fun)))
965
966 ;;; Compile LAMBDA-EXPRESSION into *COMPILE-OBJECT*, returning a
967 ;;; description of the result.
968 ;;;   * If *COMPILE-OBJECT* is a CORE-OBJECT, then write the function
969 ;;;     into core and return the compiled FUNCTION value.
970 ;;;   * If *COMPILE-OBJECT* is a fasl file, then write the function
971 ;;;     into the fasl file and return a dump handle.
972 ;;;
973 ;;; If NAME is provided, then we try to use it as the name of the
974 ;;; function for debugging/diagnostic information.
975 (defun %compile (lambda-expression
976                  *compile-object*
977                  &key
978                  name
979                  (path
980                   ;; This magical idiom seems to be the appropriate
981                   ;; path for compiling standalone LAMBDAs, judging
982                   ;; from the CMU CL code and experiment, so it's a
983                   ;; nice default for things where we don't have a
984                   ;; real source path (as in e.g. inside CL:COMPILE).
985                   '(original-source-start 0 0)))
986   (when name
987     (legal-fun-name-or-type-error name))
988   (let* ((*lexenv* (make-lexenv 
989                     :policy *policy*
990                     :handled-conditions *handled-conditions*
991                     :disabled-package-locks *disabled-package-locks*))
992          (fun (make-functional-from-toplevel-lambda lambda-expression
993                                                     :name name
994                                                     :path path)))
995
996     ;; FIXME: The compile-it code from here on is sort of a
997     ;; twisted version of the code in COMPILE-TOPLEVEL. It'd be
998     ;; better to find a way to share the code there; or
999     ;; alternatively, to use this code to replace the code there.
1000     ;; (The second alternative might be pretty easy if we used
1001     ;; the :LOCALL-ONLY option to IR1-FOR-LAMBDA. Then maybe the
1002     ;; whole FUNCTIONAL-KIND=:TOPLEVEL case could go away..)
1003
1004     (locall-analyze-clambdas-until-done (list fun))
1005
1006     (multiple-value-bind (components-from-dfo top-components hairy-top)
1007         (find-initial-dfo (list fun))
1008       (declare (ignore hairy-top))
1009
1010       (let ((*all-components* (append components-from-dfo top-components)))
1011         (dolist (component-from-dfo components-from-dfo)
1012           (compile-component component-from-dfo)
1013           (replace-toplevel-xeps component-from-dfo)))
1014
1015       (let ((entry-table (etypecase *compile-object*
1016                            (fasl-output (fasl-output-entry-table
1017                                          *compile-object*))
1018                            (core-object (core-object-entry-table
1019                                          *compile-object*)))))
1020         (multiple-value-bind (result found-p)
1021             (gethash (leaf-info fun) entry-table)
1022           (aver found-p)
1023           (prog1 
1024               result
1025             ;; KLUDGE: This code duplicates some other code in this
1026             ;; file. In the great reorganzation, the flow of program
1027             ;; logic changed from the original CMUCL model, and that
1028             ;; path (as of sbcl-0.7.5 in SUB-COMPILE-FILE) was no
1029             ;; longer followed for CORE-OBJECTS, leading to BUG
1030             ;; 156. This place is transparently not the right one for
1031             ;; this code, but I don't have a clear enough overview of
1032             ;; the compiler to know how to rearrange it all so that
1033             ;; this operation fits in nicely, and it was blocking
1034             ;; reimplementation of (DECLAIM (INLINE FOO)) (MACROLET
1035             ;; ((..)) (DEFUN FOO ...))
1036             ;;
1037             ;; FIXME: This KLUDGE doesn't solve all the problem in an
1038             ;; ideal way, as (1) definitions typed in at the REPL
1039             ;; without an INLINE declaration will give a NULL
1040             ;; FUNCTION-LAMBDA-EXPRESSION (allowable, but not ideal)
1041             ;; and (2) INLINE declarations will yield a
1042             ;; FUNCTION-LAMBDA-EXPRESSION headed by
1043             ;; SB-C:LAMBDA-WITH-LEXENV, even for null LEXENV.  -- CSR,
1044             ;; 2002-07-02
1045             ;;
1046             ;; (2) is probably fairly easy to fix -- it is, after all,
1047             ;; a matter of list manipulation (or possibly of teaching
1048             ;; CL:FUNCTION about SB-C:LAMBDA-WITH-LEXENV).  (1) is
1049             ;; significantly harder, as the association between
1050             ;; function object and source is a tricky one.
1051             ;;
1052             ;; FUNCTION-LAMBDA-EXPRESSION "works" (i.e. returns a
1053             ;; non-NULL list) when the function in question has been
1054             ;; compiled by (COMPILE <x> '(LAMBDA ...)); it does not
1055             ;; work when it has been compiled as part of the top-level
1056             ;; EVAL strategy of compiling everything inside (LAMBDA ()
1057             ;; ...).  -- CSR, 2002-11-02
1058             (when (core-object-p *compile-object*)
1059               (fix-core-source-info *source-info* *compile-object* result))
1060
1061             (mapc #'clear-ir1-info components-from-dfo)
1062             (clear-stuff)))))))
1063
1064 (defun process-toplevel-cold-fset (name lambda-expression path)
1065   (unless (producing-fasl-file)
1066     (error "can't COLD-FSET except in a fasl file"))
1067   (legal-fun-name-or-type-error name)
1068   (fasl-dump-cold-fset name
1069                        (%compile lambda-expression
1070                                  *compile-object*
1071                                  :name name
1072                                  :path path)
1073                        *compile-object*)
1074   (values))
1075
1076 (defun note-top-level-form (form &optional finalp)
1077   (when *compile-print*
1078     (cond ((not *top-level-form-noted*)
1079            (let ((*print-length* 2)
1080                  (*print-level* 2)
1081                  (*print-pretty* nil))
1082              (with-compiler-io-syntax
1083                  (compiler-mumble "~&; ~:[compiling~;converting~] ~S" 
1084                                   *block-compile* form)))
1085              form)
1086           ((and finalp
1087                 (eq :top-level-forms *compile-print*)
1088                 (neq form *top-level-form-noted*))
1089            (let ((*print-length* 1)
1090                  (*print-level* 1)
1091                  (*print-pretty* nil))
1092              (with-compiler-io-syntax
1093                  (compiler-mumble "~&; ... top level ~S" form)))
1094            form)
1095           (t
1096            *top-level-form-noted*))))
1097
1098 ;;; Process a top level FORM with the specified source PATH.
1099 ;;;  * If this is a magic top level form, then do stuff.
1100 ;;;  * If this is a macro, then expand it.
1101 ;;;  * Otherwise, just compile it.
1102 ;;;
1103 ;;; COMPILE-TIME-TOO is as defined in ANSI
1104 ;;; "3.2.3.1 Processing of Top Level Forms".
1105 (defun process-toplevel-form (form path compile-time-too)
1106   (declare (list path))
1107
1108   (catch 'process-toplevel-form-error-abort    
1109     (let* ((path (or (gethash form *source-paths*) (cons form path)))
1110            (*compiler-error-bailout*
1111             (lambda (&optional condition)
1112               (convert-and-maybe-compile
1113                (make-compiler-error-form condition form)
1114                path)
1115               (throw 'process-toplevel-form-error-abort nil))))
1116
1117       (flet ((default-processor (form)
1118                (let ((*top-level-form-noted* (note-top-level-form form)))
1119                  ;; When we're cross-compiling, consider: what should we
1120                  ;; do when we hit e.g.
1121                  ;;   (EVAL-WHEN (:COMPILE-TOPLEVEL)
1122                  ;;     (DEFUN FOO (X) (+ 7 X)))?
1123                  ;; DEFUN has a macro definition in the cross-compiler,
1124                  ;; and a different macro definition in the target
1125                  ;; compiler. The only sensible thing is to use the
1126                  ;; target compiler's macro definition, since the
1127                  ;; cross-compiler's macro is in general into target
1128                  ;; functions which can't meaningfully be executed at
1129                  ;; cross-compilation time. So make sure we do the EVAL
1130                  ;; here, before we macroexpand.
1131                  ;;
1132                  ;; Then things get even dicier with something like
1133                  ;;   (DEFCONSTANT-EQX SB!XC:LAMBDA-LIST-KEYWORDS ..)
1134                  ;; where we have to make sure that we don't uncross
1135                  ;; the SB!XC: prefix before we do EVAL, because otherwise
1136                  ;; we'd be trying to redefine the cross-compilation host's
1137                  ;; constants.
1138                  ;;
1139                  ;; (Isn't it fun to cross-compile Common Lisp?:-)
1140                  #+sb-xc-host
1141                  (progn
1142                    (when compile-time-too
1143                      (eval form)) ; letting xc host EVAL do its own macroexpansion
1144                    (let* (;; (We uncross the operator name because things
1145                           ;; like SB!XC:DEFCONSTANT and SB!XC:DEFTYPE
1146                           ;; should be equivalent to their CL: counterparts
1147                           ;; when being compiled as target code. We leave
1148                           ;; the rest of the form uncrossed because macros
1149                           ;; might yet expand into EVAL-WHEN stuff, and
1150                           ;; things inside EVAL-WHEN can't be uncrossed
1151                           ;; until after we've EVALed them in the
1152                           ;; cross-compilation host.)
1153                           (slightly-uncrossed (cons (uncross (first form))
1154                                                     (rest form)))
1155                           (expanded (preprocessor-macroexpand-1
1156                                      slightly-uncrossed)))
1157                      (if (eq expanded slightly-uncrossed)
1158                          ;; (Now that we're no longer processing toplevel
1159                          ;; forms, and hence no longer need to worry about
1160                          ;; EVAL-WHEN, we can uncross everything.)
1161                          (convert-and-maybe-compile expanded path)
1162                          ;; (We have to demote COMPILE-TIME-TOO to NIL
1163                          ;; here, no matter what it was before, since
1164                          ;; otherwise we'd tend to EVAL subforms more than
1165                          ;; once, because of WHEN COMPILE-TIME-TOO form
1166                          ;; above.)
1167                          (process-toplevel-form expanded path nil))))
1168                  ;; When we're not cross-compiling, we only need to
1169                  ;; macroexpand once, so we can follow the 1-thru-6
1170                  ;; sequence of steps in ANSI's "3.2.3.1 Processing of
1171                  ;; Top Level Forms".
1172                  #-sb-xc-host
1173                  (let ((expanded (preprocessor-macroexpand-1 form)))
1174                    (cond ((eq expanded form)
1175                           (when compile-time-too
1176                             (eval-in-lexenv form *lexenv*))
1177                           (convert-and-maybe-compile form path))
1178                          (t
1179                           (process-toplevel-form expanded
1180                                                  path
1181                                                  compile-time-too)))))))
1182         (if (atom form)
1183             #+sb-xc-host
1184             ;; (There are no xc EVAL-WHEN issues in the ATOM case until
1185             ;; (1) SBCL gets smart enough to handle global
1186             ;; DEFINE-SYMBOL-MACRO or SYMBOL-MACROLET and (2) SBCL
1187             ;; implementors start using symbol macros in a way which
1188             ;; interacts with SB-XC/CL distinction.)
1189             (convert-and-maybe-compile form path)
1190             #-sb-xc-host
1191             (default-processor form)
1192             (flet ((need-at-least-one-arg (form)
1193                      (unless (cdr form)
1194                        (compiler-error "~S form is too short: ~S"
1195                                        (car form)
1196                                        form))))
1197               (case (car form)
1198                 ;; In the cross-compiler, top level COLD-FSET arranges
1199                 ;; for static linking at cold init time.
1200                 #+sb-xc-host
1201                 ((cold-fset)
1202                  (aver (not compile-time-too))
1203                  (destructuring-bind (cold-fset fun-name lambda-expression) form
1204                    (declare (ignore cold-fset))
1205                    (process-toplevel-cold-fset fun-name
1206                                                lambda-expression
1207                                                path)))
1208                 ((eval-when macrolet symbol-macrolet);things w/ 1 arg before body
1209                  (need-at-least-one-arg form)
1210                  (destructuring-bind (special-operator magic &rest body) form
1211                    (ecase special-operator
1212                      ((eval-when)
1213                       ;; CT, LT, and E here are as in Figure 3-7 of ANSI
1214                       ;; "3.2.3.1 Processing of Top Level Forms".
1215                       (multiple-value-bind (ct lt e)
1216                           (parse-eval-when-situations magic)
1217                         (let ((new-compile-time-too (or ct
1218                                                         (and compile-time-too
1219                                                              e))))
1220                           (cond (lt (process-toplevel-progn
1221                                      body path new-compile-time-too))
1222                                 (new-compile-time-too (eval-in-lexenv
1223                                                        `(progn ,@body)
1224                                                        *lexenv*))))))
1225                      ((macrolet)
1226                       (funcall-in-macrolet-lexenv
1227                        magic
1228                        (lambda (&key funs prepend)
1229                          (declare (ignore funs))
1230                          (aver (null prepend))
1231                          (process-toplevel-locally body
1232                                                    path
1233                                                    compile-time-too))
1234                        :compile))
1235                      ((symbol-macrolet)
1236                       (funcall-in-symbol-macrolet-lexenv
1237                        magic
1238                        (lambda (&key vars prepend)
1239                          (aver (null prepend))
1240                          (process-toplevel-locally body
1241                                                    path
1242                                                    compile-time-too
1243                                                    :vars vars))
1244                        :compile)))))
1245                 ((locally)
1246                  (process-toplevel-locally (rest form) path compile-time-too))
1247                 ((progn)
1248                  (process-toplevel-progn (rest form) path compile-time-too))
1249                 (t (default-processor form))))))))
1250
1251   (values))
1252 \f
1253 ;;;; load time value support
1254 ;;;;
1255 ;;;; (See EMIT-MAKE-LOAD-FORM.)
1256
1257 ;;; Return T if we are currently producing a fasl file and hence
1258 ;;; constants need to be dumped carefully.
1259 (defun producing-fasl-file ()
1260   (fasl-output-p *compile-object*))
1261
1262 ;;; Compile FORM and arrange for it to be called at load-time. Return
1263 ;;; the dumper handle and our best guess at the type of the object.
1264 (defun compile-load-time-value (form)
1265   (let ((lambda (compile-load-time-stuff form t)))
1266     (values
1267      (fasl-dump-load-time-value-lambda lambda *compile-object*)
1268      (let ((type (leaf-type lambda)))
1269        (if (fun-type-p type)
1270            (single-value-type (fun-type-returns type))
1271            *wild-type*)))))
1272
1273 ;;; Compile the FORMS and arrange for them to be called (for effect,
1274 ;;; not value) at load time.
1275 (defun compile-make-load-form-init-forms (forms)
1276   (let ((lambda (compile-load-time-stuff `(progn ,@forms) nil)))
1277     (fasl-dump-toplevel-lambda-call lambda *compile-object*)))
1278
1279 ;;; Do the actual work of COMPILE-LOAD-TIME-VALUE or
1280 ;;; COMPILE-MAKE-LOAD-FORM-INIT-FORMS.
1281 (defun compile-load-time-stuff (form for-value)
1282   (with-ir1-namespace
1283    (let* ((*lexenv* (make-null-lexenv))
1284           (lambda (ir1-toplevel form *current-path* for-value)))
1285      (compile-toplevel (list lambda) t)
1286      lambda)))
1287
1288 ;;; This is called by COMPILE-TOPLEVEL when it was passed T for
1289 ;;; LOAD-TIME-VALUE-P (which happens in COMPILE-LOAD-TIME-STUFF). We
1290 ;;; don't try to combine this component with anything else and frob
1291 ;;; the name. If not in a :TOPLEVEL component, then don't bother
1292 ;;; compiling, because it was merged with a run-time component.
1293 (defun compile-load-time-value-lambda (lambdas)
1294   (aver (null (cdr lambdas)))
1295   (let* ((lambda (car lambdas))
1296          (component (lambda-component lambda)))
1297     (when (eql (component-kind component) :toplevel)
1298       (setf (component-name component) (leaf-debug-name lambda))
1299       (compile-component component)
1300       (clear-ir1-info component))))
1301 \f
1302 ;;;; COMPILE-FILE
1303
1304 (defun object-call-toplevel-lambda (tll)
1305   (declare (type functional tll))
1306   (let ((object *compile-object*))
1307     (etypecase object
1308       (fasl-output (fasl-dump-toplevel-lambda-call tll object))
1309       (core-object (core-call-toplevel-lambda      tll object))
1310       (null))))
1311
1312 ;;; Smash LAMBDAS into a single component, compile it, and arrange for
1313 ;;; the resulting function to be called.
1314 (defun sub-compile-toplevel-lambdas (lambdas)
1315   (declare (list lambdas))
1316   (when lambdas
1317     (multiple-value-bind (component tll) (merge-toplevel-lambdas lambdas)
1318       (compile-component component)
1319       (clear-ir1-info component)
1320       (object-call-toplevel-lambda tll)))
1321   (values))
1322
1323 ;;; Compile top level code and call the top level lambdas. We pick off
1324 ;;; top level lambdas in non-top-level components here, calling
1325 ;;; SUB-c-t-l-l on each subsequence of normal top level lambdas.
1326 (defun compile-toplevel-lambdas (lambdas)
1327   (declare (list lambdas))
1328   (let ((len (length lambdas)))
1329     (flet ((loser (start)
1330              (or (position-if (lambda (x)
1331                                 (not (eq (component-kind
1332                                           (node-component (lambda-bind x)))
1333                                          :toplevel)))
1334                               lambdas
1335                               ;; this used to read ":start start", but
1336                               ;; start can be greater than len, which
1337                               ;; is an error according to ANSI - CSR,
1338                               ;; 2002-04-25
1339                               :start (min start len))
1340                  len)))
1341       (do* ((start 0 (1+ loser))
1342             (loser (loser start) (loser start)))
1343            ((>= start len))
1344         (sub-compile-toplevel-lambdas (subseq lambdas start loser))
1345         (unless (= loser len)
1346           (object-call-toplevel-lambda (elt lambdas loser))))))
1347   (values))
1348
1349 ;;; Compile LAMBDAS (a list of CLAMBDAs for top level forms) into the
1350 ;;; object file. 
1351 ;;;
1352 ;;; LOAD-TIME-VALUE-P seems to control whether it's MAKE-LOAD-FORM and
1353 ;;; COMPILE-LOAD-TIME-VALUE stuff. -- WHN 20000201
1354 (defun compile-toplevel (lambdas load-time-value-p)
1355   (declare (list lambdas))
1356   
1357   (maybe-mumble "locall ")
1358   (locall-analyze-clambdas-until-done lambdas)
1359
1360   (maybe-mumble "IDFO ")
1361   (multiple-value-bind (components top-components hairy-top)
1362       (find-initial-dfo lambdas)
1363     (let ((*all-components* (append components top-components)))
1364       (when *check-consistency*
1365         (maybe-mumble "[check]~%")
1366         (check-ir1-consistency *all-components*))
1367
1368       (dolist (component (append hairy-top top-components))
1369         (pre-physenv-analyze-toplevel component))
1370
1371       (dolist (component components)
1372         (compile-component component)
1373         (replace-toplevel-xeps component))
1374         
1375       (when *check-consistency*
1376         (maybe-mumble "[check]~%")
1377         (check-ir1-consistency *all-components*))
1378         
1379       (if load-time-value-p
1380           (compile-load-time-value-lambda lambdas)
1381           (compile-toplevel-lambdas lambdas))
1382
1383       (mapc #'clear-ir1-info components)
1384       (clear-stuff)))
1385   (values))
1386
1387 ;;; Actually compile any stuff that has been queued up for block
1388 ;;; compilation.
1389 (defun finish-block-compilation ()
1390   (when *block-compile*
1391     (when *compile-print*
1392       (compiler-mumble "~&; block compiling converted top level forms..."))
1393     (when *toplevel-lambdas*
1394       (compile-toplevel (nreverse *toplevel-lambdas*) nil)
1395       (setq *toplevel-lambdas* ()))
1396     (setq *block-compile* nil)
1397     (setq *entry-points* nil)))
1398
1399 (defun handle-condition-p (condition)
1400   (let ((lexenv
1401          (etypecase *compiler-error-context*
1402            (node
1403             (node-lexenv *compiler-error-context*))
1404            (compiler-error-context
1405             (let ((lexenv (compiler-error-context-lexenv
1406                            *compiler-error-context*)))
1407               (aver lexenv)
1408               lexenv))
1409            (null *lexenv*))))
1410     (let ((muffles (lexenv-handled-conditions lexenv)))
1411       (if (null muffles) ; common case
1412           nil
1413           (dolist (muffle muffles nil)
1414             (destructuring-bind (typespec . restart-name) muffle
1415               (when (and (typep condition typespec)
1416                          (find-restart restart-name condition))
1417                 (return t))))))))
1418
1419 (defun handle-condition-handler (condition)
1420   (let ((lexenv
1421          (etypecase *compiler-error-context*
1422            (node
1423             (node-lexenv *compiler-error-context*))
1424            (compiler-error-context
1425             (let ((lexenv (compiler-error-context-lexenv
1426                            *compiler-error-context*)))
1427               (aver lexenv)
1428               lexenv))
1429            (null *lexenv*))))
1430     (let ((muffles (lexenv-handled-conditions lexenv)))
1431       (aver muffles)
1432       (dolist (muffle muffles (bug "fell through"))
1433         (destructuring-bind (typespec . restart-name) muffle
1434           (when (typep condition typespec)
1435             (awhen (find-restart restart-name condition)
1436               (invoke-restart it))))))))
1437
1438 ;;; Read all forms from INFO and compile them, with output to OBJECT.
1439 ;;; Return (VALUES NIL WARNINGS-P FAILURE-P).
1440 (defun sub-compile-file (info)
1441   (declare (type source-info info))
1442   (let ((*package* (sane-package))
1443         (*readtable* *readtable*)
1444         (sb!xc:*compile-file-pathname* nil) ; really bound in
1445         (sb!xc:*compile-file-truename* nil) ; SUB-SUB-COMPILE-FILE
1446         (*policy* *policy*)
1447         (*handled-conditions* *handled-conditions*)
1448         (*disabled-package-locks* *disabled-package-locks*)
1449         (*lexenv* (make-null-lexenv))
1450         (*block-compile* *block-compile-arg*)
1451         (*source-info* info)
1452         (*toplevel-lambdas* ())
1453         (*fun-names-in-this-file* ())
1454         (*allow-instrumenting* nil)
1455         (*compiler-error-bailout*
1456          (lambda ()
1457            (compiler-mumble "~2&; fatal error, aborting compilation~%")
1458            (return-from sub-compile-file (values nil t t))))
1459         (*current-path* nil)
1460         (*last-source-context* nil)
1461         (*last-original-source* nil)
1462         (*last-source-form* nil)
1463         (*last-format-string* nil)
1464         (*last-format-args* nil)
1465         (*last-message-count* 0)
1466         ;; FIXME: Do we need this rebinding here? It's a literal
1467         ;; translation of the old CMU CL rebinding to
1468         ;; (OR *BACKEND-INFO-ENVIRONMENT* *INFO-ENVIRONMENT*),
1469         ;; and it's not obvious whether the rebinding to itself is
1470         ;; needed that SBCL doesn't need *BACKEND-INFO-ENVIRONMENT*.
1471         (*info-environment* *info-environment*)
1472         (*gensym-counter* 0))
1473     (handler-case
1474         (handler-bind (((satisfies handle-condition-p) #'handle-condition-handler))
1475           (with-compilation-values
1476               (sb!xc:with-compilation-unit ()
1477                 (clear-stuff)
1478                 
1479                 (sub-sub-compile-file info)
1480                 
1481                 (finish-block-compilation)
1482                 (let ((object *compile-object*))
1483                   (etypecase object
1484                     (fasl-output (fasl-dump-source-info info object))
1485                     (core-object (fix-core-source-info info object))
1486                     (null)))
1487                 nil)))
1488       ;; Some errors are sufficiently bewildering that we just fail
1489       ;; immediately, without trying to recover and compile more of
1490       ;; the input file.
1491       (fatal-compiler-error (condition)
1492        (signal condition)
1493        (when *compile-verbose*
1494          (format *standard-output*
1495                  "~@<compilation aborted because of fatal error: ~2I~_~A~:>"
1496                  condition))
1497        (values nil t t)))))
1498
1499 ;;; Return a pathname for the named file. The file must exist.
1500 (defun verify-source-file (pathname-designator)
1501   (let* ((pathname (pathname pathname-designator))
1502          (default-host (make-pathname :host (pathname-host pathname))))
1503     (flet ((try-with-type (path type error-p)
1504              (let ((new (merge-pathnames
1505                          path (make-pathname :type type
1506                                              :defaults default-host))))
1507                (if (probe-file new)
1508                    new
1509                    (and error-p (truename new))))))
1510       (cond ((typep pathname 'logical-pathname)
1511              (try-with-type pathname "LISP" t))
1512             ((probe-file pathname) pathname)
1513             ((try-with-type pathname "lisp"  nil))
1514             ((try-with-type pathname "lisp"  t))))))
1515
1516 (defun elapsed-time-to-string (tsec)
1517   (multiple-value-bind (tmin sec) (truncate tsec 60)
1518     (multiple-value-bind (thr min) (truncate tmin 60)
1519       (format nil "~D:~2,'0D:~2,'0D" thr min sec))))
1520
1521 ;;; Print some junk at the beginning and end of compilation.
1522 (defun print-compile-start-note (source-info)
1523   (declare (type source-info source-info))
1524   (let ((file-info (source-info-file-info source-info)))
1525     (compiler-mumble "~&; compiling file ~S (written ~A):~%"
1526                      (namestring (file-info-name file-info))
1527                      (sb!int:format-universal-time nil
1528                                                    (file-info-write-date
1529                                                     file-info)
1530                                                    :style :government
1531                                                    :print-weekday nil
1532                                                    :print-timezone nil)))
1533   (values))
1534
1535 (defun print-compile-end-note (source-info won)
1536   (declare (type source-info source-info))
1537   (compiler-mumble "~&; compilation ~:[aborted after~;finished in~] ~A~&"
1538                    won
1539                    (elapsed-time-to-string
1540                     (- (get-universal-time)
1541                        (source-info-start-time source-info))))
1542   (values))
1543
1544 ;;; Open some files and call SUB-COMPILE-FILE. If something unwinds
1545 ;;; out of the compile, then abort the writing of the output file, so
1546 ;;; that we don't overwrite it with known garbage.
1547 (defun sb!xc:compile-file
1548     (input-file
1549      &key
1550
1551      ;; ANSI options
1552      (output-file (cfp-output-file-default input-file))
1553      ;; FIXME: ANSI doesn't seem to say anything about
1554      ;; *COMPILE-VERBOSE* and *COMPILE-PRINT* being rebound by this
1555      ;; function..
1556      ((:verbose sb!xc:*compile-verbose*) sb!xc:*compile-verbose*)
1557      ((:print sb!xc:*compile-print*) sb!xc:*compile-print*)
1558      (external-format :default)
1559
1560      ;; extensions
1561      (trace-file nil) 
1562      ((:block-compile *block-compile-arg*) nil))
1563   #!+sb-doc
1564   "Compile INPUT-FILE, producing a corresponding fasl file and
1565 returning its filename.
1566
1567   :PRINT
1568      If true, a message per non-macroexpanded top level form is printed 
1569      to *STANDARD-OUTPUT*. Top level forms that whose subforms are
1570      processed as top level forms (eg. EVAL-WHEN, MACROLET, PROGN) receive
1571      no such message, but their subforms do.
1572
1573      As an extension to ANSI, if :PRINT is :top-level-forms, a message 
1574      per top level form after macroexpansion is printed to *STANDARD-OUTPUT*. 
1575      For example, compiling an IN-PACKAGE form will result in a message about
1576      a top level SETQ in addition to the message about the IN-PACKAGE form'
1577      itself.
1578
1579      Both forms of reporting obey the SB-EXT:*COMPILER-PRINT-VARIABLE-ALIST*.
1580
1581   :BLOCK-COMPILE
1582      Though COMPILE-FILE accepts an additional :BLOCK-COMPILE
1583      argument, it is not currently supported. (non-standard)
1584
1585   :TRACE-FILE
1586      If given, internal data structures are dumped to the specified
1587      file, or if a value of T is given, to a file of *.trace type
1588      derived from the input file name. (non-standard)"
1589 ;;; Block compilation is currently broken.
1590 #|
1591   "Also, as a workaround for vaguely-non-ANSI behavior, the
1592 :BLOCK-COMPILE argument is quasi-supported, to determine whether
1593 multiple functions are compiled together as a unit, resolving function
1594 references at compile time. NIL means that global function names are
1595 never resolved at compilation time. Currently NIL is the default
1596 behavior, because although section 3.2.2.3, \"Semantic Constraints\",
1597 of the ANSI spec allows this behavior under all circumstances, the
1598 compiler's runtime scales badly when it tries to do this for large
1599 files. If/when this performance problem is fixed, the block
1600 compilation default behavior will probably be made dependent on the
1601 SPEED and COMPILATION-SPEED optimization values, and the
1602 :BLOCK-COMPILE argument will probably become deprecated."
1603 |#
1604   (let* ((fasl-output nil)
1605          (output-file-name nil)
1606          (compile-won nil)
1607          (warnings-p nil)
1608          (failure-p t) ; T in case error keeps this from being set later
1609          (input-pathname (verify-source-file input-file))
1610          (source-info (make-file-source-info input-pathname external-format))
1611          (*compiler-trace-output* nil)) ; might be modified below
1612
1613     (unwind-protect
1614         (progn
1615           (when output-file
1616             (setq output-file-name
1617                   (sb!xc:compile-file-pathname input-file
1618                                                :output-file output-file))
1619             (setq fasl-output
1620                   (open-fasl-output output-file-name
1621                                     (namestring input-pathname))))
1622           (when trace-file
1623             (let* ((default-trace-file-pathname
1624                      (make-pathname :type "trace" :defaults input-pathname))
1625                    (trace-file-pathname
1626                     (if (eql trace-file t)
1627                         default-trace-file-pathname
1628                         (merge-pathnames trace-file
1629                                          default-trace-file-pathname))))
1630               (setf *compiler-trace-output*
1631                     (open trace-file-pathname
1632                           :if-exists :supersede
1633                           :direction :output))))
1634
1635           (when sb!xc:*compile-verbose*
1636             (print-compile-start-note source-info))
1637           (let ((*compile-object* fasl-output)
1638                 dummy)
1639             (multiple-value-setq (dummy warnings-p failure-p)
1640               (sub-compile-file source-info)))
1641           (setq compile-won t))
1642
1643       (close-source-info source-info)
1644
1645       (when fasl-output
1646         (close-fasl-output fasl-output (not compile-won))
1647         (setq output-file-name
1648               (pathname (fasl-output-stream fasl-output)))
1649         (when (and compile-won sb!xc:*compile-verbose*)
1650           (compiler-mumble "~2&; ~A written~%" (namestring output-file-name))))
1651
1652       (when sb!xc:*compile-verbose*
1653         (print-compile-end-note source-info compile-won))
1654
1655       (when *compiler-trace-output*
1656         (close *compiler-trace-output*)))
1657
1658     (values (if output-file
1659                 ;; Hack around filesystem race condition...
1660                 (or (probe-file output-file-name) output-file-name)
1661                 nil)
1662             warnings-p
1663             failure-p)))
1664 \f
1665 ;;; a helper function for COMPILE-FILE-PATHNAME: the default for
1666 ;;; the OUTPUT-FILE argument
1667 ;;;
1668 ;;; ANSI: The defaults for the OUTPUT-FILE are taken from the pathname
1669 ;;; that results from merging the INPUT-FILE with the value of
1670 ;;; *DEFAULT-PATHNAME-DEFAULTS*, except that the type component should
1671 ;;; default to the appropriate implementation-defined default type for
1672 ;;; compiled files.
1673 (defun cfp-output-file-default (input-file)
1674   (let* ((defaults (merge-pathnames input-file *default-pathname-defaults*))
1675          (retyped (make-pathname :type *fasl-file-type* :defaults defaults)))
1676     retyped))
1677         
1678 ;;; KLUDGE: Part of the ANSI spec for this seems contradictory:
1679 ;;;   If INPUT-FILE is a logical pathname and OUTPUT-FILE is unsupplied,
1680 ;;;   the result is a logical pathname. If INPUT-FILE is a logical
1681 ;;;   pathname, it is translated into a physical pathname as if by
1682 ;;;   calling TRANSLATE-LOGICAL-PATHNAME.
1683 ;;; So I haven't really tried to make this precisely ANSI-compatible
1684 ;;; at the level of e.g. whether it returns logical pathname or a
1685 ;;; physical pathname. Patches to make it more correct are welcome.
1686 ;;; -- WHN 2000-12-09
1687 (defun sb!xc:compile-file-pathname (input-file
1688                                     &key
1689                                     (output-file (cfp-output-file-default
1690                                                   input-file))
1691                                     &allow-other-keys)
1692   #!+sb-doc
1693   "Return a pathname describing what file COMPILE-FILE would write to given
1694    these arguments."
1695   (merge-pathnames output-file (merge-pathnames input-file)))
1696 \f
1697 ;;;; MAKE-LOAD-FORM stuff
1698
1699 ;;; The entry point for MAKE-LOAD-FORM support. When IR1 conversion
1700 ;;; finds a constant structure, it invokes this to arrange for proper
1701 ;;; dumping. If it turns out that the constant has already been
1702 ;;; dumped, then we don't need to do anything.
1703 ;;;
1704 ;;; If the constant hasn't been dumped, then we check to see whether
1705 ;;; we are in the process of creating it. We detect this by
1706 ;;; maintaining the special *CONSTANTS-BEING-CREATED* as a list of all
1707 ;;; the constants we are in the process of creating. Actually, each
1708 ;;; entry is a list of the constant and any init forms that need to be
1709 ;;; processed on behalf of that constant.
1710 ;;;
1711 ;;; It's not necessarily an error for this to happen. If we are
1712 ;;; processing the init form for some object that showed up *after*
1713 ;;; the original reference to this constant, then we just need to
1714 ;;; defer the processing of that init form. To detect this, we
1715 ;;; maintain *CONSTANTS-CREATED-SINCE-LAST-INIT* as a list of the
1716 ;;; constants created since the last time we started processing an
1717 ;;; init form. If the constant passed to emit-make-load-form shows up
1718 ;;; in this list, then there is a circular chain through creation
1719 ;;; forms, which is an error.
1720 ;;;
1721 ;;; If there is some intervening init form, then we blow out of
1722 ;;; processing it by throwing to the tag PENDING-INIT. The value we
1723 ;;; throw is the entry from *CONSTANTS-BEING-CREATED*. This is so the
1724 ;;; offending init form can be tacked onto the init forms for the
1725 ;;; circular object.
1726 ;;;
1727 ;;; If the constant doesn't show up in *CONSTANTS-BEING-CREATED*, then
1728 ;;; we have to create it. We call MAKE-LOAD-FORM and check to see
1729 ;;; whether the creation form is the magic value
1730 ;;; :SB-JUST-DUMP-IT-NORMALLY. If it is, then we don't do anything. The
1731 ;;; dumper will eventually get its hands on the object and use the
1732 ;;; normal structure dumping noise on it.
1733 ;;;
1734 ;;; Otherwise, we bind *CONSTANTS-BEING-CREATED* and
1735 ;;; *CONSTANTS-CREATED-SINCE- LAST-INIT* and compile the creation form
1736 ;;; much the way LOAD-TIME-VALUE does. When this finishes, we tell the
1737 ;;; dumper to use that result instead whenever it sees this constant.
1738 ;;;
1739 ;;; Now we try to compile the init form. We bind
1740 ;;; *CONSTANTS-CREATED-SINCE-LAST-INIT* to NIL and compile the init
1741 ;;; form (and any init forms that were added because of circularity
1742 ;;; detection). If this works, great. If not, we add the init forms to
1743 ;;; the init forms for the object that caused the problems and let it
1744 ;;; deal with it.
1745 (defvar *constants-being-created* nil)
1746 (defvar *constants-created-since-last-init* nil)
1747 ;;; FIXME: Shouldn't these^ variables be unbound outside LET forms?
1748 (defun emit-make-load-form (constant)
1749   (aver (fasl-output-p *compile-object*))
1750   (unless (or (fasl-constant-already-dumped-p constant *compile-object*)
1751               ;; KLUDGE: This special hack is because I was too lazy
1752               ;; to rework DEF!STRUCT so that the MAKE-LOAD-FORM
1753               ;; function of LAYOUT returns nontrivial forms when
1754               ;; building the cross-compiler but :IGNORE-IT when
1755               ;; cross-compiling or running under the target Lisp. --
1756               ;; WHN 19990914
1757               #+sb-xc-host (typep constant 'layout))
1758     (let ((circular-ref (assoc constant *constants-being-created* :test #'eq)))
1759       (when circular-ref
1760         (when (find constant *constants-created-since-last-init* :test #'eq)
1761           (throw constant t))
1762         (throw 'pending-init circular-ref)))
1763     (multiple-value-bind (creation-form init-form)
1764         (handler-case
1765             (sb!xc:make-load-form constant (make-null-lexenv))
1766           (error (condition)
1767             (compiler-error condition)))
1768       (case creation-form
1769         (:sb-just-dump-it-normally
1770          (fasl-validate-structure constant *compile-object*)
1771          t)
1772         (:ignore-it
1773          nil)
1774         (t
1775          (when (fasl-constant-already-dumped-p constant *compile-object*)
1776            (return-from emit-make-load-form nil))
1777          (let* ((name (write-to-string constant :level 1 :length 2))
1778                 (info (if init-form
1779                           (list constant name init-form)
1780                           (list constant))))
1781            (let ((*constants-being-created*
1782                   (cons info *constants-being-created*))
1783                  (*constants-created-since-last-init*
1784                   (cons constant *constants-created-since-last-init*)))
1785              (when
1786                  (catch constant
1787                    (fasl-note-handle-for-constant
1788                     constant
1789                     (compile-load-time-value
1790                      creation-form)
1791                     *compile-object*)
1792                    nil)
1793                (compiler-error "circular references in creation form for ~S"
1794                                constant)))
1795            (when (cdr info)
1796              (let* ((*constants-created-since-last-init* nil)
1797                     (circular-ref
1798                      (catch 'pending-init
1799                        (loop for (name form) on (cdr info) by #'cddr
1800                          collect name into names
1801                          collect form into forms
1802                          finally (compile-make-load-form-init-forms forms))
1803                        nil)))
1804                (when circular-ref
1805                  (setf (cdr circular-ref)
1806                        (append (cdr circular-ref) (cdr info))))))))))))
1807
1808 \f
1809 ;;;; Host compile time definitions
1810 #+sb-xc-host
1811 (defun compile-in-lexenv (name lambda lexenv)
1812   (declare (ignore lexenv))
1813   (compile name lambda))
1814
1815 #+sb-xc-host
1816 (defun eval-in-lexenv (form lexenv)
1817   (declare (ignore lexenv))
1818   (eval form))