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