611992e8971f5602d58dbaaea40be8f338967c33
[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-variables* *component-being-compiled*
18                   *code-vector* *next-location* *result-fixups*
19                   *free-functions* *source-paths*
20                   *seen-blocks* *seen-functions* *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*))
32
33 (defvar *byte-compile-default* :maybe
34   #!+sb-doc
35   "the default value for the :BYTE-COMPILE argument to COMPILE-FILE")
36
37 (defvar *byte-compile-top-level*
38   #-sb-xc-host t
39   #+sb-xc-host nil ; since the byte compiler isn't supported in cross-compiler
40   #!+sb-doc
41   "Similar to *BYTE-COMPILE-DEFAULT*, but controls the compilation of top-level
42    forms (evaluated at load-time) when the :BYTE-COMPILE argument is :MAYBE
43    (the default.)  When true, we decide to byte-compile.")
44
45 ;;; the value of the :BYTE-COMPILE argument which was passed to the
46 ;;; compiler
47 (defvar *byte-compile* :maybe)
48
49 ;;; Bound by COMPILE-COMPONENT to T when byte-compiling, and NIL when
50 ;;; native compiling. During IR1 conversion this can also be :MAYBE,
51 ;;; in which case we must look at the policy, see (byte-compiling).
52 (defvar *byte-compiling* :maybe)
53 (declaim (type (member t nil :maybe) *byte-compile* *byte-compiling*
54                *byte-compile-default*))
55
56 (defvar *check-consistency* nil)
57 (defvar *all-components*)
58
59 ;;; Bind this to a stream to capture various internal debugging output.
60 (defvar *compiler-trace-output* nil)
61
62 ;;; The current block compilation state. These are initialized to the
63 ;;; :BLOCK-COMPILE and :ENTRY-POINTS arguments that COMPILE-FILE was
64 ;;; called with.
65 ;;;
66 ;;; *BLOCK-COMPILE-ARGUMENT* holds the original value of the
67 ;;; :BLOCK-COMPILE argument, which overrides any internal
68 ;;; declarations.
69 (defvar *block-compile*)
70 (defvar *block-compile-argument*)
71 (declaim (type (member nil t :specified)
72                *block-compile* *block-compile-argument*))
73 (defvar *entry-points*)
74 (declaim (list *entry-points*))
75
76 ;;; When block compiling, used by PROCESS-FORM to accumulate top-level
77 ;;; lambdas resulting from compiling subforms. (In reverse order.)
78 (defvar *top-level-lambdas*)
79 (declaim (list *top-level-lambdas*))
80
81 (defvar sb!xc:*compile-verbose* t
82   #!+sb-doc
83   "The default for the :VERBOSE argument to COMPILE-FILE.")
84 (defvar sb!xc:*compile-print* t
85   #!+sb-doc
86   "The default for the :PRINT argument to COMPILE-FILE.")
87 (defvar *compile-progress* nil
88   #!+sb-doc
89   "When this is true, the compiler prints to *ERROR-OUTPUT* progress
90   information about the phases of compilation of each function. (This
91   is useful mainly in large block compilations.)")
92
93 (defvar sb!xc:*compile-file-pathname* nil
94   #!+sb-doc
95   "The defaulted pathname of the file currently being compiled, or NIL if not
96   compiling.")
97 (defvar sb!xc:*compile-file-truename* nil
98   #!+sb-doc
99   "The TRUENAME of the file currently being compiled, or NIL if not
100   compiling.")
101
102 (declaim (type (or pathname null)
103                sb!xc:*compile-file-pathname*
104                sb!xc:*compile-file-truename*))
105
106 ;;; the SOURCE-INFO structure for the current compilation. This is
107 ;;; null globally to indicate that we aren't currently in any
108 ;;; identifiable compilation.
109 (defvar *source-info* nil)
110
111 ;;; This is true if we are within a WITH-COMPILATION-UNIT form (which
112 ;;; normally causes nested uses to be no-ops).
113 (defvar *in-compilation-unit* nil)
114
115 ;;; Count of the number of compilation units dynamically enclosed by
116 ;;; the current active WITH-COMPILATION-UNIT that were unwound out of.
117 (defvar *aborted-compilation-unit-count*)
118
119 ;;; Mumble conditional on *COMPILE-PROGRESS*.
120 (defun maybe-mumble (&rest foo)
121   (when *compile-progress*
122     (compiler-mumble "~&")
123     (pprint-logical-block (*error-output* nil :per-line-prefix "; ")
124        (apply #'compiler-mumble foo))))
125
126 (deftype object () '(or fasl-output core-object null))
127
128 (defvar *compile-object* nil)
129 (declaim (type object *compile-object*))
130 \f
131 ;;;; WITH-COMPILATION-UNIT and WITH-COMPILATION-VALUES
132
133 (defmacro sb!xc:with-compilation-unit (options &body body)
134   #!+sb-doc
135   "WITH-COMPILATION-UNIT ({Key Value}*) Form*
136   This form affects compilations that take place within its dynamic extent. It
137   is intended to be wrapped around the compilation of all files in the same
138   system. These keywords are defined:
139     :OVERRIDE Boolean-Form
140         One of the effects of this form is to delay undefined warnings
141         until the end of the form, instead of giving them at the end of each
142         compilation. If OVERRIDE is NIL (the default), then the outermost
143         WITH-COMPILATION-UNIT form grabs the undefined warnings. Specifying
144         OVERRIDE true causes that form to grab any enclosed warnings, even if
145         it is enclosed by another WITH-COMPILATION-UNIT."
146   `(%with-compilation-unit (lambda () ,@body) ,@options))
147
148 (defun %with-compilation-unit (fn &key override)
149   (let ((succeeded-p nil))
150     (if (and *in-compilation-unit* (not override))
151         ;; Inside another WITH-COMPILATION-UNIT, a WITH-COMPILATION-UNIT is
152         ;; ordinarily (unless OVERRIDE) basically a no-op.
153         (unwind-protect
154             (multiple-value-prog1 (funcall fn) (setf succeeded-p t))
155           (unless succeeded-p
156             (incf *aborted-compilation-unit-count*)))
157         ;; FIXME: Now *COMPILER-FOO-COUNT* stuff is bound in more than
158         ;; one place. If we can get rid of the IR1 interpreter, this
159         ;; should be easier to clean up.
160         (let ((*aborted-compilation-unit-count* 0)
161               (*compiler-error-count* 0)
162               (*compiler-warning-count* 0)
163               (*compiler-style-warning-count* 0)
164               (*compiler-note-count* 0)
165               (*undefined-warnings* nil)
166               (*in-compilation-unit* t))
167           (handler-bind ((parse-unknown-type
168                           (lambda (c)
169                             (note-undefined-reference
170                              (parse-unknown-type-specifier c)
171                              :type))))
172             (unwind-protect
173                 (multiple-value-prog1 (funcall fn) (setf succeeded-p t))
174               (unless succeeded-p
175                 (incf *aborted-compilation-unit-count*))
176               (summarize-compilation-unit (not succeeded-p))))))))
177
178 ;;; This is to be called at the end of a compilation unit. It signals
179 ;;; any residual warnings about unknown stuff, then prints the total
180 ;;; error counts. ABORT-P should be true when the compilation unit was
181 ;;; aborted by throwing out. ABORT-COUNT is the number of dynamically
182 ;;; enclosed nested compilation units that were aborted.
183 (defun summarize-compilation-unit (abort-p)
184   (unless abort-p
185     (handler-bind ((style-warning #'compiler-style-warning-handler)
186                    (warning #'compiler-warning-handler))
187
188       (let ((undefs (sort *undefined-warnings* #'string<
189                           :key #'(lambda (x)
190                                    (let ((x (undefined-warning-name x)))
191                                      (if (symbolp x)
192                                          (symbol-name x)
193                                          (prin1-to-string x)))))))
194         (unless *converting-for-interpreter*
195           (dolist (undef undefs)
196             (let ((name (undefined-warning-name undef))
197                   (kind (undefined-warning-kind undef))
198                   (warnings (undefined-warning-warnings undef))
199                   (undefined-warning-count (undefined-warning-count undef)))
200               (dolist (*compiler-error-context* warnings)
201                 (compiler-style-warning "undefined ~(~A~): ~S" kind name))
202
203               (let ((warn-count (length warnings)))
204                 (when (and warnings (> undefined-warning-count warn-count))
205                   (let ((more (- undefined-warning-count warn-count)))
206                     (compiler-style-warning
207                      "~D more use~:P of undefined ~(~A~) ~S"
208                      more kind name)))))))
209         
210         (dolist (kind '(:variable :function :type))
211           (let ((summary (mapcar #'undefined-warning-name
212                                  (remove kind undefs :test-not #'eq
213                                          :key #'undefined-warning-kind))))
214             (when summary
215               (compiler-style-warning
216                "~:[This ~(~A~) is~;These ~(~A~)s are~] undefined:~
217                 ~%  ~{~<~%  ~1:;~S~>~^ ~}"
218                (cdr summary) kind summary)))))))
219
220   (unless (or *converting-for-interpreter*
221               (and (not abort-p)
222                    (zerop *aborted-compilation-unit-count*)
223                    (zerop *compiler-error-count*)
224                    (zerop *compiler-warning-count*)
225                    (zerop *compiler-style-warning-count*)
226                    (zerop *compiler-note-count*)))
227     (format *error-output* "~&")
228     (pprint-logical-block (*error-output* nil :per-line-prefix "; ")
229       (compiler-mumble "compilation unit ~:[finished~;aborted~]~
230                        ~[~:;~:*~&  caught ~D fatal ERROR condition~:P~]~
231                        ~[~:;~:*~&  caught ~D ERROR condition~:P~]~
232                        ~[~:;~:*~&  caught ~D WARNING condition~:P~]~
233                        ~[~:;~:*~&  caught ~D STYLE-WARNING condition~:P~]~
234                        ~[~:;~:*~&  printed ~D note~:P~]"
235                        abort-p
236                        *aborted-compilation-unit-count*
237                        *compiler-error-count*
238                        *compiler-warning-count*
239                        *compiler-style-warning-count*
240                        *compiler-note-count*)))
241   (format *error-output* "~&"))
242
243 ;;; Evaluate BODY, then return (VALUES BODY-VALUE WARNINGS-P
244 ;;; FAILURE-P), where BODY-VALUE is the first value of the body, and
245 ;;; WARNINGS-P and FAILURE-P are as in CL:COMPILE or CL:COMPILE-FILE.
246 ;;; This also wraps up WITH-IR1-NAMESPACE functionality.
247 (defmacro with-compilation-values (&body body)
248   `(with-ir1-namespace
249     (let ((*warnings-p* nil)
250           (*failure-p* nil))
251       (values (progn ,@body)
252               *warnings-p*
253               *failure-p*))))
254 \f
255 ;;;; component compilation
256
257 (defparameter *max-optimize-iterations* 3 ; ARB
258   #!+sb-doc
259   "The upper limit on the number of times that we will consecutively do IR1
260   optimization that doesn't introduce any new code. A finite limit is
261   necessary, since type inference may take arbitrarily long to converge.")
262
263 (defevent ir1-optimize-until-done "IR1-OPTIMIZE-UNTIL-DONE called")
264 (defevent ir1-optimize-maxed-out "hit *MAX-OPTIMIZE-ITERATIONS* limit")
265
266 ;;; Repeatedly optimize COMPONENT until no further optimizations can
267 ;;; be found or we hit our iteration limit. When we hit the limit, we
268 ;;; clear the component and block REOPTIMIZE flags to discourage the
269 ;;; next optimization attempt from pounding on the same code.
270 (defun ir1-optimize-until-done (component)
271   (declare (type component component))
272   (maybe-mumble "opt")
273   (event ir1-optimize-until-done)
274   (let ((count 0)
275         (cleared-reanalyze nil))
276     (loop
277       (when (component-reanalyze component)
278         (setq count 0)
279         (setq cleared-reanalyze t)
280         (setf (component-reanalyze component) nil))
281       (setf (component-reoptimize component) nil)
282       (ir1-optimize component)
283       (cond ((component-reoptimize component)
284              (incf count)
285              (when (= count *max-optimize-iterations*)
286                (maybe-mumble "*")
287                (cond ((retry-delayed-ir1-transforms :optimize)
288                       (maybe-mumble "+")
289                       (setq count 0))
290                      (t
291                       (event ir1-optimize-maxed-out)
292                       (setf (component-reoptimize component) nil)
293                       (do-blocks (block component)
294                         (setf (block-reoptimize block) nil))
295                       (return)))))
296             ((retry-delayed-ir1-transforms :optimize)
297              (setf count 0)
298              (maybe-mumble "+"))
299             (t
300              (maybe-mumble " ")
301              (return)))
302       (maybe-mumble "."))
303     (when cleared-reanalyze
304       (setf (component-reanalyze component) t)))
305   (values))
306
307 (defparameter *constraint-propagate* t)
308
309 ;;; KLUDGE: This was bumped from 5 to 10 in a DTC patch ported by MNA
310 ;;; from CMU CL into sbcl-0.6.11.44, the same one which allowed IR1
311 ;;; transforms to be delayed. Either DTC or MNA or both didn't explain
312 ;;; why, and I don't know what the rationale was. -- WHN 2001-04-28
313 ;;;
314 ;;; FIXME: It would be good to document why it's important to have a
315 ;;; large value here, and what the drawbacks of an excessively large
316 ;;; value are; and it might also be good to make it depend on
317 ;;; optimization policy.
318 (defparameter *reoptimize-after-type-check-max* 10)
319
320 (defevent reoptimize-maxed-out
321   "*REOPTIMIZE-AFTER-TYPE-CHECK-MAX* exceeded.")
322
323 ;;; Iterate doing FIND-DFO until no new dead code is discovered.
324 (defun dfo-as-needed (component)
325   (declare (type component component))
326   (when (component-reanalyze component)
327     (maybe-mumble "DFO")
328     (loop
329       (find-dfo component)
330       (unless (component-reanalyze component)
331         (maybe-mumble " ")
332         (return))
333       (maybe-mumble ".")))
334   (values))
335
336 ;;; Do all the IR1 phases for a non-top-level component.
337 (defun ir1-phases (component)
338   (declare (type component component))
339   (let ((*constraint-number* 0)
340         (loop-count 1)
341         (*delayed-ir1-transforms* nil))
342     (declare (special *constraint-number* *delayed-ir1-transforms*))
343     (loop
344       (ir1-optimize-until-done component)
345       (when (or (component-new-functions component)
346                 (component-reanalyze-functions component))
347         (maybe-mumble "locall ")
348         (local-call-analyze component))
349       (dfo-as-needed component)
350       (when *constraint-propagate*
351         (maybe-mumble "constraint ")
352         (constraint-propagate component))
353       (when (retry-delayed-ir1-transforms :constraint)
354         (maybe-mumble "Rtran "))
355       ;; Delay the generation of type checks until the type
356       ;; constraints have had time to propagate, else the compiler can
357       ;; confuse itself.
358       (unless (and (or (component-reoptimize component)
359                        (component-reanalyze component)
360                        (component-new-functions component)
361                        (component-reanalyze-functions component))
362                    (< loop-count (- *reoptimize-after-type-check-max* 4)))
363         (maybe-mumble "type ")
364         (generate-type-checks component)
365         (unless (or (component-reoptimize component)
366                     (component-reanalyze component)
367                     (component-new-functions component)
368                     (component-reanalyze-functions component))
369           (return)))
370       (when (>= loop-count *reoptimize-after-type-check-max*)
371         (maybe-mumble "[reoptimize limit]")
372         (event reoptimize-maxed-out)
373         (return))
374       (incf loop-count)))
375
376   (ir1-finalize component)
377   (values))
378
379 (defun native-compile-component (component)
380   (let ((*code-segment* nil)
381         (*elsewhere* nil))
382     (maybe-mumble "GTN ")
383     (gtn-analyze component)
384     (maybe-mumble "LTN ")
385     (ltn-analyze component)
386     (dfo-as-needed component)
387     (maybe-mumble "control ")
388     (control-analyze component #'make-ir2-block)
389
390     (when (ir2-component-values-receivers (component-info component))
391       (maybe-mumble "stack ")
392       (stack-analyze component)
393       ;; Assign BLOCK-NUMBER for any cleanup blocks introduced by
394       ;; stack analysis. There shouldn't be any unreachable code after
395       ;; control, so this won't delete anything.
396       (dfo-as-needed component))
397
398     (unwind-protect
399         (progn
400           (maybe-mumble "IR2tran ")
401           (init-assembler)
402           (entry-analyze component)
403           (ir2-convert component)
404
405           (when (policy *lexenv* (>= speed compilation-speed))
406             (maybe-mumble "copy ")
407             (copy-propagate component))
408
409           (select-representations component)
410
411           (when *check-consistency*
412             (maybe-mumble "check2 ")
413             (check-ir2-consistency component))
414
415           (delete-unreferenced-tns component)
416
417           (maybe-mumble "life ")
418           (lifetime-analyze component)
419
420           (when *compile-progress*
421             (compiler-mumble "") ; Sync before doing more output.
422             (pre-pack-tn-stats component *error-output*))
423
424           (when *check-consistency*
425             (maybe-mumble "check-life ")
426             (check-life-consistency component))
427
428           (maybe-mumble "pack ")
429           (pack component)
430
431           (when *check-consistency*
432             (maybe-mumble "check-pack ")
433             (check-pack-consistency component))
434
435           (when *compiler-trace-output*
436             (describe-component component *compiler-trace-output*)
437             (describe-ir2-component component *compiler-trace-output*))
438
439           (maybe-mumble "code ")
440           (multiple-value-bind (code-length trace-table fixups)
441               (generate-code component)
442
443             (when *compiler-trace-output*
444               (format *compiler-trace-output*
445                       "~|~%disassembly of code for ~S~2%" component)
446               (sb!disassem:disassemble-assem-segment *code-segment*
447                                                      *compiler-trace-output*))
448
449             (etypecase *compile-object*
450               (fasl-output
451                (maybe-mumble "fasl")
452                (fasl-dump-component component
453                                     *code-segment*
454                                     code-length
455                                     trace-table
456                                     fixups
457                                     *compile-object*))
458               (core-object
459                (maybe-mumble "core")
460                (make-core-component component
461                                     *code-segment*
462                                     code-length
463                                     trace-table
464                                     fixups
465                                     *compile-object*))
466               (null))))))
467
468   ;; We're done, so don't bother keeping anything around.
469   (setf (component-info component) nil)
470
471   (values))
472
473 (defun policy-byte-compile-p (thing)
474   (policy thing
475           (and (zerop speed)
476                (<= debug 1))))
477
478 ;;; Return our best guess for whether we will byte compile code
479 ;;; currently being IR1 converted. This is only a guess because the
480 ;;; decision is made on a per-component basis.
481 ;;;
482 ;;; FIXME: This should be called something more mnemonic, e.g.
483 ;;; PROBABLY-BYTE-COMPILING
484 (defun byte-compiling ()
485   (if (eq *byte-compiling* :maybe)
486       (or (eq *byte-compile* t)
487           (policy-byte-compile-p *lexenv*))
488       (and *byte-compile* *byte-compiling*)))
489
490 ;;; Delete components with no external entry points before we try to
491 ;;; generate code. Unreachable closures can cause IR2 conversion to
492 ;;; puke on itself, since it is the reference to the closure which
493 ;;; normally causes the components to be combined.
494 ;;;
495 ;;; FIXME: The original CMU CL comment said "This doesn't really cover
496 ;;; all cases..." That's a little scary.
497 (defun delete-if-no-entries (component)
498   (dolist (fun (component-lambdas component)
499                (delete-component component))
500     (case (functional-kind fun)
501       (:top-level (return))
502       (:external
503        (unless (every (lambda (ref)
504                         (eq (block-component (node-block ref))
505                             component))
506                       (leaf-refs fun))
507          (return))))))
508
509 (defun byte-compile-this-component-p (component)
510   (ecase *byte-compile*
511     ((t) t)
512     ((nil) nil)
513     ((:maybe)
514      (every #'policy-byte-compile-p (component-lambdas component)))))
515
516 (defun compile-component (component)
517   (let* ((*component-being-compiled* component)
518          (*byte-compiling* (byte-compile-this-component-p component)))
519     (when sb!xc:*compile-print*
520       (compiler-mumble "~&; ~:[~;byte ~]compiling ~A: "
521                        *byte-compiling*
522                        (component-name component)))
523
524     (ir1-phases component)
525
526     ;; FIXME: What is MAYBE-MUMBLE for? Do we need it any more?
527     (maybe-mumble "env ")
528     (environment-analyze component)
529     (dfo-as-needed component)
530
531     (delete-if-no-entries component)
532
533     (unless (eq (block-next (component-head component))
534                 (component-tail component))
535       (if *byte-compiling*
536           (byte-compile-component component)
537           (native-compile-component component))))
538
539   (clear-constant-info)
540
541   (when sb!xc:*compile-print*
542     (compiler-mumble "~&"))
543
544   (values))
545 \f
546 ;;;; clearing global data structures
547 ;;;;
548 ;;;; FIXME: Is it possible to get rid of this stuff, getting rid of
549 ;;;; global data structures entirely when possible and consing up the
550 ;;;; others from scratch instead of clearing and reusing them?
551
552 ;;; Clear the INFO in constants in the *FREE-VARIABLES*, etc. In
553 ;;; addition to allowing stuff to be reclaimed, this is required for
554 ;;; correct assignment of constant offsets, since we need to assign a
555 ;;; new offset for each component. We don't clear the FUNCTIONAL-INFO
556 ;;; slots, since they are used to keep track of functions across
557 ;;; component boundaries.
558 (defun clear-constant-info ()
559   (maphash #'(lambda (k v)
560                (declare (ignore k))
561                (setf (leaf-info v) nil))
562            *constants*)
563   (maphash #'(lambda (k v)
564                (declare (ignore k))
565                (when (constant-p v)
566                  (setf (leaf-info v) nil)))
567            *free-variables*)
568   (values))
569
570 ;;; Blow away the REFS for all global variables, and let COMPONENT
571 ;;; be recycled.
572 (defun clear-ir1-info (component)
573   (declare (type component component))
574   (labels ((blast (x)
575              (maphash #'(lambda (k v)
576                           (declare (ignore k))
577                           (when (leaf-p v)
578                             (setf (leaf-refs v)
579                                   (delete-if #'here-p (leaf-refs v)))
580                             (when (basic-var-p v)
581                               (setf (basic-var-sets v)
582                                     (delete-if #'here-p (basic-var-sets v))))))
583                       x))
584            (here-p (x)
585              (eq (block-component (node-block x)) component)))
586     (blast *free-variables*)
587     (blast *free-functions*)
588     (blast *constants*))
589   (values))
590
591 ;;; Clear global variables used by the compiler.
592 ;;;
593 ;;; FIXME: It seems kinda nasty and unmaintainable to have to do this,
594 ;;; and it adds overhead even when people aren't using the compiler.
595 ;;; Perhaps we could make these global vars unbound except when
596 ;;; actually in use, so that this function could go away.
597 (defun clear-stuff (&optional (debug-too t))
598
599   ;; Clear global tables.
600   (when (boundp '*free-functions*)
601     (clrhash *free-functions*)
602     (clrhash *free-variables*)
603     (clrhash *constants*))
604
605   ;; Clear debug counters and tables.
606   (clrhash *seen-blocks*)
607   (clrhash *seen-functions*)
608   (clrhash *list-conflicts-table*)
609
610   (when debug-too
611     (clrhash *continuation-numbers*)
612     (clrhash *number-continuations*)
613     (setq *continuation-number* 0)
614     (clrhash *tn-ids*)
615     (clrhash *id-tns*)
616     (setq *tn-id* 0)
617     (clrhash *label-ids*)
618     (clrhash *id-labels*)
619     (setq *label-id* 0)
620
621     ;; Clear some PACK data structures (for GC purposes only).
622     (aver (not *in-pack*))
623     (dolist (sb *backend-sb-list*)
624       (when (finite-sb-p sb)
625         (fill (finite-sb-live-tns sb) nil))))
626
627   ;; (Note: The CMU CL code used to set CL::*GENSYM-COUNTER* to zero here.
628   ;; Superficially, this seemed harmful -- the user could reasonably be
629   ;; surprised if *GENSYM-COUNTER* turned back to zero when something was
630   ;; compiled. A closer inspection showed that this actually turned out to be
631   ;; harmless in practice, because CLEAR-STUFF was only called from within
632   ;; forms which bound CL::*GENSYM-COUNTER* to zero. However, this means that
633   ;; even though zeroing CL::*GENSYM-COUNTER* here turned out to be harmless in
634   ;; practice, it was also useless in practice. So we don't do it any more.)
635
636   (values))
637 \f
638 ;;;; trace output
639
640 ;;; Print out some useful info about Component to Stream.
641 (defun describe-component (component *standard-output*)
642   (declare (type component component))
643   (format t "~|~%;;;; component: ~S~2%" (component-name component))
644   (print-blocks component)
645   (values))
646
647 (defun describe-ir2-component (component *standard-output*)
648   (format t "~%~|~%;;;; IR2 component: ~S~2%" (component-name component))
649   (format t "entries:~%")
650   (dolist (entry (ir2-component-entries (component-info component)))
651     (format t "~4TL~D: ~S~:[~; [closure]~]~%"
652             (label-id (entry-info-offset entry))
653             (entry-info-name entry)
654             (entry-info-closure-p entry)))
655   (terpri)
656   (pre-pack-tn-stats component *standard-output*)
657   (terpri)
658   (print-ir2-blocks component)
659   (terpri)
660   (values))
661 \f
662 ;;;; file reading
663 ;;;;
664 ;;;; When reading from a file, we have to keep track of some source
665 ;;;; information. We also exploit our ability to back up for printing
666 ;;;; the error context and for recovering from errors.
667 ;;;;
668 ;;;; The interface we provide to this stuff is the stream-oid
669 ;;;; Source-Info structure. The bookkeeping is done as a side-effect
670 ;;;; of getting the next source form.
671
672 ;;; A FILE-INFO structure holds all the source information for a
673 ;;; given file.
674 (defstruct (file-info (:copier nil))
675   ;; If a file, the truename of the corresponding source file. If from
676   ;; a Lisp form, :LISP. If from a stream, :STREAM.
677   (name (required-argument) :type (or pathname (member :lisp :stream)))
678   ;; the defaulted, but not necessarily absolute file name (i.e. prior
679   ;; to TRUENAME call.) Null if not a file. This is used to set
680   ;; *COMPILE-FILE-PATHNAME*, and if absolute, is dumped in the
681   ;; debug-info.
682   (untruename nil :type (or pathname null))
683   ;; the file's write date (if relevant)
684   (write-date nil :type (or unsigned-byte null))
685   ;; the source path root number of the first form in this file (i.e.
686   ;; the total number of forms converted previously in this
687   ;; compilation)
688   (source-root 0 :type unsigned-byte)
689   ;; parallel vectors containing the forms read out of the file and
690   ;; the file positions that reading of each form started at (i.e. the
691   ;; end of the previous form)
692   (forms (make-array 10 :fill-pointer 0 :adjustable t) :type (vector t))
693   (positions (make-array 10 :fill-pointer 0 :adjustable t) :type (vector t)))
694
695 ;;; The SOURCE-INFO structure provides a handle on all the source
696 ;;; information for an entire compilation.
697 (defstruct (source-info
698             #-no-ansi-print-object
699             (:print-object (lambda (s stream)
700                              (print-unreadable-object (s stream :type t))))
701             (:copier nil))
702   ;; the UT that compilation started at
703   (start-time (get-universal-time) :type unsigned-byte)
704   ;; the FILE-INFO structure for this compilation
705   (file-info nil :type (or file-info null))
706   ;; the stream that we are using to read the FILE-INFO, or NIL if
707   ;; no stream has been opened yet
708   (stream nil :type (or stream null)))
709
710 ;;; Given a pathname, return a SOURCE-INFO structure.
711 (defun make-file-source-info (file)
712   (let ((file-info (make-file-info :name (truename file)
713                                    :untruename file
714                                    :write-date (file-write-date file))))
715
716     (make-source-info :file-info file-info)))
717
718 ;;; Return a SOURCE-INFO to describe the incremental compilation of
719 ;;; FORM. Also used by SB!EVAL:INTERNAL-EVAL.
720 (defun make-lisp-source-info (form)
721   (make-source-info :start-time (get-universal-time)
722                     :file-info (make-file-info :name :lisp
723                                                :forms (vector form)
724                                                :positions '#(0))))
725
726 ;;; Return a SOURCE-INFO which will read from STREAM.
727 (defun make-stream-source-info (stream)
728   (let ((file-info (make-file-info :name :stream)))
729     (make-source-info :file-info file-info
730                       :stream stream)))
731
732 ;;; Return a form read from STREAM; or for EOF, use the trick
733 ;;; popularized by Kent Pitman of returning STREAM itself. If an error
734 ;;; happens, then convert it to standard abort-the-compilation error
735 ;;; condition (possibly recording some extra location information).
736 (defun read-for-compile-file (stream position)
737   (handler-case (read stream nil stream)
738     (reader-error (condition)
739      (error 'input-error-in-compile-file
740             :error condition
741             ;; We don't need to supply :POSITION here because
742             ;; READER-ERRORs already know their position in the file.
743             ))
744     ;; ANSI, in its wisdom, says that READ should return END-OF-FILE
745     ;; (and that this is not a READER-ERROR) when it encounters end of
746     ;; file in the middle of something it's trying to read.
747     (end-of-file (condition)
748      (error 'input-error-in-compile-file
749             :error condition
750             ;; We need to supply :POSITION here because the END-OF-FILE
751             ;; condition doesn't carry the position that the user
752             ;; probably cares about, where the failed READ began.
753             :position position))))
754
755 ;;; If STREAM is present, return it, otherwise open a stream to the
756 ;;; current file. There must be a current file.
757 ;;;
758 ;;; FIXME: This is probably an unnecessarily roundabout way to do
759 ;;; things now that we process a single file in COMPILE-FILE (unlike
760 ;;; the old CMU CL code, which accepted multiple files). Also, the old
761 ;;; comment said
762 ;;;   When we open a new file, we also reset *PACKAGE* and policy.
763 ;;;   This gives the effect of rebinding around each file.
764 ;;; which doesn't seem to be true now. Check to make sure that if
765 ;;; such rebinding is necessary, it's still done somewhere.
766 (defun get-source-stream (info)
767   (declare (type source-info info))
768   (or (source-info-stream info)
769       (let* ((file-info (source-info-file-info info))
770              (name (file-info-name file-info)))
771         (setf sb!xc:*compile-file-truename* name
772               sb!xc:*compile-file-pathname* (file-info-untruename file-info)
773               (source-info-stream info) (open name :direction :input)))))
774
775 ;;; Close the stream in INFO if it is open.
776 (defun close-source-info (info)
777   (declare (type source-info info))
778   (let ((stream (source-info-stream info)))
779     (when stream (close stream)))
780   (setf (source-info-stream info) nil)
781   (values))
782
783 ;;; Read the source file.
784 (defun process-source (info)
785   (let* ((file-info (source-info-file-info info))
786          (stream (get-source-stream info)))
787     (loop
788      (let* ((pos (file-position stream))
789             (form (read-for-compile-file stream pos)))
790        (if (eq form stream) ; i.e., if EOF
791            (return)
792            (let* ((forms (file-info-forms file-info))
793                   (current-idx (+ (fill-pointer forms)
794                                   (file-info-source-root file-info))))
795              (vector-push-extend form forms)
796              (vector-push-extend pos (file-info-positions file-info))
797              (clrhash *source-paths*)
798              (find-source-paths form current-idx)
799              (process-top-level-form form
800                                      `(original-source-start 0
801                                                              ,current-idx))))))))
802
803 ;;; Return the INDEX'th source form read from INFO and the position
804 ;;; where it was read.
805 (defun find-source-root (index info)
806   (declare (type index index) (type source-info info))
807   (let ((file-info (source-info-file-info info)))
808     (values (aref (file-info-forms file-info) index)
809             (aref (file-info-positions file-info) index))))
810 \f
811 ;;;; top-level form processing
812
813 ;;; This is called by top-level form processing when we are ready to
814 ;;; actually compile something. If *BLOCK-COMPILE* is T, then we still
815 ;;; convert the form, but delay compilation, pushing the result on
816 ;;; *TOP-LEVEL-LAMBDAS* instead.
817 (defun convert-and-maybe-compile (form path)
818   (declare (list path))
819   (let* ((*lexenv* (make-lexenv :policy *policy*))
820          (tll (ir1-top-level form path nil)))
821     (cond ((eq *block-compile* t) (push tll *top-level-lambdas*))
822           (t (compile-top-level (list tll) nil)))))
823
824 ;;; Process a PROGN-like portion of a top-level form. Forms is a list of
825 ;;; the forms, and Path is source path of the form they came out of.
826 (defun process-top-level-progn (forms path)
827   (declare (list forms) (list path))
828   (dolist (form forms)
829     (process-top-level-form form path)))
830
831 ;;; Macroexpand form in the current environment with an error handler.
832 ;;; We only expand one level, so that we retain all the intervening
833 ;;; forms in the source path.
834 (defun preprocessor-macroexpand (form)
835   (handler-case (sb!xc:macroexpand-1 form *lexenv*)
836     (error (condition)
837        (compiler-error "(during macroexpansion)~%~A" condition))))
838
839 ;;; Process a top-level use of LOCALLY. We parse declarations and then
840 ;;; recursively process the body.
841 (defun process-top-level-locally (form path)
842   (declare (list path))
843   (multiple-value-bind (forms decls) (sb!sys:parse-body (cdr form) nil)
844     (let* ((*lexenv*
845             (process-decls decls nil nil (make-continuation)))
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            ;; FIXME: Ideally, something should be done so that DECLAIM
853            ;; inside LOCALLY works OK. Failing that, at least we could
854            ;; issue a warning instead of silently screwing up.
855            (*policy* (lexenv-policy *lexenv*)))
856       (process-top-level-progn forms path))))
857
858 ;;; Force any pending top-level forms to be compiled and dumped so
859 ;;; that they will be evaluated in the correct package environment.
860 ;;; Dump the form to be evaled at (cold) load time, and if EVAL is
861 ;;; true, eval the form immediately.
862 (defun process-cold-load-form (form path eval)
863   (let ((object *compile-object*))
864     (etypecase object
865       (fasl-output
866        (compile-top-level-lambdas () t)
867        (fasl-dump-cold-load-form form object))
868       ((or null core-object)
869        (convert-and-maybe-compile form path)))
870     (when eval
871       (eval form))))
872
873 ;;; Process a top-level FORM with the specified source PATH.
874 ;;;  * If this is a magic top-level form, then do stuff.
875 ;;;  * If this is a macro, then expand it.
876 ;;;  * Otherwise, just compile it.
877 (defun process-top-level-form (form path)
878
879   (declare (list path))
880
881   (catch 'process-top-level-form-error-abort
882     (let* ((path (or (gethash form *source-paths*) (cons form path)))
883            (*compiler-error-bailout*
884             #'(lambda ()
885                 (convert-and-maybe-compile
886                  `(error "execution of a form compiled with errors:~% ~S"
887                          ',form)
888                  path)
889                 (throw 'process-top-level-form-error-abort nil))))
890       (if (atom form)
891           (convert-and-maybe-compile form path)
892           (case (car form)
893             ;; FIXME: It's not clear to me why we would want this
894             ;; special case; it might have been needed for some
895             ;; variation of the old GENESIS system, but it certainly
896             ;; doesn't seem to be needed for ours. Sometime after the
897             ;; system is running I'd like to remove it tentatively and
898             ;; see whether anything breaks, and if nothing does break,
899             ;; remove it permanently. (And if we *do* want special
900             ;; treatment of all these, we probably want to treat WARN
901             ;; the same way..)
902             ((error cerror break signal)
903              (process-cold-load-form form path nil))
904             ;; FIXME: ANSI seems to encourage things like DEFSTRUCT to
905             ;; be done with EVAL-WHEN, without this kind of one-off
906             ;; compiler magic.
907             (sb!kernel:%compiler-defstruct
908              (convert-and-maybe-compile form path)
909              (compile-top-level-lambdas () t))
910             ((eval-when)
911              (unless (>= (length form) 2)
912                (compiler-error "EVAL-WHEN form is too short: ~S" form))
913              (do-eval-when-stuff
914               (cadr form) (cddr form)
915               #'(lambda (forms)
916                   (process-top-level-progn forms path))))
917             ((macrolet)
918              (unless (>= (length form) 2)
919                (compiler-error "MACROLET form is too short: ~S" form))
920              (do-macrolet-stuff
921               (cadr form)
922               #'(lambda ()
923                   (process-top-level-progn (cddr form) path))))
924             (locally (process-top-level-locally form path))
925             (progn (process-top-level-progn (cdr form) path))
926             (t
927              (let* ((uform (uncross form))
928                     (exp (preprocessor-macroexpand uform)))
929                (if (eq exp uform)
930                    (convert-and-maybe-compile uform path)
931                    (process-top-level-form exp path))))))))
932
933   (values))
934 \f
935 ;;;; load time value support
936 ;;;;
937 ;;;; (See EMIT-MAKE-LOAD-FORM.)
938
939 ;;; Returns T iff we are currently producing a fasl file and hence
940 ;;; constants need to be dumped carefully.
941 (defun producing-fasl-file ()
942   (unless *converting-for-interpreter*
943     (fasl-output-p *compile-object*)))
944
945 ;;; Compile FORM and arrange for it to be called at load-time. Return
946 ;;; the dumper handle and our best guess at the type of the object.
947 (defun compile-load-time-value
948        (form &optional
949              (name (let ((*print-level* 2) (*print-length* 3))
950                      (format nil "load time value of ~S"
951                              (if (and (listp form)
952                                       (eq (car form) 'make-value-cell))
953                                  (second form)
954                                  form)))))
955   (let ((lambda (compile-load-time-stuff form name t)))
956     (values
957      (fasl-dump-load-time-value-lambda lambda *compile-object*)
958      (let ((type (leaf-type lambda)))
959        (if (function-type-p type)
960            (single-value-type (function-type-returns type))
961            *wild-type*)))))
962
963 ;;; Compile the FORMS and arrange for them to be called (for effect,
964 ;;; not value) at load time.
965 (defun compile-make-load-form-init-forms (forms name)
966   (let ((lambda (compile-load-time-stuff `(progn ,@forms) name nil)))
967     (fasl-dump-top-level-lambda-call lambda *compile-object*)))
968
969 ;;; Does the actual work of COMPILE-LOAD-TIME-VALUE or
970 ;;; COMPILE-MAKE-LOAD-FORM- INIT-FORMS.
971 (defun compile-load-time-stuff (form name for-value)
972   (with-ir1-namespace
973    (let* ((*lexenv* (make-null-lexenv))
974           (lambda (ir1-top-level form *current-path* for-value)))
975      (setf (leaf-name lambda) name)
976      (compile-top-level (list lambda) t)
977      lambda)))
978
979 ;;; Called by COMPILE-TOP-LEVEL when it was pased T for
980 ;;; LOAD-TIME-VALUE-P (which happens in COMPILE-LOAD-TIME-STUFF). We
981 ;;; don't try to combine this component with anything else and frob
982 ;;; the name. If not in a :TOP-LEVEL component, then don't bother
983 ;;; compiling, because it was merged with a run-time component.
984 (defun compile-load-time-value-lambda (lambdas)
985   (aver (null (cdr lambdas)))
986   (let* ((lambda (car lambdas))
987          (component (block-component (node-block (lambda-bind lambda)))))
988     (when (eq (component-kind component) :top-level)
989       (setf (component-name component) (leaf-name lambda))
990       (compile-component component)
991       (clear-ir1-info component))))
992 \f
993 ;;;; COMPILE-FILE
994
995 ;;; We build a list of top-level lambdas, and then periodically smash
996 ;;; them together into a single component and compile it.
997 (defvar *pending-top-level-lambdas*)
998
999 ;;; The maximum number of top-level lambdas we put in a single
1000 ;;; top-level component.
1001 ;;;
1002 ;;; CMU CL 18b used this nontrivially by default (setting it to 10)
1003 ;;; but consequently suffered from the inability to execute some
1004 ;;; troublesome constructs correctly, e.g. inability to load a fasl
1005 ;;; file compiled from the source file
1006 ;;;   (defpackage "FOO" (:use "CL"))
1007 ;;;   (print 'foo::bar)
1008 ;;; because it would dump data-setup fops (including a FOP-PACKAGE for
1009 ;;; "FOO") for the second form before dumping the the code in the
1010 ;;; first form, or the fop to execute the code in the first form. By
1011 ;;; setting this value to 0 by default, we avoid this badness. This
1012 ;;; increases the number of toplevel form functions, and so increases
1013 ;;; the size of object files.
1014 ;;;
1015 ;;; The variable is still supported because when we are compiling the
1016 ;;; SBCL system itself, which is known not contain any troublesome
1017 ;;; constructs, we can set it to a nonzero value, which reduces the
1018 ;;; number of toplevel form objects, reducing the peak memory usage in
1019 ;;; GENESIS, which is desirable, since at least for SBCL version
1020 ;;; 0.6.7, this is the high water mark for memory usage during system
1021 ;;; construction.
1022 (defparameter *top-level-lambda-max* 0)
1023
1024 (defun object-call-top-level-lambda (tll)
1025   (declare (type functional tll))
1026   (let ((object *compile-object*))
1027     (etypecase object
1028       (fasl-output
1029        (fasl-dump-top-level-lambda-call tll object))
1030       (core-object
1031        (core-call-top-level-lambda tll object))
1032       (null))))
1033
1034 ;;; Add LAMBDAS to the pending lambdas. If this leaves more than
1035 ;;; *TOP-LEVEL-LAMBDA-MAX* lambdas in the list, or if FORCE-P is true,
1036 ;;; then smash the lambdas into a single component, compile it, and
1037 ;;; call the resulting function.
1038 (defun sub-compile-top-level-lambdas (lambdas force-p)
1039   (declare (list lambdas))
1040   (setq *pending-top-level-lambdas*
1041         (append *pending-top-level-lambdas* lambdas))
1042   (let ((pending *pending-top-level-lambdas*))
1043     (when (and pending
1044                (or (> (length pending) *top-level-lambda-max*)
1045                    force-p))
1046       (multiple-value-bind (component tll) (merge-top-level-lambdas pending)
1047         (setq *pending-top-level-lambdas* ())
1048         (let ((*byte-compile* (if (eq *byte-compile* :maybe)
1049                                   *byte-compile-top-level*
1050                                   *byte-compile*)))
1051           (compile-component component))
1052         (clear-ir1-info component)
1053         (object-call-top-level-lambda tll))))
1054   (values))
1055
1056 ;;; Compile top-level code and call the top-level lambdas. We pick off
1057 ;;; top-level lambdas in non-top-level components here, calling
1058 ;;; SUB-c-t-l-l on each subsequence of normal top-level lambdas.
1059 (defun compile-top-level-lambdas (lambdas force-p)
1060   (declare (list lambdas))
1061   (let ((len (length lambdas)))
1062     (flet ((loser (start)
1063              (or (position-if #'(lambda (x)
1064                                   (not (eq (component-kind
1065                                             (block-component
1066                                              (node-block
1067                                               (lambda-bind x))))
1068                                            :top-level)))
1069                               lambdas
1070                               :start start)
1071                  len)))
1072       (do* ((start 0 (1+ loser))
1073             (loser (loser start) (loser start)))
1074            ((>= start len)
1075             (when force-p
1076               (sub-compile-top-level-lambdas nil t)))
1077         (sub-compile-top-level-lambdas (subseq lambdas start loser)
1078                                        (or force-p (/= loser len)))
1079         (unless (= loser len)
1080           (object-call-top-level-lambda (elt lambdas loser))))))
1081   (values))
1082
1083 ;;; Compile LAMBDAS (a list of the lambdas for top-level forms) into
1084 ;;; the object file. We loop doing local call analysis until it
1085 ;;; converges, since a single pass might miss something due to
1086 ;;; components being joined by LET conversion.
1087 ;;;
1088 ;;; LOAD-TIME-VALUE-P seems to control whether it's MAKE-LOAD-FORM and
1089 ;;; COMPILE-LOAD-TIME-VALUE stuff. -- WHN 20000201
1090 (defun compile-top-level (lambdas load-time-value-p)
1091   (declare (list lambdas))
1092   (maybe-mumble "locall ")
1093   (loop
1094     (let ((did-something nil))
1095       (dolist (lambda lambdas)
1096         (let* ((component (block-component (node-block (lambda-bind lambda))))
1097                (*all-components* (list component)))
1098           (when (component-new-functions component)
1099             (setq did-something t)
1100             (local-call-analyze component))))
1101       (unless did-something (return))))
1102
1103   (maybe-mumble "IDFO ")
1104   (multiple-value-bind (components top-components hairy-top)
1105       (find-initial-dfo lambdas)
1106     (let ((*all-components* (append components top-components))
1107           (top-level-closure nil))
1108       (when *check-consistency*
1109         (maybe-mumble "[check]~%")
1110         (check-ir1-consistency *all-components*))
1111
1112       (dolist (component (append hairy-top top-components))
1113         (when (pre-environment-analyze-top-level component)
1114           (setq top-level-closure t)))
1115
1116       (let ((*byte-compile*
1117              (if (and top-level-closure (eq *byte-compile* :maybe))
1118                  nil
1119                  *byte-compile*)))
1120         (dolist (component components)
1121           (compile-component component)
1122           (when (replace-top-level-xeps component)
1123             (setq top-level-closure t)))
1124         
1125         (when *check-consistency*
1126           (maybe-mumble "[check]~%")
1127           (check-ir1-consistency *all-components*))
1128         
1129         (if load-time-value-p
1130             (compile-load-time-value-lambda lambdas)
1131             (compile-top-level-lambdas lambdas top-level-closure)))
1132
1133       (dolist (component components)
1134         (clear-ir1-info component))
1135       (clear-stuff)))
1136   (values))
1137
1138 ;;; Actually compile any stuff that has been queued up for block
1139 ;;; compilation.
1140 (defun finish-block-compilation ()
1141   (when *block-compile*
1142     (when *top-level-lambdas*
1143       (compile-top-level (nreverse *top-level-lambdas*) nil)
1144       (setq *top-level-lambdas* ()))
1145     (setq *block-compile* nil)
1146     (setq *entry-points* nil)))
1147
1148 ;;; Read all forms from INFO and compile them, with output to OBJECT.
1149 ;;; Return (VALUES NIL WARNINGS-P FAILURE-P).
1150 (defun sub-compile-file (info)
1151   (declare (type source-info info))
1152   (let* (;; These are bound in WITH-COMPILATION-UNIT now. -- WHN 20000308
1153          #+nil (*compiler-error-count* 0)
1154          #+nil (*compiler-warning-count* 0)
1155          #+nil (*compiler-style-warning-count* 0)
1156          #+nil (*compiler-note-count* 0)
1157          (*block-compile* *block-compile-argument*)
1158          (*package* (sane-package))
1159          (*policy* *policy*)
1160          (*lexenv* (make-null-lexenv))
1161          (*converting-for-interpreter* nil)
1162          (*source-info* info)
1163          (sb!xc:*compile-file-pathname* nil)
1164          (sb!xc:*compile-file-truename* nil)
1165          (*top-level-lambdas* ())
1166          (*pending-top-level-lambdas* ())
1167          (*compiler-error-bailout*
1168           (lambda ()
1169             (compiler-mumble "~2&; fatal error, aborting compilation~%")
1170             (return-from sub-compile-file (values nil t t))))
1171          (*current-path* nil)
1172          (*last-source-context* nil)
1173          (*last-original-source* nil)
1174          (*last-source-form* nil)
1175          (*last-format-string* nil)
1176          (*last-format-args* nil)
1177          (*last-message-count* 0)
1178          (*info-environment* (or *backend-info-environment*
1179                                  *info-environment*))
1180          (*gensym-counter* 0))
1181     (handler-case
1182         (with-compilation-values
1183          (sb!xc:with-compilation-unit ()
1184            (clear-stuff)
1185
1186            (process-source info)
1187
1188            (finish-block-compilation)
1189            (compile-top-level-lambdas () t)
1190            (let ((object *compile-object*))
1191              (etypecase object
1192                (fasl-output (fasl-dump-source-info info object))
1193                (core-object (fix-core-source-info info object))
1194                (null)))
1195            nil))
1196       ;; Some errors are sufficiently bewildering that we just fail
1197       ;; immediately, without trying to recover and compile more of
1198       ;; the input file.
1199       (input-error-in-compile-file (condition)
1200        (format *error-output*
1201                "~@<compilation aborted because of input error: ~2I~_~A~:>"
1202                condition)
1203        (values nil t t)))))
1204
1205 ;;; Return a pathname for the named file. The file must exist.
1206 (defun verify-source-file (pathname-designator)
1207   (let* ((pathname (pathname pathname-designator))
1208          (default-host (make-pathname :host (pathname-host pathname))))
1209     (flet ((try-with-type (path type error-p)
1210              (let ((new (merge-pathnames
1211                          path (make-pathname :type type
1212                                              :defaults default-host))))
1213                (if (probe-file new)
1214                    new
1215                    (and error-p (truename new))))))
1216       (cond ((typep pathname 'logical-pathname)
1217              (try-with-type pathname "LISP" t))
1218             ((probe-file pathname) pathname)
1219             ((try-with-type pathname "lisp"  nil))
1220             ((try-with-type pathname "lisp"  t))))))
1221
1222 (defun elapsed-time-to-string (tsec)
1223   (multiple-value-bind (tmin sec) (truncate tsec 60)
1224     (multiple-value-bind (thr min) (truncate tmin 60)
1225       (format nil "~D:~2,'0D:~2,'0D" thr min sec))))
1226
1227 ;;; Print some junk at the beginning and end of compilation.
1228 (defun start-error-output (source-info)
1229   (declare (type source-info source-info))
1230   (let ((file-info (source-info-file-info source-info)))
1231     (compiler-mumble "~&; compiling file ~S (written ~A):~%"
1232                      (namestring (file-info-name file-info))
1233                      (sb!int:format-universal-time nil
1234                                                    (file-info-write-date
1235                                                     file-info)
1236                                                    :style :government
1237                                                    :print-weekday nil
1238                                                    :print-timezone nil)))
1239   (values))
1240 (defun finish-error-output (source-info won)
1241   (declare (type source-info source-info))
1242   (compiler-mumble "~&; compilation ~:[aborted after~;finished in~] ~A~&"
1243                    won
1244                    (elapsed-time-to-string
1245                     (- (get-universal-time)
1246                        (source-info-start-time source-info))))
1247   (values))
1248
1249 ;;; Open some files and call SUB-COMPILE-FILE. If something unwinds
1250 ;;; out of the compile, then abort the writing of the output file, so
1251 ;;; that we don't overwrite it with known garbage.
1252 (defun sb!xc:compile-file
1253     (input-file
1254      &key
1255
1256      ;; ANSI options
1257      (output-file (cfp-output-file-default input-file))
1258      ;; FIXME: ANSI doesn't seem to say anything about
1259      ;; *COMPILE-VERBOSE* and *COMPILE-PRINT* being rebound by this
1260      ;; function..
1261      ((:verbose sb!xc:*compile-verbose*) sb!xc:*compile-verbose*)
1262      ((:print sb!xc:*compile-print*) sb!xc:*compile-print*)
1263      (external-format :default)
1264
1265      ;; extensions
1266      (trace-file nil) 
1267      ((:block-compile *block-compile-argument*) nil)
1268      ((:byte-compile *byte-compile*) *byte-compile-default*))
1269
1270   #!+sb-doc
1271   "Compile INPUT-FILE, producing a corresponding fasl file and returning
1272    its filename. Besides the ANSI &KEY arguments :OUTPUT-FILE, :VERBOSE,
1273    :PRINT, and :EXTERNAL-FORMAT,the following extensions are supported:
1274      :TRACE-FILE
1275         If given, internal data structures are dumped to the specified
1276         file, or if a value of T is given, to a file of *.trace type
1277         derived from the input file name.
1278      :BYTE-COMPILE {T | NIL | :MAYBE}
1279         Determines whether to compile into interpreted byte code instead of
1280         machine instructions. Byte code is several times smaller, but much
1281         slower. If :MAYBE, then only byte-compile when SPEED is 0 and
1282         DEBUG <= 1. The default is the value of SB-EXT:*BYTE-COMPILE-DEFAULT*,
1283         which is initially :MAYBE. (This option will probably become
1284         formally deprecated starting around sbcl-0.7.0, when various 
1285         cleanups related to the byte interpreter are planned.)
1286    Also, as a workaround for vaguely-non-ANSI behavior, the :BLOCK-COMPILE
1287    argument is quasi-supported, to determine whether multiple
1288    functions are compiled together as a unit, resolving function
1289    references at compile time. NIL means that global function names
1290    are never resolved at compilation time. Currently NIL is the
1291    default behavior, because although section 3.2.2.3, \"Semantic
1292    Constraints\", of the ANSI spec allows this behavior under all
1293    circumstances, the compiler's runtime scales badly when it
1294    tries to do this for large files. If/when this performance
1295    problem is fixed, the block compilation default behavior will
1296    probably be made dependent on the SPEED and COMPILATION-SPEED
1297    optimization values, and the :BLOCK-COMPILE argument will probably
1298    become deprecated."
1299
1300   (unless (eq external-format :default)
1301     (error "Non-:DEFAULT EXTERNAL-FORMAT values are not supported."))
1302   (let* ((fasl-output nil)
1303          (output-file-name nil)
1304          (compile-won nil)
1305          (warnings-p nil)
1306          (failure-p t) ; T in case error keeps this from being set later
1307          (input-pathname (verify-source-file input-file))
1308          (source-info (make-file-source-info input-pathname))
1309          (*compiler-trace-output* nil)) ; might be modified below
1310                                 
1311     (unwind-protect
1312         (progn
1313           (when output-file
1314             (setq output-file-name
1315                   (sb!xc:compile-file-pathname input-file
1316                                                :output-file output-file))
1317             (setq fasl-output
1318                   (open-fasl-output output-file-name
1319                                     (namestring input-pathname)
1320                                     (eq *byte-compile* t))))
1321           (when trace-file
1322             (let* ((default-trace-file-pathname
1323                      (make-pathname :type "trace" :defaults input-pathname))
1324                    (trace-file-pathname
1325                     (if (eql trace-file t)
1326                         default-trace-file-pathname
1327                         (merge-pathnames trace-file
1328                                          default-trace-file-pathname))))
1329               (setf *compiler-trace-output*
1330                     (open trace-file-pathname
1331                           :if-exists :supersede
1332                           :direction :output))))
1333
1334           (when sb!xc:*compile-verbose*
1335             (start-error-output source-info))
1336           (let ((*compile-object* fasl-output)
1337                 dummy)
1338             (multiple-value-setq (dummy warnings-p failure-p)
1339               (sub-compile-file source-info)))
1340           (setq compile-won t))
1341
1342       (close-source-info source-info)
1343
1344       (when fasl-output
1345         (close-fasl-output fasl-output (not compile-won))
1346         (setq output-file-name
1347               (pathname (fasl-output-stream fasl-output)))
1348         (when (and compile-won sb!xc:*compile-verbose*)
1349           (compiler-mumble "~2&; ~A written~%" (namestring output-file-name))))
1350
1351       (when sb!xc:*compile-verbose*
1352         (finish-error-output source-info compile-won))
1353
1354       (when *compiler-trace-output*
1355         (close *compiler-trace-output*)))
1356
1357     (values (if output-file
1358                 ;; Hack around filesystem race condition...
1359                 (or (probe-file output-file-name) output-file-name)
1360                 nil)
1361             warnings-p
1362             failure-p)))
1363 \f
1364 ;;; a helper function for COMPILE-FILE-PATHNAME: the default for
1365 ;;; the OUTPUT-FILE argument
1366 ;;;
1367 ;;; ANSI: The defaults for the OUTPUT-FILE are taken from the pathname
1368 ;;; that results from merging the INPUT-FILE with the value of
1369 ;;; *DEFAULT-PATHNAME-DEFAULTS*, except that the type component should
1370 ;;; default to the appropriate implementation-defined default type for
1371 ;;; compiled files.
1372 (defun cfp-output-file-default (input-file)
1373   (let* ((defaults (merge-pathnames input-file *default-pathname-defaults*))
1374          (retyped (make-pathname :type *backend-fasl-file-type*
1375                                  :defaults defaults)))
1376     retyped))
1377         
1378 ;;; KLUDGE: Part of the ANSI spec for this seems contradictory:
1379 ;;;   If INPUT-FILE is a logical pathname and OUTPUT-FILE is unsupplied,
1380 ;;;   the result is a logical pathname. If INPUT-FILE is a logical
1381 ;;;   pathname, it is translated into a physical pathname as if by
1382 ;;;   calling TRANSLATE-LOGICAL-PATHNAME.
1383 ;;; So I haven't really tried to make this precisely ANSI-compatible
1384 ;;; at the level of e.g. whether it returns logical pathname or a
1385 ;;; physical pathname. Patches to make it more correct are welcome.
1386 ;;; -- WHN 2000-12-09
1387 (defun sb!xc:compile-file-pathname (input-file
1388                                     &key
1389                                     (output-file (cfp-output-file-default
1390                                                   input-file))
1391                                     &allow-other-keys)
1392   #!+sb-doc
1393   "Return a pathname describing what file COMPILE-FILE would write to given
1394    these arguments."
1395   (pathname output-file))
1396 \f
1397 ;;;; MAKE-LOAD-FORM stuff
1398
1399 ;;; The entry point for MAKE-LOAD-FORM support. When IR1 conversion
1400 ;;; finds a constant structure, it invokes this to arrange for proper
1401 ;;; dumping. If it turns out that the constant has already been
1402 ;;; dumped, then we don't need to do anything.
1403 ;;;
1404 ;;; If the constant hasn't been dumped, then we check to see whether
1405 ;;; we are in the process of creating it. We detect this by
1406 ;;; maintaining the special *CONSTANTS-BEING-CREATED* as a list of all
1407 ;;; the constants we are in the process of creating. Actually, each
1408 ;;; entry is a list of the constant and any init forms that need to be
1409 ;;; processed on behalf of that constant.
1410 ;;;
1411 ;;; It's not necessarily an error for this to happen. If we are
1412 ;;; processing the init form for some object that showed up *after*
1413 ;;; the original reference to this constant, then we just need to
1414 ;;; defer the processing of that init form. To detect this, we
1415 ;;; maintain *CONSTANTS-CREATED-SINCE-LAST-INIT* as a list of the
1416 ;;; constants created since the last time we started processing an
1417 ;;; init form. If the constant passed to emit-make-load-form shows up
1418 ;;; in this list, then there is a circular chain through creation
1419 ;;; forms, which is an error.
1420 ;;;
1421 ;;; If there is some intervening init form, then we blow out of
1422 ;;; processing it by throwing to the tag PENDING-INIT. The value we
1423 ;;; throw is the entry from *CONSTANTS-BEING-CREATED*. This is so the
1424 ;;; offending init form can be tacked onto the init forms for the
1425 ;;; circular object.
1426 ;;;
1427 ;;; If the constant doesn't show up in *CONSTANTS-BEING-CREATED*, then
1428 ;;; we have to create it. We call MAKE-LOAD-FORM and check to see
1429 ;;; whether the creation form is the magic value
1430 ;;; :JUST-DUMP-IT-NORMALLY. If it is, then we don't do anything. The
1431 ;;; dumper will eventually get its hands on the object and use the
1432 ;;; normal structure dumping noise on it.
1433 ;;;
1434 ;;; Otherwise, we bind *CONSTANTS-BEING-CREATED* and
1435 ;;; *CONSTANTS-CREATED-SINCE- LAST-INIT* and compile the creation form
1436 ;;; much the way LOAD-TIME-VALUE does. When this finishes, we tell the
1437 ;;; dumper to use that result instead whenever it sees this constant.
1438 ;;;
1439 ;;; Now we try to compile the init form. We bind
1440 ;;; *CONSTANTS-CREATED-SINCE-LAST-INIT* to NIL and compile the init
1441 ;;; form (and any init forms that were added because of circularity
1442 ;;; detection). If this works, great. If not, we add the init forms to
1443 ;;; the init forms for the object that caused the problems and let it
1444 ;;; deal with it.
1445 (defvar *constants-being-created* nil)
1446 (defvar *constants-created-since-last-init* nil)
1447 ;;; FIXME: Shouldn't these^ variables be bound in LET forms?
1448 (defun emit-make-load-form (constant)
1449   (aver (fasl-output-p *compile-object*))
1450   (unless (or (fasl-constant-already-dumped-p constant *compile-object*)
1451               ;; KLUDGE: This special hack is because I was too lazy
1452               ;; to rework DEF!STRUCT so that the MAKE-LOAD-FORM
1453               ;; function of LAYOUT returns nontrivial forms when
1454               ;; building the cross-compiler but :IGNORE-IT when
1455               ;; cross-compiling or running under the target Lisp. --
1456               ;; WHN 19990914
1457               #+sb-xc-host (typep constant 'layout))
1458     (let ((circular-ref (assoc constant *constants-being-created* :test #'eq)))
1459       (when circular-ref
1460         (when (find constant *constants-created-since-last-init* :test #'eq)
1461           (throw constant t))
1462         (throw 'pending-init circular-ref)))
1463     (multiple-value-bind (creation-form init-form)
1464         (handler-case
1465             (sb!xc:make-load-form constant (make-null-lexenv))
1466           (error (condition)
1467                  (compiler-error "(while making load form for ~S)~%~A"
1468                                  constant
1469                                  condition)))
1470       (case creation-form
1471         (:just-dump-it-normally
1472          (fasl-validate-structure constant *compile-object*)
1473          t)
1474         (:ignore-it
1475          nil)
1476         (t
1477          (compile-top-level-lambdas () t)
1478          (when (fasl-constant-already-dumped-p constant *compile-object*)
1479            (return-from emit-make-load-form nil))
1480          (let* ((name (let ((*print-level* 1) (*print-length* 2))
1481                         (with-output-to-string (stream)
1482                           (write constant :stream stream))))
1483                 (info (if init-form
1484                           (list constant name init-form)
1485                           (list constant))))
1486            (let ((*constants-being-created*
1487                   (cons info *constants-being-created*))
1488                  (*constants-created-since-last-init*
1489                   (cons constant *constants-created-since-last-init*)))
1490              (when
1491                  (catch constant
1492                    (fasl-note-handle-for-constant
1493                     constant
1494                     (compile-load-time-value
1495                      creation-form
1496                      (format nil "creation form for ~A" name))
1497                     *compile-object*)
1498                    nil)
1499                (compiler-error "circular references in creation form for ~S"
1500                                constant)))
1501            (when (cdr info)
1502              (let* ((*constants-created-since-last-init* nil)
1503                     (circular-ref
1504                      (catch 'pending-init
1505                        (loop for (name form) on (cdr info) by #'cddr
1506                          collect name into names
1507                          collect form into forms
1508                          finally
1509                          (compile-make-load-form-init-forms
1510                           forms
1511                           (format nil "init form~:[~;s~] for ~{~A~^, ~}"
1512                                   (cdr forms) names)))
1513                        nil)))
1514                (when circular-ref
1515                  (setf (cdr circular-ref)
1516                        (append (cdr circular-ref) (cdr info))))))))))))