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