Work around excessive consing via ROOM by turning off
[sbcl.git] / src / code / room.lisp
1 ;;;; heap-grovelling memory usage stuff
2
3 ;;;; This software is part of the SBCL system. See the README file for
4 ;;;; more information.
5 ;;;;
6 ;;;; This software is derived from the CMU CL system, which was
7 ;;;; written at Carnegie Mellon University and released into the
8 ;;;; public domain. The software is in the public domain and is
9 ;;;; provided with absolutely no warranty. See the COPYING and CREDITS
10 ;;;; files for more information.
11
12 (in-package "SB!VM")
13
14 (declaim (special sb!vm:*read-only-space-free-pointer*
15                   sb!vm:*static-space-free-pointer*))
16 \f
17 ;;;; type format database
18
19 (eval-when (:compile-toplevel :load-toplevel :execute)
20   (def!struct (room-info (:make-load-form-fun just-dump-it-normally))
21     ;; the name of this type
22     (name nil :type symbol)
23     ;; kind of type (how we determine length)
24     (kind (missing-arg)
25           :type (member :lowtag :fixed :header :vector
26                         :string :code :closure :instance))
27     ;; length if fixed-length, shift amount for element size if :VECTOR
28     (length nil :type (or fixnum null))))
29
30 (eval-when (:compile-toplevel :execute)
31
32 (defvar *meta-room-info* (make-array 256 :initial-element nil))
33
34 (dolist (obj *primitive-objects*)
35   (let ((widetag (primitive-object-widetag obj))
36         (lowtag (primitive-object-lowtag obj))
37         (name (primitive-object-name obj))
38         (variable (primitive-object-variable-length-p obj))
39         (size (primitive-object-size obj)))
40     (cond
41      ((not lowtag))
42      ((not widetag)
43       (let ((info (make-room-info :name name
44                                   :kind :lowtag))
45             (lowtag (symbol-value lowtag)))
46         (declare (fixnum lowtag))
47         (dotimes (i 32)
48           (setf (svref *meta-room-info* (logior lowtag (ash i 3))) info))))
49      (variable)
50      (t
51       (setf (svref *meta-room-info* (symbol-value widetag))
52             (make-room-info :name name
53                             :kind :fixed
54                             :length size))))))
55
56 (dolist (code (list #!+sb-unicode complex-character-string-widetag
57                     complex-base-string-widetag simple-array-widetag
58                     complex-bit-vector-widetag complex-vector-widetag
59                     complex-array-widetag complex-vector-nil-widetag))
60   (setf (svref *meta-room-info* code)
61         (make-room-info :name 'array-header
62                         :kind :header)))
63
64 (setf (svref *meta-room-info* bignum-widetag)
65       (make-room-info :name 'bignum
66                       :kind :header))
67
68 (setf (svref *meta-room-info* closure-header-widetag)
69       (make-room-info :name 'closure
70                       :kind :closure))
71
72 ;; FIXME: This looks rather brittle. Can we get more of these numbers
73 ;; from somewhere sensible?
74 (dolist (stuff '((simple-bit-vector-widetag . -3)
75                  (simple-vector-widetag . #.sb!vm:word-shift)
76                  (simple-array-unsigned-byte-2-widetag . -2)
77                  (simple-array-unsigned-byte-4-widetag . -1)
78                  (simple-array-unsigned-byte-7-widetag . 0)
79                  (simple-array-unsigned-byte-8-widetag . 0)
80                  (simple-array-unsigned-byte-15-widetag . 1)
81                  (simple-array-unsigned-byte-16-widetag . 1)
82                  (simple-array-unsigned-byte-31-widetag . 2)
83                  (simple-array-unsigned-byte-32-widetag . 2)
84                  (simple-array-unsigned-fixnum-widetag . #.sb!vm:word-shift)
85                  (simple-array-unsigned-byte-63-widetag . 3)
86                  (simple-array-unsigned-byte-64-widetag . 3)
87                  (simple-array-signed-byte-8-widetag . 0)
88                  (simple-array-signed-byte-16-widetag . 1)
89                  (simple-array-fixnum-widetag . #.sb!vm:word-shift)
90                  (simple-array-signed-byte-32-widetag . 2)
91                  (simple-array-signed-byte-64-widetag . 3)
92                  (simple-array-single-float-widetag . 2)
93                  (simple-array-double-float-widetag . 3)
94                  (simple-array-complex-single-float-widetag . 3)
95                  (simple-array-complex-double-float-widetag . 4)))
96   (let* ((name (car stuff))
97          (size (cdr stuff))
98          (sname (string name)))
99     (when (boundp name)
100       (setf (svref *meta-room-info* (symbol-value name))
101             (make-room-info :name (intern (subseq sname
102                                                   0
103                                                   (mismatch sname "-WIDETAG"
104                                                             :from-end t)))
105                             :kind :vector
106                             :length size)))))
107
108 (setf (svref *meta-room-info* simple-base-string-widetag)
109       (make-room-info :name 'simple-base-string
110                       :kind :string
111                       :length 0))
112
113 #!+sb-unicode
114 (setf (svref *meta-room-info* simple-character-string-widetag)
115       (make-room-info :name 'simple-character-string
116                       :kind :string
117                       :length 2))
118
119 (setf (svref *meta-room-info* simple-array-nil-widetag)
120       (make-room-info :name 'simple-array-nil
121                       :kind :fixed
122                       :length 2))
123
124 (setf (svref *meta-room-info* code-header-widetag)
125       (make-room-info :name 'code
126                       :kind :code))
127
128 (setf (svref *meta-room-info* instance-header-widetag)
129       (make-room-info :name 'instance
130                       :kind :instance))
131
132 ) ; EVAL-WHEN
133
134 (defparameter *room-info* '#.*meta-room-info*)
135 (deftype spaces () '(member :static :dynamic :read-only))
136 \f
137 ;;;; MAP-ALLOCATED-OBJECTS
138
139 ;;; Since they're represented as counts of words, we should never
140 ;;; need bignums to represent these:
141 (declaim (type fixnum
142                *static-space-free-pointer*
143                *read-only-space-free-pointer*))
144
145 (defun space-bounds (space)
146   (declare (type spaces space))
147   (ecase space
148     (:static
149      (values (int-sap static-space-start)
150              (int-sap (ash *static-space-free-pointer* n-fixnum-tag-bits))))
151     (:read-only
152      (values (int-sap read-only-space-start)
153              (int-sap (ash *read-only-space-free-pointer* n-fixnum-tag-bits))))
154     (:dynamic
155      (values (int-sap (current-dynamic-space-start))
156              (dynamic-space-free-pointer)))))
157
158 ;;; Return the total number of bytes used in SPACE.
159 (defun space-bytes (space)
160   (multiple-value-bind (start end) (space-bounds space)
161     (- (sap-int end) (sap-int start))))
162
163 ;;; Round SIZE (in bytes) up to the next dualword boundary. A dualword
164 ;;; is eight bytes on platforms with 32-bit word size and 16 bytes on
165 ;;; platforms with 64-bit word size.
166 #!-sb-fluid (declaim (inline round-to-dualword))
167 (defun round-to-dualword (size)
168   (logand (the word (+ size lowtag-mask)) (lognot lowtag-mask)))
169
170 ;;; Return the total size of a vector in bytes, including any pad.
171 #!-sb-fluid (declaim (inline vector-total-size))
172 (defun vector-total-size (obj info)
173   (let ((shift (room-info-length info))
174         (len (+ (length (the (simple-array * (*)) obj))
175                 (ecase (room-info-kind info)
176                   (:vector 0)
177                   (:string 1)))))
178     (round-to-dualword
179      (+ (* vector-data-offset n-word-bytes)
180         (if (minusp shift)
181             (ash (+ len (1- (ash 1 (- shift))))
182                  shift)
183             (ash len shift))))))
184
185 ;;; Access to the GENCGC page table for better precision in
186 ;;; MAP-ALLOCATED-OBJECTS
187 #!+gencgc
188 (progn
189   (define-alien-type (struct page)
190       (struct page
191               (start long)
192               ;; On platforms with small enough GC pages, this field
193               ;; will be a short. On platforms with larger ones, it'll
194               ;; be an int.
195               (bytes-used (unsigned
196                            #.(if (typep sb!vm:gencgc-card-bytes
197                                         '(unsigned-byte 16))
198                                  16
199                                  32)))
200               (flags (unsigned 8))
201               (gen (signed 8))))
202   (declaim (inline find-page-index))
203   (define-alien-routine "find_page_index" long (index long))
204   (define-alien-variable "page_table" (* (struct page))))
205
206 ;;; Iterate over all the objects allocated in SPACE, calling FUN with
207 ;;; the object, the object's type code, and the object's total size in
208 ;;; bytes, including any header and padding. CAREFUL makes
209 ;;; MAP-ALLOCATED-OBJECTS slightly more accurate, but a lot slower: it
210 ;;; is intended for slightly more demanding uses of heap groveling
211 ;;; then ROOM.
212 #!-sb-fluid (declaim (maybe-inline map-allocated-objects))
213 (defun map-allocated-objects (fun space &optional careful)
214   (declare (type function fun) (type spaces space))
215   (declare (optimize (sb!c:alien-funcall-saves-fp-and-pc 0)))
216   (flet ((make-obj (tagged-address)
217            (if careful
218                (make-lisp-obj tagged-address nil)
219                (values (%make-lisp-obj tagged-address) t))))
220     ;; Inlining MAKE-OBJ reduces consing on platforms where dynamic
221     ;; space extends past fixnum range.
222     (declare (inline make-obj))
223     (without-gcing
224       (multiple-value-bind (start end) (space-bounds space)
225         (declare (type system-area-pointer start end))
226         (declare (optimize (speed 3)))
227         (let ((current start)
228               #!+gencgc
229               (skip-tests-until-addr 0))
230           (labels ((maybe-finish-mapping ()
231                      (unless (sap< current end)
232                        (aver (sap= current end))
233                        (return-from map-allocated-objects)))
234                    ;; GENCGC doesn't allocate linearly, which means that the
235                    ;; dynamic space can contain large blocks zeros that get
236                    ;; accounted as conses in ROOM (and slow down other
237                    ;; applications of MAP-ALLOCATED-OBJECTS). To fix this
238                    ;; check the GC page structure for the current address.
239                    ;; If the page is free or the address is beyond the page-
240                    ;; internal allocation offset (bytes-used) skip to the
241                    ;; next page immediately.
242                    (maybe-skip-page ()
243                      #!+gencgc
244                      (when (eq space :dynamic)
245                        (loop with page-mask = #.(1- sb!vm:gencgc-card-bytes)
246                              for addr of-type sb!vm:word = (sap-int current)
247                              while (>= addr skip-tests-until-addr)
248                              do
249                              ;; For some reason binding PAGE with LET
250                              ;; conses like mad (but gives no compiler notes...)
251                              ;; Work around the problem with SYMBOL-MACROLET
252                              ;; instead of trying to figure out the real
253                              ;; issue. -- JES, 2005-05-17
254                              (symbol-macrolet
255                                  ((page (deref page-table
256                                                (find-page-index addr))))
257                                ;; Don't we have any nicer way to access C struct
258                                ;; bitfields?
259                                (let ((alloc-flag (ldb (byte 3 2)
260                                                       (slot page 'flags)))
261                                      (bytes-used (slot page 'bytes-used)))
262                                  ;; If the page is not free and the current
263                                  ;; pointer is still below the allocation offset
264                                  ;; of the page
265                                  (when (and (not (zerop alloc-flag))
266                                             (< (logand page-mask addr)
267                                                bytes-used))
268                                    ;; Don't bother testing again until we
269                                    ;; get past that allocation offset
270                                    (setf skip-tests-until-addr
271                                          (+ (logandc2 addr page-mask) bytes-used))
272                                    ;; And then continue with the
273                                    ;; scheduled mapping
274                                    (return-from maybe-skip-page))
275                                  ;; Move CURRENT to start of next page.
276                                  (setf current (int-sap (+ (logandc2 addr page-mask)
277                                                            sb!vm:gencgc-card-bytes)))
278                                  (maybe-finish-mapping))))))
279                    (maybe-map (obj obj-tag n-obj-bytes &optional (ok t))
280                      (let ((next (typecase n-obj-bytes
281                                    (fixnum (sap+ current n-obj-bytes))
282                                    (integer (sap+ current n-obj-bytes)))))
283                        ;; If this object would take us past END, it must
284                        ;; be either bogus, or it has been allocated after
285                        ;; the call to M-A-O.
286                        (cond ((and ok next (sap<= next end))
287                               (funcall fun obj obj-tag n-obj-bytes)
288                               (setf current next))
289                              (t
290                               (setf current (sap+ current n-word-bytes)))))))
291             (declare (inline maybe-finish-mapping maybe-skip-page maybe-map))
292             (loop
293               (maybe-finish-mapping)
294               (maybe-skip-page)
295               (let* ((header (sap-ref-word current 0))
296                      (header-widetag (logand header #xFF))
297                      (info (svref *room-info* header-widetag)))
298                 (cond
299                   ((or (not info)
300                        (eq (room-info-kind info) :lowtag))
301                    (multiple-value-bind (obj ok)
302                        (make-obj (logior (sap-int current) list-pointer-lowtag))
303                      (maybe-map obj
304                                 list-pointer-lowtag
305                                 (* cons-size n-word-bytes)
306                                 ok)))
307                   ((eql header-widetag closure-header-widetag)
308                    (let* ((obj (%make-lisp-obj (logior (sap-int current)
309                                                        fun-pointer-lowtag)))
310                           (size (round-to-dualword
311                                  (* (the fixnum (1+ (get-closure-length obj)))
312                                     n-word-bytes))))
313                      (maybe-map obj header-widetag size)))
314                   ((eq (room-info-kind info) :instance)
315                    (let* ((obj (%make-lisp-obj
316                                 (logior (sap-int current) instance-pointer-lowtag)))
317                           (size (round-to-dualword
318                                  (* (+ (%instance-length obj) 1) n-word-bytes))))
319                      (aver (zerop (logand size lowtag-mask)))
320                      (maybe-map obj header-widetag size)))
321                   (t
322                    (multiple-value-bind (obj ok)
323                        (make-obj (logior (sap-int current) other-pointer-lowtag))
324                      (let ((size (when ok
325                                    (ecase (room-info-kind info)
326                                      (:fixed
327                                       (aver (or (eql (room-info-length info)
328                                                      (1+ (get-header-data obj)))
329                                                 (floatp obj)
330                                                 (simple-array-nil-p obj)))
331                                       (round-to-dualword
332                                        (* (room-info-length info) n-word-bytes)))
333                                      ((:vector :string)
334                                       (vector-total-size obj info))
335                                      (:header
336                                       (round-to-dualword
337                                        (* (1+ (get-header-data obj)) n-word-bytes)))
338                                      (:code
339                                       (+ (the fixnum
340                                            (* (get-header-data obj) n-word-bytes))
341                                          (round-to-dualword
342                                           (* (the fixnum (%code-code-size obj))
343                                              n-word-bytes))))))))
344                        (macrolet ((frob ()
345                                     '(progn
346                                       (when size (aver (zerop (logand size lowtag-mask))))
347                                       (maybe-map obj header-widetag size))))
348                          (typecase size
349                            (fixnum (frob))
350                            (word (frob))
351                            (null (frob))))))))))))))))
352
353 \f
354 ;;;; MEMORY-USAGE
355
356 ;;; Return a list of 3-lists (bytes object type-name) for the objects
357 ;;; allocated in Space.
358 (defun type-breakdown (space)
359   (let ((sizes (make-array 256 :initial-element 0 :element-type '(unsigned-byte #.sb!vm:n-word-bits)))
360         (counts (make-array 256 :initial-element 0 :element-type '(unsigned-byte #.sb!vm:n-word-bits))))
361     (map-allocated-objects
362      (lambda (obj type size)
363        (declare (word size) (optimize (speed 3)) (ignore obj))
364        (incf (aref sizes type) size)
365        (incf (aref counts type)))
366      space)
367
368     (let ((totals (make-hash-table :test 'eq)))
369       (dotimes (i 256)
370         (let ((total-count (aref counts i)))
371           (unless (zerop total-count)
372             (let* ((total-size (aref sizes i))
373                    (name (room-info-name (aref *room-info* i)))
374                    (found (gethash name totals)))
375               (cond (found
376                      (incf (first found) total-size)
377                      (incf (second found) total-count))
378                     (t
379                      (setf (gethash name totals)
380                            (list total-size total-count name))))))))
381
382       (collect ((totals-list))
383         (maphash (lambda (k v)
384                    (declare (ignore k))
385                    (totals-list v))
386                  totals)
387         (sort (totals-list) #'> :key #'first)))))
388
389 ;;; Handle the summary printing for MEMORY-USAGE. Totals is a list of lists
390 ;;; (space-name . totals-for-space), where totals-for-space is the list
391 ;;; returned by TYPE-BREAKDOWN.
392 (defun print-summary (spaces totals)
393   (let ((summary (make-hash-table :test 'eq)))
394     (dolist (space-total totals)
395       (dolist (total (cdr space-total))
396         (push (cons (car space-total) total)
397               (gethash (third total) summary))))
398
399     (collect ((summary-totals))
400       (maphash (lambda (k v)
401                  (declare (ignore k))
402                  (let ((sum 0))
403                    (declare (unsigned-byte sum))
404                    (dolist (space-total v)
405                      (incf sum (first (cdr space-total))))
406                    (summary-totals (cons sum v))))
407                summary)
408
409       (format t "~2&Summary of spaces: ~(~{~A ~}~)~%" spaces)
410       (let ((summary-total-bytes 0)
411             (summary-total-objects 0))
412         (declare (unsigned-byte summary-total-bytes summary-total-objects))
413         (dolist (space-totals
414                  (mapcar #'cdr (sort (summary-totals) #'> :key #'car)))
415           (let ((total-objects 0)
416                 (total-bytes 0)
417                 name)
418             (declare (unsigned-byte total-objects total-bytes))
419             (collect ((spaces))
420               (dolist (space-total space-totals)
421                 (let ((total (cdr space-total)))
422                   (setq name (third total))
423                   (incf total-bytes (first total))
424                   (incf total-objects (second total))
425                   (spaces (cons (car space-total) (first total)))))
426               (format t "~%~A:~%    ~:D bytes, ~:D object~:P"
427                       name total-bytes total-objects)
428               (dolist (space (spaces))
429                 (format t ", ~W% ~(~A~)"
430                         (round (* (cdr space) 100) total-bytes)
431                         (car space)))
432               (format t ".~%")
433               (incf summary-total-bytes total-bytes)
434               (incf summary-total-objects total-objects))))
435         (format t "~%Summary total:~%    ~:D bytes, ~:D objects.~%"
436                 summary-total-bytes summary-total-objects)))))
437
438 ;;; Report object usage for a single space.
439 (defun report-space-total (space-total cutoff)
440   (declare (list space-total) (type (or single-float null) cutoff))
441   (format t "~2&Breakdown for ~(~A~) space:~%" (car space-total))
442   (let* ((types (cdr space-total))
443          (total-bytes (reduce #'+ (mapcar #'first types)))
444          (total-objects (reduce #'+ (mapcar #'second types)))
445          (cutoff-point (if cutoff
446                            (truncate (* (float total-bytes) cutoff))
447                            0))
448          (reported-bytes 0)
449          (reported-objects 0))
450     (declare (unsigned-byte total-objects total-bytes cutoff-point reported-objects
451                             reported-bytes))
452     (loop for (bytes objects name) in types do
453       (when (<= bytes cutoff-point)
454         (format t "  ~10:D bytes for ~9:D other object~2:*~P.~%"
455                 (- total-bytes reported-bytes)
456                 (- total-objects reported-objects))
457         (return))
458       (incf reported-bytes bytes)
459       (incf reported-objects objects)
460       (format t "  ~10:D bytes for ~9:D ~(~A~) object~2:*~P.~%"
461               bytes objects name))
462     (format t "  ~10:D bytes for ~9:D ~(~A~) object~2:*~P (space total.)~%"
463             total-bytes total-objects (car space-total))))
464
465 ;;; Print information about the heap memory in use. PRINT-SPACES is a
466 ;;; list of the spaces to print detailed information for.
467 ;;; COUNT-SPACES is a list of the spaces to scan. For either one, T
468 ;;; means all spaces (i.e. :STATIC, :DYNAMIC and :READ-ONLY.) If
469 ;;; PRINT-SUMMARY is true, then summary information will be printed.
470 ;;; The defaults print only summary information for dynamic space. If
471 ;;; true, CUTOFF is a fraction of the usage in a report below which
472 ;;; types will be combined as OTHER.
473 (defun memory-usage (&key print-spaces (count-spaces '(:dynamic))
474                           (print-summary t) cutoff)
475   (declare (type (or single-float null) cutoff))
476   (let* ((spaces (if (eq count-spaces t)
477                      '(:static :dynamic :read-only)
478                      count-spaces))
479          (totals (mapcar (lambda (space)
480                            (cons space (type-breakdown space)))
481                          spaces)))
482
483     (dolist (space-total totals)
484       (when (or (eq print-spaces t)
485                 (member (car space-total) print-spaces))
486         (report-space-total space-total cutoff)))
487
488     (when print-summary (print-summary spaces totals)))
489
490   (values))
491 \f
492 ;;; Print info about how much code and no-ops there are in SPACE.
493 (defun count-no-ops (space)
494   (declare (type spaces space))
495   (let ((code-words 0)
496         (no-ops 0)
497         (total-bytes 0))
498     (declare (fixnum code-words no-ops)
499              (type unsigned-byte total-bytes))
500     (map-allocated-objects
501      (lambda (obj type size)
502        (when (eql type code-header-widetag)
503          (let ((words (truly-the fixnum (%code-code-size obj)))
504                (sap (%primitive code-instructions obj))
505                (size size))
506            (declare (fixnum size))
507            (incf total-bytes size)
508            (incf code-words words)
509            (dotimes (i words)
510              (when (zerop (sap-ref-word sap (* i n-word-bytes)))
511                (incf no-ops))))))
512      space)
513
514     (format t
515             "~:D code-object bytes, ~:D code words, with ~:D no-ops (~D%).~%"
516             total-bytes code-words no-ops
517             (round (* no-ops 100) code-words)))
518
519   (values))
520 \f
521 (defun descriptor-vs-non-descriptor-storage (&rest spaces)
522   (let ((descriptor-words 0)
523         (non-descriptor-headers 0)
524         (non-descriptor-bytes 0))
525     (declare (type unsigned-byte descriptor-words non-descriptor-headers
526                    non-descriptor-bytes))
527     (dolist (space (or spaces '(:read-only :static :dynamic)))
528       (declare (inline map-allocated-objects))
529       (map-allocated-objects
530        (lambda (obj type size)
531          (case type
532            (#.code-header-widetag
533             (let ((inst-words (truly-the fixnum (%code-code-size obj)))
534                   (size size))
535               (declare (type fixnum size inst-words))
536               (incf non-descriptor-bytes (* inst-words n-word-bytes))
537               (incf descriptor-words
538                     (- (truncate size n-word-bytes) inst-words))))
539            ((#.bignum-widetag
540              #.single-float-widetag
541              #.double-float-widetag
542              #.simple-base-string-widetag
543              #!+sb-unicode #.simple-character-string-widetag
544              #.simple-array-nil-widetag
545              #.simple-bit-vector-widetag
546              #.simple-array-unsigned-byte-2-widetag
547              #.simple-array-unsigned-byte-4-widetag
548              #.simple-array-unsigned-byte-8-widetag
549              #.simple-array-unsigned-byte-16-widetag
550              #.simple-array-unsigned-byte-32-widetag
551              #.simple-array-signed-byte-8-widetag
552              #.simple-array-signed-byte-16-widetag
553              #.simple-array-signed-byte-32-widetag
554              #.simple-array-single-float-widetag
555              #.simple-array-double-float-widetag
556              #.simple-array-complex-single-float-widetag
557              #.simple-array-complex-double-float-widetag)
558             (incf non-descriptor-headers)
559             (incf non-descriptor-bytes (- size n-word-bytes)))
560            ((#.list-pointer-lowtag
561              #.instance-pointer-lowtag
562              #.ratio-widetag
563              #.complex-widetag
564              #.simple-array-widetag
565              #.simple-vector-widetag
566              #.complex-base-string-widetag
567              #.complex-vector-nil-widetag
568              #.complex-bit-vector-widetag
569              #.complex-vector-widetag
570              #.complex-array-widetag
571              #.closure-header-widetag
572              #.funcallable-instance-header-widetag
573              #.value-cell-header-widetag
574              #.symbol-header-widetag
575              #.sap-widetag
576              #.weak-pointer-widetag
577              #.instance-header-widetag)
578             (incf descriptor-words (truncate (the fixnum size) n-word-bytes)))
579            (t
580             (error "bogus widetag: ~W" type))))
581        space))
582     (format t "~:D words allocated for descriptor objects.~%"
583             descriptor-words)
584     (format t "~:D bytes data/~:D words header for non-descriptor objects.~%"
585             non-descriptor-bytes non-descriptor-headers)
586     (values)))
587 \f
588 ;;; Print a breakdown by instance type of all the instances allocated
589 ;;; in SPACE. If TOP-N is true, print only information for the
590 ;;; TOP-N types with largest usage.
591 (defun instance-usage (space &key (top-n 15))
592   (declare (type spaces space) (type (or fixnum null) top-n))
593   (format t "~2&~@[Top ~W ~]~(~A~) instance types:~%" top-n space)
594   (let ((totals (make-hash-table :test 'eq))
595         (total-objects 0)
596         (total-bytes 0))
597     (declare (unsigned-byte total-objects total-bytes))
598     (map-allocated-objects
599      (lambda (obj type size)
600        (declare (optimize (speed 3)))
601        (when (eql type instance-header-widetag)
602          (incf total-objects)
603          (let* ((classoid (layout-classoid (%instance-ref obj 0)))
604                 (found (gethash classoid totals))
605                 (size size))
606            (declare (fixnum size))
607            (incf total-bytes size)
608            (cond (found
609                   (incf (the fixnum (car found)))
610                   (incf (the fixnum (cdr found)) size))
611                  (t
612                   (setf (gethash classoid totals) (cons 1 size)))))))
613      space)
614
615     (collect ((totals-list))
616       (maphash (lambda (classoid what)
617                  (totals-list (cons (prin1-to-string
618                                      (classoid-proper-name classoid))
619                                     what)))
620                totals)
621       (let ((sorted (sort (totals-list) #'> :key #'cddr))
622             (printed-bytes 0)
623             (printed-objects 0))
624         (declare (unsigned-byte printed-bytes printed-objects))
625         (dolist (what (if top-n
626                           (subseq sorted 0 (min (length sorted) top-n))
627                           sorted))
628           (let ((bytes (cddr what))
629                 (objects (cadr what)))
630             (incf printed-bytes bytes)
631             (incf printed-objects objects)
632             (format t "  ~A: ~:D bytes, ~:D object~:P.~%" (car what)
633                     bytes objects)))
634
635         (let ((residual-objects (- total-objects printed-objects))
636               (residual-bytes (- total-bytes printed-bytes)))
637           (unless (zerop residual-objects)
638             (format t "  Other types: ~:D bytes, ~:D object~:P.~%"
639                     residual-bytes residual-objects))))
640
641       (format t "  ~:(~A~) instance total: ~:D bytes, ~:D object~:P.~%"
642               space total-bytes total-objects)))
643
644   (values))
645 \f
646 ;;;; PRINT-ALLOCATED-OBJECTS
647
648 (defun print-allocated-objects (space &key (percent 0) (pages 5)
649                                       type larger smaller count
650                                       (stream *standard-output*))
651   (declare (type (integer 0 99) percent) (type index pages)
652            (type stream stream) (type spaces space)
653            (type (or index null) type larger smaller count))
654   (multiple-value-bind (start-sap end-sap) (space-bounds space)
655     (let* ((space-start (sap-int start-sap))
656            (space-end (sap-int end-sap))
657            (space-size (- space-end space-start))
658            (pagesize (sb!sys:get-page-size))
659            (start (+ space-start (round (* space-size percent) 100)))
660            (printed-conses (make-hash-table :test 'eq))
661            (pages-so-far 0)
662            (count-so-far 0)
663            (last-page 0))
664       (declare (type (unsigned-byte 32) last-page start)
665                (fixnum pages-so-far count-so-far pagesize))
666       (labels ((note-conses (x)
667                  (unless (or (atom x) (gethash x printed-conses))
668                    (setf (gethash x printed-conses) t)
669                    (note-conses (car x))
670                    (note-conses (cdr x)))))
671         (map-allocated-objects
672          (lambda (obj obj-type size)
673            (let ((addr (get-lisp-obj-address obj)))
674              (when (>= addr start)
675                (when (if count
676                          (> count-so-far count)
677                          (> pages-so-far pages))
678                  (return-from print-allocated-objects (values)))
679
680                (unless count
681                  (let ((this-page (* (the (values (unsigned-byte 32) t)
682                                        (truncate addr pagesize))
683                                      pagesize)))
684                    (declare (type (unsigned-byte 32) this-page))
685                    (when (/= this-page last-page)
686                      (when (< pages-so-far pages)
687                        ;; FIXME: What is this? (ERROR "Argh..")? or
688                        ;; a warning? or code that can be removed
689                        ;; once the system is stable? or what?
690                        (format stream "~2&**** Page ~W, address ~X:~%"
691                                pages-so-far addr))
692                      (setq last-page this-page)
693                      (incf pages-so-far))))
694
695                (when (and (or (not type) (eql obj-type type))
696                           (or (not smaller) (<= size smaller))
697                           (or (not larger) (>= size larger)))
698                  (incf count-so-far)
699                  (case type
700                    (#.code-header-widetag
701                     (let ((dinfo (%code-debug-info obj)))
702                       (format stream "~&Code object: ~S~%"
703                               (if dinfo
704                                   (sb!c::compiled-debug-info-name dinfo)
705                                   "No debug info."))))
706                    (#.symbol-header-widetag
707                     (format stream "~&~S~%" obj))
708                    (#.list-pointer-lowtag
709                     (unless (gethash obj printed-conses)
710                       (note-conses obj)
711                       (let ((*print-circle* t)
712                             (*print-level* 5)
713                             (*print-length* 10))
714                         (format stream "~&~S~%" obj))))
715                    (t
716                     (fresh-line stream)
717                     (let ((str (write-to-string obj :level 5 :length 10
718                                                 :pretty nil)))
719                       (unless (eql type instance-header-widetag)
720                         (format stream "~S: " (type-of obj)))
721                       (format stream "~A~%"
722                               (subseq str 0 (min (length str) 60))))))))))
723          space))))
724   (values))
725 \f
726 ;;;; LIST-ALLOCATED-OBJECTS, LIST-REFERENCING-OBJECTS
727
728 (defvar *ignore-after* nil)
729
730 (defun valid-obj (space x)
731   (or (not (eq space :dynamic))
732       ;; this test looks bogus if the allocator doesn't work linearly,
733       ;; which I suspect is the case for GENCGC.  -- CSR, 2004-06-29
734       (< (get-lisp-obj-address x) (get-lisp-obj-address *ignore-after*))))
735
736 (defun maybe-cons (space x stuff)
737   (if (valid-obj space x)
738       (cons x stuff)
739       stuff))
740
741 (defun list-allocated-objects (space &key type larger smaller count
742                                      test)
743   (declare (type spaces space)
744            (type (or index null) larger smaller type count)
745            (type (or function null) test)
746            (inline map-allocated-objects))
747   (unless *ignore-after*
748     (setq *ignore-after* (cons 1 2)))
749   (collect ((counted 0 1+))
750     (let ((res ()))
751       (map-allocated-objects
752        (lambda (obj obj-type size)
753          (when (and (or (not type) (eql obj-type type))
754                     (or (not smaller) (<= size smaller))
755                     (or (not larger) (>= size larger))
756                     (or (not test) (funcall test obj)))
757            (setq res (maybe-cons space obj res))
758            (when (and count (>= (counted) count))
759              (return-from list-allocated-objects res))))
760        space)
761       res)))
762
763 ;;; Calls FUNCTION with all object that have (possibly conservative)
764 ;;; references to them on current stack.
765 (defun map-stack-references (function)
766   (let ((end
767          (sb!di::descriptor-sap
768           #!+stack-grows-downward-not-upward *control-stack-end*
769           #!-stack-grows-downward-not-upward *control-stack-start*))
770         (sp (current-sp))
771         (seen nil))
772     (loop until #!+stack-grows-downward-not-upward (sap> sp end)
773                 #!-stack-grows-downward-not-upward (sap< sp end)
774           do (multiple-value-bind (obj ok) (make-lisp-obj (sap-ref-word sp 0) nil)
775                (when (and ok (typep obj '(not (or fixnum character))))
776                  (unless (member obj seen :test #'eq)
777                    (funcall function obj)
778                    (push obj seen))))
779              (setf sp
780                    #!+stack-grows-downward-not-upward (sap+ sp n-word-bytes)
781                    #!-stack-grows-downward-not-upward (sap+ sp (- n-word-bytes))))))
782
783 (defun map-referencing-objects (fun space object)
784   (declare (type spaces space) (inline map-allocated-objects))
785   (unless *ignore-after*
786     (setq *ignore-after* (cons 1 2)))
787   (flet ((maybe-call (fun obj)
788            (when (valid-obj space obj)
789              (funcall fun obj))))
790     (map-allocated-objects
791      (lambda (obj obj-type size)
792        (declare (ignore obj-type size))
793        (typecase obj
794          (cons
795           (when (or (eq (car obj) object)
796                     (eq (cdr obj) object))
797             (maybe-call fun obj)))
798          (instance
799           (dotimes (i (%instance-length obj))
800             (when (eq (%instance-ref obj i) object)
801               (maybe-call fun obj)
802               (return))))
803          (code-component
804           (let ((length (get-header-data obj)))
805             (do ((i code-constants-offset (1+ i)))
806                 ((= i length))
807               (when (eq (code-header-ref obj i) object)
808                 (maybe-call fun obj)
809                 (return)))))
810          (simple-vector
811           (dotimes (i (length obj))
812             (when (eq (svref obj i) object)
813               (maybe-call fun obj)
814               (return))))
815          (symbol
816           (when (or (eq (symbol-name obj) object)
817                     (eq (symbol-package obj) object)
818                     (eq (symbol-plist obj) object)
819                     (and (boundp obj)
820                          (eq (symbol-value obj) object)))
821             (maybe-call fun obj)))))
822      space)))
823
824 (defun list-referencing-objects (space object)
825   (collect ((res))
826     (map-referencing-objects
827      (lambda (obj) (res obj)) space object)
828     (res)))