1.0.36.20: prettier WITH-COMPILATION-UNIT documentation
[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* ((locall-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
1105            ;; function. Otherwise the wrong policy will be used for
1106            ;; deciding whether to type-check the parameters of the
1107            ;; real function (via CONVERT-CALL / PROPAGATE-TO-ARGS).
1108            ;; -- JES, 2007-02-27
1109            (*lexenv* (make-lexenv :policy (lexenv-policy
1110                                            (functional-lexenv locall-fun))))
1111            (fun (ir1-convert-lambda (make-xep-lambda-expression locall-fun)
1112                                     :source-name source-name
1113                                     :debug-name (debug-name 'tl-xep debug-name-tail)
1114                                     :system-lambda t)))
1115       (when name
1116         (assert-global-function-definition-type name locall-fun))
1117       (setf (functional-entry-fun fun) locall-fun
1118             (functional-kind fun) :external
1119             (functional-has-external-references-p locall-fun) t
1120             (functional-has-external-references-p fun) t)
1121       fun)))
1122
1123 ;;; Compile LAMBDA-EXPRESSION into *COMPILE-OBJECT*, returning a
1124 ;;; description of the result.
1125 ;;;   * If *COMPILE-OBJECT* is a CORE-OBJECT, then write the function
1126 ;;;     into core and return the compiled FUNCTION value.
1127 ;;;   * If *COMPILE-OBJECT* is a fasl file, then write the function
1128 ;;;     into the fasl file and return a dump handle.
1129 ;;;
1130 ;;; If NAME is provided, then we try to use it as the name of the
1131 ;;; function for debugging/diagnostic information.
1132 (defun %compile (lambda-expression
1133                  *compile-object*
1134                  &key
1135                  name
1136                  (path
1137                   ;; This magical idiom seems to be the appropriate
1138                   ;; path for compiling standalone LAMBDAs, judging
1139                   ;; from the CMU CL code and experiment, so it's a
1140                   ;; nice default for things where we don't have a
1141                   ;; real source path (as in e.g. inside CL:COMPILE).
1142                   '(original-source-start 0 0)))
1143   (when name
1144     (legal-fun-name-or-type-error name))
1145   (let* ((*lexenv* (make-lexenv
1146                     :policy *policy*
1147                     :handled-conditions *handled-conditions*
1148                     :disabled-package-locks *disabled-package-locks*))
1149          (*compiler-sset-counter* 0)
1150          (fun (make-functional-from-toplevel-lambda lambda-expression
1151                                                     :name name
1152                                                     :path path)))
1153
1154     ;; FIXME: The compile-it code from here on is sort of a
1155     ;; twisted version of the code in COMPILE-TOPLEVEL. It'd be
1156     ;; better to find a way to share the code there; or
1157     ;; alternatively, to use this code to replace the code there.
1158     ;; (The second alternative might be pretty easy if we used
1159     ;; the :LOCALL-ONLY option to IR1-FOR-LAMBDA. Then maybe the
1160     ;; whole FUNCTIONAL-KIND=:TOPLEVEL case could go away..)
1161
1162     (locall-analyze-clambdas-until-done (list fun))
1163
1164     (let ((components-from-dfo (find-initial-dfo (list fun))))
1165       (dolist (component-from-dfo components-from-dfo)
1166         (compile-component component-from-dfo)
1167         (replace-toplevel-xeps component-from-dfo))
1168
1169       (let ((entry-table (etypecase *compile-object*
1170                            (fasl-output (fasl-output-entry-table
1171                                          *compile-object*))
1172                            (core-object (core-object-entry-table
1173                                          *compile-object*)))))
1174         (multiple-value-bind (result found-p)
1175             (gethash (leaf-info fun) entry-table)
1176           (aver found-p)
1177           (prog1
1178               result
1179             ;; KLUDGE: This code duplicates some other code in this
1180             ;; file. In the great reorganzation, the flow of program
1181             ;; logic changed from the original CMUCL model, and that
1182             ;; path (as of sbcl-0.7.5 in SUB-COMPILE-FILE) was no
1183             ;; longer followed for CORE-OBJECTS, leading to BUG
1184             ;; 156. This place is transparently not the right one for
1185             ;; this code, but I don't have a clear enough overview of
1186             ;; the compiler to know how to rearrange it all so that
1187             ;; this operation fits in nicely, and it was blocking
1188             ;; reimplementation of (DECLAIM (INLINE FOO)) (MACROLET
1189             ;; ((..)) (DEFUN FOO ...))
1190             ;;
1191             ;; FIXME: This KLUDGE doesn't solve all the problem in an
1192             ;; ideal way, as (1) definitions typed in at the REPL
1193             ;; without an INLINE declaration will give a NULL
1194             ;; FUNCTION-LAMBDA-EXPRESSION (allowable, but not ideal)
1195             ;; and (2) INLINE declarations will yield a
1196             ;; FUNCTION-LAMBDA-EXPRESSION headed by
1197             ;; SB-C:LAMBDA-WITH-LEXENV, even for null LEXENV.  -- CSR,
1198             ;; 2002-07-02
1199             ;;
1200             ;; (2) is probably fairly easy to fix -- it is, after all,
1201             ;; a matter of list manipulation (or possibly of teaching
1202             ;; CL:FUNCTION about SB-C:LAMBDA-WITH-LEXENV).  (1) is
1203             ;; significantly harder, as the association between
1204             ;; function object and source is a tricky one.
1205             ;;
1206             ;; FUNCTION-LAMBDA-EXPRESSION "works" (i.e. returns a
1207             ;; non-NULL list) when the function in question has been
1208             ;; compiled by (COMPILE <x> '(LAMBDA ...)); it does not
1209             ;; work when it has been compiled as part of the top-level
1210             ;; EVAL strategy of compiling everything inside (LAMBDA ()
1211             ;; ...).  -- CSR, 2002-11-02
1212             (when (core-object-p *compile-object*)
1213               (fix-core-source-info *source-info* *compile-object* result))
1214
1215             (mapc #'clear-ir1-info components-from-dfo)
1216             (clear-stuff)))))))
1217
1218 (defun process-toplevel-cold-fset (name lambda-expression path)
1219   (unless (producing-fasl-file)
1220     (error "can't COLD-FSET except in a fasl file"))
1221   (legal-fun-name-or-type-error name)
1222   (fasl-dump-cold-fset name
1223                        (%compile lambda-expression
1224                                  *compile-object*
1225                                  :name name
1226                                  :path path)
1227                        *compile-object*)
1228   (values))
1229
1230 (defun note-top-level-form (form &optional finalp)
1231   (when *compile-print*
1232     (cond ((not *top-level-form-noted*)
1233            (let ((*print-length* 2)
1234                  (*print-level* 2)
1235                  (*print-pretty* nil))
1236              (with-compiler-io-syntax
1237                  (compiler-mumble "~&; ~:[compiling~;converting~] ~S"
1238                                   *block-compile* form)))
1239              form)
1240           ((and finalp
1241                 (eq :top-level-forms *compile-print*)
1242                 (neq form *top-level-form-noted*))
1243            (let ((*print-length* 1)
1244                  (*print-level* 1)
1245                  (*print-pretty* nil))
1246              (with-compiler-io-syntax
1247                  (compiler-mumble "~&; ... top level ~S" form)))
1248            form)
1249           (t
1250            *top-level-form-noted*))))
1251
1252 ;;; Handle the evaluation the a :COMPILE-TOPLEVEL body during
1253 ;;; compilation. Normally just evaluate in the appropriate
1254 ;;; environment, but also compile if outputting a CFASL.
1255 (defun eval-compile-toplevel (body path)
1256   (handler-case (eval-in-lexenv `(progn ,@body) *lexenv*)
1257     (error (condition)
1258       (compiler-error "(during compile-time-too processing)~%~A"
1259                       condition)))
1260   (when *compile-toplevel-object*
1261     (let ((*compile-object* *compile-toplevel-object*))
1262       (convert-and-maybe-compile `(progn ,@body) path))))
1263
1264 ;;; Process a top level FORM with the specified source PATH.
1265 ;;;  * If this is a magic top level form, then do stuff.
1266 ;;;  * If this is a macro, then expand it.
1267 ;;;  * Otherwise, just compile it.
1268 ;;;
1269 ;;; COMPILE-TIME-TOO is as defined in ANSI
1270 ;;; "3.2.3.1 Processing of Top Level Forms".
1271 (defun process-toplevel-form (form path compile-time-too)
1272   (declare (list path))
1273
1274   (catch 'process-toplevel-form-error-abort
1275     (let* ((path (or (get-source-path form) (cons form path)))
1276            (*current-path* path)
1277            (*compiler-error-bailout*
1278             (lambda (&optional condition)
1279               (convert-and-maybe-compile
1280                (make-compiler-error-form condition form)
1281                path)
1282               (throw 'process-toplevel-form-error-abort nil))))
1283
1284       (flet ((default-processor (form)
1285                (let ((*top-level-form-noted* (note-top-level-form form)))
1286                  ;; When we're cross-compiling, consider: what should we
1287                  ;; do when we hit e.g.
1288                  ;;   (EVAL-WHEN (:COMPILE-TOPLEVEL)
1289                  ;;     (DEFUN FOO (X) (+ 7 X)))?
1290                  ;; DEFUN has a macro definition in the cross-compiler,
1291                  ;; and a different macro definition in the target
1292                  ;; compiler. The only sensible thing is to use the
1293                  ;; target compiler's macro definition, since the
1294                  ;; cross-compiler's macro is in general into target
1295                  ;; functions which can't meaningfully be executed at
1296                  ;; cross-compilation time. So make sure we do the EVAL
1297                  ;; here, before we macroexpand.
1298                  ;;
1299                  ;; Then things get even dicier with something like
1300                  ;;   (DEFCONSTANT-EQX SB!XC:LAMBDA-LIST-KEYWORDS ..)
1301                  ;; where we have to make sure that we don't uncross
1302                  ;; the SB!XC: prefix before we do EVAL, because otherwise
1303                  ;; we'd be trying to redefine the cross-compilation host's
1304                  ;; constants.
1305                  ;;
1306                  ;; (Isn't it fun to cross-compile Common Lisp?:-)
1307                  #+sb-xc-host
1308                  (progn
1309                    (when compile-time-too
1310                      (eval form)) ; letting xc host EVAL do its own macroexpansion
1311                    (let* (;; (We uncross the operator name because things
1312                           ;; like SB!XC:DEFCONSTANT and SB!XC:DEFTYPE
1313                           ;; should be equivalent to their CL: counterparts
1314                           ;; when being compiled as target code. We leave
1315                           ;; the rest of the form uncrossed because macros
1316                           ;; might yet expand into EVAL-WHEN stuff, and
1317                           ;; things inside EVAL-WHEN can't be uncrossed
1318                           ;; until after we've EVALed them in the
1319                           ;; cross-compilation host.)
1320                           (slightly-uncrossed (cons (uncross (first form))
1321                                                     (rest form)))
1322                           (expanded (preprocessor-macroexpand-1
1323                                      slightly-uncrossed)))
1324                      (if (eq expanded slightly-uncrossed)
1325                          ;; (Now that we're no longer processing toplevel
1326                          ;; forms, and hence no longer need to worry about
1327                          ;; EVAL-WHEN, we can uncross everything.)
1328                          (convert-and-maybe-compile expanded path)
1329                          ;; (We have to demote COMPILE-TIME-TOO to NIL
1330                          ;; here, no matter what it was before, since
1331                          ;; otherwise we'd tend to EVAL subforms more than
1332                          ;; once, because of WHEN COMPILE-TIME-TOO form
1333                          ;; above.)
1334                          (process-toplevel-form expanded path nil))))
1335                  ;; When we're not cross-compiling, we only need to
1336                  ;; macroexpand once, so we can follow the 1-thru-6
1337                  ;; sequence of steps in ANSI's "3.2.3.1 Processing of
1338                  ;; Top Level Forms".
1339                  #-sb-xc-host
1340                  (let ((expanded (preprocessor-macroexpand-1 form)))
1341                    (cond ((eq expanded form)
1342                           (when compile-time-too
1343                             (eval-compile-toplevel (list form) path))
1344                           (convert-and-maybe-compile form path))
1345                          (t
1346                           (process-toplevel-form expanded
1347                                                  path
1348                                                  compile-time-too)))))))
1349         (if (atom form)
1350             #+sb-xc-host
1351             ;; (There are no xc EVAL-WHEN issues in the ATOM case until
1352             ;; (1) SBCL gets smart enough to handle global
1353             ;; DEFINE-SYMBOL-MACRO or SYMBOL-MACROLET and (2) SBCL
1354             ;; implementors start using symbol macros in a way which
1355             ;; interacts with SB-XC/CL distinction.)
1356             (convert-and-maybe-compile form path)
1357             #-sb-xc-host
1358             (default-processor form)
1359             (flet ((need-at-least-one-arg (form)
1360                      (unless (cdr form)
1361                        (compiler-error "~S form is too short: ~S"
1362                                        (car form)
1363                                        form))))
1364               (case (car form)
1365                 ;; In the cross-compiler, top level COLD-FSET arranges
1366                 ;; for static linking at cold init time.
1367                 #+sb-xc-host
1368                 ((cold-fset)
1369                  (aver (not compile-time-too))
1370                  (destructuring-bind (cold-fset fun-name lambda-expression) form
1371                    (declare (ignore cold-fset))
1372                    (process-toplevel-cold-fset fun-name
1373                                                lambda-expression
1374                                                path)))
1375                 ((eval-when macrolet symbol-macrolet);things w/ 1 arg before body
1376                  (need-at-least-one-arg form)
1377                  (destructuring-bind (special-operator magic &rest body) form
1378                    (ecase special-operator
1379                      ((eval-when)
1380                       ;; CT, LT, and E here are as in Figure 3-7 of ANSI
1381                       ;; "3.2.3.1 Processing of Top Level Forms".
1382                       (multiple-value-bind (ct lt e)
1383                           (parse-eval-when-situations magic)
1384                         (let ((new-compile-time-too (or ct
1385                                                         (and compile-time-too
1386                                                              e))))
1387                           (cond (lt (process-toplevel-progn
1388                                      body path new-compile-time-too))
1389                                 (new-compile-time-too
1390                                  (eval-compile-toplevel body path))))))
1391                      ((macrolet)
1392                       (funcall-in-macrolet-lexenv
1393                        magic
1394                        (lambda (&key funs prepend)
1395                          (declare (ignore funs))
1396                          (aver (null prepend))
1397                          (process-toplevel-locally body
1398                                                    path
1399                                                    compile-time-too))
1400                        :compile))
1401                      ((symbol-macrolet)
1402                       (funcall-in-symbol-macrolet-lexenv
1403                        magic
1404                        (lambda (&key vars prepend)
1405                          (aver (null prepend))
1406                          (process-toplevel-locally body
1407                                                    path
1408                                                    compile-time-too
1409                                                    :vars vars))
1410                        :compile)))))
1411                 ((locally)
1412                  (process-toplevel-locally (rest form) path compile-time-too))
1413                 ((progn)
1414                  (process-toplevel-progn (rest form) path compile-time-too))
1415                 (t (default-processor form))))))))
1416
1417   (values))
1418 \f
1419 ;;;; load time value support
1420 ;;;;
1421 ;;;; (See EMIT-MAKE-LOAD-FORM.)
1422
1423 ;;; Return T if we are currently producing a fasl file and hence
1424 ;;; constants need to be dumped carefully.
1425 (defun producing-fasl-file ()
1426   (fasl-output-p *compile-object*))
1427
1428 ;;; Compile FORM and arrange for it to be called at load-time. Return
1429 ;;; the dumper handle and our best guess at the type of the object.
1430 (defun compile-load-time-value (form)
1431   (let ((lambda (compile-load-time-stuff form t)))
1432     (values
1433      (fasl-dump-load-time-value-lambda lambda *compile-object*)
1434      (let ((type (leaf-type lambda)))
1435        (if (fun-type-p type)
1436            (single-value-type (fun-type-returns type))
1437            *wild-type*)))))
1438
1439 ;;; Compile the FORMS and arrange for them to be called (for effect,
1440 ;;; not value) at load time.
1441 (defun compile-make-load-form-init-forms (forms)
1442   (let ((lambda (compile-load-time-stuff `(progn ,@forms) nil)))
1443     (fasl-dump-toplevel-lambda-call lambda *compile-object*)))
1444
1445 ;;; Do the actual work of COMPILE-LOAD-TIME-VALUE or
1446 ;;; COMPILE-MAKE-LOAD-FORM-INIT-FORMS.
1447 (defun compile-load-time-stuff (form for-value)
1448   (with-ir1-namespace
1449    (let* ((*lexenv* (make-null-lexenv))
1450           (lambda (ir1-toplevel form *current-path* for-value nil)))
1451      (compile-toplevel (list lambda) t)
1452      lambda)))
1453
1454 ;;; This is called by COMPILE-TOPLEVEL when it was passed T for
1455 ;;; LOAD-TIME-VALUE-P (which happens in COMPILE-LOAD-TIME-STUFF). We
1456 ;;; don't try to combine this component with anything else and frob
1457 ;;; the name. If not in a :TOPLEVEL component, then don't bother
1458 ;;; compiling, because it was merged with a run-time component.
1459 (defun compile-load-time-value-lambda (lambdas)
1460   (aver (null (cdr lambdas)))
1461   (let* ((lambda (car lambdas))
1462          (component (lambda-component lambda)))
1463     (when (eql (component-kind component) :toplevel)
1464       (setf (component-name component) (leaf-debug-name lambda))
1465       (compile-component component)
1466       (clear-ir1-info component))))
1467 \f
1468 ;;;; COMPILE-FILE
1469
1470 (defun object-call-toplevel-lambda (tll)
1471   (declare (type functional tll))
1472   (let ((object *compile-object*))
1473     (etypecase object
1474       (fasl-output (fasl-dump-toplevel-lambda-call tll object))
1475       (core-object (core-call-toplevel-lambda      tll object))
1476       (null))))
1477
1478 ;;; Smash LAMBDAS into a single component, compile it, and arrange for
1479 ;;; the resulting function to be called.
1480 (defun sub-compile-toplevel-lambdas (lambdas)
1481   (declare (list lambdas))
1482   (when lambdas
1483     (multiple-value-bind (component tll) (merge-toplevel-lambdas lambdas)
1484       (compile-component component)
1485       (clear-ir1-info component)
1486       (object-call-toplevel-lambda tll)))
1487   (values))
1488
1489 ;;; Compile top level code and call the top level lambdas. We pick off
1490 ;;; top level lambdas in non-top-level components here, calling
1491 ;;; SUB-c-t-l-l on each subsequence of normal top level lambdas.
1492 (defun compile-toplevel-lambdas (lambdas)
1493   (declare (list lambdas))
1494   (let ((len (length lambdas)))
1495     (flet ((loser (start)
1496              (or (position-if (lambda (x)
1497                                 (not (eq (component-kind
1498                                           (node-component (lambda-bind x)))
1499                                          :toplevel)))
1500                               lambdas
1501                               ;; this used to read ":start start", but
1502                               ;; start can be greater than len, which
1503                               ;; is an error according to ANSI - CSR,
1504                               ;; 2002-04-25
1505                               :start (min start len))
1506                  len)))
1507       (do* ((start 0 (1+ loser))
1508             (loser (loser start) (loser start)))
1509            ((>= start len))
1510         (sub-compile-toplevel-lambdas (subseq lambdas start loser))
1511         (unless (= loser len)
1512           (object-call-toplevel-lambda (elt lambdas loser))))))
1513   (values))
1514
1515 ;;; Compile LAMBDAS (a list of CLAMBDAs for top level forms) into the
1516 ;;; object file.
1517 ;;;
1518 ;;; LOAD-TIME-VALUE-P seems to control whether it's MAKE-LOAD-FORM and
1519 ;;; COMPILE-LOAD-TIME-VALUE stuff. -- WHN 20000201
1520 (defun compile-toplevel (lambdas load-time-value-p)
1521   (declare (list lambdas))
1522
1523   (maybe-mumble "locall ")
1524   (locall-analyze-clambdas-until-done lambdas)
1525
1526   (maybe-mumble "IDFO ")
1527   (multiple-value-bind (components top-components hairy-top)
1528       (find-initial-dfo lambdas)
1529     (let ((all-components (append components top-components)))
1530       (when *check-consistency*
1531         (maybe-mumble "[check]~%")
1532         (check-ir1-consistency all-components))
1533
1534       (dolist (component (append hairy-top top-components))
1535         (pre-physenv-analyze-toplevel component))
1536
1537       (dolist (component components)
1538         (compile-component component)
1539         (replace-toplevel-xeps component))
1540
1541       (when *check-consistency*
1542         (maybe-mumble "[check]~%")
1543         (check-ir1-consistency all-components))
1544
1545       (if load-time-value-p
1546           (compile-load-time-value-lambda lambdas)
1547           (compile-toplevel-lambdas lambdas))
1548
1549       (mapc #'clear-ir1-info components)
1550       (clear-stuff)))
1551   (values))
1552
1553 ;;; Actually compile any stuff that has been queued up for block
1554 ;;; compilation.
1555 (defun finish-block-compilation ()
1556   (when *block-compile*
1557     (when *compile-print*
1558       (compiler-mumble "~&; block compiling converted top level forms..."))
1559     (when *toplevel-lambdas*
1560       (compile-toplevel (nreverse *toplevel-lambdas*) nil)
1561       (setq *toplevel-lambdas* ()))
1562     (setq *block-compile* nil)
1563     (setq *entry-points* nil)))
1564
1565 (defun handle-condition-p (condition)
1566   (let ((lexenv
1567          (etypecase *compiler-error-context*
1568            (node
1569             (node-lexenv *compiler-error-context*))
1570            (compiler-error-context
1571             (let ((lexenv (compiler-error-context-lexenv
1572                            *compiler-error-context*)))
1573               (aver lexenv)
1574               lexenv))
1575            (null *lexenv*))))
1576     (let ((muffles (lexenv-handled-conditions lexenv)))
1577       (if (null muffles) ; common case
1578           nil
1579           (dolist (muffle muffles nil)
1580             (destructuring-bind (typespec . restart-name) muffle
1581               (when (and (typep condition typespec)
1582                          (find-restart restart-name condition))
1583                 (return t))))))))
1584
1585 (defun handle-condition-handler (condition)
1586   (let ((lexenv
1587          (etypecase *compiler-error-context*
1588            (node
1589             (node-lexenv *compiler-error-context*))
1590            (compiler-error-context
1591             (let ((lexenv (compiler-error-context-lexenv
1592                            *compiler-error-context*)))
1593               (aver lexenv)
1594               lexenv))
1595            (null *lexenv*))))
1596     (let ((muffles (lexenv-handled-conditions lexenv)))
1597       (aver muffles)
1598       (dolist (muffle muffles (bug "fell through"))
1599         (destructuring-bind (typespec . restart-name) muffle
1600           (when (typep condition typespec)
1601             (awhen (find-restart restart-name condition)
1602               (invoke-restart it))))))))
1603
1604 ;;; Read all forms from INFO and compile them, with output to OBJECT.
1605 ;;; Return (VALUES ABORT-P WARNINGS-P FAILURE-P).
1606 (defun sub-compile-file (info)
1607   (declare (type source-info info))
1608   (let ((*package* (sane-package))
1609         (*readtable* *readtable*)
1610         (sb!xc:*compile-file-pathname* nil) ; really bound in
1611         (sb!xc:*compile-file-truename* nil) ; SUB-SUB-COMPILE-FILE
1612         (*policy* *policy*)
1613         (*code-coverage-records* (make-hash-table :test 'equal))
1614         (*code-coverage-blocks* (make-hash-table :test 'equal))
1615         (*handled-conditions* *handled-conditions*)
1616         (*disabled-package-locks* *disabled-package-locks*)
1617         (*lexenv* (make-null-lexenv))
1618         (*block-compile* *block-compile-arg*)
1619         (*toplevel-lambdas* ())
1620         (*fun-names-in-this-file* ())
1621         (*allow-instrumenting* nil)
1622         (*compiler-error-bailout*
1623          (lambda ()
1624            (compiler-mumble "~2&; fatal error, aborting compilation~%")
1625            (return-from sub-compile-file (values t t t))))
1626         (*current-path* nil)
1627         (*last-source-context* nil)
1628         (*last-original-source* nil)
1629         (*last-source-form* nil)
1630         (*last-format-string* nil)
1631         (*last-format-args* nil)
1632         (*last-message-count* 0)
1633         ;; FIXME: Do we need this rebinding here? It's a literal
1634         ;; translation of the old CMU CL rebinding to
1635         ;; (OR *BACKEND-INFO-ENVIRONMENT* *INFO-ENVIRONMENT*),
1636         ;; and it's not obvious whether the rebinding to itself is
1637         ;; needed that SBCL doesn't need *BACKEND-INFO-ENVIRONMENT*.
1638         (*info-environment* *info-environment*)
1639         (*compiler-sset-counter* 0)
1640         (sb!xc:*gensym-counter* 0))
1641     (handler-case
1642         (handler-bind (((satisfies handle-condition-p) #'handle-condition-handler))
1643           (with-compilation-values
1644               (sb!xc:with-compilation-unit ()
1645                 (clear-stuff)
1646
1647                 (sub-sub-compile-file info)
1648
1649                 (unless (zerop (hash-table-count *code-coverage-records*))
1650                   ;; Dump the code coverage records into the fasl.
1651                   (fopcompile `(record-code-coverage
1652                                 ',(namestring *compile-file-pathname*)
1653                                 ',(let (list)
1654                                        (maphash (lambda (k v)
1655                                                   (declare (ignore k))
1656                                                   (push v list))
1657                                                 *code-coverage-records*)
1658                                        list))
1659                               nil
1660                               nil))
1661
1662                 (finish-block-compilation)
1663                 (let ((object *compile-object*))
1664                   (etypecase object
1665                     (fasl-output (fasl-dump-source-info info object))
1666                     (core-object (fix-core-source-info info object))
1667                     (null)))
1668                 nil)))
1669       ;; Some errors are sufficiently bewildering that we just fail
1670       ;; immediately, without trying to recover and compile more of
1671       ;; the input file.
1672       (fatal-compiler-error (condition)
1673        (signal condition)
1674        (fresh-line *error-output*)
1675        (pprint-logical-block (*error-output* nil :per-line-prefix "; ")
1676          (format *error-output*
1677                  "~@<~@:_compilation aborted because of fatal error: ~2I~_~A~@:_~:>"
1678                  (encapsulated-condition condition)))
1679        (finish-output *error-output*)
1680        (values t t t)))))
1681
1682 ;;; Return a pathname for the named file. The file must exist.
1683 (defun verify-source-file (pathname-designator)
1684   (let* ((pathname (pathname pathname-designator))
1685          (default-host (make-pathname :host (pathname-host pathname))))
1686     (flet ((try-with-type (path type error-p)
1687              (let ((new (merge-pathnames
1688                          path (make-pathname :type type
1689                                              :defaults default-host))))
1690                (if (probe-file new)
1691                    new
1692                    (and error-p (truename new))))))
1693       (cond ((typep pathname 'logical-pathname)
1694              (try-with-type pathname "LISP" t))
1695             ((probe-file pathname) pathname)
1696             ((try-with-type pathname "lisp"  nil))
1697             ((try-with-type pathname "lisp"  t))))))
1698
1699 (defun elapsed-time-to-string (internal-time-delta)
1700   (multiple-value-bind (tsec remainder)
1701       (truncate internal-time-delta internal-time-units-per-second)
1702     (let ((ms (truncate remainder (/ internal-time-units-per-second 1000))))
1703       (multiple-value-bind (tmin sec) (truncate tsec 60)
1704         (multiple-value-bind (thr min) (truncate tmin 60)
1705           (format nil "~D:~2,'0D:~2,'0D.~3,'0D" thr min sec ms))))))
1706
1707 ;;; Print some junk at the beginning and end of compilation.
1708 (defun print-compile-start-note (source-info)
1709   (declare (type source-info source-info))
1710   (let ((file-info (source-info-file-info source-info)))
1711     (compiler-mumble "~&; compiling file ~S (written ~A):~%"
1712                      (namestring (file-info-name file-info))
1713                      (sb!int:format-universal-time nil
1714                                                    (file-info-write-date
1715                                                     file-info)
1716                                                    :style :government
1717                                                    :print-weekday nil
1718                                                    :print-timezone nil)))
1719   (values))
1720
1721 (defun print-compile-end-note (source-info won)
1722   (declare (type source-info source-info))
1723   (compiler-mumble "~&; compilation ~:[aborted after~;finished in~] ~A~&"
1724                    won
1725                    (elapsed-time-to-string
1726                     (- (get-internal-real-time)
1727                        (source-info-start-real-time source-info))))
1728   (values))
1729
1730 ;;; Open some files and call SUB-COMPILE-FILE. If something unwinds
1731 ;;; out of the compile, then abort the writing of the output file, so
1732 ;;; that we don't overwrite it with known garbage.
1733 (defun sb!xc:compile-file
1734     (input-file
1735      &key
1736
1737      ;; ANSI options
1738      (output-file (cfp-output-file-default input-file))
1739      ;; FIXME: ANSI doesn't seem to say anything about
1740      ;; *COMPILE-VERBOSE* and *COMPILE-PRINT* being rebound by this
1741      ;; function..
1742      ((:verbose sb!xc:*compile-verbose*) sb!xc:*compile-verbose*)
1743      ((:print sb!xc:*compile-print*) sb!xc:*compile-print*)
1744      (external-format :default)
1745
1746      ;; extensions
1747      (trace-file nil)
1748      ((:block-compile *block-compile-arg*) nil)
1749      (emit-cfasl *emit-cfasl*))
1750   #!+sb-doc
1751   "Compile INPUT-FILE, producing a corresponding fasl file and
1752 returning its filename.
1753
1754   :PRINT
1755      If true, a message per non-macroexpanded top level form is printed
1756      to *STANDARD-OUTPUT*. Top level forms that whose subforms are
1757      processed as top level forms (eg. EVAL-WHEN, MACROLET, PROGN) receive
1758      no such message, but their subforms do.
1759
1760      As an extension to ANSI, if :PRINT is :top-level-forms, a message
1761      per top level form after macroexpansion is printed to *STANDARD-OUTPUT*.
1762      For example, compiling an IN-PACKAGE form will result in a message about
1763      a top level SETQ in addition to the message about the IN-PACKAGE form'
1764      itself.
1765
1766      Both forms of reporting obey the SB-EXT:*COMPILER-PRINT-VARIABLE-ALIST*.
1767
1768   :BLOCK-COMPILE
1769      Though COMPILE-FILE accepts an additional :BLOCK-COMPILE
1770      argument, it is not currently supported. (non-standard)
1771
1772   :TRACE-FILE
1773      If given, internal data structures are dumped to the specified
1774      file, or if a value of T is given, to a file of *.trace type
1775      derived from the input file name. (non-standard)
1776
1777   :EMIT-CFASL
1778      (Experimental). If true, outputs the toplevel compile-time effects
1779      of this file into a separate .cfasl file."
1780 ;;; Block compilation is currently broken.
1781 #|
1782   "Also, as a workaround for vaguely-non-ANSI behavior, the
1783 :BLOCK-COMPILE argument is quasi-supported, to determine whether
1784 multiple functions are compiled together as a unit, resolving function
1785 references at compile time. NIL means that global function names are
1786 never resolved at compilation time. Currently NIL is the default
1787 behavior, because although section 3.2.2.3, \"Semantic Constraints\",
1788 of the ANSI spec allows this behavior under all circumstances, the
1789 compiler's runtime scales badly when it tries to do this for large
1790 files. If/when this performance problem is fixed, the block
1791 compilation default behavior will probably be made dependent on the
1792 SPEED and COMPILATION-SPEED optimization values, and the
1793 :BLOCK-COMPILE argument will probably become deprecated."
1794 |#
1795   (let* ((fasl-output nil)
1796          (cfasl-output nil)
1797          (output-file-name nil)
1798          (coutput-file-name nil)
1799          (abort-p t)
1800          (warnings-p nil)
1801          (failure-p t) ; T in case error keeps this from being set later
1802          (input-pathname (verify-source-file input-file))
1803          (source-info (make-file-source-info input-pathname external-format))
1804          (*compiler-trace-output* nil)) ; might be modified below
1805
1806     (unwind-protect
1807         (progn
1808           (when output-file
1809             (setq output-file-name
1810                   (sb!xc:compile-file-pathname input-file
1811                                                :output-file output-file))
1812             (setq fasl-output
1813                   (open-fasl-output output-file-name
1814                                     (namestring input-pathname))))
1815           (when emit-cfasl
1816             (setq coutput-file-name
1817                   (make-pathname :type "cfasl"
1818                                  :defaults output-file-name))
1819             (setq cfasl-output
1820                   (open-fasl-output coutput-file-name
1821                                     (namestring input-pathname))))
1822           (when trace-file
1823             (let* ((default-trace-file-pathname
1824                      (make-pathname :type "trace" :defaults input-pathname))
1825                    (trace-file-pathname
1826                     (if (eql trace-file t)
1827                         default-trace-file-pathname
1828                         (merge-pathnames trace-file
1829                                          default-trace-file-pathname))))
1830               (setf *compiler-trace-output*
1831                     (open trace-file-pathname
1832                           :if-exists :supersede
1833                           :direction :output))))
1834
1835           (when sb!xc:*compile-verbose*
1836             (print-compile-start-note source-info))
1837
1838           (let ((*compile-object* fasl-output)
1839                 (*compile-toplevel-object* cfasl-output))
1840             (setf (values abort-p warnings-p failure-p)
1841                   (sub-compile-file source-info))))
1842
1843       (close-source-info source-info)
1844
1845       (when fasl-output
1846         (close-fasl-output fasl-output abort-p)
1847         (setq output-file-name
1848               (pathname (fasl-output-stream fasl-output)))
1849         (when (and (not abort-p) sb!xc:*compile-verbose*)
1850           (compiler-mumble "~2&; ~A written~%" (namestring output-file-name))))
1851
1852       (when cfasl-output
1853         (close-fasl-output cfasl-output abort-p)
1854         (when (and (not abort-p) sb!xc:*compile-verbose*)
1855           (compiler-mumble "; ~A written~%" (namestring coutput-file-name))))
1856
1857       (when sb!xc:*compile-verbose*
1858         (print-compile-end-note source-info (not abort-p)))
1859
1860       (when *compiler-trace-output*
1861         (close *compiler-trace-output*)))
1862
1863     ;; CLHS says that the first value is NIL if the "file could not
1864     ;; be created". We interpret this to mean "a valid fasl could not
1865     ;; be created" -- which can happen if the compilation is aborted
1866     ;; before the whole file has been processed, due to eg. a reader
1867     ;; error.
1868     (values (when (and (not abort-p) output-file)
1869               ;; Hack around filesystem race condition...
1870               (or (probe-file output-file-name) output-file-name))
1871             warnings-p
1872             failure-p)))
1873 \f
1874 ;;; a helper function for COMPILE-FILE-PATHNAME: the default for
1875 ;;; the OUTPUT-FILE argument
1876 ;;;
1877 ;;; ANSI: The defaults for the OUTPUT-FILE are taken from the pathname
1878 ;;; that results from merging the INPUT-FILE with the value of
1879 ;;; *DEFAULT-PATHNAME-DEFAULTS*, except that the type component should
1880 ;;; default to the appropriate implementation-defined default type for
1881 ;;; compiled files.
1882 (defun cfp-output-file-default (input-file)
1883   (let* ((defaults (merge-pathnames input-file *default-pathname-defaults*))
1884          (retyped (make-pathname :type *fasl-file-type* :defaults defaults)))
1885     retyped))
1886
1887 ;;; KLUDGE: Part of the ANSI spec for this seems contradictory:
1888 ;;;   If INPUT-FILE is a logical pathname and OUTPUT-FILE is unsupplied,
1889 ;;;   the result is a logical pathname. If INPUT-FILE is a logical
1890 ;;;   pathname, it is translated into a physical pathname as if by
1891 ;;;   calling TRANSLATE-LOGICAL-PATHNAME.
1892 ;;; So I haven't really tried to make this precisely ANSI-compatible
1893 ;;; at the level of e.g. whether it returns logical pathname or a
1894 ;;; physical pathname. Patches to make it more correct are welcome.
1895 ;;; -- WHN 2000-12-09
1896 (defun sb!xc:compile-file-pathname (input-file
1897                                     &key
1898                                     (output-file nil output-file-p)
1899                                     &allow-other-keys)
1900   #!+sb-doc
1901   "Return a pathname describing what file COMPILE-FILE would write to given
1902    these arguments."
1903   (if output-file-p
1904       (merge-pathnames output-file (cfp-output-file-default input-file))
1905       (cfp-output-file-default input-file)))
1906 \f
1907 ;;;; MAKE-LOAD-FORM stuff
1908
1909 ;;; The entry point for MAKE-LOAD-FORM support. When IR1 conversion
1910 ;;; finds a constant structure, it invokes this to arrange for proper
1911 ;;; dumping. If it turns out that the constant has already been
1912 ;;; dumped, then we don't need to do anything.
1913 ;;;
1914 ;;; If the constant hasn't been dumped, then we check to see whether
1915 ;;; we are in the process of creating it. We detect this by
1916 ;;; maintaining the special *CONSTANTS-BEING-CREATED* as a list of all
1917 ;;; the constants we are in the process of creating. Actually, each
1918 ;;; entry is a list of the constant and any init forms that need to be
1919 ;;; processed on behalf of that constant.
1920 ;;;
1921 ;;; It's not necessarily an error for this to happen. If we are
1922 ;;; processing the init form for some object that showed up *after*
1923 ;;; the original reference to this constant, then we just need to
1924 ;;; defer the processing of that init form. To detect this, we
1925 ;;; maintain *CONSTANTS-CREATED-SINCE-LAST-INIT* as a list of the
1926 ;;; constants created since the last time we started processing an
1927 ;;; init form. If the constant passed to emit-make-load-form shows up
1928 ;;; in this list, then there is a circular chain through creation
1929 ;;; forms, which is an error.
1930 ;;;
1931 ;;; If there is some intervening init form, then we blow out of
1932 ;;; processing it by throwing to the tag PENDING-INIT. The value we
1933 ;;; throw is the entry from *CONSTANTS-BEING-CREATED*. This is so the
1934 ;;; offending init form can be tacked onto the init forms for the
1935 ;;; circular object.
1936 ;;;
1937 ;;; If the constant doesn't show up in *CONSTANTS-BEING-CREATED*, then
1938 ;;; we have to create it. We call MAKE-LOAD-FORM and check to see
1939 ;;; whether the creation form is the magic value
1940 ;;; :SB-JUST-DUMP-IT-NORMALLY. If it is, then we don't do anything. The
1941 ;;; dumper will eventually get its hands on the object and use the
1942 ;;; normal structure dumping noise on it.
1943 ;;;
1944 ;;; Otherwise, we bind *CONSTANTS-BEING-CREATED* and
1945 ;;; *CONSTANTS-CREATED-SINCE- LAST-INIT* and compile the creation form
1946 ;;; much the way LOAD-TIME-VALUE does. When this finishes, we tell the
1947 ;;; dumper to use that result instead whenever it sees this constant.
1948 ;;;
1949 ;;; Now we try to compile the init form. We bind
1950 ;;; *CONSTANTS-CREATED-SINCE-LAST-INIT* to NIL and compile the init
1951 ;;; form (and any init forms that were added because of circularity
1952 ;;; detection). If this works, great. If not, we add the init forms to
1953 ;;; the init forms for the object that caused the problems and let it
1954 ;;; deal with it.
1955 (defvar *constants-being-created* nil)
1956 (defvar *constants-created-since-last-init* nil)
1957 ;;; FIXME: Shouldn't these^ variables be unbound outside LET forms?
1958 (defun emit-make-load-form (constant &optional (name nil namep))
1959   (aver (fasl-output-p *compile-object*))
1960   (unless (or (fasl-constant-already-dumped-p constant *compile-object*)
1961               ;; KLUDGE: This special hack is because I was too lazy
1962               ;; to rework DEF!STRUCT so that the MAKE-LOAD-FORM
1963               ;; function of LAYOUT returns nontrivial forms when
1964               ;; building the cross-compiler but :IGNORE-IT when
1965               ;; cross-compiling or running under the target Lisp. --
1966               ;; WHN 19990914
1967               #+sb-xc-host (typep constant 'layout))
1968     (let ((circular-ref (assoc constant *constants-being-created* :test #'eq)))
1969       (when circular-ref
1970         (when (find constant *constants-created-since-last-init* :test #'eq)
1971           (throw constant t))
1972         (throw 'pending-init circular-ref)))
1973     (multiple-value-bind (creation-form init-form)
1974         (if namep
1975             ;; If the constant is a reference to a named constant, we can
1976             ;; just use SYMBOL-VALUE during LOAD.
1977             (values `(symbol-value ',name) nil)
1978             (handler-case
1979                 (sb!xc:make-load-form constant (make-null-lexenv))
1980               (error (condition)
1981                 (compiler-error condition))))
1982       (case creation-form
1983         (:sb-just-dump-it-normally
1984          (fasl-validate-structure constant *compile-object*)
1985          t)
1986         (:ignore-it
1987          nil)
1988         (t
1989          (let* ((name (write-to-string constant :level 1 :length 2))
1990                 (info (if init-form
1991                           (list constant name init-form)
1992                           (list constant))))
1993            (let ((*constants-being-created*
1994                   (cons info *constants-being-created*))
1995                  (*constants-created-since-last-init*
1996                   (cons constant *constants-created-since-last-init*)))
1997              (when
1998                  (catch constant
1999                    (fasl-note-handle-for-constant
2000                     constant
2001                     (compile-load-time-value
2002                      creation-form)
2003                     *compile-object*)
2004                    nil)
2005                (compiler-error "circular references in creation form for ~S"
2006                                constant)))
2007            (when (cdr info)
2008              (let* ((*constants-created-since-last-init* nil)
2009                     (circular-ref
2010                      (catch 'pending-init
2011                        (loop for (name form) on (cdr info) by #'cddr
2012                          collect name into names
2013                          collect form into forms
2014                          finally (compile-make-load-form-init-forms forms))
2015                        nil)))
2016                (when circular-ref
2017                  (setf (cdr circular-ref)
2018                        (append (cdr circular-ref) (cdr info))))))))))))
2019
2020 \f
2021 ;;;; Host compile time definitions
2022 #+sb-xc-host
2023 (defun compile-in-lexenv (name lambda lexenv)
2024   (declare (ignore lexenv))
2025   (compile name lambda))
2026
2027 #+sb-xc-host
2028 (defun eval-in-lexenv (form lexenv)
2029   (declare (ignore lexenv))
2030   (eval form))