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