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