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