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