bind and clear *LIST-CONFLICTS-TABLE* in LIST-CONFLICTS
[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                   *continuation-number* *continuation-numbers*
21                   *number-continuations* *tn-id* *tn-ids* *id-tns*
22                   *label-ids* *label-id* *id-labels*
23                   *undefined-warnings* *compiler-error-count*
24                   *compiler-warning-count* *compiler-style-warning-count*
25                   *compiler-note-count*
26                   *compiler-error-bailout*
27                   #!+sb-show *compiler-trace-output*
28                   *last-source-context* *last-original-source*
29                   *last-source-form* *last-format-string* *last-format-args*
30                   *last-message-count* *last-error-context*
31                   *lexenv* *fun-names-in-this-file*
32                   *allow-instrumenting*))
33
34 ;;; Whether reference to a thing which cannot be defined causes a full
35 ;;; warning.
36 (defvar *flame-on-necessarily-undefined-thing* nil)
37
38 (defvar *check-consistency* nil)
39
40 ;;; Set to NIL to disable loop analysis for register allocation.
41 (defvar *loop-analyze* t)
42
43 ;;; Bind this to a stream to capture various internal debugging output.
44 (defvar *compiler-trace-output* nil)
45
46 ;;; The current block compilation state. These are initialized to the
47 ;;; :BLOCK-COMPILE and :ENTRY-POINTS arguments that COMPILE-FILE was
48 ;;; called with.
49 ;;;
50 ;;; *BLOCK-COMPILE-ARG* holds the original value of the :BLOCK-COMPILE
51 ;;; argument, which overrides any internal declarations.
52 (defvar *block-compile*)
53 (defvar *block-compile-arg*)
54 (declaim (type (member nil t :specified) *block-compile* *block-compile-arg*))
55 (defvar *entry-points*)
56 (declaim (list *entry-points*))
57
58 ;;; When block compiling, used by PROCESS-FORM to accumulate top level
59 ;;; lambdas resulting from compiling subforms. (In reverse order.)
60 (defvar *toplevel-lambdas*)
61 (declaim (list *toplevel-lambdas*))
62
63 ;;; The current non-macroexpanded toplevel form as printed when
64 ;;; *compile-print* is true.
65 (defvar *top-level-form-noted* nil)
66
67 (defvar sb!xc:*compile-verbose* t
68   #!+sb-doc
69   "The default for the :VERBOSE argument to COMPILE-FILE.")
70 (defvar sb!xc:*compile-print* t
71   #!+sb-doc
72   "The default for the :PRINT argument to COMPILE-FILE.")
73 (defvar *compile-progress* nil
74   #!+sb-doc
75   "When this is true, the compiler prints to *STANDARD-OUTPUT* progress
76   information about the phases of compilation of each function. (This
77   is useful mainly in large block compilations.)")
78
79 (defvar sb!xc:*compile-file-pathname* nil
80   #!+sb-doc
81   "The defaulted pathname of the file currently being compiled, or NIL if not
82   compiling.")
83 (defvar sb!xc:*compile-file-truename* nil
84   #!+sb-doc
85   "The TRUENAME of the file currently being compiled, or NIL if not
86   compiling.")
87
88 (declaim (type (or pathname null)
89                sb!xc:*compile-file-pathname*
90                sb!xc:*compile-file-truename*))
91
92 ;;; the SOURCE-INFO structure for the current compilation. This is
93 ;;; null globally to indicate that we aren't currently in any
94 ;;; identifiable compilation.
95 (defvar *source-info* nil)
96
97 ;;; This is true if we are within a WITH-COMPILATION-UNIT form (which
98 ;;; normally causes nested uses to be no-ops).
99 (defvar *in-compilation-unit* nil)
100
101 ;;; Count of the number of compilation units dynamically enclosed by
102 ;;; the current active WITH-COMPILATION-UNIT that were unwound out of.
103 (defvar *aborted-compilation-unit-count*)
104
105 ;;; Mumble conditional on *COMPILE-PROGRESS*.
106 (defun maybe-mumble (&rest foo)
107   (when *compile-progress*
108     (compiler-mumble "~&")
109     (pprint-logical-block (*standard-output* nil :per-line-prefix "; ")
110        (apply #'compiler-mumble foo))))
111
112 (deftype object () '(or fasl-output core-object null))
113
114 (defvar *compile-object* nil)
115 (declaim (type object *compile-object*))
116 (defvar *compile-toplevel-object* nil)
117
118 (defvar *emit-cfasl* nil)
119
120 (defvar *fopcompile-label-counter*)
121
122 ;; Used during compilation to map code paths to the matching
123 ;; instrumentation conses.
124 (defvar *code-coverage-records* nil)
125 ;; Used during compilation to keep track of with source paths have been
126 ;; instrumented in which blocks.
127 (defvar *code-coverage-blocks* nil)
128 ;; Stores the code coverage instrumentation results. Keys are namestrings,
129 ;; the value is a list of (CONS PATH STATE), where STATE is NIL for
130 ;; a path that has not been visited, and T for one that has.
131 (defvar *code-coverage-info* (make-hash-table :test 'equal))
132
133 \f
134 ;;;; WITH-COMPILATION-UNIT and WITH-COMPILATION-VALUES
135
136 (defmacro sb!xc:with-compilation-unit (options &body body)
137   #!+sb-doc
138   "Affects compilations that take place within its dynamic extent. It is
139 intended to be eg. wrapped around the compilation of all files in the same system.
140
141 Following options are defined:
142
143   :OVERRIDE Boolean-Form
144       One of the effects of this form is to delay undefined warnings until the
145       end of the form, instead of giving them at the end of each compilation.
146       If OVERRIDE is NIL (the default), then the outermost
147       WITH-COMPILATION-UNIT form grabs the undefined warnings. Specifying
148       OVERRIDE true causes that form to grab any enclosed warnings, even if it
149       is enclosed by another WITH-COMPILATION-UNIT.
150
151   :POLICY Optimize-Declaration-Form
152       Provides dynamic scoping for global compiler optimization qualities and
153       restrictions, limiting effects of subsequent OPTIMIZE proclamations and
154       calls to SB-EXT:RESTRICT-COMPILER-POLICY to the dynamic scope of BODY.
155
156       If OVERRIDE is false, specified POLICY is merged with current global
157       policy. If OVERRIDE is true, current global policy, including any
158       restrictions, is discarded in favor of the specified POLICY.
159
160       Supplying POLICY NIL is equivalent to the option not being supplied at
161       all, ie. dynamic scoping of policy does not take place.
162
163       This option is an SBCL-specific experimental extension: Interface
164       subject to change.
165
166   :SOURCE-NAMESTRING Namestring-Form
167       Attaches the value returned by the Namestring-Form to the internal
168       debug-source information as the namestring of the source file. Normally
169       the namestring of the input-file for COMPILE-FILE is used: this option
170       can be used to provide source-file information for functions compiled
171       using COMPILE, or to override the input-file of COMPILE-FILE.
172
173       If both an outer and an inner WITH-COMPILATION-UNIT provide a
174       SOURCE-NAMESTRING, the inner one takes precedence. Unaffected
175       by :OVERRIDE.
176
177       This is an SBCL-specific extension.
178
179   :SOURCE-PLIST Plist-Form
180       Attaches the value returned by the Plist-Form to internal debug-source
181       information of functions compiled in within the dynamic extent of BODY.
182
183       Primarily for use by development environments, in order to eg. associate
184       function definitions with editor-buffers. Can be accessed using
185       SB-INTROSPECT:DEFINITION-SOURCE-PLIST.
186
187       If an outer WITH-COMPILATION-UNIT form also provide a SOURCE-PLIST, it
188       is appended to the end of the provided SOURCE-PLIST. Unaffected
189       by :OVERRIDE.
190
191       This is an SBCL-specific extension.
192
193 Examples:
194
195   ;; Prevent proclamations from the file leaking, and restrict
196   ;; SAFETY to 3 -- otherwise uses the current global policy.
197   (with-compilation-unit (:policy '(optimize))
198     (restrict-compiler-policy 'safety 3)
199     (load \"foo.lisp\"))
200
201   ;; Using default policy instead of the current global one,
202   ;; except for DEBUG 3.
203   (with-compilation-unit (:policy '(optimize debug)
204                           :override t)
205     (load \"foo.lisp\"))
206
207   ;; Same as if :POLICY had not been specified at all: SAFETY 3
208   ;; proclamation leaks out from WITH-COMPILATION-UNIT.
209   (with-compilation-unit (:policy nil)
210     (declaim (optimize safety))
211     (load \"foo.lisp\"))
212 "
213   `(%with-compilation-unit (lambda () ,@body) ,@options))
214
215 (defvar *source-plist* nil)
216 (defvar *source-namestring* nil)
217
218 (defun %with-compilation-unit (fn &key override policy source-plist source-namestring)
219   (declare (type function fn))
220   (flet ((with-it ()
221            (let ((succeeded-p nil)
222                  (*source-plist* (append source-plist *source-plist*))
223                  (*source-namestring* (or source-namestring *source-namestring*)))
224              (if (and *in-compilation-unit* (not override))
225                  ;; Inside another WITH-COMPILATION-UNIT, a WITH-COMPILATION-UNIT is
226                  ;; ordinarily (unless OVERRIDE) basically a no-op.
227                  (unwind-protect
228                       (multiple-value-prog1 (funcall fn) (setf succeeded-p t))
229                    (unless succeeded-p
230                      (incf *aborted-compilation-unit-count*)))
231                  (let ((*aborted-compilation-unit-count* 0)
232                        (*compiler-error-count* 0)
233                        (*compiler-warning-count* 0)
234                        (*compiler-style-warning-count* 0)
235                        (*compiler-note-count* 0)
236                        (*undefined-warnings* nil)
237                        (*in-compilation-unit* t))
238                    (handler-bind ((parse-unknown-type
239                                     (lambda (c)
240                                       (note-undefined-reference
241                                        (parse-unknown-type-specifier c)
242                                        :type))))
243                      (unwind-protect
244                           (multiple-value-prog1 (funcall fn) (setf succeeded-p t))
245                        (unless succeeded-p
246                          (incf *aborted-compilation-unit-count*))
247                        (summarize-compilation-unit (not succeeded-p)))))))))
248     (if policy
249         (let ((*policy* (process-optimize-decl policy (unless override *policy*)))
250               (*policy-restrictions* (unless override *policy-restrictions*)))
251           (with-it))
252         (with-it))))
253
254 ;;; Is NAME something that no conforming program can rely on
255 ;;; defining?
256 (defun name-reserved-by-ansi-p (name kind)
257   (ecase kind
258     (:function
259      (eq (symbol-package (fun-name-block-name name))
260          *cl-package*))
261     (:type
262      (let ((symbol (typecase name
263                      (symbol name)
264                      ((cons symbol) (car name))
265                      (t (return-from name-reserved-by-ansi-p nil)))))
266        (eq (symbol-package symbol) *cl-package*)))))
267
268 ;;; This is to be called at the end of a compilation unit. It signals
269 ;;; any residual warnings about unknown stuff, then prints the total
270 ;;; error counts. ABORT-P should be true when the compilation unit was
271 ;;; aborted by throwing out. ABORT-COUNT is the number of dynamically
272 ;;; enclosed nested compilation units that were aborted.
273 (defun summarize-compilation-unit (abort-p)
274   (let (summary)
275     (unless abort-p
276       (handler-bind ((style-warning #'compiler-style-warning-handler)
277                      (warning #'compiler-warning-handler))
278
279         (let ((undefs (sort *undefined-warnings* #'string<
280                             :key (lambda (x)
281                                    (let ((x (undefined-warning-name x)))
282                                      (if (symbolp x)
283                                          (symbol-name x)
284                                          (prin1-to-string x)))))))
285           (dolist (kind '(:variable :function :type))
286             (let ((names (mapcar #'undefined-warning-name
287                                    (remove kind undefs :test #'neq
288                                            :key #'undefined-warning-kind))))
289               (when names (push (cons kind names) summary))))
290           (dolist (undef undefs)
291             (let ((name (undefined-warning-name undef))
292                   (kind (undefined-warning-kind undef))
293                   (warnings (undefined-warning-warnings undef))
294                   (undefined-warning-count (undefined-warning-count undef)))
295               (dolist (*compiler-error-context* warnings)
296                 (if #-sb-xc-host (and (member kind '(:function :type))
297                                       (name-reserved-by-ansi-p name kind)
298                                       *flame-on-necessarily-undefined-thing*)
299                     #+sb-xc-host nil
300                     (ecase kind
301                       (:function
302                        (case name
303                          ((declare)
304                           (compiler-warn
305                            "~@<There is no function named ~S. References to ~S ~
306                             in some contexts (like starts of blocks) have ~
307                             special meaning, but here it would have to be a ~
308                             function, and that shouldn't be right.~:@>" name
309                             name))
310                          (t
311                           (compiler-warn
312                            "~@<The function ~S is undefined, and its name is ~
313                             reserved by ANSI CL so that even if it were ~
314                             defined later, the code doing so would not be ~
315                             portable.~:@>" name))))
316                       (:type
317                        (if (and (consp name) (eq 'quote (car name)))
318                            (compiler-warn
319                             "~@<Undefined type ~S. The name starts with ~S: ~
320                              probably use of a quoted type name in a context ~
321                              where the name is not evaluated.~:@>"
322                             name 'quote)
323                            (compiler-warn
324                             "~@<Undefined type ~S. Note that name ~S is ~
325                              reserved by ANSI CL, so code defining a type with ~
326                              that name would not be portable.~:@>" name
327                              name))))
328                     (if (eq kind :variable)
329                         (compiler-warn "undefined ~(~A~): ~S" kind name)
330                         (compiler-style-warn "undefined ~(~A~): ~S" kind name))))
331               (let ((warn-count (length warnings)))
332                 (when (and warnings (> undefined-warning-count warn-count))
333                   (let ((more (- undefined-warning-count warn-count)))
334                     (if (eq kind :variable)
335                         (compiler-warn
336                          "~W more use~:P of undefined ~(~A~) ~S"
337                          more kind name)
338                         (compiler-style-warn
339                          "~W more use~:P of undefined ~(~A~) ~S"
340                          more kind name))))))))))
341
342     (unless (and (not abort-p)
343                  (zerop *aborted-compilation-unit-count*)
344                  (zerop *compiler-error-count*)
345                  (zerop *compiler-warning-count*)
346                  (zerop *compiler-style-warning-count*)
347                  (zerop *compiler-note-count*))
348       (pprint-logical-block (*error-output* nil :per-line-prefix "; ")
349         (format *error-output* "~&compilation unit ~:[finished~;aborted~]"
350                 abort-p)
351         (dolist (cell summary)
352           (destructuring-bind (kind &rest names) cell
353             (format *error-output*
354                     "~&  Undefined ~(~A~)~p:~
355                      ~%    ~{~<~% ~1:;~S~>~^ ~}"
356                     kind (length names) names)))
357         (format *error-output* "~[~:;~:*~&  caught ~W fatal ERROR condition~:P~]~
358                                 ~[~:;~:*~&  caught ~W ERROR condition~:P~]~
359                                 ~[~:;~:*~&  caught ~W WARNING condition~:P~]~
360                                 ~[~:;~:*~&  caught ~W STYLE-WARNING condition~:P~]~
361                                 ~[~:;~:*~&  printed ~W note~:P~]"
362                 *aborted-compilation-unit-count*
363                 *compiler-error-count*
364                 *compiler-warning-count*
365                 *compiler-style-warning-count*
366                 *compiler-note-count*))
367       (terpri *error-output*)
368       (force-output *error-output*))))
369
370 ;;; Evaluate BODY, then return (VALUES BODY-VALUE WARNINGS-P
371 ;;; FAILURE-P), where BODY-VALUE is the first value of the body, and
372 ;;; WARNINGS-P and FAILURE-P are as in CL:COMPILE or CL:COMPILE-FILE.
373 ;;; This also wraps up WITH-IR1-NAMESPACE functionality.
374 (defmacro with-compilation-values (&body body)
375   `(with-ir1-namespace
376     (let ((*warnings-p* nil)
377           (*failure-p* nil))
378       (values (progn ,@body)
379               *warnings-p*
380               *failure-p*))))
381 \f
382 ;;;; component compilation
383
384 (defparameter *max-optimize-iterations* 3 ; ARB
385   #!+sb-doc
386   "The upper limit on the number of times that we will consecutively do IR1
387   optimization that doesn't introduce any new code. A finite limit is
388   necessary, since type inference may take arbitrarily long to converge.")
389
390 (defevent ir1-optimize-until-done "IR1-OPTIMIZE-UNTIL-DONE called")
391 (defevent ir1-optimize-maxed-out "hit *MAX-OPTIMIZE-ITERATIONS* limit")
392
393 ;;; Repeatedly optimize COMPONENT until no further optimizations can
394 ;;; be found or we hit our iteration limit. When we hit the limit, we
395 ;;; clear the component and block REOPTIMIZE flags to discourage the
396 ;;; next optimization attempt from pounding on the same code.
397 (defun ir1-optimize-until-done (component)
398   (declare (type component component))
399   (maybe-mumble "opt")
400   (event ir1-optimize-until-done)
401   (let ((count 0)
402         (cleared-reanalyze nil)
403         (fastp nil))
404     (loop
405       (when (component-reanalyze component)
406         (setq count 0)
407         (setq cleared-reanalyze t)
408         (setf (component-reanalyze component) nil))
409       (setf (component-reoptimize component) nil)
410       (ir1-optimize component fastp)
411       (cond ((component-reoptimize component)
412              (incf count)
413              (when (and (>= count *max-optimize-iterations*)
414                         (not (component-reanalyze component))
415                         (eq (component-reoptimize component) :maybe))
416                (maybe-mumble "*")
417                (cond ((retry-delayed-ir1-transforms :optimize)
418                       (maybe-mumble "+")
419                       (setq count 0))
420                      (t
421                       (event ir1-optimize-maxed-out)
422                       (setf (component-reoptimize component) nil)
423                       (do-blocks (block component)
424                         (setf (block-reoptimize block) nil))
425                       (return)))))
426             ((retry-delayed-ir1-transforms :optimize)
427              (setf count 0)
428              (maybe-mumble "+"))
429             (t
430              (maybe-mumble " ")
431              (return)))
432       (setq fastp (>= count *max-optimize-iterations*))
433       (maybe-mumble (if fastp "-" ".")))
434     (when cleared-reanalyze
435       (setf (component-reanalyze component) t)))
436   (values))
437
438 (defparameter *constraint-propagate* t)
439
440 ;;; KLUDGE: This was bumped from 5 to 10 in a DTC patch ported by MNA
441 ;;; from CMU CL into sbcl-0.6.11.44, the same one which allowed IR1
442 ;;; transforms to be delayed. Either DTC or MNA or both didn't explain
443 ;;; why, and I don't know what the rationale was. -- WHN 2001-04-28
444 ;;;
445 ;;; FIXME: It would be good to document why it's important to have a
446 ;;; large value here, and what the drawbacks of an excessively large
447 ;;; value are; and it might also be good to make it depend on
448 ;;; optimization policy.
449 (defparameter *reoptimize-after-type-check-max* 10)
450
451 (defevent reoptimize-maxed-out
452   "*REOPTIMIZE-AFTER-TYPE-CHECK-MAX* exceeded.")
453
454 ;;; Iterate doing FIND-DFO until no new dead code is discovered.
455 (defun dfo-as-needed (component)
456   (declare (type component component))
457   (when (component-reanalyze component)
458     (maybe-mumble "DFO")
459     (loop
460       (find-dfo component)
461       (unless (component-reanalyze component)
462         (maybe-mumble " ")
463         (return))
464       (maybe-mumble ".")))
465   (values))
466
467 ;;; Do all the IR1 phases for a non-top-level component.
468 (defun ir1-phases (component)
469   (declare (type component component))
470   (aver-live-component component)
471   (let ((*constraint-universe* (make-array 64 ; arbitrary, but don't
472                                               ;make this 0.
473                                            :fill-pointer 0 :adjustable t))
474         (loop-count 1)
475         (*delayed-ir1-transforms* nil))
476     (declare (special *constraint-universe* *delayed-ir1-transforms*))
477     (loop
478       (ir1-optimize-until-done component)
479       (when (or (component-new-functionals component)
480                 (component-reanalyze-functionals component))
481         (maybe-mumble "locall ")
482         (locall-analyze-component component))
483       (dfo-as-needed component)
484       (when *constraint-propagate*
485         (maybe-mumble "constraint ")
486         (constraint-propagate component))
487       (when (retry-delayed-ir1-transforms :constraint)
488         (maybe-mumble "Rtran "))
489       (flet ((want-reoptimization-p ()
490                (or (component-reoptimize component)
491                    (component-reanalyze component)
492                    (component-new-functionals component)
493                    (component-reanalyze-functionals component))))
494         (unless (and (want-reoptimization-p)
495                      ;; We delay the generation of type checks until
496                      ;; the type constraints have had time to
497                      ;; propagate, else the compiler can confuse itself.
498                      (< loop-count (- *reoptimize-after-type-check-max* 4)))
499           (maybe-mumble "type ")
500           (generate-type-checks component)
501           (unless (want-reoptimization-p)
502             (return))))
503       (when (>= loop-count *reoptimize-after-type-check-max*)
504         (maybe-mumble "[reoptimize limit]")
505         (event reoptimize-maxed-out)
506         (return))
507       (incf loop-count)))
508
509   (ir1-finalize component)
510   (values))
511
512 (defun %compile-component (component)
513   (let ((*code-segment* nil)
514         (*elsewhere* nil)
515         #!+inline-constants
516         (*constant-segment* nil)
517         #!+inline-constants
518         (*constant-table* nil)
519         #!+inline-constants
520         (*constant-vector* nil))
521     (maybe-mumble "GTN ")
522     (gtn-analyze component)
523     (maybe-mumble "LTN ")
524     (ltn-analyze component)
525     (dfo-as-needed component)
526     (maybe-mumble "control ")
527     (control-analyze component #'make-ir2-block)
528
529     (when (or (ir2-component-values-receivers (component-info component))
530               (component-dx-lvars component))
531       (maybe-mumble "stack ")
532       (stack-analyze component)
533       ;; Assign BLOCK-NUMBER for any cleanup blocks introduced by
534       ;; stack analysis. There shouldn't be any unreachable code after
535       ;; control, so this won't delete anything.
536       (dfo-as-needed component))
537
538     (unwind-protect
539         (progn
540           (maybe-mumble "IR2tran ")
541           (init-assembler)
542           (entry-analyze component)
543           (ir2-convert component)
544
545           (when (policy *lexenv* (>= speed compilation-speed))
546             (maybe-mumble "copy ")
547             (copy-propagate component))
548
549           (ir2-optimize component)
550
551           (select-representations component)
552
553           (when *check-consistency*
554             (maybe-mumble "check2 ")
555             (check-ir2-consistency component))
556
557           (delete-unreferenced-tns component)
558
559           (maybe-mumble "life ")
560           (lifetime-analyze component)
561
562           (when *compile-progress*
563             (compiler-mumble "") ; Sync before doing more output.
564             (pre-pack-tn-stats component *standard-output*))
565
566           (when *check-consistency*
567             (maybe-mumble "check-life ")
568             (check-life-consistency component))
569
570           (maybe-mumble "pack ")
571           (pack component)
572
573           (when *check-consistency*
574             (maybe-mumble "check-pack ")
575             (check-pack-consistency component))
576
577           (when *compiler-trace-output*
578             (describe-component component *compiler-trace-output*)
579             (describe-ir2-component component *compiler-trace-output*))
580
581           (maybe-mumble "code ")
582           (multiple-value-bind (code-length trace-table fixup-notes)
583               (generate-code component)
584
585             #-sb-xc-host
586             (when *compiler-trace-output*
587               (format *compiler-trace-output*
588                       "~|~%disassembly of code for ~S~2%" component)
589               (sb!disassem:disassemble-assem-segment *code-segment*
590                                                      *compiler-trace-output*))
591
592             (etypecase *compile-object*
593               (fasl-output
594                (maybe-mumble "fasl")
595                (fasl-dump-component component
596                                     *code-segment*
597                                     code-length
598                                     trace-table
599                                     fixup-notes
600                                     *compile-object*))
601               (core-object
602                (maybe-mumble "core")
603                (make-core-component component
604                                     *code-segment*
605                                     code-length
606                                     trace-table
607                                     fixup-notes
608                                     *compile-object*))
609               (null))))))
610
611   ;; We're done, so don't bother keeping anything around.
612   (setf (component-info component) :dead)
613
614   (values))
615
616 ;;; Delete components with no external entry points before we try to
617 ;;; generate code. Unreachable closures can cause IR2 conversion to
618 ;;; puke on itself, since it is the reference to the closure which
619 ;;; normally causes the components to be combined.
620 (defun delete-if-no-entries (component)
621   (dolist (fun (component-lambdas component) (delete-component component))
622     (when (functional-has-external-references-p fun)
623       (return))
624     (case (functional-kind fun)
625       (:toplevel (return))
626       (:external
627        (unless (every (lambda (ref)
628                         (eq (node-component ref) component))
629                       (leaf-refs fun))
630          (return))))))
631
632 (defun compile-component (component)
633
634   ;; miscellaneous sanity checks
635   ;;
636   ;; FIXME: These are basically pretty wimpy compared to the checks done
637   ;; by the old CHECK-IR1-CONSISTENCY code. It would be really nice to
638   ;; make those internal consistency checks work again and use them.
639   (aver-live-component component)
640   (do-blocks (block component)
641     (aver (eql (block-component block) component)))
642   (dolist (lambda (component-lambdas component))
643     ;; sanity check to prevent weirdness from propagating insidiously as
644     ;; far from its root cause as it did in bug 138: Make sure that
645     ;; thing-to-COMPONENT links are consistent.
646     (aver (eql (lambda-component lambda) component))
647     (aver (eql (node-component (lambda-bind lambda)) component)))
648
649   (let* ((*component-being-compiled* component))
650
651     ;; Record xref information before optimization. This way the
652     ;; stored xref data reflects the real source as closely as
653     ;; possible.
654     (record-component-xrefs component)
655
656     (ir1-phases component)
657
658     (when *loop-analyze*
659       (dfo-as-needed component)
660       (find-dominators component)
661       (loop-analyze component))
662
663     #|
664     (when (and *loop-analyze* *compiler-trace-output*)
665       (labels ((print-blocks (block)
666                  (format *compiler-trace-output* "    ~A~%" block)
667                  (when (block-loop-next block)
668                    (print-blocks (block-loop-next block))))
669                (print-loop (loop)
670                  (format *compiler-trace-output* "loop=~A~%" loop)
671                  (print-blocks (loop-blocks loop))
672                  (dolist (l (loop-inferiors loop))
673                    (print-loop l))))
674         (print-loop (component-outer-loop component))))
675     |#
676
677     ;; FIXME: What is MAYBE-MUMBLE for? Do we need it any more?
678     (maybe-mumble "env ")
679     (physenv-analyze component)
680     (dfo-as-needed component)
681
682     (delete-if-no-entries component)
683
684     (unless (eq (block-next (component-head component))
685                 (component-tail component))
686       (%compile-component component)))
687
688   (clear-constant-info)
689
690   (values))
691 \f
692 ;;;; clearing global data structures
693 ;;;;
694 ;;;; FIXME: Is it possible to get rid of this stuff, getting rid of
695 ;;;; global data structures entirely when possible and consing up the
696 ;;;; others from scratch instead of clearing and reusing them?
697
698 ;;; Clear the INFO in constants in the *FREE-VARS*, etc. In
699 ;;; addition to allowing stuff to be reclaimed, this is required for
700 ;;; correct assignment of constant offsets, since we need to assign a
701 ;;; new offset for each component. We don't clear the FUNCTIONAL-INFO
702 ;;; slots, since they are used to keep track of functions across
703 ;;; component boundaries.
704 (defun clear-constant-info ()
705   (maphash (lambda (k v)
706              (declare (ignore k))
707              (setf (leaf-info v) nil)
708              (setf (constant-boxed-tn v) nil))
709            *constants*)
710   (maphash (lambda (k v)
711              (declare (ignore k))
712              (when (constant-p v)
713                (setf (leaf-info v) nil)
714                (setf (constant-boxed-tn v) nil)))
715            *free-vars*)
716   (values))
717
718 ;;; Blow away the REFS for all global variables, and let COMPONENT
719 ;;; be recycled.
720 (defun clear-ir1-info (component)
721   (declare (type component component))
722   (labels ((blast (x)
723              (maphash (lambda (k v)
724                         (declare (ignore k))
725                         (when (leaf-p v)
726                           (setf (leaf-refs v)
727                                 (delete-if #'here-p (leaf-refs v)))
728                           (when (basic-var-p v)
729                             (setf (basic-var-sets v)
730                                   (delete-if #'here-p (basic-var-sets v))))))
731                       x))
732            (here-p (x)
733              (eq (node-component x) component)))
734     (blast *free-vars*)
735     (blast *free-funs*)
736     (blast *constants*))
737   (values))
738
739 ;;; Clear global variables used by the compiler.
740 ;;;
741 ;;; FIXME: It seems kinda nasty and unmaintainable to have to do this,
742 ;;; and it adds overhead even when people aren't using the compiler.
743 ;;; Perhaps we could make these global vars unbound except when
744 ;;; actually in use, so that this function could go away.
745 (defun clear-stuff (&optional (debug-too t))
746
747   (when debug-too
748     (clrhash *continuation-numbers*)
749     (clrhash *number-continuations*)
750     (setq *continuation-number* 0)
751     (clrhash *tn-ids*)
752     (clrhash *id-tns*)
753     (setq *tn-id* 0)
754     (clrhash *label-ids*)
755     (clrhash *id-labels*)
756     (setq *label-id* 0))
757
758   ;; (Note: The CMU CL code used to set CL::*GENSYM-COUNTER* to zero here.
759   ;; Superficially, this seemed harmful -- the user could reasonably be
760   ;; surprised if *GENSYM-COUNTER* turned back to zero when something was
761   ;; compiled. A closer inspection showed that this actually turned out to be
762   ;; harmless in practice, because CLEAR-STUFF was only called from within
763   ;; forms which bound CL::*GENSYM-COUNTER* to zero. However, this means that
764   ;; even though zeroing CL::*GENSYM-COUNTER* here turned out to be harmless in
765   ;; practice, it was also useless in practice. So we don't do it any more.)
766
767   (values))
768 \f
769 ;;;; trace output
770
771 ;;; Print out some useful info about COMPONENT to STREAM.
772 (defun describe-component (component *standard-output*)
773   (declare (type component component))
774   (format t "~|~%;;;; component: ~S~2%" (component-name component))
775   (print-all-blocks component)
776   (values))
777
778 (defun describe-ir2-component (component *standard-output*)
779   (format t "~%~|~%;;;; IR2 component: ~S~2%" (component-name component))
780   (format t "entries:~%")
781   (dolist (entry (ir2-component-entries (component-info component)))
782     (format t "~4TL~D: ~S~:[~; [closure]~]~%"
783             (label-id (entry-info-offset entry))
784             (entry-info-name entry)
785             (entry-info-closure-tn entry)))
786   (terpri)
787   (pre-pack-tn-stats component *standard-output*)
788   (terpri)
789   (print-ir2-blocks component)
790   (terpri)
791   (values))
792 \f
793 ;;;; file reading
794 ;;;;
795 ;;;; When reading from a file, we have to keep track of some source
796 ;;;; information. We also exploit our ability to back up for printing
797 ;;;; the error context and for recovering from errors.
798 ;;;;
799 ;;;; The interface we provide to this stuff is the stream-oid
800 ;;;; SOURCE-INFO structure. The bookkeeping is done as a side effect
801 ;;;; of getting the next source form.
802
803 ;;; A FILE-INFO structure holds all the source information for a
804 ;;; given file.
805 (def!struct (file-info
806              (:copier nil)
807              #-no-ansi-print-object
808              (:print-object (lambda (s stream)
809                               (print-unreadable-object (s stream :type t)
810                                 (princ (file-info-name s) stream)))))
811   ;; If a file, the truename of the corresponding source file. If from
812   ;; a Lisp form, :LISP. If from a stream, :STREAM.
813   (name (missing-arg) :type (or pathname (eql :lisp)))
814   ;; the external format that we'll call OPEN with, if NAME is a file.
815   (external-format nil)
816   ;; the defaulted, but not necessarily absolute file name (i.e. prior
817   ;; to TRUENAME call.) Null if not a file. This is used to set
818   ;; *COMPILE-FILE-PATHNAME*, and if absolute, is dumped in the
819   ;; debug-info.
820   (untruename nil :type (or pathname null))
821   ;; the file's write date (if relevant)
822   (write-date nil :type (or unsigned-byte null))
823   ;; the source path root number of the first form in this file (i.e.
824   ;; the total number of forms converted previously in this
825   ;; compilation)
826   (source-root 0 :type unsigned-byte)
827   ;; parallel vectors containing the forms read out of the file and
828   ;; the file positions that reading of each form started at (i.e. the
829   ;; end of the previous form)
830   (forms (make-array 10 :fill-pointer 0 :adjustable t) :type (vector t))
831   (positions (make-array 10 :fill-pointer 0 :adjustable t) :type (vector t)))
832
833 ;;; The SOURCE-INFO structure provides a handle on all the source
834 ;;; information for an entire compilation.
835 (def!struct (source-info
836              #-no-ansi-print-object
837              (:print-object (lambda (s stream)
838                               (print-unreadable-object (s stream :type t))))
839              (:copier nil))
840   ;; the UT that compilation started at
841   (start-time (get-universal-time) :type unsigned-byte)
842   ;; the IRT that compilation started at
843   (start-real-time (get-internal-real-time) :type unsigned-byte)
844   ;; the FILE-INFO structure for this compilation
845   (file-info nil :type (or file-info null))
846   ;; the stream that we are using to read the FILE-INFO, or NIL if
847   ;; no stream has been opened yet
848   (stream nil :type (or stream null))
849   ;; if the current compilation is recursive (e.g., due to EVAL-WHEN
850   ;; processing at compile-time), the invoking compilation's
851   ;; source-info.
852   (parent nil :type (or source-info null)))
853
854 ;;; Given a pathname, return a SOURCE-INFO structure.
855 (defun make-file-source-info (file external-format)
856   (make-source-info
857    :file-info (make-file-info :name (truename file)
858                               :untruename (merge-pathnames file)
859                               :external-format external-format
860                               :write-date (file-write-date file))))
861
862 ;;; Return a SOURCE-INFO to describe the incremental compilation of FORM.
863 (defun make-lisp-source-info (form &key parent)
864   (make-source-info
865    :file-info (make-file-info :name :lisp
866                               :forms (vector form)
867                               :positions '#(0))
868    :parent parent))
869
870 ;;; Walk up the SOURCE-INFO list until we either reach a SOURCE-INFO
871 ;;; with no parent (e.g., from a REPL evaluation) or until we reach a
872 ;;; SOURCE-INFO whose FILE-INFO denotes a file.
873 (defun get-toplevelish-file-info (&optional (source-info *source-info*))
874   (if source-info
875       (do* ((sinfo source-info (source-info-parent sinfo))
876             (finfo (source-info-file-info sinfo)
877                    (source-info-file-info sinfo)))
878            ((or (not (source-info-p (source-info-parent sinfo)))
879                 (pathnamep (file-info-name finfo)))
880             finfo))))
881
882 ;;; Return a form read from STREAM; or for EOF use the trick,
883 ;;; popularized by Kent Pitman, of returning STREAM itself. If an
884 ;;; error happens, then convert it to standard abort-the-compilation
885 ;;; error condition (possibly recording some extra location
886 ;;; information).
887 (defun read-for-compile-file (stream position)
888   (handler-case
889       (read-preserving-whitespace stream nil stream)
890     (reader-error (condition)
891       (compiler-error 'input-error-in-compile-file
892                       ;; We don't need to supply :POSITION here because
893                       ;; READER-ERRORs already know their position in the file.
894                       :condition condition
895                       :stream stream))
896     ;; ANSI, in its wisdom, says that READ should return END-OF-FILE
897     ;; (and that this is not a READER-ERROR) when it encounters end of
898     ;; file in the middle of something it's trying to read.
899     (end-of-file (condition)
900       (compiler-error 'input-error-in-compile-file
901                       :condition condition
902                       ;; We need to supply :POSITION here because the END-OF-FILE
903                       ;; condition doesn't carry the position that the user
904                       ;; probably cares about, where the failed READ began.
905                       :position position
906                       :stream stream))
907     (error (condition)
908       (compiler-error 'input-error-in-compile-file
909                       :condition condition
910                       :position position
911                       :stream stream))))
912
913 ;;; If STREAM is present, return it, otherwise open a stream to the
914 ;;; current file. There must be a current file.
915 ;;;
916 ;;; FIXME: This is probably an unnecessarily roundabout way to do
917 ;;; things now that we process a single file in COMPILE-FILE (unlike
918 ;;; the old CMU CL code, which accepted multiple files). Also, the old
919 ;;; comment said
920 ;;;   When we open a new file, we also reset *PACKAGE* and policy.
921 ;;;   This gives the effect of rebinding around each file.
922 ;;; which doesn't seem to be true now. Check to make sure that if
923 ;;; such rebinding is necessary, it's still done somewhere.
924 (defun get-source-stream (info)
925   (declare (type source-info info))
926   (or (source-info-stream info)
927       (let* ((file-info (source-info-file-info info))
928              (name (file-info-name file-info))
929              (external-format (file-info-external-format file-info)))
930         (setf sb!xc:*compile-file-truename* name
931               sb!xc:*compile-file-pathname* (file-info-untruename file-info)
932               (source-info-stream info)
933               (open name :direction :input
934                     :external-format external-format)))))
935
936 ;;; Close the stream in INFO if it is open.
937 (defun close-source-info (info)
938   (declare (type source-info info))
939   (let ((stream (source-info-stream info)))
940     (when stream (close stream)))
941   (setf (source-info-stream info) nil)
942   (values))
943
944 ;;; Loop over FORMS retrieved from INFO.  Used by COMPILE-FILE and
945 ;;; LOAD when loading from a FILE-STREAM associated with a source
946 ;;; file.
947 (defmacro do-forms-from-info (((form &rest keys) info)
948                               &body body)
949   (aver (symbolp form))
950   (once-only ((info info))
951     `(let ((*source-info* ,info))
952        (loop (destructuring-bind (,form &key ,@keys &allow-other-keys)
953                  (let* ((file-info (source-info-file-info ,info))
954                         (stream (get-source-stream ,info))
955                         (pos (file-position stream))
956                         (form (read-for-compile-file stream pos)))
957                    (if (eq form stream) ; i.e., if EOF
958                        (return)
959                        (let* ((forms (file-info-forms file-info))
960                               (current-idx (+ (fill-pointer forms)
961                                               (file-info-source-root
962                                                file-info))))
963                          (vector-push-extend form forms)
964                          (vector-push-extend pos (file-info-positions
965                                                   file-info))
966                          (list form :current-index current-idx))))
967                ,@body)))))
968
969 ;;; Read and compile the source file.
970 (defun sub-sub-compile-file (info)
971   (do-forms-from-info ((form current-index) info)
972     (find-source-paths form current-index)
973     (process-toplevel-form
974      form `(original-source-start 0 ,current-index) nil)))
975
976 ;;; Return the INDEX'th source form read from INFO and the position
977 ;;; where it was read.
978 (defun find-source-root (index info)
979   (declare (type index index) (type source-info info))
980   (let ((file-info (source-info-file-info info)))
981     (values (aref (file-info-forms file-info) index)
982             (aref (file-info-positions file-info) index))))
983 \f
984 ;;;; processing of top level forms
985
986 ;;; This is called by top level form processing when we are ready to
987 ;;; actually compile something. If *BLOCK-COMPILE* is T, then we still
988 ;;; convert the form, but delay compilation, pushing the result on
989 ;;; *TOPLEVEL-LAMBDAS* instead.
990 (defun convert-and-maybe-compile (form path)
991   (declare (list path))
992   (let ((*top-level-form-noted* (note-top-level-form form t)))
993     ;; Don't bother to compile simple objects that just sit there.
994     (when (and form (or (symbolp form) (consp form)))
995       (if (fopcompilable-p form)
996          (let ((*fopcompile-label-counter* 0))
997            (fopcompile form path nil))
998          (let ((*lexenv* (make-lexenv
999                           :policy *policy*
1000                           :handled-conditions *handled-conditions*
1001                           :disabled-package-locks *disabled-package-locks*))
1002                (tll (ir1-toplevel form path nil)))
1003            (if (eq *block-compile* t)
1004                (push tll *toplevel-lambdas*)
1005                (compile-toplevel (list tll) nil))
1006            nil)))))
1007
1008 ;;; Macroexpand FORM in the current environment with an error handler.
1009 ;;; We only expand one level, so that we retain all the intervening
1010 ;;; forms in the source path.
1011 (defun preprocessor-macroexpand-1 (form)
1012   (handler-case (%macroexpand-1 form *lexenv*)
1013     (error (condition)
1014       (compiler-error "(during macroexpansion of ~A)~%~A"
1015                       (let ((*print-level* 2)
1016                             (*print-length* 2))
1017                         (format nil "~S" form))
1018                       condition))))
1019
1020 ;;; Process a PROGN-like portion of a top level form. FORMS is a list of
1021 ;;; the forms, and PATH is the source path of the FORM they came out of.
1022 ;;; COMPILE-TIME-TOO is as in ANSI "3.2.3.1 Processing of Top Level Forms".
1023 (defun process-toplevel-progn (forms path compile-time-too)
1024   (declare (list forms) (list path))
1025   (dolist (form forms)
1026     (process-toplevel-form form path compile-time-too)))
1027
1028 ;;; Process a top level use of LOCALLY, or anything else (e.g.
1029 ;;; MACROLET) at top level which has declarations and ordinary forms.
1030 ;;; We parse declarations and then recursively process the body.
1031 (defun process-toplevel-locally (body path compile-time-too &key vars funs)
1032   (declare (list path))
1033   (multiple-value-bind (forms decls)
1034       (parse-body body :doc-string-allowed nil :toplevel t)
1035     (let* ((*lexenv* (process-decls decls vars funs))
1036            ;; FIXME: VALUES declaration
1037            ;;
1038            ;; Binding *POLICY* is pretty much of a hack, since it
1039            ;; causes LOCALLY to "capture" enclosed proclamations. It
1040            ;; is necessary because CONVERT-AND-MAYBE-COMPILE uses the
1041            ;; value of *POLICY* as the policy. The need for this hack
1042            ;; is due to the quirk that there is no way to represent in
1043            ;; a POLICY that an optimize quality came from the default.
1044            ;;
1045            ;; FIXME: Ideally, something should be done so that DECLAIM
1046            ;; inside LOCALLY works OK. Failing that, at least we could
1047            ;; issue a warning instead of silently screwing up.
1048            (*policy* (lexenv-policy *lexenv*))
1049            ;; This is probably also a hack
1050            (*handled-conditions* (lexenv-handled-conditions *lexenv*))
1051            ;; ditto
1052            (*disabled-package-locks* (lexenv-disabled-package-locks *lexenv*)))
1053       (process-toplevel-progn forms path compile-time-too))))
1054
1055 ;;; Parse an EVAL-WHEN situations list, returning three flags,
1056 ;;; (VALUES COMPILE-TOPLEVEL LOAD-TOPLEVEL EXECUTE), indicating
1057 ;;; the types of situations present in the list.
1058 (defun parse-eval-when-situations (situations)
1059   (when (or (not (listp situations))
1060             (set-difference situations
1061                             '(:compile-toplevel
1062                               compile
1063                               :load-toplevel
1064                               load
1065                               :execute
1066                               eval)))
1067     (compiler-error "bad EVAL-WHEN situation list: ~S" situations))
1068   (let ((deprecated-names (intersection situations '(compile load eval))))
1069     (when deprecated-names
1070       (style-warn "using deprecated EVAL-WHEN situation names~{ ~S~}"
1071                   deprecated-names)))
1072   (values (intersection '(:compile-toplevel compile)
1073                         situations)
1074           (intersection '(:load-toplevel load) situations)
1075           (intersection '(:execute eval) situations)))
1076
1077
1078 ;;; utilities for extracting COMPONENTs of FUNCTIONALs
1079 (defun functional-components (f)
1080   (declare (type functional f))
1081   (etypecase f
1082     (clambda (list (lambda-component f)))
1083     (optional-dispatch (let ((result nil))
1084                          (flet ((maybe-frob (maybe-clambda)
1085                                   (when (and maybe-clambda
1086                                              (promise-ready-p maybe-clambda))
1087                                     (pushnew (lambda-component
1088                                               (force maybe-clambda))
1089                                              result))))
1090                            (map nil #'maybe-frob (optional-dispatch-entry-points f))
1091                            (maybe-frob (optional-dispatch-more-entry f))
1092                            (maybe-frob (optional-dispatch-main-entry f)))
1093                          result))))
1094
1095 (defun make-functional-from-toplevel-lambda (lambda-expression
1096                                              &key
1097                                              name
1098                                              (path
1099                                               ;; I'd thought NIL should
1100                                               ;; work, but it doesn't.
1101                                               ;; -- WHN 2001-09-20
1102                                               (missing-arg)))
1103   (let* ((*current-path* path)
1104          (component (make-empty-component))
1105          (*current-component* component)
1106          (debug-name-tail (or name (name-lambdalike lambda-expression)))
1107          (source-name (or name '.anonymous.)))
1108     (setf (component-name component) (debug-name 'initial-component debug-name-tail)
1109           (component-kind component) :initial)
1110     (let* ((fun (let ((*allow-instrumenting* t))
1111                   (funcall #'ir1-convert-lambdalike
1112                            lambda-expression
1113                            :source-name source-name)))
1114            ;; Convert the XEP using the policy of the real function. Otherwise
1115            ;; the wrong policy will be used for deciding whether to type-check
1116            ;; the parameters of the real function (via CONVERT-CALL /
1117            ;; PROPAGATE-TO-ARGS). -- JES, 2007-02-27
1118            (*lexenv* (make-lexenv :policy (lexenv-policy (functional-lexenv fun))))
1119            (xep (ir1-convert-lambda (make-xep-lambda-expression fun)
1120                                     :source-name source-name
1121                                     :debug-name (debug-name 'tl-xep debug-name-tail)
1122                                     :system-lambda t)))
1123       (when name
1124         (assert-global-function-definition-type name fun))
1125       (setf (functional-kind xep) :external
1126             (functional-entry-fun xep) fun
1127             (functional-entry-fun fun) xep
1128             (component-reanalyze component) t
1129             (functional-has-external-references-p xep) t)
1130       (reoptimize-component component :maybe)
1131       (locall-analyze-xep-entry-point fun)
1132       ;; Any leftover REFs to FUN outside local calls get replaced with the
1133       ;; XEP.
1134       (substitute-leaf-if (lambda (ref)
1135                             (let* ((lvar (ref-lvar ref))
1136                                    (dest (when lvar (lvar-dest lvar)))
1137                                    (kind (when (basic-combination-p dest)
1138                                            (basic-combination-kind dest))))
1139                               (neq :local kind)))
1140                           xep
1141                           fun)
1142       xep)))
1143
1144 ;;; Compile LAMBDA-EXPRESSION into *COMPILE-OBJECT*, returning a
1145 ;;; description of the result.
1146 ;;;   * If *COMPILE-OBJECT* is a CORE-OBJECT, then write the function
1147 ;;;     into core and return the compiled FUNCTION value.
1148 ;;;   * If *COMPILE-OBJECT* is a fasl file, then write the function
1149 ;;;     into the fasl file and return a dump handle.
1150 ;;;
1151 ;;; If NAME is provided, then we try to use it as the name of the
1152 ;;; function for debugging/diagnostic information.
1153 (defun %compile (lambda-expression
1154                  *compile-object*
1155                  &key
1156                  name
1157                  (path
1158                   ;; This magical idiom seems to be the appropriate
1159                   ;; path for compiling standalone LAMBDAs, judging
1160                   ;; from the CMU CL code and experiment, so it's a
1161                   ;; nice default for things where we don't have a
1162                   ;; real source path (as in e.g. inside CL:COMPILE).
1163                   '(original-source-start 0 0)))
1164   (when name
1165     (legal-fun-name-or-type-error name))
1166   (let* ((*lexenv* (make-lexenv
1167                     :policy *policy*
1168                     :handled-conditions *handled-conditions*
1169                     :disabled-package-locks *disabled-package-locks*))
1170          (*compiler-sset-counter* 0)
1171          (fun (make-functional-from-toplevel-lambda lambda-expression
1172                                                     :name name
1173                                                     :path path)))
1174
1175     ;; FIXME: The compile-it code from here on is sort of a
1176     ;; twisted version of the code in COMPILE-TOPLEVEL. It'd be
1177     ;; better to find a way to share the code there; or
1178     ;; alternatively, to use this code to replace the code there.
1179     ;; (The second alternative might be pretty easy if we used
1180     ;; the :LOCALL-ONLY option to IR1-FOR-LAMBDA. Then maybe the
1181     ;; whole FUNCTIONAL-KIND=:TOPLEVEL case could go away..)
1182
1183     (locall-analyze-clambdas-until-done (list fun))
1184
1185     (let ((components-from-dfo (find-initial-dfo (list fun))))
1186       (dolist (component-from-dfo components-from-dfo)
1187         (compile-component component-from-dfo)
1188         (replace-toplevel-xeps component-from-dfo))
1189
1190       (let ((entry-table (etypecase *compile-object*
1191                            (fasl-output (fasl-output-entry-table
1192                                          *compile-object*))
1193                            (core-object (core-object-entry-table
1194                                          *compile-object*)))))
1195         (multiple-value-bind (result found-p)
1196             (gethash (leaf-info fun) entry-table)
1197           (aver found-p)
1198           (prog1
1199               result
1200             ;; KLUDGE: This code duplicates some other code in this
1201             ;; file. In the great reorganzation, the flow of program
1202             ;; logic changed from the original CMUCL model, and that
1203             ;; path (as of sbcl-0.7.5 in SUB-COMPILE-FILE) was no
1204             ;; longer followed for CORE-OBJECTS, leading to BUG
1205             ;; 156. This place is transparently not the right one for
1206             ;; this code, but I don't have a clear enough overview of
1207             ;; the compiler to know how to rearrange it all so that
1208             ;; this operation fits in nicely, and it was blocking
1209             ;; reimplementation of (DECLAIM (INLINE FOO)) (MACROLET
1210             ;; ((..)) (DEFUN FOO ...))
1211             ;;
1212             ;; FIXME: This KLUDGE doesn't solve all the problem in an
1213             ;; ideal way, as (1) definitions typed in at the REPL
1214             ;; without an INLINE declaration will give a NULL
1215             ;; FUNCTION-LAMBDA-EXPRESSION (allowable, but not ideal)
1216             ;; and (2) INLINE declarations will yield a
1217             ;; FUNCTION-LAMBDA-EXPRESSION headed by
1218             ;; SB-C:LAMBDA-WITH-LEXENV, even for null LEXENV.  -- CSR,
1219             ;; 2002-07-02
1220             ;;
1221             ;; (2) is probably fairly easy to fix -- it is, after all,
1222             ;; a matter of list manipulation (or possibly of teaching
1223             ;; CL:FUNCTION about SB-C:LAMBDA-WITH-LEXENV).  (1) is
1224             ;; significantly harder, as the association between
1225             ;; function object and source is a tricky one.
1226             ;;
1227             ;; FUNCTION-LAMBDA-EXPRESSION "works" (i.e. returns a
1228             ;; non-NULL list) when the function in question has been
1229             ;; compiled by (COMPILE <x> '(LAMBDA ...)); it does not
1230             ;; work when it has been compiled as part of the top-level
1231             ;; EVAL strategy of compiling everything inside (LAMBDA ()
1232             ;; ...).  -- CSR, 2002-11-02
1233             (when (core-object-p *compile-object*)
1234               (fix-core-source-info *source-info* *compile-object* result))
1235
1236             (mapc #'clear-ir1-info components-from-dfo)
1237             (clear-stuff)))))))
1238
1239 (defun process-toplevel-cold-fset (name lambda-expression path)
1240   (unless (producing-fasl-file)
1241     (error "can't COLD-FSET except in a fasl file"))
1242   (legal-fun-name-or-type-error name)
1243   (fasl-dump-cold-fset name
1244                        (%compile lambda-expression
1245                                  *compile-object*
1246                                  :name name
1247                                  :path path)
1248                        *compile-object*)
1249   (values))
1250
1251 (defun note-top-level-form (form &optional finalp)
1252   (when *compile-print*
1253     (cond ((not *top-level-form-noted*)
1254            (let ((*print-length* 2)
1255                  (*print-level* 2)
1256                  (*print-pretty* nil))
1257              (with-compiler-io-syntax
1258                  (compiler-mumble
1259                   #-sb-xc-host "~&; ~:[compiling~;converting~] ~S"
1260                   #+sb-xc-host "~&; ~:[x-compiling~;x-converting~] ~S"
1261                   *block-compile* form)))
1262              form)
1263           ((and finalp
1264                 (eq :top-level-forms *compile-print*)
1265                 (neq form *top-level-form-noted*))
1266            (let ((*print-length* 1)
1267                  (*print-level* 1)
1268                  (*print-pretty* nil))
1269              (with-compiler-io-syntax
1270                  (compiler-mumble "~&; ... top level ~S" form)))
1271            form)
1272           (t
1273            *top-level-form-noted*))))
1274
1275 ;;; Handle the evaluation the a :COMPILE-TOPLEVEL body during
1276 ;;; compilation. Normally just evaluate in the appropriate
1277 ;;; environment, but also compile if outputting a CFASL.
1278 (defun eval-compile-toplevel (body path)
1279   (eval-tlf `(progn ,@body) (source-path-tlf-number path) *lexenv*)
1280   (when *compile-toplevel-object*
1281     (let ((*compile-object* *compile-toplevel-object*))
1282       (convert-and-maybe-compile `(progn ,@body) path))))
1283
1284 ;;; Process a top level FORM with the specified source PATH.
1285 ;;;  * If this is a magic top level form, then do stuff.
1286 ;;;  * If this is a macro, then expand it.
1287 ;;;  * Otherwise, just compile it.
1288 ;;;
1289 ;;; COMPILE-TIME-TOO is as defined in ANSI
1290 ;;; "3.2.3.1 Processing of Top Level Forms".
1291 (defun process-toplevel-form (form path compile-time-too)
1292   (declare (list path))
1293
1294   (catch 'process-toplevel-form-error-abort
1295     (let* ((path (or (get-source-path form) (cons form path)))
1296            (*current-path* path)
1297            (*compiler-error-bailout*
1298             (lambda (&optional condition)
1299               (convert-and-maybe-compile
1300                (make-compiler-error-form condition form)
1301                path)
1302               (throw 'process-toplevel-form-error-abort nil))))
1303
1304       (flet ((default-processor (form)
1305                (let ((*top-level-form-noted* (note-top-level-form form)))
1306                  ;; When we're cross-compiling, consider: what should we
1307                  ;; do when we hit e.g.
1308                  ;;   (EVAL-WHEN (:COMPILE-TOPLEVEL)
1309                  ;;     (DEFUN FOO (X) (+ 7 X)))?
1310                  ;; DEFUN has a macro definition in the cross-compiler,
1311                  ;; and a different macro definition in the target
1312                  ;; compiler. The only sensible thing is to use the
1313                  ;; target compiler's macro definition, since the
1314                  ;; cross-compiler's macro is in general into target
1315                  ;; functions which can't meaningfully be executed at
1316                  ;; cross-compilation time. So make sure we do the EVAL
1317                  ;; here, before we macroexpand.
1318                  ;;
1319                  ;; Then things get even dicier with something like
1320                  ;;   (DEFCONSTANT-EQX SB!XC:LAMBDA-LIST-KEYWORDS ..)
1321                  ;; where we have to make sure that we don't uncross
1322                  ;; the SB!XC: prefix before we do EVAL, because otherwise
1323                  ;; we'd be trying to redefine the cross-compilation host's
1324                  ;; constants.
1325                  ;;
1326                  ;; (Isn't it fun to cross-compile Common Lisp?:-)
1327                  #+sb-xc-host
1328                  (progn
1329                    (when compile-time-too
1330                      (eval form)) ; letting xc host EVAL do its own macroexpansion
1331                    (let* (;; (We uncross the operator name because things
1332                           ;; like SB!XC:DEFCONSTANT and SB!XC:DEFTYPE
1333                           ;; should be equivalent to their CL: counterparts
1334                           ;; when being compiled as target code. We leave
1335                           ;; the rest of the form uncrossed because macros
1336                           ;; might yet expand into EVAL-WHEN stuff, and
1337                           ;; things inside EVAL-WHEN can't be uncrossed
1338                           ;; until after we've EVALed them in the
1339                           ;; cross-compilation host.)
1340                           (slightly-uncrossed (cons (uncross (first form))
1341                                                     (rest form)))
1342                           (expanded (preprocessor-macroexpand-1
1343                                      slightly-uncrossed)))
1344                      (if (eq expanded slightly-uncrossed)
1345                          ;; (Now that we're no longer processing toplevel
1346                          ;; forms, and hence no longer need to worry about
1347                          ;; EVAL-WHEN, we can uncross everything.)
1348                          (convert-and-maybe-compile expanded path)
1349                          ;; (We have to demote COMPILE-TIME-TOO to NIL
1350                          ;; here, no matter what it was before, since
1351                          ;; otherwise we'd tend to EVAL subforms more than
1352                          ;; once, because of WHEN COMPILE-TIME-TOO form
1353                          ;; above.)
1354                          (process-toplevel-form expanded path nil))))
1355                  ;; When we're not cross-compiling, we only need to
1356                  ;; macroexpand once, so we can follow the 1-thru-6
1357                  ;; sequence of steps in ANSI's "3.2.3.1 Processing of
1358                  ;; Top Level Forms".
1359                  #-sb-xc-host
1360                  (let ((expanded (preprocessor-macroexpand-1 form)))
1361                    (cond ((eq expanded form)
1362                           (when compile-time-too
1363                             (eval-compile-toplevel (list form) path))
1364                           (convert-and-maybe-compile form path))
1365                          (t
1366                           (process-toplevel-form expanded
1367                                                  path
1368                                                  compile-time-too)))))))
1369         (if (atom form)
1370             #+sb-xc-host
1371             ;; (There are no xc EVAL-WHEN issues in the ATOM case until
1372             ;; (1) SBCL gets smart enough to handle global
1373             ;; DEFINE-SYMBOL-MACRO or SYMBOL-MACROLET and (2) SBCL
1374             ;; implementors start using symbol macros in a way which
1375             ;; interacts with SB-XC/CL distinction.)
1376             (convert-and-maybe-compile form path)
1377             #-sb-xc-host
1378             (default-processor form)
1379             (flet ((need-at-least-one-arg (form)
1380                      (unless (cdr form)
1381                        (compiler-error "~S form is too short: ~S"
1382                                        (car form)
1383                                        form))))
1384               (case (car form)
1385                 ;; In the cross-compiler, top level COLD-FSET arranges
1386                 ;; for static linking at cold init time.
1387                 #+sb-xc-host
1388                 ((cold-fset)
1389                  (aver (not compile-time-too))
1390                  (destructuring-bind (cold-fset fun-name lambda-expression) form
1391                    (declare (ignore cold-fset))
1392                    (process-toplevel-cold-fset fun-name
1393                                                lambda-expression
1394                                                path)))
1395                 ((eval-when macrolet symbol-macrolet);things w/ 1 arg before body
1396                  (need-at-least-one-arg form)
1397                  (destructuring-bind (special-operator magic &rest body) form
1398                    (ecase special-operator
1399                      ((eval-when)
1400                       ;; CT, LT, and E here are as in Figure 3-7 of ANSI
1401                       ;; "3.2.3.1 Processing of Top Level Forms".
1402                       (multiple-value-bind (ct lt e)
1403                           (parse-eval-when-situations magic)
1404                         (let ((new-compile-time-too (or ct
1405                                                         (and compile-time-too
1406                                                              e))))
1407                           (cond (lt (process-toplevel-progn
1408                                      body path new-compile-time-too))
1409                                 (new-compile-time-too
1410                                  (eval-compile-toplevel body path))))))
1411                      ((macrolet)
1412                       (funcall-in-macrolet-lexenv
1413                        magic
1414                        (lambda (&key funs prepend)
1415                          (declare (ignore funs))
1416                          (aver (null prepend))
1417                          (process-toplevel-locally body
1418                                                    path
1419                                                    compile-time-too))
1420                        :compile))
1421                      ((symbol-macrolet)
1422                       (funcall-in-symbol-macrolet-lexenv
1423                        magic
1424                        (lambda (&key vars prepend)
1425                          (aver (null prepend))
1426                          (process-toplevel-locally body
1427                                                    path
1428                                                    compile-time-too
1429                                                    :vars vars))
1430                        :compile)))))
1431                 ((locally)
1432                  (process-toplevel-locally (rest form) path compile-time-too))
1433                 ((progn)
1434                  (process-toplevel-progn (rest form) path compile-time-too))
1435                 (t (default-processor form))))))))
1436
1437   (values))
1438 \f
1439 ;;;; load time value support
1440 ;;;;
1441 ;;;; (See EMIT-MAKE-LOAD-FORM.)
1442
1443 ;;; Return T if we are currently producing a fasl file and hence
1444 ;;; constants need to be dumped carefully.
1445 (defun producing-fasl-file ()
1446   (fasl-output-p *compile-object*))
1447
1448 ;;; Compile FORM and arrange for it to be called at load-time. Return
1449 ;;; the dumper handle and our best guess at the type of the object.
1450 (defun compile-load-time-value (form)
1451   (let ((lambda (compile-load-time-stuff form t)))
1452     (values
1453      (fasl-dump-load-time-value-lambda lambda *compile-object*)
1454      (let ((type (leaf-type lambda)))
1455        (if (fun-type-p type)
1456            (single-value-type (fun-type-returns type))
1457            *wild-type*)))))
1458
1459 ;;; Compile the FORMS and arrange for them to be called (for effect,
1460 ;;; not value) at load time.
1461 (defun compile-make-load-form-init-forms (forms)
1462   (let ((lambda (compile-load-time-stuff `(progn ,@forms) nil)))
1463     (fasl-dump-toplevel-lambda-call lambda *compile-object*)))
1464
1465 ;;; Do the actual work of COMPILE-LOAD-TIME-VALUE or
1466 ;;; COMPILE-MAKE-LOAD-FORM-INIT-FORMS.
1467 (defun compile-load-time-stuff (form for-value)
1468   (with-ir1-namespace
1469    (let* ((*lexenv* (make-null-lexenv))
1470           (lambda (ir1-toplevel form *current-path* for-value nil)))
1471      (compile-toplevel (list lambda) t)
1472      lambda)))
1473
1474 ;;; This is called by COMPILE-TOPLEVEL when it was passed T for
1475 ;;; LOAD-TIME-VALUE-P (which happens in COMPILE-LOAD-TIME-STUFF). We
1476 ;;; don't try to combine this component with anything else and frob
1477 ;;; the name. If not in a :TOPLEVEL component, then don't bother
1478 ;;; compiling, because it was merged with a run-time component.
1479 (defun compile-load-time-value-lambda (lambdas)
1480   (aver (null (cdr lambdas)))
1481   (let* ((lambda (car lambdas))
1482          (component (lambda-component lambda)))
1483     (when (eql (component-kind component) :toplevel)
1484       (setf (component-name component) (leaf-debug-name lambda))
1485       (compile-component component)
1486       (clear-ir1-info component))))
1487 \f
1488 ;;;; COMPILE-FILE
1489
1490 (defun object-call-toplevel-lambda (tll)
1491   (declare (type functional tll))
1492   (let ((object *compile-object*))
1493     (etypecase object
1494       (fasl-output (fasl-dump-toplevel-lambda-call tll object))
1495       (core-object (core-call-toplevel-lambda      tll object))
1496       (null))))
1497
1498 ;;; Smash LAMBDAS into a single component, compile it, and arrange for
1499 ;;; the resulting function to be called.
1500 (defun sub-compile-toplevel-lambdas (lambdas)
1501   (declare (list lambdas))
1502   (when lambdas
1503     (multiple-value-bind (component tll) (merge-toplevel-lambdas lambdas)
1504       (compile-component component)
1505       (clear-ir1-info component)
1506       (object-call-toplevel-lambda tll)))
1507   (values))
1508
1509 ;;; Compile top level code and call the top level lambdas. We pick off
1510 ;;; top level lambdas in non-top-level components here, calling
1511 ;;; SUB-c-t-l-l on each subsequence of normal top level lambdas.
1512 (defun compile-toplevel-lambdas (lambdas)
1513   (declare (list lambdas))
1514   (let ((len (length lambdas)))
1515     (flet ((loser (start)
1516              (or (position-if (lambda (x)
1517                                 (not (eq (component-kind
1518                                           (node-component (lambda-bind x)))
1519                                          :toplevel)))
1520                               lambdas
1521                               ;; this used to read ":start start", but
1522                               ;; start can be greater than len, which
1523                               ;; is an error according to ANSI - CSR,
1524                               ;; 2002-04-25
1525                               :start (min start len))
1526                  len)))
1527       (do* ((start 0 (1+ loser))
1528             (loser (loser start) (loser start)))
1529            ((>= start len))
1530         (sub-compile-toplevel-lambdas (subseq lambdas start loser))
1531         (unless (= loser len)
1532           (object-call-toplevel-lambda (elt lambdas loser))))))
1533   (values))
1534
1535 ;;; Compile LAMBDAS (a list of CLAMBDAs for top level forms) into the
1536 ;;; object file.
1537 ;;;
1538 ;;; LOAD-TIME-VALUE-P seems to control whether it's MAKE-LOAD-FORM and
1539 ;;; COMPILE-LOAD-TIME-VALUE stuff. -- WHN 20000201
1540 (defun compile-toplevel (lambdas load-time-value-p)
1541   (declare (list lambdas))
1542
1543   (maybe-mumble "locall ")
1544   (locall-analyze-clambdas-until-done lambdas)
1545
1546   (maybe-mumble "IDFO ")
1547   (multiple-value-bind (components top-components hairy-top)
1548       (find-initial-dfo lambdas)
1549     (let ((all-components (append components top-components)))
1550       (when *check-consistency*
1551         (maybe-mumble "[check]~%")
1552         (check-ir1-consistency all-components))
1553
1554       (dolist (component (append hairy-top top-components))
1555         (pre-physenv-analyze-toplevel component))
1556
1557       (dolist (component components)
1558         (compile-component component)
1559         (replace-toplevel-xeps component))
1560
1561       (when *check-consistency*
1562         (maybe-mumble "[check]~%")
1563         (check-ir1-consistency all-components))
1564
1565       (if load-time-value-p
1566           (compile-load-time-value-lambda lambdas)
1567           (compile-toplevel-lambdas lambdas))
1568
1569       (mapc #'clear-ir1-info components)
1570       (clear-stuff)))
1571   (values))
1572
1573 ;;; Actually compile any stuff that has been queued up for block
1574 ;;; compilation.
1575 (defun finish-block-compilation ()
1576   (when *block-compile*
1577     (when *compile-print*
1578       (compiler-mumble "~&; block compiling converted top level forms..."))
1579     (when *toplevel-lambdas*
1580       (compile-toplevel (nreverse *toplevel-lambdas*) nil)
1581       (setq *toplevel-lambdas* ()))
1582     (setq *block-compile* nil)
1583     (setq *entry-points* nil)))
1584
1585 (defun handle-condition-p (condition)
1586   (let ((lexenv
1587          (etypecase *compiler-error-context*
1588            (node
1589             (node-lexenv *compiler-error-context*))
1590            (compiler-error-context
1591             (let ((lexenv (compiler-error-context-lexenv
1592                            *compiler-error-context*)))
1593               (aver lexenv)
1594               lexenv))
1595            (null *lexenv*))))
1596     (let ((muffles (lexenv-handled-conditions lexenv)))
1597       (if (null muffles) ; common case
1598           nil
1599           (dolist (muffle muffles nil)
1600             (destructuring-bind (typespec . restart-name) muffle
1601               (when (and (typep condition typespec)
1602                          (find-restart restart-name condition))
1603                 (return t))))))))
1604
1605 (defun handle-condition-handler (condition)
1606   (let ((lexenv
1607          (etypecase *compiler-error-context*
1608            (node
1609             (node-lexenv *compiler-error-context*))
1610            (compiler-error-context
1611             (let ((lexenv (compiler-error-context-lexenv
1612                            *compiler-error-context*)))
1613               (aver lexenv)
1614               lexenv))
1615            (null *lexenv*))))
1616     (let ((muffles (lexenv-handled-conditions lexenv)))
1617       (aver muffles)
1618       (dolist (muffle muffles (bug "fell through"))
1619         (destructuring-bind (typespec . restart-name) muffle
1620           (when (typep condition typespec)
1621             (awhen (find-restart restart-name condition)
1622               (invoke-restart it))))))))
1623
1624 ;;; Read all forms from INFO and compile them, with output to OBJECT.
1625 ;;; Return (VALUES ABORT-P WARNINGS-P FAILURE-P).
1626 (defun sub-compile-file (info)
1627   (declare (type source-info info))
1628   (let ((*package* (sane-package))
1629         (*readtable* *readtable*)
1630         (sb!xc:*compile-file-pathname* nil) ; really bound in
1631         (sb!xc:*compile-file-truename* nil) ; SUB-SUB-COMPILE-FILE
1632         (*policy* *policy*)
1633         (*code-coverage-records* (make-hash-table :test 'equal))
1634         (*code-coverage-blocks* (make-hash-table :test 'equal))
1635         (*handled-conditions* *handled-conditions*)
1636         (*disabled-package-locks* *disabled-package-locks*)
1637         (*lexenv* (make-null-lexenv))
1638         (*block-compile* *block-compile-arg*)
1639         (*toplevel-lambdas* ())
1640         (*fun-names-in-this-file* ())
1641         (*allow-instrumenting* nil)
1642         (*compiler-error-bailout*
1643          (lambda (&optional error)
1644            (declare (ignore error))
1645            (return-from sub-compile-file (values t t t))))
1646         (*current-path* nil)
1647         (*last-source-context* nil)
1648         (*last-original-source* nil)
1649         (*last-source-form* nil)
1650         (*last-format-string* nil)
1651         (*last-format-args* nil)
1652         (*last-message-count* 0)
1653         ;; FIXME: Do we need this rebinding here? It's a literal
1654         ;; translation of the old CMU CL rebinding to
1655         ;; (OR *BACKEND-INFO-ENVIRONMENT* *INFO-ENVIRONMENT*),
1656         ;; and it's not obvious whether the rebinding to itself is
1657         ;; needed that SBCL doesn't need *BACKEND-INFO-ENVIRONMENT*.
1658         (*info-environment* *info-environment*)
1659         (*compiler-sset-counter* 0)
1660         (sb!xc:*gensym-counter* 0))
1661     (handler-case
1662         (handler-bind (((satisfies handle-condition-p) #'handle-condition-handler))
1663           (with-compilation-values
1664             (sb!xc:with-compilation-unit ()
1665               (with-world-lock ()
1666                 (clear-stuff)
1667                 (sub-sub-compile-file info)
1668                 (unless (zerop (hash-table-count *code-coverage-records*))
1669                   ;; Dump the code coverage records into the fasl.
1670                   (fopcompile `(record-code-coverage
1671                                 ',(namestring *compile-file-pathname*)
1672                                 ',(let (list)
1673                                     (maphash (lambda (k v)
1674                                                (declare (ignore k))
1675                                                (push v list))
1676                                              *code-coverage-records*)
1677                                     list))
1678                               nil
1679                               nil))
1680                 (finish-block-compilation)
1681                 (let ((object *compile-object*))
1682                   (etypecase object
1683                     (fasl-output (fasl-dump-source-info info object))
1684                     (core-object (fix-core-source-info info object))
1685                     (null)))
1686                 nil))))
1687       ;; Some errors are sufficiently bewildering that we just fail
1688       ;; immediately, without trying to recover and compile more of
1689       ;; the input file.
1690       (fatal-compiler-error (condition)
1691        (signal condition)
1692        (fresh-line *error-output*)
1693        (pprint-logical-block (*error-output* nil :per-line-prefix "; ")
1694          (format *error-output*
1695                  "~@<~@:_compilation aborted because of fatal error: ~2I~_~A~@:_~:>"
1696                  (encapsulated-condition condition)))
1697        (finish-output *error-output*)
1698        (values t t t)))))
1699
1700 ;;; Return a pathname for the named file. The file must exist.
1701 (defun verify-source-file (pathname-designator)
1702   (let* ((pathname (pathname pathname-designator))
1703          (default-host (make-pathname :host (pathname-host pathname))))
1704     (flet ((try-with-type (path type error-p)
1705              (let ((new (merge-pathnames
1706                          path (make-pathname :type type
1707                                              :defaults default-host))))
1708                (if (probe-file new)
1709                    new
1710                    (and error-p (truename new))))))
1711       (cond ((typep pathname 'logical-pathname)
1712              (try-with-type pathname "LISP" t))
1713             ((probe-file pathname) pathname)
1714             ((try-with-type pathname "lisp"  nil))
1715             ((try-with-type pathname "lisp"  t))))))
1716
1717 (defun elapsed-time-to-string (internal-time-delta)
1718   (multiple-value-bind (tsec remainder)
1719       (truncate internal-time-delta internal-time-units-per-second)
1720     (let ((ms (truncate remainder (/ internal-time-units-per-second 1000))))
1721       (multiple-value-bind (tmin sec) (truncate tsec 60)
1722         (multiple-value-bind (thr min) (truncate tmin 60)
1723           (format nil "~D:~2,'0D:~2,'0D.~3,'0D" thr min sec ms))))))
1724
1725 ;;; Print some junk at the beginning and end of compilation.
1726 (defun print-compile-start-note (source-info)
1727   (declare (type source-info source-info))
1728   (let ((file-info (source-info-file-info source-info)))
1729     (compiler-mumble "~&; compiling file ~S (written ~A):~%"
1730                      (namestring (file-info-name file-info))
1731                      (sb!int:format-universal-time nil
1732                                                    (file-info-write-date
1733                                                     file-info)
1734                                                    :style :government
1735                                                    :print-weekday nil
1736                                                    :print-timezone nil)))
1737   (values))
1738
1739 (defun print-compile-end-note (source-info won)
1740   (declare (type source-info source-info))
1741   (compiler-mumble "~&; compilation ~:[aborted after~;finished in~] ~A~&"
1742                    won
1743                    (elapsed-time-to-string
1744                     (- (get-internal-real-time)
1745                        (source-info-start-real-time source-info))))
1746   (values))
1747
1748 ;;; Open some files and call SUB-COMPILE-FILE. If something unwinds
1749 ;;; out of the compile, then abort the writing of the output file, so
1750 ;;; that we don't overwrite it with known garbage.
1751 (defun sb!xc:compile-file
1752     (input-file
1753      &key
1754
1755      ;; ANSI options
1756      (output-file (cfp-output-file-default input-file))
1757      ;; FIXME: ANSI doesn't seem to say anything about
1758      ;; *COMPILE-VERBOSE* and *COMPILE-PRINT* being rebound by this
1759      ;; function..
1760      ((:verbose sb!xc:*compile-verbose*) sb!xc:*compile-verbose*)
1761      ((:print sb!xc:*compile-print*) sb!xc:*compile-print*)
1762      (external-format :default)
1763
1764      ;; extensions
1765      (trace-file nil)
1766      ((:block-compile *block-compile-arg*) nil)
1767      (emit-cfasl *emit-cfasl*))
1768   #!+sb-doc
1769   "Compile INPUT-FILE, producing a corresponding fasl file and
1770 returning its filename.
1771
1772   :PRINT
1773      If true, a message per non-macroexpanded top level form is printed
1774      to *STANDARD-OUTPUT*. Top level forms that whose subforms are
1775      processed as top level forms (eg. EVAL-WHEN, MACROLET, PROGN) receive
1776      no such message, but their subforms do.
1777
1778      As an extension to ANSI, if :PRINT is :top-level-forms, a message
1779      per top level form after macroexpansion is printed to *STANDARD-OUTPUT*.
1780      For example, compiling an IN-PACKAGE form will result in a message about
1781      a top level SETQ in addition to the message about the IN-PACKAGE form'
1782      itself.
1783
1784      Both forms of reporting obey the SB-EXT:*COMPILER-PRINT-VARIABLE-ALIST*.
1785
1786   :BLOCK-COMPILE
1787      Though COMPILE-FILE accepts an additional :BLOCK-COMPILE
1788      argument, it is not currently supported. (non-standard)
1789
1790   :TRACE-FILE
1791      If given, internal data structures are dumped to the specified
1792      file, or if a value of T is given, to a file of *.trace type
1793      derived from the input file name. (non-standard)
1794
1795   :EMIT-CFASL
1796      (Experimental). If true, outputs the toplevel compile-time effects
1797      of this file into a separate .cfasl file."
1798 ;;; Block compilation is currently broken.
1799 #|
1800   "Also, as a workaround for vaguely-non-ANSI behavior, the
1801 :BLOCK-COMPILE argument is quasi-supported, to determine whether
1802 multiple functions are compiled together as a unit, resolving function
1803 references at compile time. NIL means that global function names are
1804 never resolved at compilation time. Currently NIL is the default
1805 behavior, because although section 3.2.2.3, \"Semantic Constraints\",
1806 of the ANSI spec allows this behavior under all circumstances, the
1807 compiler's runtime scales badly when it tries to do this for large
1808 files. If/when this performance problem is fixed, the block
1809 compilation default behavior will probably be made dependent on the
1810 SPEED and COMPILATION-SPEED optimization values, and the
1811 :BLOCK-COMPILE argument will probably become deprecated."
1812 |#
1813   (let* ((fasl-output nil)
1814          (cfasl-output nil)
1815          (output-file-name nil)
1816          (coutput-file-name nil)
1817          (abort-p t)
1818          (warnings-p nil)
1819          (failure-p t) ; T in case error keeps this from being set later
1820          (input-pathname (verify-source-file input-file))
1821          (source-info (make-file-source-info input-pathname external-format))
1822          (*compiler-trace-output* nil)) ; might be modified below
1823
1824     (unwind-protect
1825         (progn
1826           (when output-file
1827             (setq output-file-name
1828                   (sb!xc:compile-file-pathname input-file
1829                                                :output-file output-file))
1830             (setq fasl-output
1831                   (open-fasl-output output-file-name
1832                                     (namestring input-pathname))))
1833           (when emit-cfasl
1834             (setq coutput-file-name
1835                   (make-pathname :type "cfasl"
1836                                  :defaults output-file-name))
1837             (setq cfasl-output
1838                   (open-fasl-output coutput-file-name
1839                                     (namestring input-pathname))))
1840           (when trace-file
1841             (let* ((default-trace-file-pathname
1842                      (make-pathname :type "trace" :defaults input-pathname))
1843                    (trace-file-pathname
1844                     (if (eql trace-file t)
1845                         default-trace-file-pathname
1846                         (merge-pathnames trace-file
1847                                          default-trace-file-pathname))))
1848               (setf *compiler-trace-output*
1849                     (open trace-file-pathname
1850                           :if-exists :supersede
1851                           :direction :output))))
1852
1853           (when sb!xc:*compile-verbose*
1854             (print-compile-start-note source-info))
1855
1856           (let ((*compile-object* fasl-output)
1857                 (*compile-toplevel-object* cfasl-output))
1858             (setf (values abort-p warnings-p failure-p)
1859                   (sub-compile-file source-info))))
1860
1861       (close-source-info source-info)
1862
1863       (when fasl-output
1864         (close-fasl-output fasl-output abort-p)
1865         (setq output-file-name
1866               (pathname (fasl-output-stream fasl-output)))
1867         (when (and (not abort-p) sb!xc:*compile-verbose*)
1868           (compiler-mumble "~2&; ~A written~%" (namestring output-file-name))))
1869
1870       (when cfasl-output
1871         (close-fasl-output cfasl-output abort-p)
1872         (when (and (not abort-p) sb!xc:*compile-verbose*)
1873           (compiler-mumble "; ~A written~%" (namestring coutput-file-name))))
1874
1875       (when sb!xc:*compile-verbose*
1876         (print-compile-end-note source-info (not abort-p)))
1877
1878       (when *compiler-trace-output*
1879         (close *compiler-trace-output*)))
1880
1881     ;; CLHS says that the first value is NIL if the "file could not
1882     ;; be created". We interpret this to mean "a valid fasl could not
1883     ;; be created" -- which can happen if the compilation is aborted
1884     ;; before the whole file has been processed, due to eg. a reader
1885     ;; error.
1886     (values (when (and (not abort-p) output-file)
1887               ;; Hack around filesystem race condition...
1888               (or (probe-file output-file-name) output-file-name))
1889             warnings-p
1890             failure-p)))
1891 \f
1892 ;;; a helper function for COMPILE-FILE-PATHNAME: the default for
1893 ;;; the OUTPUT-FILE argument
1894 ;;;
1895 ;;; ANSI: The defaults for the OUTPUT-FILE are taken from the pathname
1896 ;;; that results from merging the INPUT-FILE with the value of
1897 ;;; *DEFAULT-PATHNAME-DEFAULTS*, except that the type component should
1898 ;;; default to the appropriate implementation-defined default type for
1899 ;;; compiled files.
1900 (defun cfp-output-file-default (input-file)
1901   (let* ((defaults (merge-pathnames input-file *default-pathname-defaults*))
1902          (retyped (make-pathname :type *fasl-file-type* :defaults defaults)))
1903     retyped))
1904
1905 ;;; KLUDGE: Part of the ANSI spec for this seems contradictory:
1906 ;;;   If INPUT-FILE is a logical pathname and OUTPUT-FILE is unsupplied,
1907 ;;;   the result is a logical pathname. If INPUT-FILE is a logical
1908 ;;;   pathname, it is translated into a physical pathname as if by
1909 ;;;   calling TRANSLATE-LOGICAL-PATHNAME.
1910 ;;; So I haven't really tried to make this precisely ANSI-compatible
1911 ;;; at the level of e.g. whether it returns logical pathname or a
1912 ;;; physical pathname. Patches to make it more correct are welcome.
1913 ;;; -- WHN 2000-12-09
1914 (defun sb!xc:compile-file-pathname (input-file
1915                                     &key
1916                                     (output-file nil output-file-p)
1917                                     &allow-other-keys)
1918   #!+sb-doc
1919   "Return a pathname describing what file COMPILE-FILE would write to given
1920    these arguments."
1921   (if output-file-p
1922       (merge-pathnames output-file (cfp-output-file-default input-file))
1923       (cfp-output-file-default input-file)))
1924 \f
1925 ;;;; MAKE-LOAD-FORM stuff
1926
1927 ;;; The entry point for MAKE-LOAD-FORM support. When IR1 conversion
1928 ;;; finds a constant structure, it invokes this to arrange for proper
1929 ;;; dumping. If it turns out that the constant has already been
1930 ;;; dumped, then we don't need to do anything.
1931 ;;;
1932 ;;; If the constant hasn't been dumped, then we check to see whether
1933 ;;; we are in the process of creating it. We detect this by
1934 ;;; maintaining the special *CONSTANTS-BEING-CREATED* as a list of all
1935 ;;; the constants we are in the process of creating. Actually, each
1936 ;;; entry is a list of the constant and any init forms that need to be
1937 ;;; processed on behalf of that constant.
1938 ;;;
1939 ;;; It's not necessarily an error for this to happen. If we are
1940 ;;; processing the init form for some object that showed up *after*
1941 ;;; the original reference to this constant, then we just need to
1942 ;;; defer the processing of that init form. To detect this, we
1943 ;;; maintain *CONSTANTS-CREATED-SINCE-LAST-INIT* as a list of the
1944 ;;; constants created since the last time we started processing an
1945 ;;; init form. If the constant passed to emit-make-load-form shows up
1946 ;;; in this list, then there is a circular chain through creation
1947 ;;; forms, which is an error.
1948 ;;;
1949 ;;; If there is some intervening init form, then we blow out of
1950 ;;; processing it by throwing to the tag PENDING-INIT. The value we
1951 ;;; throw is the entry from *CONSTANTS-BEING-CREATED*. This is so the
1952 ;;; offending init form can be tacked onto the init forms for the
1953 ;;; circular object.
1954 ;;;
1955 ;;; If the constant doesn't show up in *CONSTANTS-BEING-CREATED*, then
1956 ;;; we have to create it. We call MAKE-LOAD-FORM and check to see
1957 ;;; whether the creation form is the magic value
1958 ;;; :SB-JUST-DUMP-IT-NORMALLY. If it is, then we don't do anything. The
1959 ;;; dumper will eventually get its hands on the object and use the
1960 ;;; normal structure dumping noise on it.
1961 ;;;
1962 ;;; Otherwise, we bind *CONSTANTS-BEING-CREATED* and
1963 ;;; *CONSTANTS-CREATED-SINCE- LAST-INIT* and compile the creation form
1964 ;;; much the way LOAD-TIME-VALUE does. When this finishes, we tell the
1965 ;;; dumper to use that result instead whenever it sees this constant.
1966 ;;;
1967 ;;; Now we try to compile the init form. We bind
1968 ;;; *CONSTANTS-CREATED-SINCE-LAST-INIT* to NIL and compile the init
1969 ;;; form (and any init forms that were added because of circularity
1970 ;;; detection). If this works, great. If not, we add the init forms to
1971 ;;; the init forms for the object that caused the problems and let it
1972 ;;; deal with it.
1973 (defvar *constants-being-created* nil)
1974 (defvar *constants-created-since-last-init* nil)
1975 ;;; FIXME: Shouldn't these^ variables be unbound outside LET forms?
1976 (defun emit-make-load-form (constant &optional (name nil namep))
1977   (aver (fasl-output-p *compile-object*))
1978   (unless (or (fasl-constant-already-dumped-p constant *compile-object*)
1979               ;; KLUDGE: This special hack is because I was too lazy
1980               ;; to rework DEF!STRUCT so that the MAKE-LOAD-FORM
1981               ;; function of LAYOUT returns nontrivial forms when
1982               ;; building the cross-compiler but :IGNORE-IT when
1983               ;; cross-compiling or running under the target Lisp. --
1984               ;; WHN 19990914
1985               #+sb-xc-host (typep constant 'layout))
1986     (let ((circular-ref (assoc constant *constants-being-created* :test #'eq)))
1987       (when circular-ref
1988         (when (find constant *constants-created-since-last-init* :test #'eq)
1989           (throw constant t))
1990         (throw 'pending-init circular-ref)))
1991     (multiple-value-bind (creation-form init-form)
1992         (if namep
1993             ;; If the constant is a reference to a named constant, we can
1994             ;; just use SYMBOL-VALUE during LOAD.
1995             (values `(symbol-value ',name) nil)
1996             (handler-case
1997                 (sb!xc:make-load-form constant (make-null-lexenv))
1998               (error (condition)
1999                 (compiler-error condition))))
2000       (case creation-form
2001         (:sb-just-dump-it-normally
2002          (fasl-validate-structure constant *compile-object*)
2003          t)
2004         (:ignore-it
2005          nil)
2006         (t
2007          (let* ((name (write-to-string constant :level 1 :length 2))
2008                 (info (if init-form
2009                           (list constant name init-form)
2010                           (list constant))))
2011            (let ((*constants-being-created*
2012                   (cons info *constants-being-created*))
2013                  (*constants-created-since-last-init*
2014                   (cons constant *constants-created-since-last-init*)))
2015              (when
2016                  (catch constant
2017                    (fasl-note-handle-for-constant
2018                     constant
2019                     (compile-load-time-value
2020                      creation-form)
2021                     *compile-object*)
2022                    nil)
2023                (compiler-error "circular references in creation form for ~S"
2024                                constant)))
2025            (when (cdr info)
2026              (let* ((*constants-created-since-last-init* nil)
2027                     (circular-ref
2028                      (catch 'pending-init
2029                        (loop for (name form) on (cdr info) by #'cddr
2030                          collect name into names
2031                          collect form into forms
2032                          finally (compile-make-load-form-init-forms forms))
2033                        nil)))
2034                (when circular-ref
2035                  (setf (cdr circular-ref)
2036                        (append (cdr circular-ref) (cdr info))))))))))))
2037
2038 \f
2039 ;;;; Host compile time definitions
2040 #+sb-xc-host
2041 (defun compile-in-lexenv (name lambda lexenv)
2042   (declare (ignore lexenv))
2043   (compile name lambda))
2044
2045 #+sb-xc-host
2046 (defun eval-tlf (form index &optional lexenv)
2047   (declare (ignore index lexenv))
2048   (eval form))