0.8.0.31:
[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                          (flet ((maybe-frob (maybe-clambda)
867                                   (when (and maybe-clambda
868                                              (promise-ready-p maybe-clambda))
869                                     (pushnew (lambda-component
870                                               (force maybe-clambda))
871                                              result))))
872                            (map nil #'maybe-frob (optional-dispatch-entry-points f))
873                            (maybe-frob (optional-dispatch-more-entry f))
874                            (maybe-frob (optional-dispatch-main-entry f)))
875                          result))))
876
877 (defun make-functional-from-toplevel-lambda (definition
878                                              &key
879                                              name
880                                              (path
881                                               ;; I'd thought NIL should
882                                               ;; work, but it doesn't.
883                                               ;; -- WHN 2001-09-20
884                                               (missing-arg)))
885   (let* ((*current-path* path)
886          (component (make-empty-component))
887          (*current-component* component))
888     (setf (component-name component)
889           (debug-namify "~S initial component" name))
890     (setf (component-kind component) :initial)
891     (let* ((locall-fun (ir1-convert-lambdalike
892                         definition
893                         :debug-name (debug-namify "top level local call ~S"
894                                                   name)
895                         ;; KLUDGE: we do this so that we get to have
896                         ;; nice debug returnness in functions defined
897                         ;; from the REPL
898                         :allow-debug-catch-tag t))
899            (fun (ir1-convert-lambda (make-xep-lambda-expression locall-fun)
900                                     :source-name (or name '.anonymous.)
901                                     :debug-name (unless name
902                                                   "top level form"))))
903       (when name
904         (assert-global-function-definition-type name locall-fun))
905       (setf (functional-entry-fun fun) locall-fun
906             (functional-kind fun) :external
907             (functional-has-external-references-p fun) t)
908       fun)))
909
910 ;;; Compile LAMBDA-EXPRESSION into *COMPILE-OBJECT*, returning a
911 ;;; description of the result.
912 ;;;   * If *COMPILE-OBJECT* is a CORE-OBJECT, then write the function
913 ;;;     into core and return the compiled FUNCTION value.
914 ;;;   * If *COMPILE-OBJECT* is a fasl file, then write the function
915 ;;;     into the fasl file and return a dump handle.
916 ;;;
917 ;;; If NAME is provided, then we try to use it as the name of the
918 ;;; function for debugging/diagnostic information.
919 (defun %compile (lambda-expression
920                  *compile-object*
921                  &key
922                  name
923                  (path
924                   ;; This magical idiom seems to be the appropriate
925                   ;; path for compiling standalone LAMBDAs, judging
926                   ;; from the CMU CL code and experiment, so it's a
927                   ;; nice default for things where we don't have a
928                   ;; real source path (as in e.g. inside CL:COMPILE).
929                   '(original-source-start 0 0)))
930   (when name
931     (legal-fun-name-or-type-error name))
932   (let* ((*lexenv* (make-lexenv :policy *policy*))
933          (fun (make-functional-from-toplevel-lambda lambda-expression
934                                                     :name name
935                                                     :path path)))
936
937     ;; FIXME: The compile-it code from here on is sort of a
938     ;; twisted version of the code in COMPILE-TOPLEVEL. It'd be
939     ;; better to find a way to share the code there; or
940     ;; alternatively, to use this code to replace the code there.
941     ;; (The second alternative might be pretty easy if we used
942     ;; the :LOCALL-ONLY option to IR1-FOR-LAMBDA. Then maybe the
943     ;; whole FUNCTIONAL-KIND=:TOPLEVEL case could go away..)
944
945     (locall-analyze-clambdas-until-done (list fun))
946     
947     (multiple-value-bind (components-from-dfo top-components hairy-top)
948         (find-initial-dfo (list fun))
949
950       (let ((*all-components* (append components-from-dfo top-components)))
951         ;; FIXME: This is more monkey see monkey do based on CMU CL
952         ;; code. If anyone figures out why to only prescan HAIRY-TOP
953         ;; and TOP-COMPONENTS here, instead of *ALL-COMPONENTS* or
954         ;; some other combination of results from FIND-INITIAL-VALUES,
955         ;; it'd be good to explain it.
956         (mapc #'preallocate-physenvs-for-toplevelish-lambdas hairy-top)
957         (mapc #'preallocate-physenvs-for-toplevelish-lambdas top-components)
958         (dolist (component-from-dfo components-from-dfo)
959           (compile-component component-from-dfo)
960           (replace-toplevel-xeps component-from-dfo)))
961
962       (let ((entry-table (etypecase *compile-object*
963                            (fasl-output (fasl-output-entry-table
964                                          *compile-object*))
965                            (core-object (core-object-entry-table
966                                          *compile-object*)))))
967         (multiple-value-bind (result found-p)
968             (gethash (leaf-info fun) entry-table)
969           (aver found-p)
970           (prog1 
971               result
972             ;; KLUDGE: This code duplicates some other code in this
973             ;; file. In the great reorganzation, the flow of program
974             ;; logic changed from the original CMUCL model, and that
975             ;; path (as of sbcl-0.7.5 in SUB-COMPILE-FILE) was no
976             ;; longer followed for CORE-OBJECTS, leading to BUG
977             ;; 156. This place is transparently not the right one for
978             ;; this code, but I don't have a clear enough overview of
979             ;; the compiler to know how to rearrange it all so that
980             ;; this operation fits in nicely, and it was blocking
981             ;; reimplementation of (DECLAIM (INLINE FOO)) (MACROLET
982             ;; ((..)) (DEFUN FOO ...))
983             ;;
984             ;; FIXME: This KLUDGE doesn't solve all the problem in an
985             ;; ideal way, as (1) definitions typed in at the REPL
986             ;; without an INLINE declaration will give a NULL
987             ;; FUNCTION-LAMBDA-EXPRESSION (allowable, but not ideal)
988             ;; and (2) INLINE declarations will yield a
989             ;; FUNCTION-LAMBDA-EXPRESSION headed by
990             ;; SB-C:LAMBDA-WITH-LEXENV, even for null LEXENV.  -- CSR,
991             ;; 2002-07-02
992             ;;
993             ;; (2) is probably fairly easy to fix -- it is, after all,
994             ;; a matter of list manipulation (or possibly of teaching
995             ;; CL:FUNCTION about SB-C:LAMBDA-WITH-LEXENV).  (1) is
996             ;; significantly harder, as the association between
997             ;; function object and source is a tricky one.
998             ;;
999             ;; FUNCTION-LAMBDA-EXPRESSION "works" (i.e. returns a
1000             ;; non-NULL list) when the function in question has been
1001             ;; compiled by (COMPILE <x> '(LAMBDA ...)); it does not
1002             ;; work when it has been compiled as part of the top-level
1003             ;; EVAL strategy of compiling everything inside (LAMBDA ()
1004             ;; ...).  -- CSR, 2002-11-02
1005             (when (core-object-p *compile-object*)
1006               (fix-core-source-info *source-info* *compile-object* result))
1007
1008             (mapc #'clear-ir1-info components-from-dfo)
1009             (clear-stuff)))))))
1010
1011 (defun process-toplevel-cold-fset (name lambda-expression path)
1012   (unless (producing-fasl-file)
1013     (error "can't COLD-FSET except in a fasl file"))
1014   (legal-fun-name-or-type-error name)
1015   (fasl-dump-cold-fset name
1016                        (%compile lambda-expression
1017                                  *compile-object*
1018                                  :name name
1019                                  :path path)
1020                        *compile-object*)
1021   (values))
1022
1023 ;;; Process a top level FORM with the specified source PATH.
1024 ;;;  * If this is a magic top level form, then do stuff.
1025 ;;;  * If this is a macro, then expand it.
1026 ;;;  * Otherwise, just compile it.
1027 ;;;
1028 ;;; COMPILE-TIME-TOO is as defined in ANSI
1029 ;;; "3.2.3.1 Processing of Top Level Forms".
1030 (defun process-toplevel-form (form path compile-time-too)
1031
1032   (declare (list path))
1033
1034   (catch 'process-toplevel-form-error-abort
1035     (let* ((path (or (gethash form *source-paths*) (cons form path)))
1036            (*compiler-error-bailout*
1037             (lambda ()
1038               (convert-and-maybe-compile
1039                `(error 'simple-program-error
1040                  :format-control "execution of a form compiled with errors:~% ~S"
1041                  :format-arguments (list ',form))
1042                path)
1043               (throw 'process-toplevel-form-error-abort nil))))
1044
1045       (flet ((default-processor (form)
1046                ;; When we're cross-compiling, consider: what should we
1047                ;; do when we hit e.g.
1048                ;;   (EVAL-WHEN (:COMPILE-TOPLEVEL)
1049                ;;     (DEFUN FOO (X) (+ 7 X)))?
1050                ;; DEFUN has a macro definition in the cross-compiler,
1051                ;; and a different macro definition in the target
1052                ;; compiler. The only sensible thing is to use the
1053                ;; target compiler's macro definition, since the
1054                ;; cross-compiler's macro is in general into target
1055                ;; functions which can't meaningfully be executed at
1056                ;; cross-compilation time. So make sure we do the EVAL
1057                ;; here, before we macroexpand.
1058                ;;
1059                ;; Then things get even dicier with something like
1060                ;;   (DEFCONSTANT-EQX SB!XC:LAMBDA-LIST-KEYWORDS ..)
1061                ;; where we have to make sure that we don't uncross
1062                ;; the SB!XC: prefix before we do EVAL, because otherwise
1063                ;; we'd be trying to redefine the cross-compilation host's
1064                ;; constants.
1065                ;;
1066                ;; (Isn't it fun to cross-compile Common Lisp?:-)
1067                #+sb-xc-host
1068                (progn
1069                  (when compile-time-too
1070                    (eval form)) ; letting xc host EVAL do its own macroexpansion
1071                  (let* (;; (We uncross the operator name because things
1072                         ;; like SB!XC:DEFCONSTANT and SB!XC:DEFTYPE
1073                         ;; should be equivalent to their CL: counterparts
1074                         ;; when being compiled as target code. We leave
1075                         ;; the rest of the form uncrossed because macros
1076                         ;; might yet expand into EVAL-WHEN stuff, and
1077                         ;; things inside EVAL-WHEN can't be uncrossed
1078                         ;; until after we've EVALed them in the
1079                         ;; cross-compilation host.)
1080                         (slightly-uncrossed (cons (uncross (first form))
1081                                                   (rest form)))
1082                         (expanded (preprocessor-macroexpand-1
1083                                    slightly-uncrossed)))
1084                    (if (eq expanded slightly-uncrossed)
1085                        ;; (Now that we're no longer processing toplevel
1086                        ;; forms, and hence no longer need to worry about
1087                        ;; EVAL-WHEN, we can uncross everything.)
1088                        (convert-and-maybe-compile expanded path)
1089                        ;; (We have to demote COMPILE-TIME-TOO to NIL
1090                        ;; here, no matter what it was before, since
1091                        ;; otherwise we'd tend to EVAL subforms more than
1092                        ;; once, because of WHEN COMPILE-TIME-TOO form
1093                        ;; above.)
1094                        (process-toplevel-form expanded path nil))))
1095                ;; When we're not cross-compiling, we only need to
1096                ;; macroexpand once, so we can follow the 1-thru-6
1097                ;; sequence of steps in ANSI's "3.2.3.1 Processing of
1098                ;; Top Level Forms".
1099                #-sb-xc-host
1100                (let ((expanded (preprocessor-macroexpand-1 form)))
1101                  (cond ((eq expanded form)
1102                         (when compile-time-too
1103                           (eval-in-lexenv form *lexenv*))
1104                         (convert-and-maybe-compile form path))
1105                        (t
1106                         (process-toplevel-form expanded
1107                                                path
1108                                                compile-time-too))))))
1109         (if (atom form)
1110             #+sb-xc-host
1111             ;; (There are no xc EVAL-WHEN issues in the ATOM case until
1112             ;; (1) SBCL gets smart enough to handle global
1113             ;; DEFINE-SYMBOL-MACRO or SYMBOL-MACROLET and (2) SBCL
1114             ;; implementors start using symbol macros in a way which
1115             ;; interacts with SB-XC/CL distinction.)
1116             (convert-and-maybe-compile form path)
1117             #-sb-xc-host
1118             (default-processor form)
1119             (flet ((need-at-least-one-arg (form)
1120                      (unless (cdr form)
1121                        (compiler-error "~S form is too short: ~S"
1122                                        (car form)
1123                                        form))))
1124               (case (car form)
1125                 ;; In the cross-compiler, top level COLD-FSET arranges
1126                 ;; for static linking at cold init time.
1127                 #+sb-xc-host
1128                 ((cold-fset)
1129                  (aver (not compile-time-too))
1130                  (destructuring-bind (cold-fset fun-name lambda-expression) form
1131                    (declare (ignore cold-fset))
1132                    (process-toplevel-cold-fset fun-name
1133                                                lambda-expression
1134                                                path)))
1135                 ((eval-when macrolet symbol-macrolet);things w/ 1 arg before body
1136                  (need-at-least-one-arg form)
1137                  (destructuring-bind (special-operator magic &rest body) form
1138                    (ecase special-operator
1139                      ((eval-when)
1140                       ;; CT, LT, and E here are as in Figure 3-7 of ANSI
1141                       ;; "3.2.3.1 Processing of Top Level Forms".
1142                       (multiple-value-bind (ct lt e)
1143                           (parse-eval-when-situations magic)
1144                         (let ((new-compile-time-too (or ct
1145                                                         (and compile-time-too
1146                                                              e))))
1147                           (cond (lt (process-toplevel-progn
1148                                      body path new-compile-time-too))
1149                                 (new-compile-time-too (eval-in-lexenv
1150                                                        `(progn ,@body)
1151                                                        *lexenv*))))))
1152                      ((macrolet)
1153                       (funcall-in-macrolet-lexenv
1154                        magic
1155                        (lambda (&key funs)
1156                          (declare (ignore funs))
1157                          (process-toplevel-locally body
1158                                                    path
1159                                                    compile-time-too))))
1160                      ((symbol-macrolet)
1161                       (funcall-in-symbol-macrolet-lexenv
1162                        magic
1163                        (lambda (&key vars)
1164                          (process-toplevel-locally body
1165                                                    path
1166                                                    compile-time-too
1167                                                    :vars vars)))))))
1168                 ((locally)
1169                  (process-toplevel-locally (rest form) path compile-time-too))
1170                 ((progn)
1171                  (process-toplevel-progn (rest form) path compile-time-too))
1172                 (t (default-processor form))))))))
1173
1174   (values))
1175 \f
1176 ;;;; load time value support
1177 ;;;;
1178 ;;;; (See EMIT-MAKE-LOAD-FORM.)
1179
1180 ;;; Return T if we are currently producing a fasl file and hence
1181 ;;; constants need to be dumped carefully.
1182 (defun producing-fasl-file ()
1183   (fasl-output-p *compile-object*))
1184
1185 ;;; Compile FORM and arrange for it to be called at load-time. Return
1186 ;;; the dumper handle and our best guess at the type of the object.
1187 (defun compile-load-time-value (form)
1188   (let ((lambda (compile-load-time-stuff form t)))
1189     (values
1190      (fasl-dump-load-time-value-lambda lambda *compile-object*)
1191      (let ((type (leaf-type lambda)))
1192        (if (fun-type-p type)
1193            (single-value-type (fun-type-returns type))
1194            *wild-type*)))))
1195
1196 ;;; Compile the FORMS and arrange for them to be called (for effect,
1197 ;;; not value) at load time.
1198 (defun compile-make-load-form-init-forms (forms)
1199   (let ((lambda (compile-load-time-stuff `(progn ,@forms) nil)))
1200     (fasl-dump-toplevel-lambda-call lambda *compile-object*)))
1201
1202 ;;; Do the actual work of COMPILE-LOAD-TIME-VALUE or
1203 ;;; COMPILE-MAKE-LOAD-FORM-INIT-FORMS.
1204 (defun compile-load-time-stuff (form for-value)
1205   (with-ir1-namespace
1206    (let* ((*lexenv* (make-null-lexenv))
1207           (lambda (ir1-toplevel form *current-path* for-value)))
1208      (compile-toplevel (list lambda) t)
1209      lambda)))
1210
1211 ;;; This is called by COMPILE-TOPLEVEL when it was passed T for
1212 ;;; LOAD-TIME-VALUE-P (which happens in COMPILE-LOAD-TIME-STUFF). We
1213 ;;; don't try to combine this component with anything else and frob
1214 ;;; the name. If not in a :TOPLEVEL component, then don't bother
1215 ;;; compiling, because it was merged with a run-time component.
1216 (defun compile-load-time-value-lambda (lambdas)
1217   (aver (null (cdr lambdas)))
1218   (let* ((lambda (car lambdas))
1219          (component (lambda-component lambda)))
1220     (when (eql (component-kind component) :toplevel)
1221       (setf (component-name component) (leaf-debug-name lambda))
1222       (compile-component component)
1223       (clear-ir1-info component))))
1224 \f
1225 ;;;; COMPILE-FILE
1226
1227 (defun object-call-toplevel-lambda (tll)
1228   (declare (type functional tll))
1229   (let ((object *compile-object*))
1230     (etypecase object
1231       (fasl-output (fasl-dump-toplevel-lambda-call tll object))
1232       (core-object (core-call-toplevel-lambda      tll object))
1233       (null))))
1234
1235 ;;; Smash LAMBDAS into a single component, compile it, and arrange for
1236 ;;; the resulting function to be called.
1237 (defun sub-compile-toplevel-lambdas (lambdas)
1238   (declare (list lambdas))
1239   (when lambdas
1240     (multiple-value-bind (component tll) (merge-toplevel-lambdas lambdas)
1241       (compile-component component)
1242       (clear-ir1-info component)
1243       (object-call-toplevel-lambda tll)))
1244   (values))
1245
1246 ;;; Compile top level code and call the top level lambdas. We pick off
1247 ;;; top level lambdas in non-top-level components here, calling
1248 ;;; SUB-c-t-l-l on each subsequence of normal top level lambdas.
1249 (defun compile-toplevel-lambdas (lambdas)
1250   (declare (list lambdas))
1251   (let ((len (length lambdas)))
1252     (flet ((loser (start)
1253              (or (position-if (lambda (x)
1254                                 (not (eq (component-kind
1255                                           (node-component (lambda-bind x)))
1256                                          :toplevel)))
1257                               lambdas
1258                               ;; this used to read ":start start", but
1259                               ;; start can be greater than len, which
1260                               ;; is an error according to ANSI - CSR,
1261                               ;; 2002-04-25
1262                               :start (min start len))
1263                  len)))
1264       (do* ((start 0 (1+ loser))
1265             (loser (loser start) (loser start)))
1266            ((>= start len))
1267         (sub-compile-toplevel-lambdas (subseq lambdas start loser))
1268         (unless (= loser len)
1269           (object-call-toplevel-lambda (elt lambdas loser))))))
1270   (values))
1271
1272 ;;; Compile LAMBDAS (a list of CLAMBDAs for top level forms) into the
1273 ;;; object file. 
1274 ;;;
1275 ;;; LOAD-TIME-VALUE-P seems to control whether it's MAKE-LOAD-FORM and
1276 ;;; COMPILE-LOAD-TIME-VALUE stuff. -- WHN 20000201
1277 (defun compile-toplevel (lambdas load-time-value-p)
1278   (declare (list lambdas))
1279
1280   (maybe-mumble "locall ")
1281   (locall-analyze-clambdas-until-done lambdas)
1282
1283   (maybe-mumble "IDFO ")
1284   (multiple-value-bind (components top-components hairy-top)
1285       (find-initial-dfo lambdas)
1286     (let ((*all-components* (append components top-components)))
1287       (when *check-consistency*
1288         (maybe-mumble "[check]~%")
1289         (check-ir1-consistency *all-components*))
1290
1291       (dolist (component (append hairy-top top-components))
1292         (pre-physenv-analyze-toplevel component))
1293
1294       (dolist (component components)
1295         (compile-component component)
1296         (replace-toplevel-xeps component))
1297         
1298       (when *check-consistency*
1299         (maybe-mumble "[check]~%")
1300         (check-ir1-consistency *all-components*))
1301         
1302       (if load-time-value-p
1303           (compile-load-time-value-lambda lambdas)
1304           (compile-toplevel-lambdas lambdas))
1305
1306       (mapc #'clear-ir1-info components)
1307       (clear-stuff)))
1308   (values))
1309
1310 ;;; Actually compile any stuff that has been queued up for block
1311 ;;; compilation.
1312 (defun finish-block-compilation ()
1313   (when *block-compile*
1314     (when *toplevel-lambdas*
1315       (compile-toplevel (nreverse *toplevel-lambdas*) nil)
1316       (setq *toplevel-lambdas* ()))
1317     (setq *block-compile* nil)
1318     (setq *entry-points* nil)))
1319
1320 ;;; Read all forms from INFO and compile them, with output to OBJECT.
1321 ;;; Return (VALUES NIL WARNINGS-P FAILURE-P).
1322 (defun sub-compile-file (info)
1323   (declare (type source-info info))
1324   (let* ((*block-compile* *block-compile-arg*)
1325          (*package* (sane-package))
1326          (*policy* *policy*)
1327          (*lexenv* (make-null-lexenv))
1328          (*source-info* info)
1329          (sb!xc:*compile-file-pathname* nil)
1330          (sb!xc:*compile-file-truename* nil)
1331          (*toplevel-lambdas* ())
1332          (*compiler-error-bailout*
1333           (lambda ()
1334             (compiler-mumble "~2&; fatal error, aborting compilation~%")
1335             (return-from sub-compile-file (values nil t t))))
1336          (*current-path* nil)
1337          (*last-source-context* nil)
1338          (*last-original-source* nil)
1339          (*last-source-form* nil)
1340          (*last-format-string* nil)
1341          (*last-format-args* nil)
1342          (*last-message-count* 0)
1343          ;; FIXME: Do we need this rebinding here? It's a literal
1344          ;; translation of the old CMU CL rebinding to
1345          ;; (OR *BACKEND-INFO-ENVIRONMENT* *INFO-ENVIRONMENT*),
1346          ;; and it's not obvious whether the rebinding to itself is
1347          ;; needed that SBCL doesn't need *BACKEND-INFO-ENVIRONMENT*.
1348          (*info-environment* *info-environment*)
1349          (*gensym-counter* 0))
1350     (handler-case
1351         (with-compilation-values
1352          (sb!xc:with-compilation-unit ()
1353            (clear-stuff)
1354
1355            (sub-sub-compile-file info)
1356
1357            (finish-block-compilation)
1358            (let ((object *compile-object*))
1359              (etypecase object
1360                (fasl-output (fasl-dump-source-info info object))
1361                (core-object (fix-core-source-info info object))
1362                (null)))
1363            nil))
1364       ;; Some errors are sufficiently bewildering that we just fail
1365       ;; immediately, without trying to recover and compile more of
1366       ;; the input file.
1367       (input-error-in-compile-file (condition)
1368        (format *error-output*
1369                "~@<compilation aborted because of input error: ~2I~_~A~:>"
1370                condition)
1371        (values nil t t)))))
1372
1373 ;;; Return a pathname for the named file. The file must exist.
1374 (defun verify-source-file (pathname-designator)
1375   (let* ((pathname (pathname pathname-designator))
1376          (default-host (make-pathname :host (pathname-host pathname))))
1377     (flet ((try-with-type (path type error-p)
1378              (let ((new (merge-pathnames
1379                          path (make-pathname :type type
1380                                              :defaults default-host))))
1381                (if (probe-file new)
1382                    new
1383                    (and error-p (truename new))))))
1384       (cond ((typep pathname 'logical-pathname)
1385              (try-with-type pathname "LISP" t))
1386             ((probe-file pathname) pathname)
1387             ((try-with-type pathname "lisp"  nil))
1388             ((try-with-type pathname "lisp"  t))))))
1389
1390 (defun elapsed-time-to-string (tsec)
1391   (multiple-value-bind (tmin sec) (truncate tsec 60)
1392     (multiple-value-bind (thr min) (truncate tmin 60)
1393       (format nil "~D:~2,'0D:~2,'0D" thr min sec))))
1394
1395 ;;; Print some junk at the beginning and end of compilation.
1396 (defun start-error-output (source-info)
1397   (declare (type source-info source-info))
1398   (let ((file-info (source-info-file-info source-info)))
1399     (compiler-mumble "~&; compiling file ~S (written ~A):~%"
1400                      (namestring (file-info-name file-info))
1401                      (sb!int:format-universal-time nil
1402                                                    (file-info-write-date
1403                                                     file-info)
1404                                                    :style :government
1405                                                    :print-weekday nil
1406                                                    :print-timezone nil)))
1407   (values))
1408 (defun finish-error-output (source-info won)
1409   (declare (type source-info source-info))
1410   (compiler-mumble "~&; compilation ~:[aborted after~;finished in~] ~A~&"
1411                    won
1412                    (elapsed-time-to-string
1413                     (- (get-universal-time)
1414                        (source-info-start-time source-info))))
1415   (values))
1416
1417 ;;; Open some files and call SUB-COMPILE-FILE. If something unwinds
1418 ;;; out of the compile, then abort the writing of the output file, so
1419 ;;; that we don't overwrite it with known garbage.
1420 (defun sb!xc:compile-file
1421     (input-file
1422      &key
1423
1424      ;; ANSI options
1425      (output-file (cfp-output-file-default input-file))
1426      ;; FIXME: ANSI doesn't seem to say anything about
1427      ;; *COMPILE-VERBOSE* and *COMPILE-PRINT* being rebound by this
1428      ;; function..
1429      ((:verbose sb!xc:*compile-verbose*) sb!xc:*compile-verbose*)
1430      ((:print sb!xc:*compile-print*) sb!xc:*compile-print*)
1431      (external-format :default)
1432
1433      ;; extensions
1434      (trace-file nil) 
1435      ((:block-compile *block-compile-arg*) nil))
1436
1437   #!+sb-doc
1438   "Compile INPUT-FILE, producing a corresponding fasl file and returning
1439    its filename. Besides the ANSI &KEY arguments :OUTPUT-FILE, :VERBOSE,
1440    :PRINT, and :EXTERNAL-FORMAT,the following extensions are supported:
1441      :TRACE-FILE
1442         If given, internal data structures are dumped to the specified
1443         file, or if a value of T is given, to a file of *.trace type
1444         derived from the input file name.
1445    Also, as a workaround for vaguely-non-ANSI behavior, the :BLOCK-COMPILE
1446    argument is quasi-supported, to determine whether multiple
1447    functions are compiled together as a unit, resolving function
1448    references at compile time. NIL means that global function names
1449    are never resolved at compilation time. Currently NIL is the
1450    default behavior, because although section 3.2.2.3, \"Semantic
1451    Constraints\", of the ANSI spec allows this behavior under all
1452    circumstances, the compiler's runtime scales badly when it
1453    tries to do this for large files. If/when this performance
1454    problem is fixed, the block compilation default behavior will
1455    probably be made dependent on the SPEED and COMPILATION-SPEED
1456    optimization values, and the :BLOCK-COMPILE argument will probably
1457    become deprecated."
1458
1459   (unless (eq external-format :default)
1460     (error "Non-:DEFAULT EXTERNAL-FORMAT values are not supported."))
1461   (let* ((fasl-output nil)
1462          (output-file-name nil)
1463          (compile-won nil)
1464          (warnings-p nil)
1465          (failure-p t) ; T in case error keeps this from being set later
1466          (input-pathname (verify-source-file input-file))
1467          (source-info (make-file-source-info input-pathname))
1468          (*compiler-trace-output* nil)) ; might be modified below
1469
1470     (unwind-protect
1471         (progn
1472           (when output-file
1473             (setq output-file-name
1474                   (sb!xc:compile-file-pathname input-file
1475                                                :output-file output-file))
1476             (setq fasl-output
1477                   (open-fasl-output output-file-name
1478                                     (namestring input-pathname))))
1479           (when trace-file
1480             (let* ((default-trace-file-pathname
1481                      (make-pathname :type "trace" :defaults input-pathname))
1482                    (trace-file-pathname
1483                     (if (eql trace-file t)
1484                         default-trace-file-pathname
1485                         (merge-pathnames trace-file
1486                                          default-trace-file-pathname))))
1487               (setf *compiler-trace-output*
1488                     (open trace-file-pathname
1489                           :if-exists :supersede
1490                           :direction :output))))
1491
1492           (when sb!xc:*compile-verbose*
1493             (start-error-output source-info))
1494           (let ((*compile-object* fasl-output)
1495                 dummy)
1496             (multiple-value-setq (dummy warnings-p failure-p)
1497               (sub-compile-file source-info)))
1498           (setq compile-won t))
1499
1500       (close-source-info source-info)
1501
1502       (when fasl-output
1503         (close-fasl-output fasl-output (not compile-won))
1504         (setq output-file-name
1505               (pathname (fasl-output-stream fasl-output)))
1506         (when (and compile-won sb!xc:*compile-verbose*)
1507           (compiler-mumble "~2&; ~A written~%" (namestring output-file-name))))
1508
1509       (when sb!xc:*compile-verbose*
1510         (finish-error-output source-info compile-won))
1511
1512       (when *compiler-trace-output*
1513         (close *compiler-trace-output*)))
1514
1515     (values (if output-file
1516                 ;; Hack around filesystem race condition...
1517                 (or (probe-file output-file-name) output-file-name)
1518                 nil)
1519             warnings-p
1520             failure-p)))
1521 \f
1522 ;;; a helper function for COMPILE-FILE-PATHNAME: the default for
1523 ;;; the OUTPUT-FILE argument
1524 ;;;
1525 ;;; ANSI: The defaults for the OUTPUT-FILE are taken from the pathname
1526 ;;; that results from merging the INPUT-FILE with the value of
1527 ;;; *DEFAULT-PATHNAME-DEFAULTS*, except that the type component should
1528 ;;; default to the appropriate implementation-defined default type for
1529 ;;; compiled files.
1530 (defun cfp-output-file-default (input-file)
1531   (let* ((defaults (merge-pathnames input-file *default-pathname-defaults*))
1532          (retyped (make-pathname :type *fasl-file-type* :defaults defaults)))
1533     retyped))
1534         
1535 ;;; KLUDGE: Part of the ANSI spec for this seems contradictory:
1536 ;;;   If INPUT-FILE is a logical pathname and OUTPUT-FILE is unsupplied,
1537 ;;;   the result is a logical pathname. If INPUT-FILE is a logical
1538 ;;;   pathname, it is translated into a physical pathname as if by
1539 ;;;   calling TRANSLATE-LOGICAL-PATHNAME.
1540 ;;; So I haven't really tried to make this precisely ANSI-compatible
1541 ;;; at the level of e.g. whether it returns logical pathname or a
1542 ;;; physical pathname. Patches to make it more correct are welcome.
1543 ;;; -- WHN 2000-12-09
1544 (defun sb!xc:compile-file-pathname (input-file
1545                                     &key
1546                                     (output-file (cfp-output-file-default
1547                                                   input-file))
1548                                     &allow-other-keys)
1549   #!+sb-doc
1550   "Return a pathname describing what file COMPILE-FILE would write to given
1551    these arguments."
1552   (merge-pathnames output-file (merge-pathnames input-file)))
1553 \f
1554 ;;;; MAKE-LOAD-FORM stuff
1555
1556 ;;; The entry point for MAKE-LOAD-FORM support. When IR1 conversion
1557 ;;; finds a constant structure, it invokes this to arrange for proper
1558 ;;; dumping. If it turns out that the constant has already been
1559 ;;; dumped, then we don't need to do anything.
1560 ;;;
1561 ;;; If the constant hasn't been dumped, then we check to see whether
1562 ;;; we are in the process of creating it. We detect this by
1563 ;;; maintaining the special *CONSTANTS-BEING-CREATED* as a list of all
1564 ;;; the constants we are in the process of creating. Actually, each
1565 ;;; entry is a list of the constant and any init forms that need to be
1566 ;;; processed on behalf of that constant.
1567 ;;;
1568 ;;; It's not necessarily an error for this to happen. If we are
1569 ;;; processing the init form for some object that showed up *after*
1570 ;;; the original reference to this constant, then we just need to
1571 ;;; defer the processing of that init form. To detect this, we
1572 ;;; maintain *CONSTANTS-CREATED-SINCE-LAST-INIT* as a list of the
1573 ;;; constants created since the last time we started processing an
1574 ;;; init form. If the constant passed to emit-make-load-form shows up
1575 ;;; in this list, then there is a circular chain through creation
1576 ;;; forms, which is an error.
1577 ;;;
1578 ;;; If there is some intervening init form, then we blow out of
1579 ;;; processing it by throwing to the tag PENDING-INIT. The value we
1580 ;;; throw is the entry from *CONSTANTS-BEING-CREATED*. This is so the
1581 ;;; offending init form can be tacked onto the init forms for the
1582 ;;; circular object.
1583 ;;;
1584 ;;; If the constant doesn't show up in *CONSTANTS-BEING-CREATED*, then
1585 ;;; we have to create it. We call MAKE-LOAD-FORM and check to see
1586 ;;; whether the creation form is the magic value
1587 ;;; :SB-JUST-DUMP-IT-NORMALLY. If it is, then we don't do anything. The
1588 ;;; dumper will eventually get its hands on the object and use the
1589 ;;; normal structure dumping noise on it.
1590 ;;;
1591 ;;; Otherwise, we bind *CONSTANTS-BEING-CREATED* and
1592 ;;; *CONSTANTS-CREATED-SINCE- LAST-INIT* and compile the creation form
1593 ;;; much the way LOAD-TIME-VALUE does. When this finishes, we tell the
1594 ;;; dumper to use that result instead whenever it sees this constant.
1595 ;;;
1596 ;;; Now we try to compile the init form. We bind
1597 ;;; *CONSTANTS-CREATED-SINCE-LAST-INIT* to NIL and compile the init
1598 ;;; form (and any init forms that were added because of circularity
1599 ;;; detection). If this works, great. If not, we add the init forms to
1600 ;;; the init forms for the object that caused the problems and let it
1601 ;;; deal with it.
1602 (defvar *constants-being-created* nil)
1603 (defvar *constants-created-since-last-init* nil)
1604 ;;; FIXME: Shouldn't these^ variables be unbound outside LET forms?
1605 (defun emit-make-load-form (constant)
1606   (aver (fasl-output-p *compile-object*))
1607   (unless (or (fasl-constant-already-dumped-p constant *compile-object*)
1608               ;; KLUDGE: This special hack is because I was too lazy
1609               ;; to rework DEF!STRUCT so that the MAKE-LOAD-FORM
1610               ;; function of LAYOUT returns nontrivial forms when
1611               ;; building the cross-compiler but :IGNORE-IT when
1612               ;; cross-compiling or running under the target Lisp. --
1613               ;; WHN 19990914
1614               #+sb-xc-host (typep constant 'layout))
1615     (let ((circular-ref (assoc constant *constants-being-created* :test #'eq)))
1616       (when circular-ref
1617         (when (find constant *constants-created-since-last-init* :test #'eq)
1618           (throw constant t))
1619         (throw 'pending-init circular-ref)))
1620     (multiple-value-bind (creation-form init-form)
1621         (handler-case
1622             (sb!xc:make-load-form constant (make-null-lexenv))
1623           (error (condition)
1624                  (compiler-error "(while making load form for ~S)~%~A"
1625                                  constant
1626                                  condition)))
1627       (case creation-form
1628         (:sb-just-dump-it-normally
1629          (fasl-validate-structure constant *compile-object*)
1630          t)
1631         (:ignore-it
1632          nil)
1633         (t
1634          (when (fasl-constant-already-dumped-p constant *compile-object*)
1635            (return-from emit-make-load-form nil))
1636          (let* ((name (let ((*print-level* 1) (*print-length* 2))
1637                         (with-output-to-string (stream)
1638                           (write constant :stream stream))))
1639                 (info (if init-form
1640                           (list constant name init-form)
1641                           (list constant))))
1642            (let ((*constants-being-created*
1643                   (cons info *constants-being-created*))
1644                  (*constants-created-since-last-init*
1645                   (cons constant *constants-created-since-last-init*)))
1646              (when
1647                  (catch constant
1648                    (fasl-note-handle-for-constant
1649                     constant
1650                     (compile-load-time-value
1651                      creation-form)
1652                     *compile-object*)
1653                    nil)
1654                (compiler-error "circular references in creation form for ~S"
1655                                constant)))
1656            (when (cdr info)
1657              (let* ((*constants-created-since-last-init* nil)
1658                     (circular-ref
1659                      (catch 'pending-init
1660                        (loop for (name form) on (cdr info) by #'cddr
1661                          collect name into names
1662                          collect form into forms
1663                          finally (compile-make-load-form-init-forms forms))
1664                        nil)))
1665                (when circular-ref
1666                  (setf (cdr circular-ref)
1667                        (append (cdr circular-ref) (cdr info))))))))))))
1668
1669 \f
1670 ;;;; Host compile time definitions
1671 #+sb-xc-host
1672 (defun compile-in-lexenv (name lambda lexenv)
1673   (declare (ignore lexenv))
1674   (compile name lambda))
1675
1676 #+sb-xc-host
1677 (defun eval-in-lexenv (form lexenv)
1678   (declare (ignore lexenv))
1679   (eval form))