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