(I seem to've screwed up during the checkin of 0.pre7.131 before, so
[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-vars* *component-being-compiled*
18                   *code-vector* *next-location* *result-fixups*
19                   *free-funs* *source-paths*
20                   *seen-blocks* *seen-funs* *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-warn "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-warn
182                    "~W 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-warn
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 ~W fatal ERROR condition~:P~]~
205                        ~[~:;~:*~&  caught ~W ERROR condition~:P~]~
206                        ~[~:;~:*~&  caught ~W WARNING condition~:P~]~
207                        ~[~:;~:*~&  caught ~W STYLE-WARNING condition~:P~]~
208                        ~[~:;~:*~&  printed ~W 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   (aver-live-component component)
314   (let ((*constraint-number* 0)
315         (loop-count 1)
316         (*delayed-ir1-transforms* nil))
317     (declare (special *constraint-number* *delayed-ir1-transforms*))
318     (loop
319       (ir1-optimize-until-done component)
320       (when (or (component-new-funs component)
321                 (component-reanalyze-funs component))
322         (maybe-mumble "locall ")
323         (locall-analyze-component component))
324       (dfo-as-needed component)
325       (when *constraint-propagate*
326         (maybe-mumble "constraint ")
327         (constraint-propagate component))
328       (when (retry-delayed-ir1-transforms :constraint)
329         (maybe-mumble "Rtran "))
330       (flet ((want-reoptimization-p ()
331                (or (component-reoptimize component)
332                    (component-reanalyze component)
333                    (component-new-funs component)
334                    (component-reanalyze-funs component))))
335         (unless (and (want-reoptimization-p)
336                      ;; We delay the generation of type checks until
337                      ;; the type constraints have had time to
338                      ;; propagate, else the compiler can confuse itself.
339                      (< loop-count (- *reoptimize-after-type-check-max* 4)))
340           (maybe-mumble "type ")
341           (generate-type-checks component)
342           (unless (want-reoptimization-p)
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) :dead)
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 (node-component ref) component))
460                       (leaf-refs fun))
461          (return))))))
462
463 (defun compile-component (component)
464
465   ;; miscellaneous sanity checks
466   ;;
467   ;; FIXME: These are basically pretty wimpy compared to the checks done
468   ;; by the old CHECK-IR1-CONSISTENCY code. It would be really nice to
469   ;; make those internal consistency checks work again and use them.
470   (aver-live-component component)
471   (do-blocks (block component)
472     (aver (eql (block-component block) component)))
473   (dolist (lambda (component-lambdas component))
474     ;; sanity check to prevent weirdness from propagating insidiously as
475     ;; far from its root cause as it did in bug 138: Make sure that
476     ;; thing-to-COMPONENT links are consistent.
477     (aver (eql (lambda-component lambda) component))
478     (aver (eql (node-component (lambda-bind lambda)) component)))
479
480   (let* ((*component-being-compiled* component))
481     (when sb!xc:*compile-print*
482       (compiler-mumble "~&; compiling ~A: " (component-name component)))
483
484     (ir1-phases component)
485
486     ;; FIXME: What is MAYBE-MUMBLE for? Do we need it any more?
487     (maybe-mumble "env ")
488     (physenv-analyze component)
489     (dfo-as-needed component)
490
491     (delete-if-no-entries component)
492
493     (unless (eq (block-next (component-head component))
494                 (component-tail component))
495       (%compile-component component)))
496
497   (clear-constant-info)
498
499   (when sb!xc:*compile-print*
500     (compiler-mumble "~&"))
501
502   (values))
503 \f
504 ;;;; clearing global data structures
505 ;;;;
506 ;;;; FIXME: Is it possible to get rid of this stuff, getting rid of
507 ;;;; global data structures entirely when possible and consing up the
508 ;;;; others from scratch instead of clearing and reusing them?
509
510 ;;; Clear the INFO in constants in the *FREE-VARS*, etc. In
511 ;;; addition to allowing stuff to be reclaimed, this is required for
512 ;;; correct assignment of constant offsets, since we need to assign a
513 ;;; new offset for each component. We don't clear the FUNCTIONAL-INFO
514 ;;; slots, since they are used to keep track of functions across
515 ;;; component boundaries.
516 (defun clear-constant-info ()
517   (maphash (lambda (k v)
518              (declare (ignore k))
519              (setf (leaf-info v) nil))
520            *constants*)
521   (maphash (lambda (k v)
522              (declare (ignore k))
523              (when (constant-p v)
524                (setf (leaf-info v) nil)))
525            *free-vars*)
526   (values))
527
528 ;;; Blow away the REFS for all global variables, and let COMPONENT
529 ;;; be recycled.
530 (defun clear-ir1-info (component)
531   (declare (type component component))
532   (labels ((blast (x)
533              (maphash (lambda (k v)
534                         (declare (ignore k))
535                         (when (leaf-p v)
536                           (setf (leaf-refs v)
537                                 (delete-if #'here-p (leaf-refs v)))
538                           (when (basic-var-p v)
539                             (setf (basic-var-sets v)
540                                   (delete-if #'here-p (basic-var-sets v))))))
541                       x))
542            (here-p (x)
543              (eq (node-component x) component)))
544     (blast *free-vars*)
545     (blast *free-funs*)
546     (blast *constants*))
547   (values))
548
549 ;;; Clear global variables used by the compiler.
550 ;;;
551 ;;; FIXME: It seems kinda nasty and unmaintainable to have to do this,
552 ;;; and it adds overhead even when people aren't using the compiler.
553 ;;; Perhaps we could make these global vars unbound except when
554 ;;; actually in use, so that this function could go away.
555 (defun clear-stuff (&optional (debug-too t))
556
557   ;; Clear global tables.
558   (when (boundp '*free-funs*)
559     (clrhash *free-funs*)
560     (clrhash *free-vars*)
561     (clrhash *constants*))
562
563   ;; Clear debug counters and tables.
564   (clrhash *seen-blocks*)
565   (clrhash *seen-funs*)
566   (clrhash *list-conflicts-table*)
567
568   (when debug-too
569     (clrhash *continuation-numbers*)
570     (clrhash *number-continuations*)
571     (setq *continuation-number* 0)
572     (clrhash *tn-ids*)
573     (clrhash *id-tns*)
574     (setq *tn-id* 0)
575     (clrhash *label-ids*)
576     (clrhash *id-labels*)
577     (setq *label-id* 0)
578
579     ;; Clear some PACK data structures (for GC purposes only).
580     (aver (not *in-pack*))
581     (dolist (sb *backend-sb-list*)
582       (when (finite-sb-p sb)
583         (fill (finite-sb-live-tns sb) nil))))
584
585   ;; (Note: The CMU CL code used to set CL::*GENSYM-COUNTER* to zero here.
586   ;; Superficially, this seemed harmful -- the user could reasonably be
587   ;; surprised if *GENSYM-COUNTER* turned back to zero when something was
588   ;; compiled. A closer inspection showed that this actually turned out to be
589   ;; harmless in practice, because CLEAR-STUFF was only called from within
590   ;; forms which bound CL::*GENSYM-COUNTER* to zero. However, this means that
591   ;; even though zeroing CL::*GENSYM-COUNTER* here turned out to be harmless in
592   ;; practice, it was also useless in practice. So we don't do it any more.)
593
594   (values))
595 \f
596 ;;;; trace output
597
598 ;;; Print out some useful info about Component to Stream.
599 (defun describe-component (component *standard-output*)
600   (declare (type component component))
601   (format t "~|~%;;;; component: ~S~2%" (component-name component))
602   (print-blocks component)
603   (values))
604
605 (defun describe-ir2-component (component *standard-output*)
606   (format t "~%~|~%;;;; IR2 component: ~S~2%" (component-name component))
607   (format t "entries:~%")
608   (dolist (entry (ir2-component-entries (component-info component)))
609     (format t "~4TL~D: ~S~:[~; [closure]~]~%"
610             (label-id (entry-info-offset entry))
611             (entry-info-name entry)
612             (entry-info-closure-p entry)))
613   (terpri)
614   (pre-pack-tn-stats component *standard-output*)
615   (terpri)
616   (print-ir2-blocks component)
617   (terpri)
618   (values))
619 \f
620 ;;;; file reading
621 ;;;;
622 ;;;; When reading from a file, we have to keep track of some source
623 ;;;; information. We also exploit our ability to back up for printing
624 ;;;; the error context and for recovering from errors.
625 ;;;;
626 ;;;; The interface we provide to this stuff is the stream-oid
627 ;;;; Source-Info structure. The bookkeeping is done as a side-effect
628 ;;;; of getting the next source form.
629
630 ;;; A FILE-INFO structure holds all the source information for a
631 ;;; given file.
632 (defstruct (file-info (:copier nil))
633   ;; If a file, the truename of the corresponding source file. If from
634   ;; a Lisp form, :LISP. If from a stream, :STREAM.
635   (name (missing-arg) :type (or pathname (member :lisp :stream)))
636   ;; the defaulted, but not necessarily absolute file name (i.e. prior
637   ;; to TRUENAME call.) Null if not a file. This is used to set
638   ;; *COMPILE-FILE-PATHNAME*, and if absolute, is dumped in the
639   ;; debug-info.
640   (untruename nil :type (or pathname null))
641   ;; the file's write date (if relevant)
642   (write-date nil :type (or unsigned-byte null))
643   ;; the source path root number of the first form in this file (i.e.
644   ;; the total number of forms converted previously in this
645   ;; compilation)
646   (source-root 0 :type unsigned-byte)
647   ;; parallel vectors containing the forms read out of the file and
648   ;; the file positions that reading of each form started at (i.e. the
649   ;; end of the previous form)
650   (forms (make-array 10 :fill-pointer 0 :adjustable t) :type (vector t))
651   (positions (make-array 10 :fill-pointer 0 :adjustable t) :type (vector t)))
652
653 ;;; The SOURCE-INFO structure provides a handle on all the source
654 ;;; information for an entire compilation.
655 (defstruct (source-info
656             #-no-ansi-print-object
657             (:print-object (lambda (s stream)
658                              (print-unreadable-object (s stream :type t))))
659             (:copier nil))
660   ;; the UT that compilation started at
661   (start-time (get-universal-time) :type unsigned-byte)
662   ;; the FILE-INFO structure for this compilation
663   (file-info nil :type (or file-info null))
664   ;; the stream that we are using to read the FILE-INFO, or NIL if
665   ;; no stream has been opened yet
666   (stream nil :type (or stream null)))
667
668 ;;; Given a pathname, return a SOURCE-INFO structure.
669 (defun make-file-source-info (file)
670   (let ((file-info (make-file-info :name (truename file)
671                                    :untruename file
672                                    :write-date (file-write-date file))))
673
674     (make-source-info :file-info file-info)))
675
676 ;;; Return a SOURCE-INFO to describe the incremental compilation of FORM. 
677 (defun make-lisp-source-info (form)
678   (make-source-info :start-time (get-universal-time)
679                     :file-info (make-file-info :name :lisp
680                                                :forms (vector form)
681                                                :positions '#(0))))
682
683 ;;; Return a SOURCE-INFO which will read from STREAM.
684 (defun make-stream-source-info (stream)
685   (let ((file-info (make-file-info :name :stream)))
686     (make-source-info :file-info file-info
687                       :stream stream)))
688
689 ;;; Return a form read from STREAM; or for EOF use the trick,
690 ;;; popularized by Kent Pitman, of returning STREAM itself. If an
691 ;;; error happens, then convert it to standard abort-the-compilation
692 ;;; error condition (possibly recording some extra location
693 ;;; information).
694 (defun read-for-compile-file (stream position)
695   (handler-case (read stream nil stream)
696     (reader-error (condition)
697      (error 'input-error-in-compile-file
698             :error condition
699             ;; We don't need to supply :POSITION here because
700             ;; READER-ERRORs already know their position in the file.
701             ))
702     ;; ANSI, in its wisdom, says that READ should return END-OF-FILE
703     ;; (and that this is not a READER-ERROR) when it encounters end of
704     ;; file in the middle of something it's trying to read.
705     (end-of-file (condition)
706      (error 'input-error-in-compile-file
707             :error condition
708             ;; We need to supply :POSITION here because the END-OF-FILE
709             ;; condition doesn't carry the position that the user
710             ;; probably cares about, where the failed READ began.
711             :position position))))
712
713 ;;; If STREAM is present, return it, otherwise open a stream to the
714 ;;; current file. There must be a current file.
715 ;;;
716 ;;; FIXME: This is probably an unnecessarily roundabout way to do
717 ;;; things now that we process a single file in COMPILE-FILE (unlike
718 ;;; the old CMU CL code, which accepted multiple files). Also, the old
719 ;;; comment said
720 ;;;   When we open a new file, we also reset *PACKAGE* and policy.
721 ;;;   This gives the effect of rebinding around each file.
722 ;;; which doesn't seem to be true now. Check to make sure that if
723 ;;; such rebinding is necessary, it's still done somewhere.
724 (defun get-source-stream (info)
725   (declare (type source-info info))
726   (or (source-info-stream info)
727       (let* ((file-info (source-info-file-info info))
728              (name (file-info-name file-info)))
729         (setf sb!xc:*compile-file-truename* name
730               sb!xc:*compile-file-pathname* (file-info-untruename file-info)
731               (source-info-stream info) (open name :direction :input)))))
732
733 ;;; Close the stream in INFO if it is open.
734 (defun close-source-info (info)
735   (declare (type source-info info))
736   (let ((stream (source-info-stream info)))
737     (when stream (close stream)))
738   (setf (source-info-stream info) nil)
739   (values))
740
741 ;;; Read and compile the source file.
742 (defun sub-sub-compile-file (info)
743   (let* ((file-info (source-info-file-info info))
744          (stream (get-source-stream info)))
745     (loop
746      (let* ((pos (file-position stream))
747             (form (read-for-compile-file stream pos)))
748        (if (eq form stream) ; i.e., if EOF
749            (return)
750            (let* ((forms (file-info-forms file-info))
751                   (current-idx (+ (fill-pointer forms)
752                                   (file-info-source-root file-info))))
753              (vector-push-extend form forms)
754              (vector-push-extend pos (file-info-positions file-info))
755              (find-source-paths form current-idx)
756              (process-toplevel-form form
757                                     `(original-source-start 0 ,current-idx)
758                                     nil)))))))
759
760 ;;; Return the INDEX'th source form read from INFO and the position
761 ;;; where it was read.
762 (defun find-source-root (index info)
763   (declare (type index index) (type source-info info))
764   (let ((file-info (source-info-file-info info)))
765     (values (aref (file-info-forms file-info) index)
766             (aref (file-info-positions file-info) index))))
767 \f
768 ;;;; processing of top level forms
769
770 ;;; This is called by top level form processing when we are ready to
771 ;;; actually compile something. If *BLOCK-COMPILE* is T, then we still
772 ;;; convert the form, but delay compilation, pushing the result on
773 ;;; *TOPLEVEL-LAMBDAS* instead.
774 (defun convert-and-maybe-compile (form path)
775   (declare (list path))
776   (let* ((*lexenv* (make-lexenv :policy *policy*))
777          (tll (ir1-toplevel form path nil)))
778     (cond ((eq *block-compile* t) (push tll *toplevel-lambdas*))
779           (t (compile-toplevel (list tll) nil)))))
780
781 ;;; Macroexpand FORM in the current environment with an error handler.
782 ;;; We only expand one level, so that we retain all the intervening
783 ;;; forms in the source path.
784 (defun preprocessor-macroexpand-1 (form)
785   (handler-case (sb!xc:macroexpand-1 form *lexenv*)
786     (error (condition)
787       (compiler-error "(during macroexpansion of ~A)~%~A"
788                       (let ((*print-level* 1)
789                             (*print-length* 2))
790                         (format nil "~S" form))
791                       condition))))
792
793 ;;; Process a PROGN-like portion of a top level form. FORMS is a list of
794 ;;; the forms, and PATH is the source path of the FORM they came out of.
795 ;;; COMPILE-TIME-TOO is as in ANSI "3.2.3.1 Processing of Top Level Forms".
796 (defun process-toplevel-progn (forms path compile-time-too)
797   (declare (list forms) (list path))
798   (dolist (form forms)
799     (process-toplevel-form form path compile-time-too)))
800
801 ;;; Process a top level use of LOCALLY, or anything else (e.g.
802 ;;; MACROLET) at top level which has declarations and ordinary forms.
803 ;;; We parse declarations and then recursively process the body.
804 (defun process-toplevel-locally (body path compile-time-too)
805   (declare (list path))
806   (multiple-value-bind (forms decls) (sb!sys:parse-body body nil)
807     (let* ((*lexenv*
808             (process-decls decls nil nil (make-continuation)))
809            ;; Binding *POLICY* is pretty much of a hack, since it
810            ;; causes LOCALLY to "capture" enclosed proclamations. It
811            ;; is necessary because CONVERT-AND-MAYBE-COMPILE uses the
812            ;; value of *POLICY* as the policy. The need for this hack
813            ;; is due to the quirk that there is no way to represent in
814            ;; a POLICY that an optimize quality came from the default.
815            ;;
816            ;; FIXME: Ideally, something should be done so that DECLAIM
817            ;; inside LOCALLY works OK. Failing that, at least we could
818            ;; issue a warning instead of silently screwing up.
819            (*policy* (lexenv-policy *lexenv*)))
820       (process-toplevel-progn forms path compile-time-too))))
821
822 ;;; Parse an EVAL-WHEN situations list, returning three flags,
823 ;;; (VALUES COMPILE-TOPLEVEL LOAD-TOPLEVEL EXECUTE), indicating
824 ;;; the types of situations present in the list.
825 (defun parse-eval-when-situations (situations)
826   (when (or (not (listp situations))
827             (set-difference situations
828                             '(:compile-toplevel
829                               compile
830                               :load-toplevel
831                               load
832                               :execute
833                               eval)))
834     (compiler-error "bad EVAL-WHEN situation list: ~S" situations))
835   (let ((deprecated-names (intersection situations '(compile load eval))))
836     (when deprecated-names
837       (style-warn "using deprecated EVAL-WHEN situation names~{ ~S~}"
838                   deprecated-names)))
839   (values (intersection '(:compile-toplevel compile)
840                         situations)
841           (intersection '(:load-toplevel load) situations)
842           (intersection '(:execute eval) situations)))
843
844
845 ;;; utilities for extracting COMPONENTs of FUNCTIONALs
846 (defun functional-components (f)
847   (declare (type functional f))
848   (etypecase f
849     (clambda (list (lambda-component f)))
850     (optional-dispatch (let ((result nil))
851                          (labels ((frob (clambda)
852                                     (pushnew (lambda-component clambda)
853                                              result))
854                                   (maybe-frob (maybe-clambda)
855                                     (when maybe-clambda
856                                       (frob maybe-clambda))))
857                            (mapc #'frob (optional-dispatch-entry-points f))
858                            (maybe-frob (optional-dispatch-more-entry f))
859                            (maybe-frob (optional-dispatch-main-entry f)))))))
860
861 (defun make-functional-from-toplevel-lambda (definition
862                                              &key
863                                              name
864                                              (path
865                                               ;; I'd thought NIL should
866                                               ;; work, but it doesn't.
867                                               ;; -- WHN 2001-09-20
868                                               (missing-arg)))
869   (let* ((*current-path* path)
870          (component (make-empty-component))
871          (*current-component* component))
872     (setf (component-name component)
873           (debug-namify "~S initial component" name))
874     (setf (component-kind component) :initial)
875     (let* ((locall-fun (ir1-convert-lambda
876                         definition
877                         :debug-name (debug-namify "top level local call ~S"
878                                                   name)))
879            (fun (ir1-convert-lambda (make-xep-lambda-expression locall-fun)
880                                     :source-name (or name '.anonymous.)
881                                     :debug-name (unless name
882                                                   "top level form"))))
883       (setf (functional-entry-fun fun) locall-fun
884             (functional-kind fun) :external
885             (functional-has-external-references-p fun) t)
886       fun)))
887
888 ;;; Compile LAMBDA-EXPRESSION into *COMPILE-OBJECT*, returning a
889 ;;; description of the result.
890 ;;;   * If *COMPILE-OBJECT* is a CORE-OBJECT, then write the function
891 ;;;     into core and return the compiled FUNCTION value.
892 ;;;   * If *COMPILE-OBJECT* is a fasl file, then write the function
893 ;;;     into the fasl file and return a dump handle.
894 ;;;
895 ;;; If NAME is provided, then we try to use it as the name of the
896 ;;; function for debugging/diagnostic information.
897 (defun %compile (lambda-expression
898                  *compile-object*
899                  &key
900                  name
901                  (path
902                   ;; This magical idiom seems to be the appropriate
903                   ;; path for compiling standalone LAMBDAs, judging
904                   ;; from the CMU CL code and experiment, so it's a
905                   ;; nice default for things where we don't have a
906                   ;; real source path (as in e.g. inside CL:COMPILE).
907                   '(original-source-start 0 0)))
908   (unless (or (null name) (legal-fun-name-p name))
909     (error "not a legal function name: ~S" name))
910   (let* ((*lexenv* (make-lexenv :policy *policy*))
911          (fun (make-functional-from-toplevel-lambda lambda-expression
912                                                     :name name
913                                                     :path path)))
914
915     ;; FIXME: The compile-it code from here on is sort of a
916     ;; twisted version of the code in COMPILE-TOPLEVEL. It'd be
917     ;; better to find a way to share the code there; or
918     ;; alternatively, to use this code to replace the code there.
919     ;; (The second alternative might be pretty easy if we used
920     ;; the :LOCALL-ONLY option to IR1-FOR-LAMBDA. Then maybe the
921     ;; whole FUNCTIONAL-KIND=:TOPLEVEL case could go away..)
922
923     (locall-analyze-clambdas-until-done (list fun))
924     
925     (multiple-value-bind (components-from-dfo top-components hairy-top)
926         (find-initial-dfo (list fun))
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           (compile-component component-from-dfo)
938           (replace-toplevel-xeps component-from-dfo)))
939
940       (prog1
941           (let ((entry-table (etypecase *compile-object*
942                                (fasl-output (fasl-output-entry-table
943                                              *compile-object*))
944                                (core-object (core-object-entry-table
945                                              *compile-object*)))))
946             (multiple-value-bind (result found-p)
947                 (gethash (leaf-info fun) entry-table)
948               (aver found-p)
949               result))
950         (mapc #'clear-ir1-info components-from-dfo)
951         (clear-stuff)))))
952
953 (defun process-toplevel-cold-fset (name lambda-expression path)
954   (unless (producing-fasl-file)
955     (error "can't COLD-FSET except in a fasl file"))
956   (unless (legal-fun-name-p name)
957     (error "not a legal function name: ~S" name))
958   (fasl-dump-cold-fset name
959                        (%compile lambda-expression
960                                  *compile-object*
961                                  :name name
962                                  :path path)
963                        *compile-object*)
964   (values))
965
966 ;;; Process a top level FORM with the specified source PATH.
967 ;;;  * If this is a magic top level form, then do stuff.
968 ;;;  * If this is a macro, then expand it.
969 ;;;  * Otherwise, just compile it.
970 ;;;
971 ;;; COMPILE-TIME-TOO is as defined in ANSI
972 ;;; "3.2.3.1 Processing of Top Level Forms".
973 (defun process-toplevel-form (form path compile-time-too)
974
975   (declare (list path))
976
977   (catch 'process-toplevel-form-error-abort
978     (let* ((path (or (gethash form *source-paths*) (cons form path)))
979            (*compiler-error-bailout*
980             (lambda ()
981               (convert-and-maybe-compile
982                `(error "execution of a form compiled with errors:~% ~S"
983                        ',form)
984                path)
985               (throw 'process-toplevel-form-error-abort nil))))
986
987       (if (atom form)
988           ;; (There are no EVAL-WHEN issues in the ATOM case until
989           ;; SBCL gets smart enough to handle global
990           ;; DEFINE-SYMBOL-MACRO.)
991           (convert-and-maybe-compile form path)
992           (flet ((need-at-least-one-arg (form)
993                    (unless (cdr form)
994                      (compiler-error "~S form is too short: ~S"
995                                      (car form)
996                                      form))))
997             (case (car form)
998               ;; In the cross-compiler, top level COLD-FSET arranges
999               ;; for static linking at cold init time.
1000               #+sb-xc-host
1001               ((cold-fset)
1002                (aver (not compile-time-too))
1003                (destructuring-bind (cold-fset fun-name lambda-expression) form
1004                  (declare (ignore cold-fset))
1005                  (process-toplevel-cold-fset fun-name
1006                                              lambda-expression
1007                                              path)))
1008               ((eval-when macrolet symbol-macrolet);things w/ 1 arg before body
1009                (need-at-least-one-arg form)
1010                (destructuring-bind (special-operator magic &rest body) form
1011                  (ecase special-operator
1012                    ((eval-when)
1013                     ;; CT, LT, and E here are as in Figure 3-7 of ANSI
1014                     ;; "3.2.3.1 Processing of Top Level Forms".
1015                     (multiple-value-bind (ct lt e)
1016                         (parse-eval-when-situations magic)
1017                       (let ((new-compile-time-too (or ct
1018                                                       (and compile-time-too
1019                                                            e))))
1020                         (cond (lt (process-toplevel-progn
1021                                    body path new-compile-time-too))
1022                               (new-compile-time-too (eval
1023                                                      `(progn ,@body)))))))
1024                    ((macrolet)
1025                     (funcall-in-macrolet-lexenv
1026                      magic
1027                      (lambda ()
1028                        (process-toplevel-locally body
1029                                                  path
1030                                                  compile-time-too))))
1031                    ((symbol-macrolet)
1032                     (funcall-in-symbol-macrolet-lexenv
1033                      magic
1034                      (lambda ()
1035                        (process-toplevel-locally body
1036                                                  path
1037                                                  compile-time-too)))))))
1038               ((locally)
1039                (process-toplevel-locally (rest form) path compile-time-too))
1040               ((progn)
1041                (process-toplevel-progn (rest form) path compile-time-too))
1042               ;; When we're cross-compiling, consider: what should we
1043               ;; do when we hit e.g.
1044               ;;   (EVAL-WHEN (:COMPILE-TOPLEVEL)
1045               ;;     (DEFUN FOO (X) (+ 7 X)))?
1046               ;; DEFUN has a macro definition in the cross-compiler,
1047               ;; and a different macro definition in the target
1048               ;; compiler. The only sensible thing is to use the
1049               ;; target compiler's macro definition, since the
1050               ;; cross-compiler's macro is in general into target
1051               ;; functions which can't meaningfully be executed at
1052               ;; cross-compilation time. So make sure we do the EVAL
1053               ;; here, before we macroexpand.
1054               ;;
1055               ;; Then things get even dicier with something like
1056               ;;   (DEFCONSTANT-EQX SB!XC:LAMBDA-LIST-KEYWORDS ..)
1057               ;; where we have to make sure that we don't uncross
1058               ;; the SB!XC: prefix before we do EVAL, because otherwise
1059               ;; we'd be trying to redefine the cross-compilation host's
1060               ;; constants.
1061               ;;
1062               ;; (Isn't it fun to cross-compile Common Lisp?:-)
1063               #+sb-xc-host
1064               (t
1065                (when compile-time-too
1066                  (eval form)) ; letting xc host EVAL do its own macroexpansion
1067                (let* (;; (We uncross the operator name because things
1068                       ;; like SB!XC:DEFCONSTANT and SB!XC:DEFTYPE
1069                       ;; should be equivalent to their CL: counterparts
1070                       ;; when being compiled as target code. We leave
1071                       ;; the rest of the form uncrossed because macros
1072                       ;; might yet expand into EVAL-WHEN stuff, and
1073                       ;; things inside EVAL-WHEN can't be uncrossed
1074                       ;; until after we've EVALed them in the
1075                       ;; cross-compilation host.)
1076                       (slightly-uncrossed (cons (uncross (first form))
1077                                                 (rest form)))
1078                       (expanded (preprocessor-macroexpand-1
1079                                  slightly-uncrossed)))
1080                  (if (eq expanded slightly-uncrossed)
1081                      ;; (Now that we're no longer processing toplevel
1082                      ;; forms, and hence no longer need to worry about
1083                      ;; EVAL-WHEN, we can uncross everything.)
1084                      (convert-and-maybe-compile expanded path)
1085                      ;; (We have to demote COMPILE-TIME-TOO to NIL
1086                      ;; here, no matter what it was before, since
1087                      ;; otherwise we'd tend to EVAL subforms more than
1088                      ;; once, because of WHEN COMPILE-TIME-TOO form
1089                      ;; above.)
1090                      (process-toplevel-form expanded path nil))))
1091               ;; When we're not cross-compiling, we only need to
1092               ;; macroexpand once, so we can follow the 1-thru-6
1093               ;; sequence of steps in ANSI's "3.2.3.1 Processing of
1094               ;; Top Level Forms".
1095               #-sb-xc-host
1096               (t
1097                (let ((expanded (preprocessor-macroexpand-1 form)))
1098                  (cond ((eq expanded form)
1099                         (when compile-time-too
1100                           (eval form))
1101                         (convert-and-maybe-compile form path))
1102                        (t
1103                         (process-toplevel-form expanded
1104                                                path
1105                                                compile-time-too))))))))))
1106
1107   (values))
1108 \f
1109 ;;;; load time value support
1110 ;;;;
1111 ;;;; (See EMIT-MAKE-LOAD-FORM.)
1112
1113 ;;; Return T if we are currently producing a fasl file and hence
1114 ;;; constants need to be dumped carefully.
1115 (defun producing-fasl-file ()
1116   (fasl-output-p *compile-object*))
1117
1118 ;;; Compile FORM and arrange for it to be called at load-time. Return
1119 ;;; the dumper handle and our best guess at the type of the object.
1120 (defun compile-load-time-value
1121        (form &optional
1122              (name (let ((*print-level* 2) (*print-length* 3))
1123                      (format nil "load time value of ~S"
1124                              (if (and (listp form)
1125                                       (eq (car form) 'make-value-cell))
1126                                  (second form)
1127                                  form)))))
1128   (let ((lambda (compile-load-time-stuff form name t)))
1129     (values
1130      (fasl-dump-load-time-value-lambda lambda *compile-object*)
1131      (let ((type (leaf-type lambda)))
1132        (if (fun-type-p type)
1133            (single-value-type (fun-type-returns type))
1134            *wild-type*)))))
1135
1136 ;;; Compile the FORMS and arrange for them to be called (for effect,
1137 ;;; not value) at load time.
1138 (defun compile-make-load-form-init-forms (forms name)
1139   (let ((lambda (compile-load-time-stuff `(progn ,@forms) name nil)))
1140     (fasl-dump-toplevel-lambda-call lambda *compile-object*)))
1141
1142 ;;; Do the actual work of COMPILE-LOAD-TIME-VALUE or
1143 ;;; COMPILE-MAKE-LOAD-FORM-INIT-FORMS.
1144 (defun compile-load-time-stuff (form name for-value)
1145   (with-ir1-namespace
1146    (let* ((*lexenv* (make-null-lexenv))
1147           (lambda (ir1-toplevel form *current-path* for-value)))
1148      (compile-toplevel (list lambda) t)
1149      lambda)))
1150
1151 ;;; This is called by COMPILE-TOPLEVEL when it was passed T for
1152 ;;; LOAD-TIME-VALUE-P (which happens in COMPILE-LOAD-TIME-STUFF). We
1153 ;;; don't try to combine this component with anything else and frob
1154 ;;; the name. If not in a :TOPLEVEL component, then don't bother
1155 ;;; compiling, because it was merged with a run-time component.
1156 (defun compile-load-time-value-lambda (lambdas)
1157   (aver (null (cdr lambdas)))
1158   (let* ((lambda (car lambdas))
1159          (component (lambda-component lambda)))
1160     (when (eql (component-kind component) :toplevel)
1161       (setf (component-name component) (leaf-debug-name lambda))
1162       (compile-component component)
1163       (clear-ir1-info component))))
1164 \f
1165 ;;;; COMPILE-FILE
1166
1167 ;;; We build a list of top level lambdas, and then periodically smash
1168 ;;; them together into a single component and compile it.
1169 (defvar *pending-toplevel-lambdas*)
1170
1171 ;;; The maximum number of top level lambdas we put in a single
1172 ;;; top level component.
1173 ;;;
1174 ;;; CMU CL 18b used this nontrivially by default (setting it to 10)
1175 ;;; but consequently suffered from the inability to execute some
1176 ;;; troublesome constructs correctly, e.g. inability to load a fasl
1177 ;;; file compiled from the source file
1178 ;;;   (defpackage "FOO" (:use "CL"))
1179 ;;;   (print 'foo::bar)
1180 ;;; because it would dump data-setup fops (including a FOP-PACKAGE for
1181 ;;; "FOO") for the second form before dumping the the code in the
1182 ;;; first form, or the fop to execute the code in the first form. By
1183 ;;; setting this value to 0 by default, we avoid this badness. This
1184 ;;; increases the number of toplevel form functions, and so increases
1185 ;;; the size of object files.
1186 ;;;
1187 ;;; The variable is still supported because when we are compiling the
1188 ;;; SBCL system itself, which is known not contain any troublesome
1189 ;;; constructs, we can set it to a nonzero value, which reduces the
1190 ;;; number of toplevel form objects, reducing the peak memory usage in
1191 ;;; GENESIS, which is desirable, since at least for SBCL version
1192 ;;; 0.6.7, this is the high water mark for memory usage during system
1193 ;;; construction.
1194 (defparameter *toplevel-lambda-max* 0)
1195
1196 (defun object-call-toplevel-lambda (tll)
1197   (declare (type functional tll))
1198   (let ((object *compile-object*))
1199     (etypecase object
1200       (fasl-output
1201        (fasl-dump-toplevel-lambda-call tll object))
1202       (core-object
1203        (core-call-toplevel-lambda tll object))
1204       (null))))
1205
1206 ;;; Add LAMBDAS to the pending lambdas. If this leaves more than
1207 ;;; *TOPLEVEL-LAMBDA-MAX* lambdas in the list, or if FORCE-P is true,
1208 ;;; then smash the lambdas into a single component, compile it, and
1209 ;;; call the resulting function.
1210 (defun sub-compile-toplevel-lambdas (lambdas force-p)
1211   (declare (list lambdas))
1212   (setq *pending-toplevel-lambdas*
1213         (append *pending-toplevel-lambdas* lambdas))
1214   (let ((pending *pending-toplevel-lambdas*))
1215     (when (and pending
1216                (or (> (length pending) *toplevel-lambda-max*)
1217                    force-p))
1218       (multiple-value-bind (component tll) (merge-toplevel-lambdas pending)
1219         (setq *pending-toplevel-lambdas* ())
1220         (compile-component component)
1221         (clear-ir1-info component)
1222         (object-call-toplevel-lambda tll))))
1223   (values))
1224
1225 ;;; Compile top level code and call the top level lambdas. We pick off
1226 ;;; top level lambdas in non-top-level components here, calling
1227 ;;; SUB-c-t-l-l on each subsequence of normal top level lambdas.
1228 (defun compile-toplevel-lambdas (lambdas force-p)
1229   (declare (list lambdas))
1230   (let ((len (length lambdas)))
1231     (flet ((loser (start)
1232              (or (position-if (lambda (x)
1233                                 (not (eq (component-kind
1234                                           (node-component (lambda-bind x)))
1235                                          :toplevel)))
1236                               lambdas
1237                               :start start)
1238                  len)))
1239       (do* ((start 0 (1+ loser))
1240             (loser (loser start) (loser start)))
1241            ((>= start len)
1242             (when force-p
1243               (sub-compile-toplevel-lambdas nil t)))
1244         (sub-compile-toplevel-lambdas (subseq lambdas start loser)
1245                                       (or force-p (/= loser len)))
1246         (unless (= loser len)
1247           (object-call-toplevel-lambda (elt lambdas loser))))))
1248   (values))
1249
1250 ;;; Compile LAMBDAS (a list of CLAMBDAs for top level forms) into the
1251 ;;; object file. 
1252 ;;;
1253 ;;; LOAD-TIME-VALUE-P seems to control whether it's MAKE-LOAD-FORM and
1254 ;;; COMPILE-LOAD-TIME-VALUE stuff. -- WHN 20000201
1255 (defun compile-toplevel (lambdas load-time-value-p)
1256   (declare (list lambdas))
1257
1258   (maybe-mumble "locall ")
1259   (locall-analyze-clambdas-until-done lambdas)
1260
1261   (maybe-mumble "IDFO ")
1262   (multiple-value-bind (components top-components hairy-top)
1263       (find-initial-dfo lambdas)
1264     (let ((*all-components* (append components top-components))
1265           (toplevel-closure nil))
1266       (when *check-consistency*
1267         (maybe-mumble "[check]~%")
1268         (check-ir1-consistency *all-components*))
1269
1270       (dolist (component (append hairy-top top-components))
1271         (when (pre-physenv-analyze-toplevel component)
1272           (setq toplevel-closure t)))
1273
1274       (dolist (component components)
1275         (compile-component component)
1276         (when (replace-toplevel-xeps component)
1277           (setq toplevel-closure t)))
1278         
1279       (when *check-consistency*
1280         (maybe-mumble "[check]~%")
1281         (check-ir1-consistency *all-components*))
1282         
1283       (if load-time-value-p
1284           (compile-load-time-value-lambda lambdas)
1285           (compile-toplevel-lambdas lambdas toplevel-closure))
1286
1287       (mapc #'clear-ir1-info components)
1288       (clear-stuff)))
1289   (values))
1290
1291 ;;; Actually compile any stuff that has been queued up for block
1292 ;;; compilation.
1293 (defun finish-block-compilation ()
1294   (when *block-compile*
1295     (when *toplevel-lambdas*
1296       (compile-toplevel (nreverse *toplevel-lambdas*) nil)
1297       (setq *toplevel-lambdas* ()))
1298     (setq *block-compile* nil)
1299     (setq *entry-points* nil)))
1300
1301 ;;; Read all forms from INFO and compile them, with output to OBJECT.
1302 ;;; Return (VALUES NIL WARNINGS-P FAILURE-P).
1303 (defun sub-compile-file (info)
1304   (declare (type source-info info))
1305   (let* ((*block-compile* *block-compile-argument*)
1306          (*package* (sane-package))
1307          (*policy* *policy*)
1308          (*lexenv* (make-null-lexenv))
1309          (*source-info* info)
1310          (sb!xc:*compile-file-pathname* nil)
1311          (sb!xc:*compile-file-truename* nil)
1312          (*toplevel-lambdas* ())
1313          (*pending-toplevel-lambdas* ())
1314          (*compiler-error-bailout*
1315           (lambda ()
1316             (compiler-mumble "~2&; fatal error, aborting compilation~%")
1317             (return-from sub-compile-file (values nil t t))))
1318          (*current-path* nil)
1319          (*last-source-context* nil)
1320          (*last-original-source* nil)
1321          (*last-source-form* nil)
1322          (*last-format-string* nil)
1323          (*last-format-args* nil)
1324          (*last-message-count* 0)
1325          ;; FIXME: Do we need this rebinding here? It's a literal
1326          ;; translation of the old CMU CL rebinding to
1327          ;; (OR *BACKEND-INFO-ENVIRONMENT* *INFO-ENVIRONMENT*),
1328          ;; and it's not obvious whether the rebinding to itself is
1329          ;; needed that SBCL doesn't need *BACKEND-INFO-ENVIRONMENT*.
1330          (*info-environment* *info-environment*)
1331          (*gensym-counter* 0))
1332     (handler-case
1333         (with-compilation-values
1334          (sb!xc:with-compilation-unit ()
1335            (clear-stuff)
1336
1337            (sub-sub-compile-file info)
1338
1339            (finish-block-compilation)
1340            (compile-toplevel-lambdas () t)
1341            (let ((object *compile-object*))
1342              (etypecase object
1343                (fasl-output (fasl-dump-source-info info object))
1344                (core-object (fix-core-source-info info object))
1345                (null)))
1346            nil))
1347       ;; Some errors are sufficiently bewildering that we just fail
1348       ;; immediately, without trying to recover and compile more of
1349       ;; the input file.
1350       (input-error-in-compile-file (condition)
1351        (format *error-output*
1352                "~@<compilation aborted because of input error: ~2I~_~A~:>"
1353                condition)
1354        (values nil t t)))))
1355
1356 ;;; Return a pathname for the named file. The file must exist.
1357 (defun verify-source-file (pathname-designator)
1358   (let* ((pathname (pathname pathname-designator))
1359          (default-host (make-pathname :host (pathname-host pathname))))
1360     (flet ((try-with-type (path type error-p)
1361              (let ((new (merge-pathnames
1362                          path (make-pathname :type type
1363                                              :defaults default-host))))
1364                (if (probe-file new)
1365                    new
1366                    (and error-p (truename new))))))
1367       (cond ((typep pathname 'logical-pathname)
1368              (try-with-type pathname "LISP" t))
1369             ((probe-file pathname) pathname)
1370             ((try-with-type pathname "lisp"  nil))
1371             ((try-with-type pathname "lisp"  t))))))
1372
1373 (defun elapsed-time-to-string (tsec)
1374   (multiple-value-bind (tmin sec) (truncate tsec 60)
1375     (multiple-value-bind (thr min) (truncate tmin 60)
1376       (format nil "~D:~2,'0D:~2,'0D" thr min sec))))
1377
1378 ;;; Print some junk at the beginning and end of compilation.
1379 (defun start-error-output (source-info)
1380   (declare (type source-info source-info))
1381   (let ((file-info (source-info-file-info source-info)))
1382     (compiler-mumble "~&; compiling file ~S (written ~A):~%"
1383                      (namestring (file-info-name file-info))
1384                      (sb!int:format-universal-time nil
1385                                                    (file-info-write-date
1386                                                     file-info)
1387                                                    :style :government
1388                                                    :print-weekday nil
1389                                                    :print-timezone nil)))
1390   (values))
1391 (defun finish-error-output (source-info won)
1392   (declare (type source-info source-info))
1393   (compiler-mumble "~&; compilation ~:[aborted after~;finished in~] ~A~&"
1394                    won
1395                    (elapsed-time-to-string
1396                     (- (get-universal-time)
1397                        (source-info-start-time source-info))))
1398   (values))
1399
1400 ;;; Open some files and call SUB-COMPILE-FILE. If something unwinds
1401 ;;; out of the compile, then abort the writing of the output file, so
1402 ;;; that we don't overwrite it with known garbage.
1403 (defun sb!xc:compile-file
1404     (input-file
1405      &key
1406
1407      ;; ANSI options
1408      (output-file (cfp-output-file-default input-file))
1409      ;; FIXME: ANSI doesn't seem to say anything about
1410      ;; *COMPILE-VERBOSE* and *COMPILE-PRINT* being rebound by this
1411      ;; function..
1412      ((:verbose sb!xc:*compile-verbose*) sb!xc:*compile-verbose*)
1413      ((:print sb!xc:*compile-print*) sb!xc:*compile-print*)
1414      (external-format :default)
1415
1416      ;; extensions
1417      (trace-file nil) 
1418      ((:block-compile *block-compile-argument*) nil))
1419
1420   #!+sb-doc
1421   "Compile INPUT-FILE, producing a corresponding fasl file and returning
1422    its filename. Besides the ANSI &KEY arguments :OUTPUT-FILE, :VERBOSE,
1423    :PRINT, and :EXTERNAL-FORMAT,the following extensions are supported:
1424      :TRACE-FILE
1425         If given, internal data structures are dumped to the specified
1426         file, or if a value of T is given, to a file of *.trace type
1427         derived from the input file name.
1428    Also, as a workaround for vaguely-non-ANSI behavior, the :BLOCK-COMPILE
1429    argument is quasi-supported, to determine whether multiple
1430    functions are compiled together as a unit, resolving function
1431    references at compile time. NIL means that global function names
1432    are never resolved at compilation time. Currently NIL is the
1433    default behavior, because although section 3.2.2.3, \"Semantic
1434    Constraints\", of the ANSI spec allows this behavior under all
1435    circumstances, the compiler's runtime scales badly when it
1436    tries to do this for large files. If/when this performance
1437    problem is fixed, the block compilation default behavior will
1438    probably be made dependent on the SPEED and COMPILATION-SPEED
1439    optimization values, and the :BLOCK-COMPILE argument will probably
1440    become deprecated."
1441
1442   (unless (eq external-format :default)
1443     (error "Non-:DEFAULT EXTERNAL-FORMAT values are not supported."))
1444   (let* ((fasl-output nil)
1445          (output-file-name nil)
1446          (compile-won nil)
1447          (warnings-p nil)
1448          (failure-p t) ; T in case error keeps this from being set later
1449          (input-pathname (verify-source-file input-file))
1450          (source-info (make-file-source-info input-pathname))
1451          (*compiler-trace-output* nil)) ; might be modified below
1452                                 
1453     (unwind-protect
1454         (progn
1455           (when output-file
1456             (setq output-file-name
1457                   (sb!xc:compile-file-pathname input-file
1458                                                :output-file output-file))
1459             (setq fasl-output
1460                   (open-fasl-output output-file-name
1461                                     (namestring input-pathname))))
1462           (when trace-file
1463             (let* ((default-trace-file-pathname
1464                      (make-pathname :type "trace" :defaults input-pathname))
1465                    (trace-file-pathname
1466                     (if (eql trace-file t)
1467                         default-trace-file-pathname
1468                         (merge-pathnames trace-file
1469                                          default-trace-file-pathname))))
1470               (setf *compiler-trace-output*
1471                     (open trace-file-pathname
1472                           :if-exists :supersede
1473                           :direction :output))))
1474
1475           (when sb!xc:*compile-verbose*
1476             (start-error-output source-info))
1477           (let ((*compile-object* fasl-output)
1478                 dummy)
1479             (multiple-value-setq (dummy warnings-p failure-p)
1480               (sub-compile-file source-info)))
1481           (setq compile-won t))
1482
1483       (close-source-info source-info)
1484
1485       (when fasl-output
1486         (close-fasl-output fasl-output (not compile-won))
1487         (setq output-file-name
1488               (pathname (fasl-output-stream fasl-output)))
1489         (when (and compile-won sb!xc:*compile-verbose*)
1490           (compiler-mumble "~2&; ~A written~%" (namestring output-file-name))))
1491
1492       (when sb!xc:*compile-verbose*
1493         (finish-error-output source-info compile-won))
1494
1495       (when *compiler-trace-output*
1496         (close *compiler-trace-output*)))
1497
1498     (values (if output-file
1499                 ;; Hack around filesystem race condition...
1500                 (or (probe-file output-file-name) output-file-name)
1501                 nil)
1502             warnings-p
1503             failure-p)))
1504 \f
1505 ;;; a helper function for COMPILE-FILE-PATHNAME: the default for
1506 ;;; the OUTPUT-FILE argument
1507 ;;;
1508 ;;; ANSI: The defaults for the OUTPUT-FILE are taken from the pathname
1509 ;;; that results from merging the INPUT-FILE with the value of
1510 ;;; *DEFAULT-PATHNAME-DEFAULTS*, except that the type component should
1511 ;;; default to the appropriate implementation-defined default type for
1512 ;;; compiled files.
1513 (defun cfp-output-file-default (input-file)
1514   (let* ((defaults (merge-pathnames input-file *default-pathname-defaults*))
1515          (retyped (make-pathname :type *fasl-file-type* :defaults defaults)))
1516     retyped))
1517         
1518 ;;; KLUDGE: Part of the ANSI spec for this seems contradictory:
1519 ;;;   If INPUT-FILE is a logical pathname and OUTPUT-FILE is unsupplied,
1520 ;;;   the result is a logical pathname. If INPUT-FILE is a logical
1521 ;;;   pathname, it is translated into a physical pathname as if by
1522 ;;;   calling TRANSLATE-LOGICAL-PATHNAME.
1523 ;;; So I haven't really tried to make this precisely ANSI-compatible
1524 ;;; at the level of e.g. whether it returns logical pathname or a
1525 ;;; physical pathname. Patches to make it more correct are welcome.
1526 ;;; -- WHN 2000-12-09
1527 (defun sb!xc:compile-file-pathname (input-file
1528                                     &key
1529                                     (output-file (cfp-output-file-default
1530                                                   input-file))
1531                                     &allow-other-keys)
1532   #!+sb-doc
1533   "Return a pathname describing what file COMPILE-FILE would write to given
1534    these arguments."
1535   (pathname output-file))
1536 \f
1537 ;;;; MAKE-LOAD-FORM stuff
1538
1539 ;;; The entry point for MAKE-LOAD-FORM support. When IR1 conversion
1540 ;;; finds a constant structure, it invokes this to arrange for proper
1541 ;;; dumping. If it turns out that the constant has already been
1542 ;;; dumped, then we don't need to do anything.
1543 ;;;
1544 ;;; If the constant hasn't been dumped, then we check to see whether
1545 ;;; we are in the process of creating it. We detect this by
1546 ;;; maintaining the special *CONSTANTS-BEING-CREATED* as a list of all
1547 ;;; the constants we are in the process of creating. Actually, each
1548 ;;; entry is a list of the constant and any init forms that need to be
1549 ;;; processed on behalf of that constant.
1550 ;;;
1551 ;;; It's not necessarily an error for this to happen. If we are
1552 ;;; processing the init form for some object that showed up *after*
1553 ;;; the original reference to this constant, then we just need to
1554 ;;; defer the processing of that init form. To detect this, we
1555 ;;; maintain *CONSTANTS-CREATED-SINCE-LAST-INIT* as a list of the
1556 ;;; constants created since the last time we started processing an
1557 ;;; init form. If the constant passed to emit-make-load-form shows up
1558 ;;; in this list, then there is a circular chain through creation
1559 ;;; forms, which is an error.
1560 ;;;
1561 ;;; If there is some intervening init form, then we blow out of
1562 ;;; processing it by throwing to the tag PENDING-INIT. The value we
1563 ;;; throw is the entry from *CONSTANTS-BEING-CREATED*. This is so the
1564 ;;; offending init form can be tacked onto the init forms for the
1565 ;;; circular object.
1566 ;;;
1567 ;;; If the constant doesn't show up in *CONSTANTS-BEING-CREATED*, then
1568 ;;; we have to create it. We call MAKE-LOAD-FORM and check to see
1569 ;;; whether the creation form is the magic value
1570 ;;; :JUST-DUMP-IT-NORMALLY. If it is, then we don't do anything. The
1571 ;;; dumper will eventually get its hands on the object and use the
1572 ;;; normal structure dumping noise on it.
1573 ;;;
1574 ;;; Otherwise, we bind *CONSTANTS-BEING-CREATED* and
1575 ;;; *CONSTANTS-CREATED-SINCE- LAST-INIT* and compile the creation form
1576 ;;; much the way LOAD-TIME-VALUE does. When this finishes, we tell the
1577 ;;; dumper to use that result instead whenever it sees this constant.
1578 ;;;
1579 ;;; Now we try to compile the init form. We bind
1580 ;;; *CONSTANTS-CREATED-SINCE-LAST-INIT* to NIL and compile the init
1581 ;;; form (and any init forms that were added because of circularity
1582 ;;; detection). If this works, great. If not, we add the init forms to
1583 ;;; the init forms for the object that caused the problems and let it
1584 ;;; deal with it.
1585 (defvar *constants-being-created* nil)
1586 (defvar *constants-created-since-last-init* nil)
1587 ;;; FIXME: Shouldn't these^ variables be bound in LET forms?
1588 (defun emit-make-load-form (constant)
1589   (aver (fasl-output-p *compile-object*))
1590   (unless (or (fasl-constant-already-dumped-p constant *compile-object*)
1591               ;; KLUDGE: This special hack is because I was too lazy
1592               ;; to rework DEF!STRUCT so that the MAKE-LOAD-FORM
1593               ;; function of LAYOUT returns nontrivial forms when
1594               ;; building the cross-compiler but :IGNORE-IT when
1595               ;; cross-compiling or running under the target Lisp. --
1596               ;; WHN 19990914
1597               #+sb-xc-host (typep constant 'layout))
1598     (let ((circular-ref (assoc constant *constants-being-created* :test #'eq)))
1599       (when circular-ref
1600         (when (find constant *constants-created-since-last-init* :test #'eq)
1601           (throw constant t))
1602         (throw 'pending-init circular-ref)))
1603     (multiple-value-bind (creation-form init-form)
1604         (handler-case
1605             (sb!xc:make-load-form constant (make-null-lexenv))
1606           (error (condition)
1607                  (compiler-error "(while making load form for ~S)~%~A"
1608                                  constant
1609                                  condition)))
1610       (case creation-form
1611         (:just-dump-it-normally
1612          (fasl-validate-structure constant *compile-object*)
1613          t)
1614         (:ignore-it
1615          nil)
1616         (t
1617          (compile-toplevel-lambdas () t)
1618          (when (fasl-constant-already-dumped-p constant *compile-object*)
1619            (return-from emit-make-load-form nil))
1620          (let* ((name (let ((*print-level* 1) (*print-length* 2))
1621                         (with-output-to-string (stream)
1622                           (write constant :stream stream))))
1623                 (info (if init-form
1624                           (list constant name init-form)
1625                           (list constant))))
1626            (let ((*constants-being-created*
1627                   (cons info *constants-being-created*))
1628                  (*constants-created-since-last-init*
1629                   (cons constant *constants-created-since-last-init*)))
1630              (when
1631                  (catch constant
1632                    (fasl-note-handle-for-constant
1633                     constant
1634                     (compile-load-time-value
1635                      creation-form
1636                      (format nil "creation form for ~A" name))
1637                     *compile-object*)
1638                    nil)
1639                (compiler-error "circular references in creation form for ~S"
1640                                constant)))
1641            (when (cdr info)
1642              (let* ((*constants-created-since-last-init* nil)
1643                     (circular-ref
1644                      (catch 'pending-init
1645                        (loop for (name form) on (cdr info) by #'cddr
1646                          collect name into names
1647                          collect form into forms
1648                          finally
1649                          (compile-make-load-form-init-forms
1650                           forms
1651                           (format nil "init form~:[~;s~] for ~{~A~^, ~}"
1652                                   (cdr forms) names)))
1653                        nil)))
1654                (when circular-ref
1655                  (setf (cdr circular-ref)
1656                        (append (cdr circular-ref) (cdr info))))))))))))