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