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