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