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