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