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