1 ;;; Copyright (C) 2003 Gerd Moellmann <gerd.moellmann@t-online.de>
2 ;;; All rights reserved.
4 ;;; Redistribution and use in source and binary forms, with or without
5 ;;; modification, are permitted provided that the following conditions
8 ;;; 1. Redistributions of source code must retain the above copyright
9 ;;; notice, this list of conditions and the following disclaimer.
10 ;;; 2. Redistributions in binary form must reproduce the above copyright
11 ;;; notice, this list of conditions and the following disclaimer in the
12 ;;; documentation and/or other materials provided with the distribution.
13 ;;; 3. The name of the author may not be used to endorse or promote
14 ;;; products derived from this software without specific prior written
17 ;;; THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS
18 ;;; OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
19 ;;; WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20 ;;; ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE
21 ;;; LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
22 ;;; CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
23 ;;; OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
24 ;;; BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
25 ;;; LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26 ;;; (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
27 ;;; USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
30 ;;; Statistical profiler.
34 ;;; This profiler arranges for SIGPROF interrupts to interrupt a
35 ;;; running program at regular intervals. Each time a SIGPROF occurs,
36 ;;; the current program counter and return address is recorded in a
37 ;;; vector, until a configurable maximum number of samples have been
40 ;;; A profiling report is generated from the samples array by
41 ;;; determining the Lisp functions corresponding to the recorded
42 ;;; addresses. Each program counter/return address pair forms one
43 ;;; edge in a call graph.
47 ;;; The code being generated on x86 makes determining callers reliably
48 ;;; something between extremely difficult and impossible. Example:
50 ;;; 10979F00: .entry eval::eval-stack-args(arg-count)
51 ;;; 18: pop dword ptr [ebp-8]
52 ;;; 1B: lea esp, [ebp-32]
57 ;;; 29: mov [ebp-12], edi
58 ;;; 2C: mov dword ptr [ebp-16], #x28F0000B ; nil
59 ;;; ; No-arg-parsing entry point
60 ;;; 33: mov dword ptr [ebp-20], 0
62 ;;; 3C: L0: mov edx, esp
64 ;;; 41: mov eax, [#x10979EF8] ; #<FDEFINITION object for eval::eval-stack-pop>
66 ;;; 49: mov [edx-4], ebp
68 ;;; 4E: call dword ptr [eax+5]
71 ;;; Suppose this function is interrupted by SIGPROF at 4E. At that
72 ;;; point, the frame pointer EBP has been modified so that the
73 ;;; original return address of the caller of eval-stack-args is no
74 ;;; longer where it can be found by x86-call-context, and the new
75 ;;; return address, for the call to eval-stack-pop, is not yet on the
76 ;;; stack. The effect is that x86-call-context returns something
77 ;;; bogus, which leads to wrong edges in the call graph.
79 ;;; One thing that one might try is filtering cases where the program
80 ;;; is interrupted at a call instruction. But since the above example
81 ;;; of an interrupt at a call instruction isn't the only case where
82 ;;; the stack is something x86-call-context can't really cope with,
83 ;;; this is not a general solution.
85 ;;; Random ideas for implementation:
87 ;;; * Space profiler. Sample when new pages are allocated instead of
90 ;;; * Record a configurable number of callers up the stack. That
91 ;;; could give a more complete graph when there are many small
94 ;;; * Print help strings for reports, include hints to the problem
97 ;;; * Make flat report the default since call-graph isn't that
100 (defpackage #:sb-sprof
101 (:use #:cl #:sb-ext #:sb-unix #:sb-alien #:sb-sys)
102 (:export #:*sample-interval* #:*max-samples*
103 #:start-sampling #:stop-sampling #:with-sampling
104 #:with-profiling #:start-profiling #:stop-profiling
107 (in-package #:sb-sprof)
112 (defstruct (vertex (:constructor make-vertex)
113 (:constructor make-scc (scc-vertices edges)))
114 (visited nil :type boolean)
115 (root nil :type (or null vertex))
117 (edges () :type list)
118 (scc-vertices () :type list))
121 (vertex (sb-impl::missing-arg) :type vertex))
124 (vertices () :type list))
126 (declaim (inline scc-p))
127 (defun scc-p (vertex)
128 (not (null (vertex-scc-vertices vertex))))
130 (defmacro do-vertices ((vertex graph) &body body)
131 `(dolist (,vertex (graph-vertices ,graph))
134 (defmacro do-edges ((edge edge-to vertex) &body body)
135 `(dolist (,edge (vertex-edges ,vertex))
136 (let ((,edge-to (edge-vertex ,edge)))
139 (defun self-cycle-p (vertex)
140 (do-edges (e to vertex)
144 (defun map-vertices (fn vertices)
146 (setf (vertex-visited v) nil))
148 (unless (vertex-visited v)
151 ;;; Eeko Nuutila, Eljas Soisalon-Soininen, around 1992. Improves on
152 ;;; Tarjan's original algorithm by not using the stack when processing
153 ;;; trivial components. Trivial components should appear frequently
154 ;;; in a call-graph such as ours, I think. Same complexity O(V+E) as
156 (defun strong-components (vertices)
157 (let ((in-component (make-array (length vertices)
158 :element-type 'boolean
159 :initial-element nil))
163 (labels ((min-root (x y)
164 (let ((rx (vertex-root x))
165 (ry (vertex-root y)))
166 (if (< (vertex-dfn rx) (vertex-dfn ry))
170 (aref in-component (vertex-dfn v)))
171 ((setf in-component) (in v)
172 (setf (aref in-component (vertex-dfn v)) in))
174 (> (vertex-dfn x) (vertex-dfn y)))
176 (setf (vertex-dfn v) (incf dfn)
179 (vertex-visited v) t)
181 (unless (vertex-visited w)
183 (unless (in-component w)
184 (setf (vertex-root v) (min-root v w))))
185 (if (eq v (vertex-root v))
186 (loop while (and stack (vertex-> (car stack) v))
188 collect w into this-component
189 do (setf (in-component w) t)
191 (setf (in-component v) t)
192 (push (cons v this-component) components))
194 (map-vertices #'visit vertices)
197 ;;; Given a dag as a list of vertices, return the list sorted
198 ;;; topologically, children first.
199 (defun topological-sort (dag)
202 (labels ((rec-sort (v)
203 (setf (vertex-visited v) t)
204 (setf (vertex-dfn v) (incf dfn))
205 (dolist (e (vertex-edges v))
206 (unless (vertex-visited (edge-vertex e))
207 (rec-sort (edge-vertex e))))
209 (map-vertices #'rec-sort dag)
212 ;;; Reduce graph G to a dag by coalescing strongly connected components
213 ;;; into vertices. Sort the result topologically.
214 (defun reduce-graph (graph &optional (scc-constructor #'make-scc))
215 (sb-int:collect ((sccs) (trivial))
216 (dolist (c (strong-components (graph-vertices graph)))
217 (if (or (cdr c) (self-cycle-p (car c)))
218 (sb-int:collect ((outgoing))
223 (sccs (funcall scc-constructor c (outgoing))))
226 (dolist (v (trivial))
228 (when (member w (vertex-scc-vertices scc))
229 (setf (edge-vertex e) scc)))))
230 (setf (graph-vertices graph)
231 (topological-sort (nconc (sccs) (trivial))))))
236 "Type used for addresses, for instance, program counters,
237 code start/end locations etc."
238 '(unsigned-byte #.sb-vm::n-machine-word-bits))
240 (defconstant +unknown-address+ 0
241 "Constant representing an address that cannot be determined.")
243 ;;; A call graph. Vertices are NODE structures, edges are CALL
245 (defstruct (call-graph (:include graph)
246 (:constructor %make-call-graph))
247 ;; the value of *Sample-Interval* at the time the graph was created
248 (sample-interval (sb-impl::missing-arg) :type number)
249 ;; number of samples taken
250 (nsamples (sb-impl::missing-arg) :type sb-impl::index)
251 ;; sample count for samples not in any function
252 (elsewhere-count (sb-impl::missing-arg) :type sb-impl::index)
253 ;; a flat list of NODEs, sorted by sample count
254 (flat-nodes () :type list))
256 ;;; A node in a call graph, representing a function that has been
257 ;;; sampled. The edges of a node are CALL structures that represent
258 ;;; functions called from a given node.
259 (defstruct (node (:include vertex)
260 (:constructor %make-node))
261 ;; A numeric label for the node. The most frequently called function
262 ;; gets label 1. This is just for identification purposes in the
264 (index 0 :type fixnum)
265 ;; start and end address of the function's code
266 (start-pc 0 :type address)
267 (end-pc 0 :type address)
268 ;; the name of the function
270 ;; sample count for this function
271 (count 0 :type fixnum)
272 ;; count including time spent in functions called from this one
273 (accrued-count 0 :type fixnum)
274 ;; list of NODEs for functions calling this one
275 (callers () :type list))
277 ;;; A cycle in a call graph. The functions forming the cycle are
278 ;;; found in the SCC-VERTICES slot of the VERTEX structure.
279 (defstruct (cycle (:include node)))
281 ;;; An edge in a call graph. EDGE-VERTEX is the function being
283 (defstruct (call (:include edge)
284 (:constructor make-call (vertex)))
285 ;; number of times the call was sampled
286 (count 1 :type sb-impl::index))
288 ;;; Info about a function in dynamic-space. This is used to track
289 ;;; address changes of functions during GC.
290 (defstruct (dyninfo (:constructor make-dyninfo (code start end)))
291 ;; component this info is for
292 (code (sb-impl::missing-arg) :type sb-kernel::code-component)
293 ;; current start and end address of the component
294 (start (sb-impl::missing-arg) :type address)
295 (end (sb-impl::missing-arg) :type address)
296 ;; new start address of the component, after GC.
297 (new-start 0 :type address))
299 (defmethod print-object ((call-graph call-graph) stream)
300 (print-unreadable-object (call-graph stream :type t :identity t)
301 (format stream "~d samples" (call-graph-nsamples call-graph))))
303 (defmethod print-object ((node node) stream)
304 (print-unreadable-object (node stream :type t :identity t)
305 (format stream "~s [~d]" (node-name node) (node-index node))))
307 (defmethod print-object ((call call) stream)
308 (print-unreadable-object (call stream :type t :identity t)
309 (format stream "~s [~d]" (node-name (call-vertex call))
310 (node-index (call-vertex call)))))
312 (deftype report-type ()
313 '(member nil :flat :graph))
315 (defvar *sample-interval* 0.01
316 "Default number of seconds between samples.")
317 (declaim (number *sample-interval*))
319 (defvar *max-samples* 50000
320 "Default number of samples taken.")
321 (declaim (type sb-impl::index *max-samples*))
323 ;; For every profiler event we store this many samples (frames 0-n on
325 (defconstant +sample-depth+
329 ;; We store two elements for each sample. The debug-info of the sample
330 ;; and either its absolute PC or a PC offset, depending on the type of
332 (defconstant +sample-size+ (* +sample-depth+ 2))
334 (defvar *samples* nil)
335 (declaim (type (or null simple-vector) *samples*))
337 (defvar *samples-index* 0)
338 (declaim (type sb-impl::index *samples-index*))
340 (defvar *profiling* nil)
341 (defvar *sampling* nil)
342 (declaim (type boolean *profiling* *sampling*))
344 (defvar *show-progress* nil)
346 (defvar *old-sampling* nil)
348 (defun turn-off-sampling ()
349 (setq *old-sampling* *sampling*)
350 (setq *sampling* nil))
352 (defun turn-on-sampling ()
353 (setq *sampling* *old-sampling*))
355 (defun show-progress (format-string &rest args)
356 (when *show-progress*
357 (apply #'format t format-string args)
360 (defun start-sampling ()
361 "Switch on statistical sampling."
364 (defun stop-sampling ()
365 "Switch off statistical sampling."
366 (setq *sampling* nil))
368 (defmacro with-sampling ((&optional (on t)) &body body)
369 "Evaluate body with statistical sampling turned on or off."
370 `(let ((*sampling* ,on))
373 ;;; Return something serving as debug info for address PC.
374 (declaim (inline debug-info))
375 (defun debug-info (pc)
376 (declare (type system-area-pointer pc))
377 (let ((ptr (sb-di::component-ptr-from-pc pc)))
378 (cond ((sap= ptr (int-sap 0))
379 (let ((name (sap-foreign-symbol pc)))
381 (values (format nil "foreign function ~a" name)
383 (values nil (sap-int pc)))))
385 (let* ((code (sb-di::component-from-component-ptr ptr))
386 (code-header-len (* (sb-kernel:get-header-data code)
388 (pc-offset (- (sap-int pc)
389 (- (sb-kernel:get-lisp-obj-address code)
390 sb-vm:other-pointer-lowtag)
392 (df (sb-di::debug-fun-from-pc code pc-offset)))
393 (cond ((typep df 'sb-di::bogus-debug-fun)
394 (values code (sap-int pc)))
396 ;; The code component might be moved by the GC. Store
397 ;; a PC offset, and reconstruct the data in
398 ;; SAMPLE-PC-FROM-PC-OR-OFFSET.
399 (values df pc-offset))
401 (values nil 0))))))))
403 (declaim (inline record))
405 (declare (type system-area-pointer pc))
406 (multiple-value-bind (info pc-or-offset)
408 ;; For each sample, store the debug-info and the PC/offset into
410 (setf (aref *samples* *samples-index*) info
411 (aref *samples* (1+ *samples-index*)) pc-or-offset))
412 (incf *samples-index* 2))
414 ;;; Ensure that only one thread at a time will be executing sigprof handler.
415 (defvar *sigprof-handler-lock* (sb-thread:make-mutex :name "SIGPROF handler"))
417 ;;; SIGPROF handler. Record current PC and return address in
420 (defun sigprof-handler (signal code scp)
421 (declare (ignore signal code)
422 (optimize speed (space 0))
423 (type system-area-pointer scp))
424 (sb-sys:without-interrupts
425 (when (and *sampling*
427 (< *samples-index* (length (the simple-vector *samples*))))
428 (sb-sys:without-gcing
429 (sb-thread:with-mutex (*sigprof-handler-lock*)
430 (with-alien ((scp (* os-context-t) :local scp))
431 (let* ((pc-ptr (sb-vm:context-pc scp))
432 (fp (sb-vm::context-register scp #.sb-vm::ebp-offset)))
433 ;; For some reason completely bogus small values for the
434 ;; frame pointer are returned every now and then, leading
435 ;; to segfaults. Try to avoid these cases.
437 ;; FIXME: Do a more thorough sanity check on ebp, or figure
438 ;; out why this is happening.
439 ;; -- JES, 2005-01-11
441 (dotimes (i +sample-depth+)
442 (record (int-sap 0)))
443 (return-from sigprof-handler nil))
444 (let ((fp (int-sap fp))
446 (declare (type system-area-pointer fp pc-ptr))
447 (dotimes (i +sample-depth+)
450 (setf (values ok pc-ptr fp)
451 (sb-di::x86-call-context fp)))))))))))
454 ;; FIXME: On non-x86 platforms we don't yet walk the call stack deeper
457 (defun sigprof-handler (signal code scp)
458 (declare (ignore signal code))
459 (sb-sys:without-interrupts
460 (when (and *sampling*
461 (< *samples-index* (length *samples*)))
462 (sb-sys:without-gcing
463 (with-alien ((scp (* os-context-t) :local scp))
464 (locally (declare (optimize (inhibit-warnings 2)))
465 (let* ((pc-ptr (sb-vm:context-pc scp))
466 (fp (sb-vm::context-register scp #.sb-vm::cfp-offset))
469 (* sb-vm::lra-save-offset sb-vm::n-word-bytes))))
471 (record (int-sap ra)))))))))
473 ;;; Return the start address of CODE.
474 (defun code-start (code)
475 (declare (type sb-kernel:code-component code))
476 (sap-int (sb-kernel:code-instructions code)))
478 ;;; Return start and end address of CODE as multiple values.
479 (defun code-bounds (code)
480 (declare (type sb-kernel:code-component code))
481 (let* ((start (code-start code))
482 (end (+ start (sb-kernel:%code-code-size code))))
485 (defmacro with-profiling ((&key (sample-interval '*sample-interval*)
486 (max-samples '*max-samples*)
489 (report nil report-p))
491 "Repeatedly evaluate Body with statistical profiling turned on.
492 The following keyword args are recognized:
494 :Sample-Interval <seconds>
495 Take a sample every <seconds> seconds. Default is
499 Repeat evaluating body until <max> samples are taken.
500 Default is *Max-Samples*.
503 If specified, call Report with :Type <type> at the end.
506 It true, call Reset at the beginning."
507 (declare (type report-type report))
508 `(let ((*sample-interval* ,sample-interval)
509 (*max-samples* ,max-samples))
510 ,@(when reset '((reset)))
515 (when (>= *samples-index* (length *samples*))
517 ,@(when show-progress
518 `((format t "~&===> ~d of ~d samples taken.~%"
519 (/ *samples-index* +sample-size+)
521 (let ((.last-index. *samples-index*))
523 (when (= .last-index. *samples-index*)
524 (warn "No sampling progress; possibly a profiler bug.")
527 ,@(when report-p `((report :type ,report)))))
529 (defun start-profiling (&key (max-samples *max-samples*)
530 (sample-interval *sample-interval*)
532 "Start profiling statistically if not already profiling.
533 The following keyword args are recognized:
535 :Sample-Interval <seconds>
536 Take a sample every <seconds> seconds. Default is
540 Maximum number of samples. Default is *Max-Samples*.
543 If true, the default, start sampling right away.
544 If false, Start-Sampling can be used to turn sampling on."
546 (multiple-value-bind (secs usecs)
547 (multiple-value-bind (secs rest)
548 (truncate sample-interval)
549 (values secs (truncate (* rest 1000000))))
550 (setq *samples* (make-array (* max-samples +sample-size+)))
551 (setq *samples-index* 0)
552 (setq *sampling* sampling)
553 (sb-sys:enable-interrupt sb-unix:sigprof #'sigprof-handler)
554 (unix-setitimer :profile secs usecs secs usecs)
555 (setq *profiling* t)))
558 (defun stop-profiling ()
559 "Stop profiling if profiling."
561 (unix-setitimer :profile 0 0 0 0)
562 ;; Even with the timer shut down we cannot be sure that there is
563 ;; no undelivered sigprof. Besides, leaving the signal handler
564 ;; installed won't hurt.
565 (setq *sampling* nil)
566 (setq *profiling* nil))
570 "Reset the profiler."
572 (setq *sampling* nil)
574 (setq *samples-index* 0)
577 ;;; Make a NODE for debug-info INFO.
578 (defun make-node (info)
579 (flet ((clean-name (name)
580 (if (and (consp name)
582 '(sb-c::xep sb-c::tl-xep sb-c::&more-processor
583 sb-c::hairy-arg-processor
584 sb-c::&optional-processor)))
588 (sb-kernel::code-component
589 (multiple-value-bind (start end)
591 (%make-node :name (or (sb-disassem::find-assembler-routine start)
592 (format nil "~a" info))
593 :start-pc start :end-pc end)))
594 (sb-di::compiled-debug-fun
595 (let* ((name (sb-di::debug-fun-name info))
596 (cdf (sb-di::compiled-debug-fun-compiler-debug-fun info))
597 (start-offset (sb-c::compiled-debug-fun-start-pc cdf))
598 (end-offset (sb-c::compiled-debug-fun-elsewhere-pc cdf))
599 (component (sb-di::compiled-debug-fun-component info))
600 (start-pc (code-start component)))
601 ;; Call graphs are mostly useless unless we somehow
602 ;; distinguish a gazillion different (LAMBDA ())'s.
603 (when (equal name '(lambda ()))
604 (setf name (format nil "Unknown component: #x~x" start-pc)))
605 (%make-node :name (clean-name name)
606 :start-pc (+ start-pc start-offset)
607 :end-pc (+ start-pc end-offset))))
609 (%make-node :name (clean-name (sb-di::debug-fun-name info))))
611 (%make-node :name (coerce info 'string))))))
613 ;;; One function can have more than one COMPILED-DEBUG-FUNCTION with
614 ;;; the same name. Reduce the number of calls to Debug-Info by first
615 ;;; looking for a given PC in a red-black tree. If not found in the
616 ;;; tree, get debug info, and look for a node in a hash-table by
617 ;;; function name. If not found in the hash-table, make a new node.
619 (defvar *name->node*)
621 (defmacro with-lookup-tables (() &body body)
622 `(let ((*name->node* (make-hash-table :test 'equal)))
625 ;;; Find or make a new node for address PC. Value is the NODE found
626 ;;; or made; NIL if not enough information exists to make a NODE for
628 (defun lookup-node (info)
630 (let* ((new (make-node info))
631 (key (cons (node-name new)
632 (node-start-pc new)))
633 (found (gethash key *name->node*)))
635 (setf (node-start-pc found)
636 (min (node-start-pc found) (node-start-pc new)))
637 (setf (node-end-pc found)
638 (max (node-end-pc found) (node-end-pc new)))
641 (setf (gethash key *name->node*) new)
644 ;;; Return a list of all nodes created by LOOKUP-NODE.
645 (defun collect-nodes ()
646 (loop for node being the hash-values of *name->node*
649 ;;; Value is a CALL-GRAPH for the current contents of *SAMPLES*.
650 (defun make-call-graph-1 (depth)
651 (let ((elsewhere-count 0)
653 (with-lookup-tables ()
654 (loop for i below (- *samples-index* 2) by 2
655 for callee = (lookup-node (aref *samples* i))
656 for caller = (lookup-node (aref *samples* (+ i 2)))
658 (when (and *show-progress* (plusp i))
659 (cond ((zerop (mod i 1000))
660 (show-progress "~d" i))
662 (show-progress "."))))
663 (when (< (mod i +sample-size+) depth)
664 (when (= (mod i +sample-size+) 0)
665 (setf visited-nodes nil)
667 (incf (node-accrued-count callee))
668 (incf (node-count callee)))
670 (incf elsewhere-count))))
672 (push callee visited-nodes))
674 (unless (member caller visited-nodes)
675 (incf (node-accrued-count caller)))
677 (let ((call (find callee (node-edges caller)
678 :key #'call-vertex)))
679 (pushnew caller (node-callers callee))
681 (unless (member caller visited-nodes)
682 (incf (call-count call)))
683 (push (make-call callee) (node-edges caller))))))))
684 (let ((sorted-nodes (sort (collect-nodes) #'> :key #'node-count)))
685 (loop for node in sorted-nodes and i from 1 do
686 (setf (node-index node) i))
687 (%make-call-graph :nsamples (/ *samples-index* +sample-size+)
688 :sample-interval *sample-interval*
689 :elsewhere-count elsewhere-count
690 :vertices sorted-nodes)))))
692 ;;; Reduce CALL-GRAPH to a dag, creating CYCLE structures for call
694 (defun reduce-call-graph (call-graph)
696 (flet ((make-one-cycle (vertices edges)
697 (let* ((name (format nil "<Cycle ~d>" (incf cycle-no)))
698 (count (loop for v in vertices sum (node-count v))))
699 (make-cycle :name name
702 :scc-vertices vertices
704 (reduce-graph call-graph #'make-one-cycle))))
706 ;;; For all nodes in CALL-GRAPH, compute times including the time
707 ;;; spent in functions called from them. Note that the call-graph
708 ;;; vertices are in reverse topological order, children first, so we
709 ;;; will have computed accrued counts of called functions before they
710 ;;; are used to compute accrued counts for callers.
711 (defun compute-accrued-counts (call-graph)
712 (do-vertices (from call-graph)
713 (setf (node-accrued-count from) (node-count from))
714 (do-edges (call to from)
715 (incf (node-accrued-count from)
716 (round (* (/ (call-count call) (node-count to))
717 (node-accrued-count to)))))))
719 ;;; Return a CALL-GRAPH structure for the current contents of
720 ;;; *SAMPLES*. The result contain a list of nodes sorted by self-time
721 ;;; in the FLAT-NODES slot, and a dag in VERTICES, with call cycles
722 ;;; reduced to CYCLE structures.
723 (defun make-call-graph (depth)
725 (show-progress "~&Computing call graph ")
726 (let ((call-graph (without-gcing (make-call-graph-1 depth))))
727 (setf (call-graph-flat-nodes call-graph)
728 (copy-list (graph-vertices call-graph)))
729 (show-progress "~&Finding cycles")
730 (reduce-call-graph call-graph)
731 (show-progress "~&Propagating counts")
732 #+nil (compute-accrued-counts call-graph)
738 (defun print-separator (&key (length 72) (char #\-))
739 (format t "~&~V,,,V<~>~%" length char))
741 (defun samples-percent (call-graph count)
743 (* 100.0 (/ count (call-graph-nsamples call-graph)))
746 (defun print-call-graph-header (call-graph)
747 (let ((nsamples (call-graph-nsamples call-graph))
748 (interval (call-graph-sample-interval call-graph))
749 (ncycles (loop for v in (graph-vertices call-graph)
751 (format t "~2&Number of samples: ~d~%~
752 Sample interval: ~f seconds~%~
753 Total sampling time: ~f seconds~%~
754 Number of cycles: ~d~2%"
757 (* nsamples interval)
760 (defun print-flat (call-graph &key (stream *standard-output*) max
761 min-percent (print-header t))
762 (let ((*standard-output* stream)
766 (min-count (if min-percent
767 (round (* (/ min-percent 100.0)
768 (call-graph-nsamples call-graph)))
771 (print-call-graph-header call-graph))
772 (format t "~& Self Cumul Total~%")
773 (format t "~& Nr Count % Count % Count % Function~%")
775 (let ((elsewhere-count (call-graph-elsewhere-count call-graph))
777 (dolist (node (call-graph-flat-nodes call-graph))
778 (when (or (and max (> (incf i) max))
779 (< (node-count node) min-count))
781 (let* ((count (node-count node))
782 (percent (samples-percent call-graph count))
783 (accrued-count (node-accrued-count node))
784 (accrued-percent (samples-percent call-graph accrued-count)))
785 (incf total-count count)
786 (incf total-percent percent)
787 (format t "~&~4d ~6d ~5,1f ~6d ~5,1f ~6d ~5,1f ~s~%"
798 (format t "~& ~6d ~5,1f elsewhere~%"
800 (samples-percent call-graph elsewhere-count)))))
802 (defun print-cycles (call-graph)
803 (when (some #'cycle-p (graph-vertices call-graph))
804 (format t "~& Cycle~%")
805 (format t "~& Count % Parts~%")
806 (do-vertices (node call-graph)
808 (flet ((print-info (indent index count percent name)
809 (format t "~&~6d ~5,1f ~11@t ~V@t ~s [~d]~%"
810 count percent indent name index)))
812 (format t "~&~6d ~5,1f ~a...~%"
814 (samples-percent call-graph (cycle-count node))
816 (dolist (v (vertex-scc-vertices node))
817 (print-info 4 (node-index v) (node-count v)
818 (samples-percent call-graph (node-count v))
823 (defun print-graph (call-graph &key (stream *standard-output*)
825 (let ((*standard-output* stream)
826 (*print-pretty* nil))
827 (print-call-graph-header call-graph)
828 (print-cycles call-graph)
829 (flet ((find-call (from to)
830 (find to (node-edges from) :key #'call-vertex))
831 (print-info (indent index count percent name)
832 (format t "~&~6d ~5,1f ~11@t ~V@t ~s [~d]~%"
833 count percent indent name index)))
834 (format t "~& Callers~%")
835 (format t "~& Cumul. Function~%")
836 (format t "~& Count % Count % Callees~%")
837 (do-vertices (node call-graph)
840 ;; Print caller information.
841 (dolist (caller (node-callers node))
842 (let ((call (find-call caller node)))
843 (print-info 4 (node-index caller)
845 (samples-percent call-graph (call-count call))
846 (node-name caller))))
847 ;; Print the node itself.
848 (format t "~&~6d ~5,1f ~6d ~5,1f ~s [~d]~%"
850 (samples-percent call-graph (node-count node))
851 (node-accrued-count node)
852 (samples-percent call-graph (node-accrued-count node))
856 (do-edges (call called node)
857 (print-info 4 (node-index called)
859 (samples-percent call-graph (call-count call))
860 (node-name called))))
863 (print-flat call-graph :stream stream :max max
864 :min-percent min-percent :print-header nil))))
866 (defun report (&key (type :graph) max min-percent call-graph
867 (stream *standard-output*) ((:show-progress *show-progress*)))
868 "Report statistical profiling results. The following keyword
872 Specifies the type of report to generate. If :FLAT, show
873 flat report, if :GRAPH show a call graph and a flat report.
874 If nil, don't print out a report.
877 Specify a stream to print the report on. Default is
881 Don't show more than <max> entries in the flat report.
883 :Min-Percent <min-percent>
884 Don't show functions taking less than <min-percent> of the
885 total time in the flat report.
887 :Show-Progress <bool>
888 If true, print progress messages while generating the call graph.
891 Print a report from <graph> instead of the latest profiling
894 Value of this function is a Call-Graph object representing the
895 resulting call-graph."
896 (let ((graph (or call-graph (make-call-graph (1- +sample-depth+)))))
899 (print-flat graph :stream stream :max max :min-percent min-percent))
901 (print-graph graph :stream stream :max max :min-percent min-percent))
905 ;;; Interface to DISASSEMBLE
907 (defun sample-pc-from-pc-or-offset (sample pc-or-offset)
909 ;; Assembly routines or foreign functions don't move around, so we've
911 ((or sb-kernel:code-component string)
913 ;; Lisp functions might move, so we've stored a offset from the
914 ;; start of the code component.
915 (sb-di::compiled-debug-fun
916 (let* ((component (sb-di::compiled-debug-fun-component sample))
917 (start-pc (code-start component)))
918 (+ start-pc pc-or-offset)))))
920 (defun add-disassembly-profile-note (chunk stream dstate)
921 (declare (ignore chunk stream))
922 (unless (zerop *samples-index*)
924 (+ (sb-disassem::seg-virtual-location
925 (sb-disassem:dstate-segment dstate))
926 (sb-disassem::dstate-cur-offs dstate)))
927 (samples (loop for x from 0 below *samples-index* by +sample-size+
928 for sample = (aref *samples* x)
929 for pc-or-offset = (aref *samples* (1+ x))
931 (sample-pc-from-pc-or-offset sample
933 (unless (zerop samples)
934 (sb-disassem::note (format nil "~A/~A samples"
935 samples (/ *samples-index* +sample-size+))
938 (pushnew 'add-disassembly-profile-note sb-disassem::*default-dstate-hooks*)
942 (defun test-0 (n &optional (depth 0))
943 (declare (optimize (debug 3)))
946 (test-0 n (1+ depth))
947 (test-0 n (1+ depth)))))
950 (with-profiling (:reset t :max-samples 1000 :report :graph)