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