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