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