main.lisp 50 KB
Newer Older
wlott's avatar
wlott committed
1
2
3
;;; -*- Package: C; Log: C.Log -*-
;;;
;;; **********************************************************************
ram's avatar
ram committed
4
5
6
7
8
9
;;; This code was written as part of the CMU Common Lisp project at
;;; Carnegie Mellon University, and has been placed in the public domain.
;;; If you want to use this code or any part of CMU Common Lisp, please contact
;;; Scott Fahlman or slisp-group@cs.cmu.edu.
;;;
(ext:file-comment
10
  "$Header: /Volumes/share2/src/cmucl/cvs2git/cvsroot/src/compiler/main.lisp,v 1.45 1991/11/08 15:28:02 ram Exp $")
ram's avatar
ram committed
11
;;;
wlott's avatar
wlott committed
12
13
14
15
16
17
;;; **********************************************************************
;;;
;;;    This file contains the top-level interfaces to the compiler.
;;; 
;;; Written by Rob MacLachlan
;;;
ram's avatar
ram committed
18
(in-package "C")
19
(in-package "EXTENSIONS")
20
21
22
23
24
(export '(*compile-progress* compile-from-stream *block-compile-default*
			     start-block end-block))
(in-package "LISP")
(export '(*compile-verbose* *compile-print* *compile-file-pathname*
			    *compile-file-truename*))
25
(in-package "C")
wlott's avatar
wlott committed
26
27
28
29
30
31
32

(proclaim '(special *constants* *free-variables* *compile-component*
		    *code-vector* *next-location* *result-fixups*
		    *free-functions* *source-paths* *failed-optimizations*
		    *seen-blocks* *seen-functions* *list-conflicts-table*
		    *continuation-number* *continuation-numbers*
		    *number-continuations* *tn-id* *tn-ids* *id-tns*
33
		    *label-ids* *label-id* *id-labels*
ram's avatar
ram committed
34
		    *undefined-warnings* *compiler-error-count*
wlott's avatar
wlott committed
35
36
37
38
39
		    *compiler-warning-count* *compiler-note-count*
		    *compiler-error-output* *compiler-error-bailout*
		    *compiler-trace-output*
		    *last-source-context* *last-original-source*
		    *last-source-form* *last-format-string* *last-format-args*
40
		    *last-message-count* *lexical-environment*))
wlott's avatar
wlott committed
41

42
43
44
(defvar *block-compile-default* :specified
  "The default value for the :Block-Compile argument to COMPILE-FILE.")

45
(defvar compiler-version "1.0")
wlott's avatar
wlott committed
46

47
(defvar *check-consistency* nil)
wlott's avatar
wlott committed
48
49
(defvar *all-components*)

50
51
52
;;; The current block compilation state.  These are initialized to the 
;;; :Block-Compile and :Entry-Points arguments that COMPILE-FILE was called
;;; with.  Subsequent START-BLOCK or END-BLOCK declarations alter the values.
wlott's avatar
wlott committed
53
54
;;;
(defvar *block-compile*)
55
56
57
(declaim (type (member nil t :specified) *block-compile*))
(defvar *entry-points*)
(declaim (list *entry-points*))
wlott's avatar
wlott committed
58
59
60
61
62

;;; When block compiling, used by PROCESS-FORM to accumulate top-level lambdas
;;; resulting from compiling subforms.  (In reverse order.)
;;;
(defvar *top-level-lambdas*)
63
(declaim (list *top-level-lambdas*))
wlott's avatar
wlott committed
64

65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
(defvar *compile-verbose* t
  "The default for the :VERBOSE argument to COMPILE-FILE.")
(defvar *compile-print* t
  "The default for the :PRINT argument to COMPILE-FILE.")
(defvar *compile-progress* nil
  "The default for the :PROGRESS argument to COMPILE-FILE.")

(defvar *compile-file-pathname* nil
  "The defaulted pathname of the file currently being compiler, or NIL if not
  compiling.")
(defvar *compile-file-truename* nil
  "The TRUENAME of the file currently being compiler, or NIL if not
  compiling.")

(declaim (type (or pathname null) *compile-file-pathname*
	       *compile-file-truename*))
wlott's avatar
wlott committed
81

82
;;; The values of *Package* and policy when compilation started.
wlott's avatar
wlott committed
83
84
85
;;;
(defvar *initial-package*)
(defvar *initial-cookie*)
86
(defvar *initial-interface-cookie*)
wlott's avatar
wlott committed
87
88
89
90
91
92
93
94
95
96

;;; The source-info structure for the current compilation.  This is null
;;; globally to indicate that we aren't currently in any identifiable
;;; compilation.
;;;
(defvar *source-info* nil)


;;; Maybe-Mumble  --  Internal
;;;
97
;;;    Mumble conditional on *compile-progress*.
wlott's avatar
wlott committed
98
99
;;;
(defun maybe-mumble (&rest foo)
100
  (when *compile-progress*
wlott's avatar
wlott committed
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
    (apply #'compiler-mumble foo)))

(deftype object () '(or fasl-file core-object null))


;;;; Component compilation:

(defparameter max-optimize-iterations 3
  "The upper limit on the number of times that we will consecutively do IR1
  optimization that doesn't introduce any new code.  A finite limit is
  necessary, since type inference may take arbitrarily long to converge.")

(defevent ir1-optimize-until-done "IR1-OPTIMIZE-UNTIL-DONE called.")
(defevent ir1-optimize-maxed-out "Hit MAX-OPTIMIZE-ITERATIONS limit.")

;;; IR1-Optimize-Until-Done  --  Internal
;;;
;;;    Repeatedly optimize Component until no further optimizations can be
;;; found or we hit our iteration limit.  When we hit the limit, we clear the
;;; component and block REOPTIMIZE flags to discourage following the next
;;; optimization attempt from pounding on the same code.
;;;
(defun ir1-optimize-until-done (component)
  (declare (type component component))
  (maybe-mumble "Opt")
  (event ir1-optimize-until-done)
  (let ((count 0)
	(cleared-reanalyze nil))
    (loop
      (when (component-reanalyze component)
	(setq count 0)
	(setq cleared-reanalyze t)
	(setf (component-reanalyze component) nil))
      (setf (component-reoptimize component) nil)
      (ir1-optimize component)
      (unless (component-reoptimize component)
	(maybe-mumble " ")
	(return))
      (incf count)
      (when (= count max-optimize-iterations)
	(event ir1-optimize-maxed-out)
	(maybe-mumble "* ")
	(setf (component-reoptimize component) nil)
	(do-blocks (block component)
	  (setf (block-reoptimize block) nil))
	(return))
      (maybe-mumble "."))
    (when cleared-reanalyze
      (setf (component-reanalyze component) t)))
  (undefined-value))

152
153
154
155
156
(defparameter *constraint-propagate* t)
(defparameter *reoptimize-after-type-check-max* 5)

(defevent reoptimize-maxed-out
  "*REOPTIMIZE-AFTER-TYPE-CHECK-MAX* exceeded.")
wlott's avatar
wlott committed
157
158
159
160
161
162
163

;;; IR1-Phases  --  Internal
;;;
;;;    Do all the IR1 phases for a non-top-level component.
;;;
(defun ir1-phases (component)
  (declare (type component component))
164
165
  (let ((*constraint-number* 0)
	(loop-count 1))
wlott's avatar
wlott committed
166
    (declare (special *constraint-number*))
167
    (loop
wlott's avatar
wlott committed
168
      (ir1-optimize-until-done component)
169
170
171
      (when (component-reanalyze component)
	(maybe-mumble "DFO ")
	(find-dfo component))
wlott's avatar
wlott committed
172
173
174
175
176
177
178
      (when *constraint-propagate*
	(maybe-mumble "Constraint ")
	(constraint-propagate component))
      (maybe-mumble "Type ")
      (generate-type-checks component)
      (unless (or (component-reoptimize component)
		  (component-reanalyze component))
179
180
181
182
183
184
	(return))
      (when (>= loop-count *reoptimize-after-type-check-max*)
	(maybe-mumble "[Reoptimize Limit]")
	(event reoptimize-maxed-out)
	(return))
      (incf loop-count)))
185
186

  (ir1-finalize component)
187
  (undefined-value))
wlott's avatar
wlott committed
188
189
190
191
192


;;; Compile-Component  --  Internal
;;;
(defun compile-component (component object)
193
194
  (when *compile-print*
    (compiler-mumble "Compiling ~A: " (component-name component)))
wlott's avatar
wlott committed
195
196
197
198
199
200
201
202
203
204
  
  (ir1-phases component)
  
  #|
  (maybe-mumble "Dom ")
  (find-dominators component)
  (maybe-mumble "Loop ")
  (loop-analyze component)
  |#

wlott's avatar
wlott committed
205
206
207
  (let ((*compile-component* component)
	(*code-segment* nil)
	(*elsewhere* nil))
wlott's avatar
wlott committed
208
209
    (maybe-mumble "Env ")
    (environment-analyze component)
210
211
212
    (when (component-reanalyze component)
      (maybe-mumble "DFO ")
      (find-dfo component))
wlott's avatar
wlott committed
213
214
215
216
    (maybe-mumble "GTN ")
    (gtn-analyze component)
    (maybe-mumble "LTN ")
    (ltn-analyze component)
ram's avatar
ram committed
217
218
    (maybe-mumble "Control ")
    (control-analyze component)
wlott's avatar
wlott committed
219
220
221
222
223

    (when (ir2-component-values-receivers (component-info component))
      (maybe-mumble "Stack ")
      (stack-analyze component))

ram's avatar
ram committed
224
225
226
    ;; Assign BLOCK-NUMBER for any cleanup blocks introduced by environment
    ;; or stack analysis.  There shouldn't be any unreachable code after
    ;; control, so this won't delete anything.
wlott's avatar
wlott committed
227
228
229
230
231
232
233
234
    (when (component-reanalyze component)
      (find-dfo component))

    (maybe-mumble "IR2Tran ")
    (init-assembler)
    (entry-analyze component)
    (ir2-convert component)

ram's avatar
ram committed
235
236
237
238
    (when (policy nil (>= speed cspeed))
      (maybe-mumble "Copy ")
      (copy-propagate component))

ram's avatar
ram committed
239
240
    (select-representations component)

wlott's avatar
wlott committed
241
242
243
244
245
246
247
    (when *check-consistency*
      (maybe-mumble "Check2 ")
      (check-ir2-consistency component))
    
    (maybe-mumble "Life ")
    (lifetime-analyze component)

248
    (when *compile-progress*
wlott's avatar
wlott committed
249
250
251
252
253
254
255
256
257
258
259
260
      (compiler-mumble "") ; Sync before doing random output.
      (pre-pack-tn-stats component *compiler-error-output*))

    (delete-unreferenced-tns component)

    (when *check-consistency*
      (maybe-mumble "CheckL ")
      (check-life-consistency component))

    (maybe-mumble "Pack ")
    (pack component)

261
262
263
264
    (when *check-consistency*
      (maybe-mumble "CheckP ")
      (check-pack-consistency component))

wlott's avatar
wlott committed
265
266
267
268
    (when *compiler-trace-output*
      (describe-component component *compiler-trace-output*))
    
    (maybe-mumble "Code ")
269
270
271
    (multiple-value-bind
	(length trace-table)
	(generate-code component)
wlott's avatar
wlott committed
272
273
274
275
276
      
      (when *compiler-trace-output*
	(format *compiler-trace-output*
		"~|~%Assembly code for ~S~2%"
		component)
277
	(dump-segment *code-segment* :stream *compiler-trace-output*))
wlott's avatar
wlott committed
278

279
      (when *count-vop-usages*
280
281
282
283
	(count-vops component))

      (when *collect-dynamic-statistics*
	(setup-dynamic-count-info component))
284

wlott's avatar
wlott committed
285
286
287
      (etypecase object
	(fasl-file
	 (maybe-mumble "FASL")
288
289
	 (fasl-dump-component component *code-segment*
			      length trace-table object))
wlott's avatar
wlott committed
290
291
	(core-object
	 (maybe-mumble "Core")
292
293
	 (make-core-component component *code-segment*
			      length trace-table object))
wlott's avatar
wlott committed
294
295
296
297
	(null))

      (nuke-segment *code-segment*)))

298
299
  (when *compile-print*
    (compiler-mumble "~&"))
wlott's avatar
wlott committed
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
  (undefined-value))


;;;; Clearing global data structures:

;;; CLEAR-IR2-INFO  --  Internal
;;;
;;;    Clear all the INFO slots in sight in Component to allow the IR2 data
;;; structures to be reclaimed.  We also clear the INFO in constants in the
;;; *FREE-VARIABLES*, etc.  The latter is required for correct assignment of
;;; costant TNs, in addition to allowing stuff to be reclaimed.
;;;
;;;    We don't clear the FUNCTIONAL-INFO slots, since they are used to keep
;;; track of functions across component boundaries.
;;;
(defun clear-ir2-info (component)
  (declare (type component component))
317
  (nuke-ir2-component component)
wlott's avatar
wlott committed
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
  (setf (component-info component) nil)

  (maphash #'(lambda (k v)
	       (declare (ignore k))
	       (setf (leaf-info v) nil))
	   *constants*)

  (maphash #'(lambda (k v)
	       (declare (ignore k))
	       (when (constant-p v)
		 (setf (leaf-info v) nil)))
	   *free-variables*)

  (undefined-value))


334
335
336
337
338
339
340
;;; CLEAR-IR1-INFO  --  Internal
;;;
;;;    Blow away the REFS for all global variables, and recycle the IR1 for
;;; Component.
;;;
(defun clear-ir1-info (component)
  (declare (type component component))
341
342
343
344
345
346
347
348
349
350
351
  (labels ((blast (x)
	     (maphash #'(lambda (k v)
			  (declare (ignore k))
			  (setf (leaf-refs v)
				(delete-if #'here-p (leaf-refs v)))
			  (when (basic-var-p v)
			    (setf (basic-var-sets v)
				  (delete-if #'here-p (basic-var-sets v)))))
		      x))
	   (here-p (x)
	     (eq (block-component (node-block x)) component)))
352
353
354
355
356
357
358
    (blast *free-variables*)
    (blast *free-functions*)
    (blast *constants*))
  (macerate-ir1-component component)
  (undefined-value))


359
;;; CLEAR-STUFF  --  Interface
360
361
;;;
;;;    Clear all the global variables used by the compiler.
wlott's avatar
wlott committed
362
;;;
363
(defun clear-stuff (&optional (debug-too t))
wlott's avatar
wlott committed
364
365
  ;;
  ;; Clear global tables.
366
367
368
369
  (when (boundp '*free-functions*)
    (clrhash *free-functions*)
    (clrhash *free-variables*)
    (clrhash *constants*))
wlott's avatar
wlott committed
370
371
372
373
374
375
  (clrhash *failed-optimizations*)
  ;;
  ;; Clear debug counters and tables.
  (clrhash *seen-blocks*)
  (clrhash *seen-functions*)
  (clrhash *list-conflicts-table*)
376
377
378
379
380
381
382
383
384
385

  (when debug-too
    (clrhash *continuation-numbers*)
    (clrhash *number-continuations*)
    (setq *continuation-number* 0)
    (clrhash *tn-ids*)
    (clrhash *id-tns*)
    (setq *tn-id* 0)
    (clrhash *label-ids*)
    (clrhash *id-labels*)
386
387
388
389
390
391
392
    (setq *label-id* 0)
    ;;
    ;; Clear some Pack data structures (for GC purposes only.)
    (assert (not *in-pack*))
    (dolist (sb (backend-sb-list *backend*))
      (when (finite-sb-p sb)
	(fill (finite-sb-live-tns sb) nil))))
wlott's avatar
wlott committed
393
394
  ;;
  ;; Reset Gensym.
395
396
397
  (setq lisp:*gensym-counter* 0)

  (values))
wlott's avatar
wlott committed
398

399

wlott's avatar
wlott committed
400
401
402
403
404
405
406
407
408
409
;;; PRINT-SUMMARY  --  Interface
;;;
;;;    This function is called by WITH-COMPILATION-UNIT at the end of a
;;; compilation unit.  It prints out any residual unknown function warnings and
;;; the total error counts.  Abort-P should be true when the compilation unit
;;; was aborted by throwing out.  Abort-Count is the number of dynamically
;;; enclosed nested compilation units that were aborted.
;;;
(defun print-summary (abort-p abort-count)
  (unless abort-p
410
411
412
413
414
415
    (let ((undefs (sort *undefined-warnings* #'string<
			:key #'(lambda (x)
				 (let ((x (undefined-warning-name x)))
				   (if (symbolp x)
				       (symbol-name x)
				       (prin1-to-string x)))))))
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
      (unless *converting-for-interpreter*
	(dolist (undef undefs)
	  (let ((name (undefined-warning-name undef))
		(kind (undefined-warning-kind undef))
		(warnings (undefined-warning-warnings undef))
		(count (undefined-warning-count undef)))
	    (dolist (*compiler-error-context* warnings)
	      (compiler-warning "Undefined ~(~A~): ~S" kind name))
	    
	    (let ((warn-count (length warnings)))
	      (when (and warnings (> count warn-count))
		(let ((more (- count warn-count)))
		  (compiler-warning "~D more use~:P of undefined ~(~A~) ~S."
				    more kind name)))))))
  
431
432
433
434
435
436
      (dolist (kind '(:variable :function :type))
	(let ((summary (mapcar #'undefined-warning-name
			       (remove kind undefs :test-not #'eq
				       :key #'undefined-warning-kind))))
	  (when summary
	    (compiler-warning
437
438
439
	     "~:[This ~(~A~) is~;These ~(~A~)s are~] undefined:~
	      ~%  ~{~<~%  ~1:;~S~>~^ ~}"
	     (cdr summary) kind summary))))))
440
  
441
  (unless (or *converting-for-interpreter*
442
	      (not *compile-verbose*)
443
444
445
446
	      (and (not abort-p) (zerop abort-count)
		   (zerop *compiler-error-count*)
		   (zerop *compiler-warning-count*)
		   (zerop *compiler-note-count*)))
447
448
449
450
451
452
453
454
455
456
457
    (compiler-mumble
     "~2&Compilation unit ~:[finished~;aborted~].~
      ~[~:;~:*~&  ~D fatal error~:P~]~
      ~[~:;~:*~&  ~D error~:P~]~
      ~[~:;~:*~&  ~D warning~:P~]~
      ~[~:;~:*~&  ~D note~:P~]~2%"
     abort-p
     abort-count
     *compiler-error-count*
     *compiler-warning-count*
     *compiler-note-count*)))
458

459
   
wlott's avatar
wlott committed
460
461
462
463
464
465
;;; Describe-Component  --  Internal
;;;
;;;    Print out some useful info about Component to Stream.
;;;
(defun describe-component (component &optional
				     (*standard-output* *standard-output*))
466
  (declare (type component component))
wlott's avatar
wlott committed
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
  (format t "~|~%;;;; Component: ~S~2%" (component-name component))
  (print-blocks component)
  
  (format t "~%~|~%;;;; IR2 component: ~S~2%" (component-name component))
  
  (format t "Entries:~%")
  (dolist (entry (ir2-component-entries (component-info component)))
    (format t "~4TL~D: ~S~:[~; [Closure]~]~%"
	    (label-id (entry-info-offset entry))
	    (entry-info-name entry)
	    (entry-info-closure-p entry)))
  
  (terpri)
  (pre-pack-tn-stats component *standard-output*)
  (terpri)
  (print-ir2-blocks component)
  (terpri)
  
  (undefined-value))


;;;; File reading:
;;;
;;;    When reading from a file, we have to keep track of some source
;;; information.  We also exploit our ability to back up for printing the error
;;; context and for recovering from errors.
;;;
;;; The interface we provide to this stuff is the stream-oid Source-Info
;;; structure.  The bookkeeping is done as a side-effect of getting the next
;;; source form.


;;; The File-Info structure holds all the source information for a given file.
;;;
(defstruct file-info
  ;;
  ;; If a file, the truename of the corresponding source file.  If from a Lisp
  ;; form, :LISP, if from a stream, :STREAM.
505
  (name (required-argument) :type (or pathname (member :lisp :stream)))
wlott's avatar
wlott committed
506
  ;;
507
508
509
510
511
  ;; The defaulted, but not necessarily absolute file name (i.e. prior to
  ;; TRUENAME call.)  Null if not a file.  This is only used to set
  ;; *COMPILE-FILE-PATHNAME* 
  (untruename nil :type (or pathname null))
  ;;
wlott's avatar
wlott committed
512
513
514
  ;; The file's write date (if relevant.)
  (write-date nil :type (or unsigned-byte null))
  ;;
ram's avatar
ram committed
515
516
517
  ;; This file's FILE-COMMENT, or NIL if none.
  (comment nil :type (or simple-string null))
  ;;
wlott's avatar
wlott committed
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
  ;; The source path root number of the first form in this file (i.e. the
  ;; total number of forms converted previously in this compilation.)
  (source-root 0 :type unsigned-byte)
  ;;
  ;; Parallel vectors containing the forms read out of the file and the file
  ;; positions that reading of each form started at (i.e. the end of the
  ;; previous form.)
  (forms (make-array 10 :fill-pointer 0 :adjustable t) (vector t))
  (positions (make-array 10 :fill-pointer 0 :adjustable t) (vector t)))


;;; The Source-Info structure provides a handle on all the source information
;;; for an entire compilation.
;;;
(defstruct (source-info
	    (:print-function
	     (lambda (s stream d)
	       (declare (ignore s d))
	       (format stream "#<Source-Info>"))))
  ;;
  ;; The UT that compilation started at.
  (start-time (get-universal-time) :type unsigned-byte)
  ;;
  ;; A list of the file-info structures for this compilation.
  (files nil :type list)
  ;;
  ;; The tail of the Files for the file we are currently reading.
  (current-file nil :type list)
  ;;
  ;; The stream that we are using to read the Current-File.  Null if no stream
  ;; has been opened yet.
  (stream nil :type (or stream null)))


;;; Make-File-Source-Info  --  Internal
;;;
;;;    Given a list of pathnames, return a Source-Info structure.
;;;
(defun make-file-source-info (files)
  (declare (list files))
  (let ((file-info
	 (mapcar #'(lambda (x)
560
561
		     (make-file-info :name (truename x)
				     :untruename x
wlott's avatar
wlott committed
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
				     :write-date (file-write-date x)))
		 files)))

    (make-source-info :files file-info
		      :current-file file-info)))


;;; MAKE-LISP-SOURCE-INFO  --  Interface
;;;
;;;    Return a SOURCE-INFO to describe the incremental compilation of Form.
;;; Also used by EVAL:INTERNAL-EVAL.
;;;
(defun make-lisp-source-info (form)
  (make-source-info
   :start-time (get-universal-time)
   :files (list (make-file-info :name :lisp
				:forms (vector form)
				:positions '#(0)))))


;;; MAKE-STREAM-SOURCE-INFO  --  Internal
;;;
;;;    Return a SOURCE-INFO which will read from Stream.
;;;
(defun make-stream-source-info (stream)
  (let ((files (list (make-file-info :name :stream))))
    (make-source-info
     :files files
     :current-file files
     :stream stream)))


;;; Normal-Read-Error  --  Internal
;;;
;;;    Print an error message for a non-EOF error on Stream.  Old-Pos is a
;;; preceding file position that hopefully comes before the beginning of the
;;; line.  Of course, this only works on streams that support the file-position
;;; operation.
;;;
(defun normal-read-error (stream old-pos condition)
602
  (declare (type stream stream) (type unsigned-byte old-pos))
wlott's avatar
wlott committed
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
  (let ((pos (file-position stream)))
    (file-position stream old-pos)
    (let ((start old-pos))
      (loop
	(let ((line (read-line stream nil))
	      (end (file-position stream)))
	  (when (>= end pos)
	    (compiler-error-message
	     "Read error at ~D:~% \"~A/\\~A\"~%~A"
	     pos
	     (string-left-trim " 	"
			       (subseq line 0 (- pos start)))
	     (subseq line (- pos start))
	     condition)
	    (return))
	  (setq start end)))))
  (undefined-value))


;;; Ignore-Error-Form  --  Internal
;;;
;;;    Back Stream up to the position Pos, then read a form with
;;; *Read-Suppress* on, discarding the result.  If an error happens during this
;;; read, then bail out using Compiler-Error (fatal in this context).
;;;
(defun ignore-error-form (stream pos)
  (declare (type stream stream) (type unsigned-byte pos))
  (file-position stream pos)
  (handler-case (let ((*read-suppress* t))
		  (read stream))
    (error (condition)
      (declare (ignore condition))
      (compiler-error "Unable to recover from read error."))))


;;; Unexpected-EOF-Error  --  Internal
;;;
;;;    Print an error message giving some context for an EOF error.  We print
;;; the first line after Pos that contains #\" or #\(, or lacking that, the
;;; first non-empty line.
;;;
(defun unexpected-eof-error (stream pos condition)
  (declare (type stream stream) (type unsigned-byte pos))
  (let ((res nil))
    (file-position stream pos)
    (loop
      (let ((line (read-line stream nil nil))) 
	(unless line (return))
	(when (or (find #\" line) (find #\( line))
	  (setq res line)
	  (return))
	(unless (or res (zerop (length line)))
	  (setq res line))))

    (compiler-error-message
     "Read error in form starting at ~D:~%~@[ \"~A\"~%~]~A"
     pos res condition))

  (file-position stream (file-length stream))
  (undefined-value))


;;; Careful-Read  --  Internal
;;;
;;;    Read a form from Stream, returning EOF at EOF.  If a read error happens,
;;; then attempt to recover if possible, returing a proxy error form.
;;;
(defun careful-read (stream eof pos)
  (handler-case (read stream nil eof)
    (error (condition)
      (let ((new-pos (file-position stream)))
	(cond ((= new-pos (file-length stream))
	       (unexpected-eof-error stream pos condition))
	      (t
	       (normal-read-error stream pos condition)
	       (ignore-error-form stream pos))))
679
680
      '(cerror "Skip this form."
	       "Attempt to load a file having a compile-time read error."))))
wlott's avatar
wlott committed
681
682
683
684
685
686


;;; Get-Source-Stream  --  Internal
;;;
;;;    If Stream is present, return it, otherwise open a stream to the current
;;; file.  There must be a current file.  When we open a new file, we also
687
;;; reset *Package* and policy.  This gives the effect of rebinding
wlott's avatar
wlott committed
688
689
690
691
692
693
694
695
;;; around each file.
;;;
(defun get-source-stream (info)
  (declare (type source-info info))
  (cond ((source-info-stream info))
	(t
	 (setq *package* *initial-package*)
	 (setq *default-cookie* (copy-cookie *initial-cookie*))
696
697
	 (setq *default-interface-cookie*
	       (copy-cookie *initial-interface-cookie*))
698
699
700
701
702
	 (let* ((finfo (first (source-info-current-file info)))
		(name (file-info-name finfo)))
	   (setq *compile-file-truename* name)
	   (setq *compile-file-pathname* (file-info-untruename finfo))
	   (setf (source-info-stream info) (open name :direction :input))))))
wlott's avatar
wlott committed
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735

;;; CLOSE-SOURCE-INFO  --  Internal
;;;
;;;    Close the stream in Info if it is open.
;;;
(defun close-source-info (info)
  (declare (type source-info info))
  (let ((stream (source-info-stream info)))
    (when stream (close stream)))
  (setf (source-info-stream info) nil)
  (undefined-value))


;;; Advance-Source-File  --  Internal
;;;
;;;    Advance Info to the next source file.  If none, return NIL, otherwise T.
;;;
(defun advance-source-file (info)
  (declare (type source-info info))
  (close-source-info info)
  (let ((prev (pop (source-info-current-file info))))
    (if (source-info-current-file info)
	(let ((current (first (source-info-current-file info))))
	  (setf (file-info-source-root current)
		(+ (file-info-source-root prev)
		   (length (file-info-forms prev))))
	  t)
	nil)))


;;; Read-Source-Form  --  Internal
;;;
;;;    Read the next form from the source designated by Info.  The second value
736
737
;;; is the top-level form number of the read form.  The third value is true
;;; when at EOF.
wlott's avatar
wlott committed
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
;;;
;;;   We carefully read from the current source file.  If it is at EOF, we
;;; advance to the next file and try again.  When we get a form, we enter it
;;; into the per-file Forms and Positions vectors.
;;;
(defun read-source-form (info) 
  (declare (type source-info info))
  (let ((eof '(*eof*)))
    (loop
      (let* ((file (first (source-info-current-file info)))
	     (stream (get-source-stream info))
	     (pos (file-position stream))
	     (res (careful-read stream eof pos)))
	(unless (eq res eof)
	  (let* ((forms (file-info-forms file))
		 (current-idx (+ (fill-pointer forms)
				 (file-info-source-root file))))
	    (vector-push-extend res forms)
	    (vector-push-extend pos (file-info-positions file))
757
	    (return (values res current-idx nil))))
wlott's avatar
wlott committed
758
759
760
761
762

	(unless (advance-source-file info)
	  (return (values nil nil t)))))))


763
764
765
766
767
768
769
770
771
772
773
774
775
776
;;; FIND-FILE-INFO  --  Interface
;;;
;;;    Return the File-Info describing the Index'th form.
;;;
(defun find-file-info (index info)
  (declare (type index index) (type source-info info))
  (dolist (file (source-info-files info))
    (when (> (+ (length (file-info-forms file))
		(file-info-source-root file))
	     index)
      (return file))))


;;; FIND-SOURCE-ROOT  --  Interface
wlott's avatar
wlott committed
777
778
779
780
781
;;;
;;;    Return the Index'th source form read from Info and the position that it
;;; was read at.
;;;
(defun find-source-root (index info)
782
783
784
785
786
  (declare (type source-info info) (type index index))
  (let* ((file (find-file-info index info))
	 (idx (- index (file-info-source-root file))))
    (values (aref (file-info-forms file) idx)
	    (aref (file-info-positions file) idx))))
wlott's avatar
wlott committed
787
788
789
790
791
792

;;;; Top-level form processing:

;;; CONVERT-AND-MAYBE-COMPILE  --  Internal
;;;
;;;    Called by top-level form processing when we are ready to actually
793
;;; compile something.  If *BLOCK-COMPILE* is T, then we still convert the
wlott's avatar
wlott committed
794
795
;;; form, but delay compilation, pushing the result on *TOP-LEVEL-LAMBDAS*
;;; instead.
796
;;;
797
798
799
;;;   The cookies at this time becomes the default policy for compiling the
;;; form.  Any enclosed PROCLAIMs will affect only subsequent forms.
;;;
800
801
(defun convert-and-maybe-compile (form path object)
  (declare (list path) (type object object))
802
803
804
805
806
807
808
809
810
811
812
813
814
  ;;
  ;; This W/O GC is pretty much of a hack, and should be replaced with a less
  ;; drastic GC procrastination mechanism.  The problem is that in addition to
  ;; wasting time GC'ing during a compilation (when there is lots of dynamic
  ;; stuff), it also seems to cause a memory leak.
  (without-gcing
    (let* ((*lexical-environment*
	    (make-lexenv :cookie *default-cookie*
			 :interface-cookie *default-interface-cookie*))
	   (tll (ir1-top-level form path nil)))
      (cond ((eq *block-compile* t) (push tll *top-level-lambdas*))
	    (t
	     (compile-top-level (list tll) object))))))
wlott's avatar
wlott committed
815
816
817
818
819


;;; PROCESS-PROGN  --  Internal
;;;
;;;    Process a PROGN-like portion of a top-level form.  Forms is a list of
820
;;; the forms, and Path is source path of the form they came out of.
wlott's avatar
wlott committed
821
;;;
822
823
(defun process-progn (forms path object)
  (declare (list forms) (list path) (type object object))
824
  (dolist (form forms)
825
    (process-form form path object)))
wlott's avatar
wlott committed
826
827


828
829
;;; PREPROCESSOR-MACROEXPAND  --  Internal
;;;
830
831
832
;;;    Macroexpand form in the current environment with an error handler.  We
;;; only expand one level, so that we retain all the intervening forms in the
;;; source path.
833
834
;;;
(defun preprocessor-macroexpand (form)
835
  (handler-case (macroexpand-1 form *lexical-environment*)
836
    (error (condition)
837
       (compiler-error "(during macroexpansion)~%~A" condition))))
838
839


840
841
842
843
844
;;; PROCESS-LOCALLY  --  Internal
;;;
;;;    Process a top-level use of LOCALLY.  We parse declarations and then
;;; recursively process the body.
;;;
845
;;;    Binding *DEFAULT-xxx-COOKIE* is pretty much of a hack, since it causes
846
847
848
849
850
851
852
853
854
855
856
857
;;; LOCALLY to "capture" enclosed proclamations.  It is necessary because
;;; CONVERT-AND-MAYBE-COMPILE uses the value of *DEFAULT-COOKIE* as the policy.
;;; The need for this hack is due to the quirk that there is no way to
;;; represent in a cookie that an optimize quality came from the default.
;;;
(defun process-locally (form path object)
  (declare (list path) (type object object))
  (multiple-value-bind
      (body decls)
      (system:parse-body (cdr form) *lexical-environment* nil)
    (let* ((*lexical-environment*
	    (process-declarations decls nil nil (make-continuation)))
858
859
860
	   (*default-cookie* (lexenv-cookie *lexical-environment*))
	   (*default-interface-cookie*
	    (lexenv-interface-cookie *lexical-environment*)))
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
      (process-progn body path object))))


;;; PROCESS-FILE-COMMENT  --  Internal
;;;
;;;    Stash file comment in the file-info structure.
;;;
(defun process-file-comment (form)
  (unless (and (= (length form) 2) (stringp (second form)))
    (compiler-error "Bad FILE-COMMENT form: ~S." form))
  (let ((file (first (source-info-current-file *source-info*))))
    (cond ((file-info-comment file)
	   (compiler-warning "Ignoring extra file comment:~%  ~S." form))
	  (t
	   (let ((comment (coerce (second form) 'simple-string)))
	     (setf (file-info-comment file) comment)
	     (when *compile-verbose*
	       (compiler-mumble "~&Comment: ~A~2&" comment)))))))


881
;;; PROCESS-COLD-LOAD-FORM  --  Internal
882
883
;;;
;;;    Force any pending top-level forms to be compiled and dumped so that they
884
885
;;; will be evaluated in the correct package environment.  Eval the form if
;;; Eval is true, then dump the form to evaled at (cold) load time.
886
;;;
887
(defun process-cold-load-form (form path object eval)
888
889
890
  (typecase object
    (fasl-file
     (compile-top-level-lambdas () t object)))
891
  (when eval (eval form))
892
893
894
895
896
897
898
899
900
901
  (etypecase object
    (fasl-file
     (fasl-dump-cold-load-form form object))
    ((or null core-object)
     (convert-and-maybe-compile form path object))))


;;; PROCESS-PROCLAIM  --  Internal
;;;
;;;    If a special block compilation delimiter, then start or end the block as
902
903
;;; appropriate.  Otherwise, just convert-and-maybe-compile the form.  If
;;; *BLOCK-COMPILE* is NIL, then we ignore block declarations.
904
905
906
907
908
909
910
;;;
(defun process-proclaim (form path object)
  (if (and (eql (length form) 2) (constantp (cadr form)))
      (let ((spec (eval (cadr form))))
	(if (consp spec)
	    (case (first spec)
	      (start-block
911
912
913
914
915
916
	       (when *block-compile*
		 (finish-block-compilation object)
		 (setq *block-compile* t)
		 (setq *entry-points* (rest spec))))
	      (end-block
	       (finish-block-compilation object))
917
918
919
920
921
922
	      (t
	       (convert-and-maybe-compile form path object)))
	    (convert-and-maybe-compile form path object)))
      (convert-and-maybe-compile form path object)))


wlott's avatar
wlott committed
923
924
925
926
927
(proclaim '(special *compiler-error-bailout*))

;;; PROCESS-FORM  --  Internal
;;;
;;;    Process a top-level Form with the specified source Path and output to
ram's avatar
ram committed
928
929
930
931
;;; Object.
;;; -- If this is a magic top-level form, then do stuff.
;;; -- If it is a macro expand it.
;;; -- Otherwise, just compile it.
wlott's avatar
wlott committed
932
;;;
933
934
(defun process-form (form path object)
  (declare (list path) (type object object))
wlott's avatar
wlott committed
935
  (catch 'process-form-error-abort
936
937
    (let* ((path (or (gethash form *source-paths*) (cons form path)))
	   (*compiler-error-bailout*
938
939
940
941
	    #'(lambda ()
		(convert-and-maybe-compile
		 `(error "Execution of a form compiled with errors:~% ~S"
			 ',form)
942
943
		 path object)
		(throw 'process-form-error-abort nil))))
wlott's avatar
wlott committed
944
      (if (atom form)
945
	  (convert-and-maybe-compile form path object)
wlott's avatar
wlott committed
946
947
948
	  (case (car form)
	    ((make-package in-package shadow shadowing-import export
			   unexport use-package unuse-package import)
949
950
951
	     (process-cold-load-form form path object t))
	    ((error cerror break signal)
	     (process-cold-load-form form path object nil))
wlott's avatar
wlott committed
952
953
954
955
956
957
	    ((eval-when)
	     (unless (>= (length form) 2)
	       (compiler-error "EVAL-WHEN form is too short: ~S." form))
	     (do-eval-when-stuff
	      (cadr form) (cddr form)
	      #'(lambda (forms)
958
		  (process-progn forms path object))))
wlott's avatar
wlott committed
959
960
961
962
963
964
	    ((macrolet)
	     (unless (>= (length form) 2)
	       (compiler-error "MACROLET form is too short: ~S." form))
	     (do-macrolet-stuff
	      (cadr form)
	      #'(lambda ()
965
		  (process-progn (cddr form) path object))))
966
	    (locally (process-locally form path object))
967
	    (progn (process-progn (cdr form) path object))
968
969
	    (file-comment (process-file-comment form))
	    (proclaim (process-proclaim form path object))
wlott's avatar
wlott committed
970
	    (t
ram's avatar
ram committed
971
972
	     (let ((exp (preprocessor-macroexpand form)))
	       (if (eq exp form)
973
974
		   (convert-and-maybe-compile form path object)
		   (process-form exp path object))))))))
wlott's avatar
wlott committed
975
976
977
978
979
980
      
  (undefined-value))


;;;; COMPILE-FILE and COMPILE-FROM-STREAM: 

981
982
983
984
985
986
987
988
;;; We build a list of top-level lambdas, and then periodically smash them
;;; together into a single component and compile it.
;;;
(defvar *pending-top-level-lambdas*)

;;; The maximum number of top-level lambdas we put in a single top-level
;;; component.
;;;
989
(defparameter top-level-lambda-max 10)
990
991


992
993
994
995
996
997
998
999
1000
;;; OBJECT-CALL-TOP-LEVEL-LAMBDA  --  Internal
;;;
(defun object-call-top-level-lambda (tll object)
  (declare (type functional tll) (type object object))
  (etypecase object
    (fasl-file
     (fasl-dump-top-level-lambda-call tll object))
    (core-object
     (core-call-top-level-lambda tll object))