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