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