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