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