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