d1c14a3acee57a9117bbd8f4ac05685de012391f
[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 SOURCE-INFO structure for the current compilation. This is
105 ;;; null globally to indicate that we aren't currently in any
106 ;;; identifiable compilation.
107 (defvar *source-info* nil)
108
109 ;;; This is true if we are within a WITH-COMPILATION-UNIT form (which
110 ;;; normally causes nested uses to be no-ops).
111 (defvar *in-compilation-unit* nil)
112
113 ;;; Count of the number of compilation units dynamically enclosed by
114 ;;; the current active WITH-COMPILATION-UNIT that were unwound out of.
115 (defvar *aborted-compilation-unit-count*)
116
117 ;;; Mumble conditional on *COMPILE-PROGRESS*.
118 (defun maybe-mumble (&rest foo)
119   (when *compile-progress*
120     (compiler-mumble "~&")
121     (pprint-logical-block (*error-output* nil :per-line-prefix "; ")
122        (apply #'compiler-mumble foo))))
123
124 (deftype object () '(or fasl-file core-object null))
125
126 (defvar *compile-object* nil)
127 (declaim (type object *compile-object*))
128 \f
129 ;;;; WITH-COMPILATION-UNIT and WITH-COMPILATION-VALUES
130
131 (defmacro sb!xc:with-compilation-unit (options &body body)
132   #!+sb-doc
133   "WITH-COMPILATION-UNIT ({Key Value}*) Form*
134   This form affects compilations that take place within its dynamic extent. It
135   is intended to be wrapped around the compilation of all files in the same
136   system. These keywords are defined:
137     :OVERRIDE Boolean-Form
138         One of the effects of this form is to delay undefined warnings
139         until the end of the form, instead of giving them at the end of each
140         compilation. If OVERRIDE is NIL (the default), then the outermost
141         WITH-COMPILATION-UNIT form grabs the undefined warnings. Specifying
142         OVERRIDE true causes that form to grab any enclosed warnings, even if
143         it is enclosed by another WITH-COMPILATION-UNIT."
144   `(%with-compilation-unit (lambda () ,@body) ,@options))
145
146 (defun %with-compilation-unit (fn &key override)
147   (let ((succeeded-p nil))
148     (if (and *in-compilation-unit* (not override))
149         ;; Inside another WITH-COMPILATION-UNIT, a WITH-COMPILATION-UNIT is
150         ;; ordinarily (unless OVERRIDE) basically a no-op.
151         (unwind-protect
152             (multiple-value-prog1 (funcall fn) (setf succeeded-p t))
153           (unless succeeded-p
154             (incf *aborted-compilation-unit-count*)))
155         ;; FIXME: Now *COMPILER-FOO-COUNT* stuff is bound in more than
156         ;; one place. If we can get rid of the IR1 interpreter, this
157         ;; should be easier to clean up.
158         (let ((*aborted-compilation-unit-count* 0)
159               (*compiler-error-count* 0)
160               (*compiler-warning-count* 0)
161               (*compiler-style-warning-count* 0)
162               (*compiler-note-count* 0)
163               (*undefined-warnings* nil)
164               (*in-compilation-unit* t))
165           (handler-bind ((parse-unknown-type
166                           (lambda (c)
167                             (note-undefined-reference
168                              (parse-unknown-type-specifier c)
169                              :type))))
170             (unwind-protect
171                 (multiple-value-prog1 (funcall fn) (setf succeeded-p t))
172               (unless succeeded-p
173                 (incf *aborted-compilation-unit-count*))
174               (summarize-compilation-unit (not succeeded-p))))))))
175
176 ;;; This is to be called at the end of a compilation unit. It signals
177 ;;; any residual warnings about unknown stuff, then prints the total
178 ;;; error counts. ABORT-P should be true when the compilation unit was
179 ;;; aborted by throwing out. ABORT-COUNT is the number of dynamically
180 ;;; enclosed nested compilation units that were aborted.
181 (defun summarize-compilation-unit (abort-p)
182   (unless abort-p
183     (handler-bind ((style-warning #'compiler-style-warning-handler)
184                    (warning #'compiler-warning-handler))
185
186       (let ((undefs (sort *undefined-warnings* #'string<
187                           :key #'(lambda (x)
188                                    (let ((x (undefined-warning-name x)))
189                                      (if (symbolp x)
190                                          (symbol-name x)
191                                          (prin1-to-string x)))))))
192         (unless *converting-for-interpreter*
193           (dolist (undef undefs)
194             (let ((name (undefined-warning-name undef))
195                   (kind (undefined-warning-kind undef))
196                   (warnings (undefined-warning-warnings undef))
197                   (undefined-warning-count (undefined-warning-count undef)))
198               (dolist (*compiler-error-context* warnings)
199                 (compiler-style-warning "undefined ~(~A~): ~S" kind name))
200
201               (let ((warn-count (length warnings)))
202                 (when (and warnings (> undefined-warning-count warn-count))
203                   (let ((more (- undefined-warning-count warn-count)))
204                     (compiler-style-warning
205                      "~D more use~:P of undefined ~(~A~) ~S"
206                      more kind name)))))))
207         
208         (dolist (kind '(:variable :function :type))
209           (let ((summary (mapcar #'undefined-warning-name
210                                  (remove kind undefs :test-not #'eq
211                                          :key #'undefined-warning-kind))))
212             (when summary
213               (compiler-style-warning
214                "~:[This ~(~A~) is~;These ~(~A~)s are~] undefined:~
215                 ~%  ~{~<~%  ~1:;~S~>~^ ~}"
216                (cdr summary) kind summary)))))))
217
218   (unless (or *converting-for-interpreter*
219               (and (not abort-p)
220                    (zerop *aborted-compilation-unit-count*)
221                    (zerop *compiler-error-count*)
222                    (zerop *compiler-warning-count*)
223                    (zerop *compiler-style-warning-count*)
224                    (zerop *compiler-note-count*)))
225     (format *error-output* "~&")
226     (pprint-logical-block (*error-output* nil :per-line-prefix "; ")
227       (compiler-mumble "compilation unit ~:[finished~;aborted~]~
228                        ~[~:;~:*~&  caught ~D fatal ERROR condition~:P~]~
229                        ~[~:;~:*~&  caught ~D ERROR condition~:P~]~
230                        ~[~:;~:*~&  caught ~D WARNING condition~:P~]~
231                        ~[~:;~:*~&  caught ~D STYLE-WARNING condition~:P~]~
232                        ~[~:;~:*~&  printed ~D note~:P~]"
233                        abort-p
234                        *aborted-compilation-unit-count*
235                        *compiler-error-count*
236                        *compiler-warning-count*
237                        *compiler-style-warning-count*
238                        *compiler-note-count*)))
239   (format *error-output* "~&"))
240
241 ;;; Evaluate BODY, then return (VALUES BODY-VALUE WARNINGS-P
242 ;;; FAILURE-P), where BODY-VALUE is the first value of the body, and
243 ;;; WARNINGS-P and FAILURE-P are as in CL:COMPILE or CL:COMPILE-FILE.
244 ;;; This also wraps up WITH-IR1-NAMESPACE functionality.
245 (defmacro with-compilation-values (&body body)
246   `(with-ir1-namespace
247     (let ((*warnings-p* nil)
248           (*failure-p* nil))
249       (values (progn ,@body)
250               *warnings-p*
251               *failure-p*))))
252 \f
253 ;;;; component compilation
254
255 (defparameter *max-optimize-iterations* 3 ; ARB
256   #!+sb-doc
257   "The upper limit on the number of times that we will consecutively do IR1
258   optimization that doesn't introduce any new code. A finite limit is
259   necessary, since type inference may take arbitrarily long to converge.")
260
261 (defevent ir1-optimize-until-done "IR1-OPTIMIZE-UNTIL-DONE called")
262 (defevent ir1-optimize-maxed-out "hit *MAX-OPTIMIZE-ITERATIONS* limit")
263
264 ;;; Repeatedly optimize COMPONENT until no further optimizations can
265 ;;; be found or we hit our iteration limit. When we hit the limit, we
266 ;;; clear the component and block REOPTIMIZE flags to discourage the
267 ;;; next optimization attempt from pounding on the same code.
268 (defun ir1-optimize-until-done (component)
269   (declare (type component component))
270   (maybe-mumble "opt")
271   (event ir1-optimize-until-done)
272   (let ((count 0)
273         (cleared-reanalyze nil))
274     (loop
275       (when (component-reanalyze component)
276         (setq count 0)
277         (setq cleared-reanalyze t)
278         (setf (component-reanalyze component) nil))
279       (setf (component-reoptimize component) nil)
280       (ir1-optimize component)
281       (unless (component-reoptimize component)
282         (maybe-mumble " ")
283         (return))
284       (incf count)
285       (when (= count *max-optimize-iterations*)
286         (event ir1-optimize-maxed-out)
287         (maybe-mumble "* ")
288         (setf (component-reoptimize component) nil)
289         (do-blocks (block component)
290           (setf (block-reoptimize block) nil))
291         (return))
292       (maybe-mumble "."))
293     (when cleared-reanalyze
294       (setf (component-reanalyze component) t)))
295   (values))
296
297 (defparameter *constraint-propagate* t)
298 (defparameter *reoptimize-after-type-check-max* 5)
299
300 (defevent reoptimize-maxed-out
301   "*REOPTIMIZE-AFTER-TYPE-CHECK-MAX* exceeded.")
302
303 ;;; Iterate doing FIND-DFO until no new dead code is discovered.
304 (defun dfo-as-needed (component)
305   (declare (type component component))
306   (when (component-reanalyze component)
307     (maybe-mumble "DFO")
308     (loop
309       (find-dfo component)
310       (unless (component-reanalyze component)
311         (maybe-mumble " ")
312         (return))
313       (maybe-mumble ".")))
314   (values))
315
316 ;;; Do all the IR1 phases for a non-top-level component.
317 (defun ir1-phases (component)
318   (declare (type component component))
319   (let ((*constraint-number* 0)
320         (loop-count 1))
321     (declare (special *constraint-number*))
322     (loop
323       (ir1-optimize-until-done component)
324       (when (or (component-new-functions component)
325                 (component-reanalyze-functions component))
326         (maybe-mumble "locall ")
327         (local-call-analyze component))
328       (dfo-as-needed component)
329       (when *constraint-propagate*
330         (maybe-mumble "constraint ")
331         (constraint-propagate component))
332       (maybe-mumble "type ")
333       ;; Delay the generation of type checks until the type
334       ;; constraints have had time to propagate, else the compiler can
335       ;; confuse itself.
336       (unless (and (or (component-reoptimize component)
337                        (component-reanalyze component)
338                        (component-new-functions component)
339                        (component-reanalyze-functions component))
340                    (< loop-count (- *reoptimize-after-type-check-max* 2)))
341         (generate-type-checks component)
342         (unless (or (component-reoptimize component)
343                     (component-reanalyze component)
344                     (component-new-functions component)
345                     (component-reanalyze-functions component))
346           (return)))
347       (when (>= loop-count *reoptimize-after-type-check-max*)
348         (maybe-mumble "[reoptimize limit]")
349         (event reoptimize-maxed-out)
350         (return))
351       (incf loop-count)))
352
353   (ir1-finalize component)
354   (values))
355
356 (defun native-compile-component (component)
357   (let ((*code-segment* nil)
358         (*elsewhere* nil))
359     (maybe-mumble "GTN ")
360     (gtn-analyze component)
361     (maybe-mumble "LTN ")
362     (ltn-analyze component)
363     (dfo-as-needed component)
364     (maybe-mumble "control ")
365     (control-analyze component #'make-ir2-block)
366
367     (when (ir2-component-values-receivers (component-info component))
368       (maybe-mumble "stack ")
369       (stack-analyze component)
370       ;; Assign BLOCK-NUMBER for any cleanup blocks introduced by
371       ;; stack analysis. There shouldn't be any unreachable code after
372       ;; control, so this won't delete anything.
373       (dfo-as-needed component))
374
375     (unwind-protect
376         (progn
377           (maybe-mumble "IR2tran ")
378           (init-assembler)
379           (entry-analyze component)
380           (ir2-convert component)
381
382           (when (policy nil (>= speed compilation-speed))
383             (maybe-mumble "copy ")
384             (copy-propagate component))
385
386           (select-representations component)
387
388           (when *check-consistency*
389             (maybe-mumble "check2 ")
390             (check-ir2-consistency component))
391
392           (delete-unreferenced-tns component)
393
394           (maybe-mumble "life ")
395           (lifetime-analyze component)
396
397           (when *compile-progress*
398             (compiler-mumble "") ; Sync before doing more output.
399             (pre-pack-tn-stats component *error-output*))
400
401           (when *check-consistency*
402             (maybe-mumble "check-life ")
403             (check-life-consistency component))
404
405           (maybe-mumble "pack ")
406           (pack component)
407
408           (when *check-consistency*
409             (maybe-mumble "check-pack ")
410             (check-pack-consistency component))
411
412           #!+sb-show
413           (when *compiler-trace-output*
414             (describe-component component *compiler-trace-output*)
415             (describe-ir2-component component *compiler-trace-output*))
416
417           (maybe-mumble "code ")
418           (multiple-value-bind (code-length trace-table fixups)
419               (generate-code component)
420
421             #!+sb-show
422             (when *compiler-trace-output*
423               (format *compiler-trace-output*
424                       "~|~%disassembly of code for ~S~2%" component)
425               (sb!disassem:disassemble-assem-segment *code-segment*
426                                                      *compiler-trace-output*))
427
428             (etypecase *compile-object*
429               (fasl-file
430                (maybe-mumble "fasl")
431                (fasl-dump-component component
432                                     *code-segment*
433                                     code-length
434                                     trace-table
435                                     fixups
436                                     *compile-object*))
437               (core-object
438                (maybe-mumble "core")
439                (make-core-component component
440                                     *code-segment*
441                                     code-length
442                                     trace-table
443                                     fixups
444                                     *compile-object*))
445               (null))))))
446
447   ;; We are done, so don't bother keeping anything around.
448   (setf (component-info component) nil)
449
450   (values))
451
452 ;;; Return our best guess for whether we will byte compile code
453 ;;; currently being IR1 converted. This is only a guess because the
454 ;;; decision is made on a per-component basis.
455 ;;;
456 ;;; FIXME: This should be called something more mnemonic, e.g.
457 ;;; PROBABLY-BYTE-COMPILING
458 (defun byte-compiling ()
459   (if (eq *byte-compiling* :maybe)
460       (or (eq *byte-compile* t)
461           (policy nil (and (zerop speed) (<= debug 1))))
462       (and *byte-compile* *byte-compiling*)))
463
464 ;;; Delete components with no external entry points before we try to
465 ;;; generate code. Unreachable closures can cause IR2 conversion to
466 ;;; puke on itself, since it is the reference to the closure which
467 ;;; normally causes the components to be combined. This doesn't really
468 ;;; 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                                (and (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 ;;; A 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
650   ;; a Lisp 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
653   ;; to TRUENAME call.) Null if not a file. This is used to set
654   ;; *COMPILE-FILE-PATHNAME*, and if absolute, is dumped in the
655   ;; debug-info.
656   (untruename nil :type (or pathname null))
657   ;; the file's write date (if relevant)
658   (write-date nil :type (or unsigned-byte null))
659   ;; the source path root number of the first form in this file (i.e.
660   ;; the total number of forms converted previously in this
661   ;; compilation)
662   (source-root 0 :type unsigned-byte)
663   ;; parallel vectors containing the forms read out of the file and
664   ;; the file positions that reading of each form started at (i.e. the
665   ;; end of the 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) this code is
805 ;;; becoming stale, and the remaining bits of it (and the related code
806 ;;; in ADVANCE-SOURCE-FILE) can go away.
807 (defun get-source-stream (info)
808   (declare (type source-info info))
809   (cond ((source-info-stream info))
810         (t
811          (let* ((finfo (first (source-info-current-file info)))
812                 (name (file-info-name finfo)))
813            (setq sb!xc:*compile-file-truename* name)
814            (setq sb!xc:*compile-file-pathname* (file-info-untruename finfo))
815            (setf (source-info-stream info)
816                  (open name :direction :input))))))
817
818 ;;; Close the stream in INFO if it is open.
819 (defun close-source-info (info)
820   (declare (type source-info info))
821   (let ((stream (source-info-stream info)))
822     (when stream (close stream)))
823   (setf (source-info-stream info) nil)
824   (values))
825
826 ;;; Advance INFO to the next source file. If there is no next source
827 ;;; file, return NIL, otherwise T.
828 (defun advance-source-file (info)
829   (declare (type source-info info))
830   (close-source-info info)
831   (let ((prev (pop (source-info-current-file info))))
832     (if (source-info-current-file info)
833         (let ((current (first (source-info-current-file info))))
834           (setf (file-info-source-root current)
835                 (+ (file-info-source-root prev)
836                    (length (file-info-forms prev))))
837           t)
838         nil)))
839
840 ;;; Read the sources from the source files and process them.
841 (defun process-sources (info)
842   (let* ((file (first (source-info-current-file info)))
843          (stream (get-source-stream info)))
844     (loop
845      (let* ((pos (file-position stream))
846             (eof '(*eof*))
847             (form (careful-read stream eof pos)))
848        (if (eq form eof)
849          (return)
850          (let* ((forms (file-info-forms file))
851                 (current-idx (+ (fill-pointer forms)
852                                 (file-info-source-root file))))
853            (vector-push-extend form forms)
854            (vector-push-extend pos (file-info-positions file))
855            (clrhash *source-paths*)
856            (find-source-paths form current-idx)
857            (process-top-level-form form
858                                    `(original-source-start 0 ,current-idx))))))
859     (when (advance-source-file info)
860       (process-sources info))))
861
862 ;;; Return the FILE-INFO describing the INDEX'th form.
863 (defun find-file-info (index info)
864   (declare (type index index) (type source-info info))
865   (dolist (file (source-info-files info))
866     (when (> (+ (length (file-info-forms file))
867                 (file-info-source-root file))
868              index)
869       (return file))))
870
871 ;;; Return the INDEX'th source form read from INFO and the position
872 ;;; where it was read.
873 (defun find-source-root (index info)
874   (declare (type source-info info) (type index index))
875   (let* ((file (find-file-info index info))
876          (idx (- index (file-info-source-root file))))
877     (values (aref (file-info-forms file) idx)
878             (aref (file-info-positions file) idx))))
879 \f
880 ;;;; top-level form processing
881
882 ;;; This is called by top-level form processing when we are ready to
883 ;;; actually compile something. If *BLOCK-COMPILE* is T, then we still
884 ;;; convert the form, but delay compilation, pushing the result on
885 ;;; *TOP-LEVEL-LAMBDAS* instead.
886 (defun convert-and-maybe-compile (form path)
887   (declare (list path))
888   (let* ((*lexenv* (make-lexenv :policy *policy*
889                                 :interface-policy *interface-policy*))
890          (tll (ir1-top-level form path nil)))
891     (cond ((eq *block-compile* t) (push tll *top-level-lambdas*))
892           (t (compile-top-level (list tll) nil)))))
893
894 ;;; Process a PROGN-like portion of a top-level form. Forms is a list of
895 ;;; the forms, and Path is source path of the form they came out of.
896 (defun process-top-level-progn (forms path)
897   (declare (list forms) (list path))
898   (dolist (form forms)
899     (process-top-level-form form path)))
900
901 ;;; Macroexpand form in the current environment with an error handler.
902 ;;; We only expand one level, so that we retain all the intervening
903 ;;; forms in the source path.
904 (defun preprocessor-macroexpand (form)
905   (handler-case (sb!xc:macroexpand-1 form *lexenv*)
906     (error (condition)
907        (compiler-error "(during macroexpansion)~%~A" condition))))
908
909 ;;; Process a top-level use of LOCALLY. We parse declarations and then
910 ;;; recursively process the body.
911 (defun process-top-level-locally (form path)
912   (declare (list path))
913   (multiple-value-bind (forms decls) (sb!sys:parse-body (cdr form) nil)
914     (let* ((*lexenv*
915             (process-decls decls nil nil (make-continuation)))
916            ;; Binding *xxx-POLICY* is pretty much of a hack, since it
917            ;; causes LOCALLY to "capture" enclosed proclamations. It
918            ;; is necessary because CONVERT-AND-MAYBE-COMPILE uses the
919            ;; value of *POLICY* as the policy. The need for this hack
920            ;; is due to the quirk that there is no way to represent in
921            ;; a POLICY that an optimize quality came from the default.
922            ;; FIXME: Ideally, something should be done so that DECLAIM
923            ;; inside LOCALLY works OK. Failing that, at least we could
924            ;; issue a warning instead of silently screwing up.
925            (*policy* (lexenv-policy *lexenv*))
926            (*interface-policy* (lexenv-interface-policy *lexenv*)))
927       (process-top-level-progn forms path))))
928
929 ;;; Force any pending top-level forms to be compiled and dumped so
930 ;;; that they will be evaluated in the correct package environment.
931 ;;; Dump the form to be evaled at (cold) load time, and if EVAL is
932 ;;; true, eval the form immediately.
933 (defun process-cold-load-form (form path eval)
934   (let ((object *compile-object*))
935     (etypecase object
936       (fasl-file
937        (compile-top-level-lambdas () t)
938        (fasl-dump-cold-load-form form object))
939       ((or null core-object)
940        (convert-and-maybe-compile form path)))
941     (when eval
942       (eval form))))
943
944 (declaim (special *compiler-error-bailout*))
945
946 ;;; Process a top-level FORM with the specified source PATH.
947 ;;;  * If this is a magic top-level form, then do stuff.
948 ;;;  * If this is a macro, then expand it.
949 ;;;  * Otherwise, just compile it.
950 (defun process-top-level-form (form path)
951
952   (declare (list path))
953
954   (catch 'process-top-level-form-error-abort
955     (let* ((path (or (gethash form *source-paths*) (cons form path)))
956            (*compiler-error-bailout*
957             #'(lambda ()
958                 (convert-and-maybe-compile
959                  `(error "execution of a form compiled with errors:~% ~S"
960                          ',form)
961                  path)
962                 (throw 'process-top-level-form-error-abort nil))))
963       (if (atom form)
964           (convert-and-maybe-compile form path)
965           (case (car form)
966             ;; FIXME: It's not clear to me why we would want this
967             ;; special case; it might have been needed for some
968             ;; variation of the old GENESIS system, but it certainly
969             ;; doesn't seem to be needed for ours. Sometime after the
970             ;; system is running I'd like to remove it tentatively and
971             ;; see whether anything breaks, and if nothing does break,
972             ;; remove it permanently. (And if we *do* want special
973             ;; treatment of all these, we probably want to treat WARN
974             ;; the same way..)
975             ((error cerror break signal)
976              (process-cold-load-form form path nil))
977             ;; FIXME: ANSI seems to encourage things like DEFSTRUCT to
978             ;; be done with EVAL-WHEN, without this kind of one-off
979             ;; compiler magic.
980             (sb!kernel:%compiler-defstruct
981              (convert-and-maybe-compile form path)
982              (compile-top-level-lambdas () t))
983             ((eval-when)
984              (unless (>= (length form) 2)
985                (compiler-error "EVAL-WHEN form is too short: ~S" form))
986              (do-eval-when-stuff
987               (cadr form) (cddr form)
988               #'(lambda (forms)
989                   (process-top-level-progn forms path))))
990             ((macrolet)
991              (unless (>= (length form) 2)
992                (compiler-error "MACROLET form is too short: ~S" form))
993              (do-macrolet-stuff
994               (cadr form)
995               #'(lambda ()
996                   (process-top-level-progn (cddr form) path))))
997             (locally (process-top-level-locally form path))
998             (progn (process-top-level-progn (cdr form) path))
999             (t
1000              (let* ((uform (uncross form))
1001                     (exp (preprocessor-macroexpand uform)))
1002                (if (eq exp uform)
1003                    (convert-and-maybe-compile uform path)
1004                    (process-top-level-form exp path))))))))
1005
1006   (values))
1007 \f
1008 ;;;; load time value support
1009 ;;;;
1010 ;;;; (See EMIT-MAKE-LOAD-FORM.)
1011
1012 ;;; Returns T iff we are currently producing a fasl-file and hence
1013 ;;; constants need to be dumped carefully.
1014 (defun producing-fasl-file ()
1015   (unless *converting-for-interpreter*
1016     (fasl-file-p *compile-object*)))
1017
1018 ;;; Compile FORM and arrange for it to be called at load-time. Return
1019 ;;; the dumper handle and our best guess at the type of the object.
1020 (defun compile-load-time-value
1021        (form &optional
1022              (name (let ((*print-level* 2) (*print-length* 3))
1023                      (format nil "load time value of ~S"
1024                              (if (and (listp form)
1025                                       (eq (car form) 'make-value-cell))
1026                                  (second form)
1027                                  form)))))
1028   (let ((lambda (compile-load-time-stuff form name t)))
1029     (values
1030      (fasl-dump-load-time-value-lambda lambda *compile-object*)
1031      (let ((type (leaf-type lambda)))
1032        (if (function-type-p type)
1033            (single-value-type (function-type-returns type))
1034            *wild-type*)))))
1035
1036 ;;; Compile the FORMS and arrange for them to be called (for effect,
1037 ;;; not value) at load time.
1038 (defun compile-make-load-form-init-forms (forms name)
1039   (let ((lambda (compile-load-time-stuff `(progn ,@forms) name nil)))
1040     (fasl-dump-top-level-lambda-call lambda *compile-object*)))
1041
1042 ;;; Does the actual work of COMPILE-LOAD-TIME-VALUE or
1043 ;;; COMPILE-MAKE-LOAD-FORM- INIT-FORMS.
1044 (defun compile-load-time-stuff (form name for-value)
1045   (with-ir1-namespace
1046    (let* ((*lexenv* (make-null-lexenv))
1047           (lambda (ir1-top-level form *current-path* for-value)))
1048      (setf (leaf-name lambda) name)
1049      (compile-top-level (list lambda) t)
1050      lambda)))
1051
1052 ;;; Called by COMPILE-TOP-LEVEL when it was pased T for
1053 ;;; LOAD-TIME-VALUE-P (which happens in COMPILE-LOAD-TIME-STUFF). We
1054 ;;; don't try to combine this component with anything else and frob
1055 ;;; the name. If not in a :TOP-LEVEL component, then don't bother
1056 ;;; compiling, because it was merged with a run-time component.
1057 (defun compile-load-time-value-lambda (lambdas)
1058   (assert (null (cdr lambdas)))
1059   (let* ((lambda (car lambdas))
1060          (component (block-component (node-block (lambda-bind lambda)))))
1061     (when (eq (component-kind component) :top-level)
1062       (setf (component-name component) (leaf-name lambda))
1063       (compile-component component)
1064       (clear-ir1-info component))))
1065
1066 ;;; The entry point for MAKE-LOAD-FORM support. When IR1 conversion
1067 ;;; finds a constant structure, it invokes this to arrange for proper
1068 ;;; dumping. If it turns out that the constant has already been
1069 ;;; dumped, then we don't need to do anything.
1070 ;;;
1071 ;;; If the constant hasn't been dumped, then we check to see whether
1072 ;;; we are in the process of creating it. We detect this by
1073 ;;; maintaining the special *CONSTANTS-BEING-CREATED* as a list of all
1074 ;;; the constants we are in the process of creating. Actually, each
1075 ;;; entry is a list of the constant and any init forms that need to be
1076 ;;; processed on behalf of that constant.
1077 ;;;
1078 ;;; It's not necessarily an error for this to happen. If we are
1079 ;;; processing the init form for some object that showed up *after*
1080 ;;; the original reference to this constant, then we just need to
1081 ;;; defer the processing of that init form. To detect this, we
1082 ;;; maintain *CONSTANTS-CREATED-SINCE-LAST-INIT* as a list of the
1083 ;;; constants created since the last time we started processing an
1084 ;;; init form. If the constant passed to emit-make-load-form shows up
1085 ;;; in this list, then there is a circular chain through creation
1086 ;;; forms, which is an error.
1087 ;;;
1088 ;;; If there is some intervening init form, then we blow out of
1089 ;;; processing it by throwing to the tag PENDING-INIT. The value we
1090 ;;; throw is the entry from *CONSTANTS-BEING-CREATED*. This is so the
1091 ;;; offending init form can be tacked onto the init forms for the
1092 ;;; circular object.
1093 ;;;
1094 ;;; If the constant doesn't show up in *CONSTANTS-BEING-CREATED*, then
1095 ;;; we have to create it. We call MAKE-LOAD-FORM and check to see
1096 ;;; whether the creation form is the magic value
1097 ;;; :JUST-DUMP-IT-NORMALLY. If it is, then we don't do anything. The
1098 ;;; dumper will eventually get its hands on the object and use the
1099 ;;; normal structure dumping noise on it.
1100 ;;;
1101 ;;; Otherwise, we bind *CONSTANTS-BEING-CREATED* and
1102 ;;; *CONSTANTS-CREATED-SINCE- LAST-INIT* and compile the creation form
1103 ;;; much the way LOAD-TIME-VALUE does. When this finishes, we tell the
1104 ;;; dumper to use that result instead whenever it sees this constant.
1105 ;;;
1106 ;;; Now we try to compile the init form. We bind
1107 ;;; *CONSTANTS-CREATED-SINCE- LAST-INIT* to NIL and compile the init
1108 ;;; form (and any init forms that were added because of circularity
1109 ;;; detection). If this works, great. If not, we add the init forms to
1110 ;;; the init forms for the object that caused the problems and let it
1111 ;;; deal with it.
1112 (defvar *constants-being-created* nil)
1113 (defvar *constants-created-since-last-init* nil)
1114 ;;; FIXME: Shouldn't these^ variables be bound in LET forms?
1115 (defun emit-make-load-form (constant)
1116   (assert (fasl-file-p *compile-object*))
1117   (unless (or (fasl-constant-already-dumped constant *compile-object*)
1118               ;; KLUDGE: This special hack is because I was too lazy
1119               ;; to rework DEF!STRUCT so that the MAKE-LOAD-FORM
1120               ;; function of LAYOUT returns nontrivial forms when
1121               ;; building the cross-compiler but :IGNORE-IT when
1122               ;; cross-compiling or running under the target Lisp. --
1123               ;; WHN 19990914
1124               #+sb-xc-host (typep constant 'layout))
1125     (let ((circular-ref (assoc constant *constants-being-created* :test #'eq)))
1126       (when circular-ref
1127         (when (find constant *constants-created-since-last-init* :test #'eq)
1128           (throw constant t))
1129         (throw 'pending-init circular-ref)))
1130     (multiple-value-bind (creation-form init-form)
1131         (handler-case
1132             (sb!xc:make-load-form constant (make-null-lexenv))
1133           (error (condition)
1134                  (compiler-error "(while making load form for ~S)~%~A"
1135                                  constant
1136                                  condition)))
1137       (case creation-form
1138         (:just-dump-it-normally
1139          (fasl-validate-structure constant *compile-object*)
1140          t)
1141         (:ignore-it
1142          nil)
1143         (t
1144          (compile-top-level-lambdas () t)
1145          (when (fasl-constant-already-dumped constant *compile-object*)
1146            (return-from emit-make-load-form nil))
1147          (let* ((name (let ((*print-level* 1) (*print-length* 2))
1148                         (with-output-to-string (stream)
1149                           (write constant :stream stream))))
1150                 (info (if init-form
1151                           (list constant name init-form)
1152                           (list constant))))
1153            (let ((*constants-being-created*
1154                   (cons info *constants-being-created*))
1155                  (*constants-created-since-last-init*
1156                   (cons constant *constants-created-since-last-init*)))
1157              (when
1158                  (catch constant
1159                    (fasl-note-handle-for-constant
1160                     constant
1161                     (compile-load-time-value
1162                      creation-form
1163                      (format nil "creation form for ~A" name))
1164                     *compile-object*)
1165                    nil)
1166                (compiler-error "circular references in creation form for ~S"
1167                                constant)))
1168            (when (cdr info)
1169              (let* ((*constants-created-since-last-init* nil)
1170                     (circular-ref
1171                      (catch 'pending-init
1172                        (loop for (name form) on (cdr info) by #'cddr
1173                          collect name into names
1174                          collect form into forms
1175                          finally
1176                          (compile-make-load-form-init-forms
1177                           forms
1178                           (format nil "init form~:[~;s~] for ~{~A~^, ~}"
1179                                   (cdr forms) names)))
1180                        nil)))
1181                (when circular-ref
1182                  (setf (cdr circular-ref)
1183                        (append (cdr circular-ref) (cdr info))))))))))))
1184 \f
1185 ;;;; COMPILE-FILE
1186
1187 ;;; We build a list of top-level lambdas, and then periodically smash
1188 ;;; them together into a single component and compile it.
1189 (defvar *pending-top-level-lambdas*)
1190
1191 ;;; The maximum number of top-level lambdas we put in a single
1192 ;;; top-level component.
1193 ;;;
1194 ;;; CMU CL 18b used this nontrivially by default (setting it to 10)
1195 ;;; but consequently suffered from the inability to execute some
1196 ;;; troublesome constructs correctly, e.g. inability to load a fasl
1197 ;;; file compiled from the source file
1198 ;;;   (defpackage "FOO" (:use "CL"))
1199 ;;;   (print 'foo::bar)
1200 ;;; because it would dump data-setup fops (including a FOP-PACKAGE for
1201 ;;; "FOO") for the second form before dumping the the code in the
1202 ;;; first form, or the fop to execute the code in the first form. By
1203 ;;; setting this value to 0 by default, we avoid this badness. This
1204 ;;; increases the number of toplevel form functions, and so increases
1205 ;;; the size of object files.
1206 ;;;
1207 ;;; The variable is still supported because when we are compiling the
1208 ;;; SBCL system itself, which is known not contain any troublesome
1209 ;;; constructs, we can set it to a nonzero value, which reduces the
1210 ;;; number of toplevel form objects, reducing the peak memory usage in
1211 ;;; GENESIS, which is desirable, since at least for SBCL version
1212 ;;; 0.6.7, this is the high water mark for memory usage during system
1213 ;;; construction.
1214 (defparameter *top-level-lambda-max* 0)
1215
1216 (defun object-call-top-level-lambda (tll)
1217   (declare (type functional tll))
1218   (let ((object *compile-object*))
1219     (etypecase object
1220       (fasl-file
1221        (fasl-dump-top-level-lambda-call tll object))
1222       (core-object
1223        (core-call-top-level-lambda tll object))
1224       (null))))
1225
1226 ;;; Add LAMBDAS to the pending lambdas. If this leaves more than
1227 ;;; *TOP-LEVEL-LAMBDA-MAX* lambdas in the list, or if FORCE-P is true,
1228 ;;; then smash the lambdas into a single component, compile it, and
1229 ;;; call the resulting function.
1230 (defun sub-compile-top-level-lambdas (lambdas force-p)
1231   (declare (list lambdas))
1232   (setq *pending-top-level-lambdas*
1233         (append *pending-top-level-lambdas* lambdas))
1234   (let ((pending *pending-top-level-lambdas*))
1235     (when (and pending
1236                (or (> (length pending) *top-level-lambda-max*)
1237                    force-p))
1238       (multiple-value-bind (component tll) (merge-top-level-lambdas pending)
1239         (setq *pending-top-level-lambdas* ())
1240         (let ((*byte-compile* (if (eq *byte-compile* :maybe)
1241                                   *byte-compile-top-level*
1242                                   *byte-compile*)))
1243           (compile-component component))
1244         (clear-ir1-info component)
1245         (object-call-top-level-lambda tll))))
1246   (values))
1247
1248 ;;; Compile top-level code and call the top-level lambdas. We pick off
1249 ;;; top-level lambdas in non-top-level components here, calling
1250 ;;; SUB-c-t-l-l on each subsequence of normal top-level lambdas.
1251 (defun compile-top-level-lambdas (lambdas force-p)
1252   (declare (list lambdas))
1253   (let ((len (length lambdas)))
1254     (flet ((loser (start)
1255              (or (position-if #'(lambda (x)
1256                                   (not (eq (component-kind
1257                                             (block-component
1258                                              (node-block
1259                                               (lambda-bind x))))
1260                                            :top-level)))
1261                               lambdas
1262                               :start start)
1263                  len)))
1264       (do* ((start 0 (1+ loser))
1265             (loser (loser start) (loser start)))
1266            ((>= start len)
1267             (when force-p
1268               (sub-compile-top-level-lambdas nil t)))
1269         (sub-compile-top-level-lambdas (subseq lambdas start loser)
1270                                        (or force-p (/= loser len)))
1271         (unless (= loser len)
1272           (object-call-top-level-lambda (elt lambdas loser))))))
1273   (values))
1274
1275 ;;; Compile LAMBDAS (a list of the lambdas for top-level forms) into
1276 ;;; the object file. We loop doing local call analysis until it
1277 ;;; converges, since a single pass might miss something due to
1278 ;;; components being joined by LET conversion.
1279 ;;;
1280 ;;; LOAD-TIME-VALUE-P seems to control whether it's MAKE-LOAD-FORM and
1281 ;;; COMPILE-LOAD-TIME-VALUE stuff. -- WHN 20000201
1282 (defun compile-top-level (lambdas load-time-value-p)
1283   (declare (list lambdas))
1284   (maybe-mumble "locall ")
1285   (loop
1286     (let ((did-something nil))
1287       (dolist (lambda lambdas)
1288         (let* ((component (block-component (node-block (lambda-bind lambda))))
1289                (*all-components* (list component)))
1290           (when (component-new-functions component)
1291             (setq did-something t)
1292             (local-call-analyze component))))
1293       (unless did-something (return))))
1294
1295   (maybe-mumble "IDFO ")
1296   (multiple-value-bind (components top-components hairy-top)
1297       (find-initial-dfo lambdas)
1298     (let ((*all-components* (append components top-components))
1299           (top-level-closure nil))
1300       (when *check-consistency*
1301         (maybe-mumble "[check]~%")
1302         (check-ir1-consistency *all-components*))
1303
1304       (dolist (component (append hairy-top top-components))
1305         (when (pre-environment-analyze-top-level component)
1306           (setq top-level-closure t)))
1307
1308       (let ((*byte-compile*
1309              (if (and top-level-closure (eq *byte-compile* :maybe))
1310                  nil
1311                  *byte-compile*)))
1312         (dolist (component components)
1313           (compile-component component)
1314           (when (replace-top-level-xeps component)
1315             (setq top-level-closure t)))
1316         
1317         (when *check-consistency*
1318           (maybe-mumble "[check]~%")
1319           (check-ir1-consistency *all-components*))
1320         
1321         (if load-time-value-p
1322             (compile-load-time-value-lambda lambdas)
1323             (compile-top-level-lambdas lambdas top-level-closure)))
1324
1325       (dolist (component components)
1326         (clear-ir1-info component))
1327       (clear-stuff)))
1328   (values))
1329
1330 ;;; Actually compile any stuff that has been queued up for block
1331 ;;; compilation.
1332 (defun finish-block-compilation ()
1333   (when *block-compile*
1334     (when *top-level-lambdas*
1335       (compile-top-level (nreverse *top-level-lambdas*) nil)
1336       (setq *top-level-lambdas* ()))
1337     (setq *block-compile* nil)
1338     (setq *entry-points* nil)))
1339
1340 ;;; Read all forms from INFO and compile them, with output to OBJECT.
1341 ;;; Return (VALUES NIL WARNINGS-P FAILURE-P).
1342 (defun sub-compile-file (info &optional d-s-info)
1343   (declare (type source-info info))
1344   (let* (;; These are bound in WITH-COMPILATION-UNIT now. -- WHN 20000308
1345          #+nil (*compiler-error-count* 0)
1346          #+nil (*compiler-warning-count* 0)
1347          #+nil (*compiler-style-warning-count* 0)
1348          #+nil (*compiler-note-count* 0)
1349          (*block-compile* *block-compile-argument*)
1350          (*package* (sane-package))
1351          (*policy* *policy*)
1352          (*interface-policy* *interface-policy*)
1353          (*lexenv* (make-null-lexenv))
1354          (*converting-for-interpreter* nil)
1355          (*source-info* info)
1356          (sb!xc:*compile-file-pathname* nil)
1357          (sb!xc:*compile-file-truename* nil)
1358          (*top-level-lambdas* ())
1359          (*pending-top-level-lambdas* ())
1360          (*compiler-error-bailout*
1361           (lambda ()
1362             (compiler-mumble "~2&; fatal error, aborting compilation~%")
1363             (return-from sub-compile-file (values nil t t))))
1364          (*current-path* nil)
1365          (*last-source-context* nil)
1366          (*last-original-source* nil)
1367          (*last-source-form* nil)
1368          (*last-format-string* nil)
1369          (*last-format-args* nil)
1370          (*last-message-count* 0)
1371          (*info-environment* (or *backend-info-environment*
1372                                  *info-environment*))
1373          (*gensym-counter* 0))
1374     (with-compilation-values
1375       (sb!xc:with-compilation-unit ()
1376         (clear-stuff)
1377
1378         (process-sources info)
1379
1380         (finish-block-compilation)
1381         (compile-top-level-lambdas () t)
1382         (let ((object *compile-object*))
1383           (etypecase object
1384             (fasl-file (fasl-dump-source-info info object))
1385             (core-object (fix-core-source-info info object d-s-info))
1386             (null)))
1387         nil))))
1388
1389 ;;; Return a list of pathnames for the named files. All the files must
1390 ;;; exist.
1391 (defun verify-source-files (stuff)
1392   (let* ((stuff (if (listp stuff) stuff (list stuff)))
1393          (default-host (make-pathname
1394                         :host (pathname-host (pathname (first stuff))))))
1395     (flet ((try-with-type (path type error-p)
1396              (let ((new (merge-pathnames
1397                          path (make-pathname :type type
1398                                              :defaults default-host))))
1399                (if (probe-file new)
1400                    new
1401                    (and error-p (truename new))))))
1402       (unless stuff
1403         (error "can't compile with no source files"))
1404       (mapcar #'(lambda (x)
1405                   (let ((x (pathname x)))
1406                     (cond ((typep x 'logical-pathname)
1407                            (try-with-type x "LISP" t))
1408                           ((probe-file x) x)
1409                           ((try-with-type x "lisp"  nil))
1410                           ((try-with-type x "lisp"  t)))))
1411               stuff))))
1412
1413 (defun elapsed-time-to-string (tsec)
1414   (multiple-value-bind (tmin sec) (truncate tsec 60)
1415     (multiple-value-bind (thr min) (truncate tmin 60)
1416       (format nil "~D:~2,'0D:~2,'0D" thr min sec))))
1417
1418 ;;; Print some junk at the beginning and end of compilation.
1419 (defun start-error-output (source-info)
1420   (declare (type source-info source-info))
1421   (dolist (x (source-info-files source-info))
1422     (compiler-mumble "~&; compiling file ~S (written ~A):~%"
1423                      (namestring (file-info-name x))
1424                      (sb!int:format-universal-time nil
1425                                                    (file-info-write-date x)
1426                                                    :style :government
1427                                                    :print-weekday nil
1428                                                    :print-timezone nil)))
1429   (values))
1430
1431 (defun finish-error-output (source-info won)
1432   (declare (type source-info source-info))
1433   (compiler-mumble "~&; compilation ~:[aborted after~;finished in~] ~A~&"
1434                    won
1435                    (elapsed-time-to-string
1436                     (- (get-universal-time)
1437                        (source-info-start-time source-info))))
1438   (values))
1439
1440 ;;; Open some files and call SUB-COMPILE-FILE. If something unwinds
1441 ;;; out of the compile, then abort the writing of the output file, so
1442 ;;; we don't overwrite it with known garbage.
1443 (defun sb!xc:compile-file
1444     (input-file
1445      &key
1446      (output-file (cfp-output-file-default input-file))
1447      ;; FIXME: ANSI doesn't seem to say anything about
1448      ;; *COMPILE-VERBOSE* and *COMPILE-PRINT* being rebound by this
1449      ;; function..
1450      ((:verbose sb!xc:*compile-verbose*) sb!xc:*compile-verbose*)
1451      ((:print sb!xc:*compile-print*) sb!xc:*compile-print*)
1452      (external-format :default)
1453      ((:block-compile *block-compile-argument*) nil)
1454      ((:entry-points *entry-points*) nil)
1455      ((:byte-compile *byte-compile*) *byte-compile-default*))
1456   #!+sb-doc
1457   "Compile INPUT-FILE, producing a corresponding fasl file. 
1458    :Output-File
1459       The name of the fasl to output.
1460    :Block-Compile
1461       Determines whether multiple functions are compiled together as a unit,
1462       resolving function references at compile time. NIL means that global
1463       function names are never resolved at compilation time.
1464    :Entry-Points
1465       This specifies a list of function names for functions in the file(s) that
1466       must be given global definitions. This only applies to block
1467       compilation. If the value is NIL (the default) then all functions
1468       will be globally defined.
1469    :Byte-Compile {T | NIL | :MAYBE}
1470       Determines whether to compile into interpreted byte code instead of
1471       machine instructions. Byte code is several times smaller, but much
1472       slower. If :MAYBE, then only byte-compile when SPEED is 0 and
1473       DEBUG <= 1. The default is the value of SB-EXT:*BYTE-COMPILE-DEFAULT*,
1474       which is initially :MAYBE."
1475   (unless (eq external-format :default)
1476     (error "Non-:DEFAULT EXTERNAL-FORMAT values are not supported."))
1477   (let* ((fasl-file nil)
1478          (output-file-name nil)
1479          (compile-won nil)
1480          (warnings-p nil)
1481          (failure-p t) ; T in case error keeps this from being set later
1482          ;; KLUDGE: The listifying and unlistifying in the next calls
1483          ;; is to interface to old CMU CL code which accepted and
1484          ;; returned lists of multiple source files. It would be
1485          ;; cleaner to redo VERIFY-SOURCE-FILES and as
1486          ;; VERIFY-SOURCE-FILE, accepting a single source file, and
1487          ;; do a similar transformation on MAKE-FILE-SOURCE-INFO too.
1488          ;; -- WHN 20000201
1489          (input-pathname (first (verify-source-files (list input-file))))
1490          (source-info (make-file-source-info (list input-pathname))))
1491     (unwind-protect
1492         (progn
1493           (when output-file
1494             (setq output-file-name
1495                   (sb!xc:compile-file-pathname input-file
1496                                                :output-file output-file))
1497             (setq fasl-file
1498                   (open-fasl-file output-file-name
1499                                   (namestring input-pathname)
1500                                   (eq *byte-compile* t))))
1501
1502           (when sb!xc:*compile-verbose*
1503             (start-error-output source-info))
1504           (let ((*compile-object* fasl-file)
1505                 dummy)
1506             (multiple-value-setq (dummy warnings-p failure-p)
1507               (sub-compile-file source-info)))
1508           (setq compile-won t))
1509
1510       (close-source-info source-info)
1511
1512       (when fasl-file
1513         (close-fasl-file fasl-file (not compile-won))
1514         (setq output-file-name (pathname (fasl-file-stream fasl-file)))
1515         (when (and compile-won sb!xc:*compile-verbose*)
1516           (compiler-mumble "~2&; ~A written~%" (namestring output-file-name))))
1517
1518       (when sb!xc:*compile-verbose*
1519         (finish-error-output source-info compile-won)))
1520
1521     (values (if output-file
1522                 ;; Hack around filesystem race condition...
1523                 (or (probe-file output-file-name) output-file-name)
1524                 nil)
1525             warnings-p
1526             failure-p)))
1527 \f
1528 ;;; a helper function for COMPILE-FILE-PATHNAME: the default for
1529 ;;; the OUTPUT-FILE argument
1530 ;;;
1531 ;;; ANSI: The defaults for the OUTPUT-FILE are taken from the pathname
1532 ;;; that results from merging the INPUT-FILE with the value of
1533 ;;; *DEFAULT-PATHNAME-DEFAULTS*, except that the type component should
1534 ;;; default to the appropriate implementation-defined default type for
1535 ;;; compiled files.
1536 (defun cfp-output-file-default (input-file)
1537   (let* ((defaults (merge-pathnames input-file
1538                                     *default-pathname-defaults*))
1539          (retyped (make-pathname :type *backend-fasl-file-type*
1540                                  :defaults defaults)))
1541     retyped))
1542         
1543 ;;; KLUDGE: Part of the ANSI spec for this seems contradictory:
1544 ;;;   If INPUT-FILE is a logical pathname and OUTPUT-FILE is unsupplied,
1545 ;;;   the result is a logical pathname. If INPUT-FILE is a logical
1546 ;;;   pathname, it is translated into a physical pathname as if by
1547 ;;;   calling TRANSLATE-LOGICAL-PATHNAME.
1548 ;;; So I haven't really tried to make this precisely ANSI-compatible
1549 ;;; at the level of e.g. whether it returns logical pathname or a
1550 ;;; physical pathname. Patches to make it more correct are welcome.
1551 ;;; -- WHN 2000-12-09
1552 (defun sb!xc:compile-file-pathname (input-file
1553                                     &key
1554                                     (output-file (cfp-output-file-default
1555                                                   input-file))
1556                                     &allow-other-keys)
1557   #!+sb-doc
1558   "Return a pathname describing what file COMPILE-FILE would write to given
1559    these arguments."
1560   (pathname output-file))