1.0.42.1: add release script
[sbcl.git] / contrib / sb-sprof / sb-sprof.lisp
blobb7a9dcc90811223d4af7c22d93dad2293eb9ccaf
1 ;;; Copyright (C) 2003 Gerd Moellmann <gerd.moellmann@t-online.de>
2 ;;; All rights reserved.
3 ;;;
4 ;;; Redistribution and use in source and binary forms, with or without
5 ;;; modification, are permitted provided that the following conditions
6 ;;; are met:
7 ;;;
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
15 ;;; permission.
16 ;;;
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
28 ;;; DAMAGE.
30 ;;; Statistical profiler.
32 ;;; Overview:
33 ;;;
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
38 ;;; taken.
39 ;;;
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.
45 ;;; Problems:
46 ;;;
47 ;;; The code being generated on x86 makes determining callers reliably
48 ;;; something between extremely difficult and impossible. Example:
49 ;;;
50 ;;; 10979F00: .entry eval::eval-stack-args(arg-count)
51 ;;; 18: pop dword ptr [ebp-8]
52 ;;; 1B: lea esp, [ebp-32]
53 ;;; 1E: mov edi, edx
54 ;;;
55 ;;; 20: cmp ecx, 4
56 ;;; 23: jne L4
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
61 ;;; 3A: jmp L3
62 ;;; 3C: L0: mov edx, esp
63 ;;; 3E: sub esp, 12
64 ;;; 41: mov eax, [#x10979EF8] ; #<FDEFINITION object for eval::eval-stack-pop>
65 ;;; 47: xor ecx, ecx
66 ;;; 49: mov [edx-4], ebp
67 ;;; 4C: mov ebp, edx
68 ;;; 4E: call dword ptr [eax+5]
69 ;;; 51: mov esp, ebx
70 ;;;
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.
78 ;;;
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.
84 ;;;
85 ;;; Random ideas for implementation:
86 ;;;
87 ;;; * Space profiler. Sample when new pages are allocated instead of
88 ;;; at SIGPROF.
89 ;;;
90 ;;; * Record a configurable number of callers up the stack. That
91 ;;; could give a more complete graph when there are many small
92 ;;; functions.
93 ;;;
94 ;;; * Print help strings for reports, include hints to the problem
95 ;;; explained above.
96 ;;;
97 ;;; * Make flat report the default since call-graph isn't that
98 ;;; reliable?
100 (defpackage #:sb-sprof
101 (:use #:cl #:sb-ext #:sb-unix #:sb-alien #:sb-sys)
102 (:export #:*sample-interval* #:*max-samples* #:*alloc-interval*
103 #:*report-sort-by* #:*report-sort-order*
104 #:start-sampling #:stop-sampling #:with-sampling
105 #:with-profiling #:start-profiling #:stop-profiling
106 #:profile-call-counts #:unprofile-call-counts
107 #:reset #:report))
109 (in-package #:sb-sprof)
112 ;;;; Graph Utilities
114 (defstruct (vertex (:constructor make-vertex)
115 (:constructor make-scc (scc-vertices edges)))
116 (visited nil :type boolean)
117 (root nil :type (or null vertex))
118 (dfn 0 :type fixnum)
119 (edges () :type list)
120 (scc-vertices () :type list))
122 (defstruct edge
123 (vertex (sb-impl::missing-arg) :type vertex))
125 (defstruct graph
126 (vertices () :type list))
128 (declaim (inline scc-p))
129 (defun scc-p (vertex)
130 (not (null (vertex-scc-vertices vertex))))
132 (defmacro do-vertices ((vertex graph) &body body)
133 `(dolist (,vertex (graph-vertices ,graph))
134 ,@body))
136 (defmacro do-edges ((edge edge-to vertex) &body body)
137 `(dolist (,edge (vertex-edges ,vertex))
138 (let ((,edge-to (edge-vertex ,edge)))
139 ,@body)))
141 (defun self-cycle-p (vertex)
142 (do-edges (e to vertex)
143 (when (eq to vertex)
144 (return t))))
146 (defun map-vertices (fn vertices)
147 (dolist (v vertices)
148 (setf (vertex-visited v) nil))
149 (dolist (v vertices)
150 (unless (vertex-visited v)
151 (funcall fn v))))
153 ;;; Eeko Nuutila, Eljas Soisalon-Soininen, around 1992. Improves on
154 ;;; Tarjan's original algorithm by not using the stack when processing
155 ;;; trivial components. Trivial components should appear frequently
156 ;;; in a call-graph such as ours, I think. Same complexity O(V+E) as
157 ;;; Tarjan.
158 (defun strong-components (vertices)
159 (let ((in-component (make-array (length vertices)
160 :element-type 'boolean
161 :initial-element nil))
162 (stack ())
163 (components ())
164 (dfn -1))
165 (labels ((min-root (x y)
166 (let ((rx (vertex-root x))
167 (ry (vertex-root y)))
168 (if (< (vertex-dfn rx) (vertex-dfn ry))
170 ry)))
171 (in-component (v)
172 (aref in-component (vertex-dfn v)))
173 ((setf in-component) (in v)
174 (setf (aref in-component (vertex-dfn v)) in))
175 (vertex-> (x y)
176 (> (vertex-dfn x) (vertex-dfn y)))
177 (visit (v)
178 (setf (vertex-dfn v) (incf dfn)
179 (in-component v) nil
180 (vertex-root v) v
181 (vertex-visited v) t)
182 (do-edges (e w v)
183 (unless (vertex-visited w)
184 (visit w))
185 (unless (in-component w)
186 (setf (vertex-root v) (min-root v w))))
187 (if (eq v (vertex-root v))
188 (loop while (and stack (vertex-> (car stack) v))
189 as w = (pop stack)
190 collect w into this-component
191 do (setf (in-component w) t)
192 finally
193 (setf (in-component v) t)
194 (push (cons v this-component) components))
195 (push v stack))))
196 (map-vertices #'visit vertices)
197 components)))
199 ;;; Given a dag as a list of vertices, return the list sorted
200 ;;; topologically, children first.
201 (defun topological-sort (dag)
202 (let ((sorted ())
203 (dfn -1))
204 (labels ((rec-sort (v)
205 (setf (vertex-visited v) t)
206 (setf (vertex-dfn v) (incf dfn))
207 (dolist (e (vertex-edges v))
208 (unless (vertex-visited (edge-vertex e))
209 (rec-sort (edge-vertex e))))
210 (push v sorted)))
211 (map-vertices #'rec-sort dag)
212 (nreverse sorted))))
214 ;;; Reduce graph G to a dag by coalescing strongly connected components
215 ;;; into vertices. Sort the result topologically.
216 (defun reduce-graph (graph &optional (scc-constructor #'make-scc))
217 (sb-int:collect ((sccs) (trivial))
218 (dolist (c (strong-components (graph-vertices graph)))
219 (if (or (cdr c) (self-cycle-p (car c)))
220 (sb-int:collect ((outgoing))
221 (dolist (v c)
222 (do-edges (e w v)
223 (unless (member w c)
224 (outgoing e))))
225 (sccs (funcall scc-constructor c (outgoing))))
226 (trivial (car c))))
227 (dolist (scc (sccs))
228 (dolist (v (trivial))
229 (do-edges (e w v)
230 (when (member w (vertex-scc-vertices scc))
231 (setf (edge-vertex e) scc)))))
232 (setf (graph-vertices graph)
233 (topological-sort (nconc (sccs) (trivial))))))
235 ;;;; The Profiler
237 (deftype address ()
238 "Type used for addresses, for instance, program counters,
239 code start/end locations etc."
240 '(unsigned-byte #.sb-vm::n-machine-word-bits))
242 (defconstant +unknown-address+ 0
243 "Constant representing an address that cannot be determined.")
245 ;;; A call graph. Vertices are NODE structures, edges are CALL
246 ;;; structures.
247 (defstruct (call-graph (:include graph)
248 (:constructor %make-call-graph))
249 ;; the value of *SAMPLE-INTERVAL* or *ALLOC-INTERVAL* at the time
250 ;; the graph was created (depending on the current allocation mode)
251 (sample-interval (sb-impl::missing-arg) :type number)
252 ;; the sampling-mode that was used for the profiling run
253 (sampling-mode (sb-impl::missing-arg) :type (member :cpu :alloc :time))
254 ;; number of samples taken
255 (nsamples (sb-impl::missing-arg) :type sb-int:index)
256 ;; threads that have been sampled
257 (sampled-threads nil :type list)
258 ;; sample count for samples not in any function
259 (elsewhere-count (sb-impl::missing-arg) :type sb-int:index)
260 ;; a flat list of NODEs, sorted by sample count
261 (flat-nodes () :type list))
263 ;;; A node in a call graph, representing a function that has been
264 ;;; sampled. The edges of a node are CALL structures that represent
265 ;;; functions called from a given node.
266 (defstruct (node (:include vertex)
267 (:constructor %make-node))
268 ;; A numeric label for the node. The most frequently called function
269 ;; gets label 1. This is just for identification purposes in the
270 ;; profiling report.
271 (index 0 :type fixnum)
272 ;; Start and end address of the function's code. Depending on the
273 ;; debug-info, this might be either as absolute addresses for things
274 ;; that won't move around in memory, or as relative offsets from
275 ;; some point for things that might move.
276 (start-pc-or-offset 0 :type address)
277 (end-pc-or-offset 0 :type address)
278 ;; the name of the function
279 (name nil :type t)
280 ;; sample count for this function
281 (count 0 :type fixnum)
282 ;; count including time spent in functions called from this one
283 (accrued-count 0 :type fixnum)
284 ;; the debug-info that this node was created from
285 (debug-info nil :type t)
286 ;; list of NODEs for functions calling this one
287 (callers () :type list)
288 ;; the call count for the function that corresponds to this node (or NIL
289 ;; if call counting wasn't enabled for this function)
290 (call-count nil :type (or null integer)))
292 ;;; A cycle in a call graph. The functions forming the cycle are
293 ;;; found in the SCC-VERTICES slot of the VERTEX structure.
294 (defstruct (cycle (:include node)))
296 ;;; An edge in a call graph. EDGE-VERTEX is the function being
297 ;;; called.
298 (defstruct (call (:include edge)
299 (:constructor make-call (vertex)))
300 ;; number of times the call was sampled
301 (count 1 :type sb-int:index))
303 (defvar *sample-interval* 0.01
304 "Default number of seconds between samples.")
305 (declaim (type number *sample-interval*))
307 (defvar *alloc-interval* 4
308 "Default number of allocation region openings between samples.")
309 (declaim (type number *alloc-interval*))
311 (defvar *max-samples* 50000
312 "Default number of traces taken. This variable is somewhat misnamed:
313 each trace may actually consist of an arbitrary number of samples, depending
314 on the depth of the call stack.")
315 (declaim (type sb-int:index *max-samples*))
317 ;;; Encapsulate all the information about a sampling run
318 (defstruct (samples)
319 ;; When this vector fills up, we allocate a new one and copy over
320 ;; the old contents.
321 (vector (make-array (* *max-samples*
322 ;; Arbitrary guess at how many samples we'll be
323 ;; taking for each trace. The exact amount doesn't
324 ;; matter, this is just to decrease the amount of
325 ;; re-allocation that will need to be done.
327 ;; Each sample takes two cells in the vector
329 :type simple-vector)
330 (trace-count 0 :type sb-int:index)
331 (index 0 :type sb-int:index)
332 (mode nil :type (member :cpu :alloc :time))
333 (sample-interval (sb-int:missing-arg) :type number)
334 (alloc-interval (sb-int:missing-arg) :type number)
335 (max-depth most-positive-fixnum :type number)
336 (max-samples (sb-int:missing-arg) :type sb-int:index)
337 (sampled-threads nil :type list))
339 (defmethod print-object ((call-graph call-graph) stream)
340 (print-unreadable-object (call-graph stream :type t :identity t)
341 (format stream "~d samples" (call-graph-nsamples call-graph))))
343 (defmethod print-object ((node node) stream)
344 (print-unreadable-object (node stream :type t :identity t)
345 (format stream "~s [~d]" (node-name node) (node-index node))))
347 (defmethod print-object ((call call) stream)
348 (print-unreadable-object (call stream :type t :identity t)
349 (format stream "~s [~d]" (node-name (call-vertex call))
350 (node-index (call-vertex call)))))
352 (deftype report-type ()
353 '(member nil :flat :graph))
355 (defvar *sampling-mode* :cpu
356 "Default sampling mode. :CPU for cpu profiling, :ALLOC for allocation
357 profiling")
358 (declaim (type (member :cpu :alloc :time) *sampling-mode*))
360 (defvar *alloc-region-size*
361 #-gencgc
362 (get-page-size)
363 ;; This hardcoded 2 matches the one in gc_find_freeish_pages. It's not
364 ;; really worth genesifying.
365 #+gencgc
366 (* 2 sb-vm:gencgc-page-bytes))
367 (declaim (type number *alloc-region-size*))
369 (defvar *samples* nil)
370 (declaim (type (or null samples) *samples*))
372 (defvar *profiling* nil)
373 (declaim (type (member nil :alloc :cpu :time) *profiling*))
374 (defvar *sampling* nil)
375 (declaim (type boolean *sampling*))
377 (defvar *show-progress* nil)
379 (defvar *old-sampling* nil)
381 ;; Call count encapsulation information
382 (defvar *encapsulations* (make-hash-table :test 'equal))
384 (defun turn-off-sampling ()
385 (setq *old-sampling* *sampling*)
386 (setq *sampling* nil))
388 (defun turn-on-sampling ()
389 (setq *sampling* *old-sampling*))
391 (defun show-progress (format-string &rest args)
392 (when *show-progress*
393 (apply #'format t format-string args)
394 (finish-output)))
396 (defun start-sampling ()
397 "Switch on statistical sampling."
398 (setq *sampling* t))
400 (defun stop-sampling ()
401 "Switch off statistical sampling."
402 (setq *sampling* nil))
404 (defmacro with-sampling ((&optional (on t)) &body body)
405 "Evaluate body with statistical sampling turned on or off."
406 `(let ((*sampling* ,on)
407 (sb-vm:*alloc-signal* sb-vm:*alloc-signal*))
408 ,@body))
410 ;;; Return something serving as debug info for address PC.
411 (declaim (inline debug-info))
412 (defun debug-info (pc)
413 (declare (type system-area-pointer pc)
414 (muffle-conditions compiler-note))
415 (let ((ptr (sb-di::component-ptr-from-pc pc)))
416 (cond ((sap= ptr (int-sap 0))
417 (let ((name (sap-foreign-symbol pc)))
418 (if name
419 (values (format nil "foreign function ~a" name)
420 (sap-int pc))
421 (values nil (sap-int pc)))))
423 (let* ((code (sb-di::component-from-component-ptr ptr))
424 (code-header-len (* (sb-kernel:get-header-data code)
425 sb-vm:n-word-bytes))
426 (pc-offset (- (sap-int pc)
427 (- (sb-kernel:get-lisp-obj-address code)
428 sb-vm:other-pointer-lowtag)
429 code-header-len))
430 (df (sb-di::debug-fun-from-pc code pc-offset)))
431 (cond ((typep df 'sb-di::bogus-debug-fun)
432 (values code (sap-int pc)))
434 ;; The code component might be moved by the GC. Store
435 ;; a PC offset, and reconstruct the data in
436 ;; SAMPLE-PC-FROM-PC-OR-OFFSET.
437 (values df pc-offset))
439 (values nil 0))))))))
441 (defun ensure-samples-vector (samples)
442 (let ((vector (samples-vector samples))
443 (index (samples-index samples)))
444 ;; Allocate a new sample vector if the old one is full
445 (if (= (length vector) index)
446 (let ((new-vector (make-array (* 2 index))))
447 (format *trace-output* "Profiler sample vector full (~a traces / ~a samples), doubling the size~%"
448 (samples-trace-count samples)
449 (truncate index 2))
450 (replace new-vector vector)
451 (setf (samples-vector samples) new-vector))
452 vector)))
454 (declaim (inline record))
455 (defun record (samples pc)
456 (declare (type system-area-pointer pc)
457 (muffle-conditions compiler-note))
458 (multiple-value-bind (info pc-or-offset)
459 (debug-info pc)
460 (let ((vector (ensure-samples-vector samples))
461 (index (samples-index samples)))
462 (declare (type simple-vector vector))
463 ;; Allocate a new sample vector if the old one is full
464 (when (= (length vector) index)
465 (let ((new-vector (make-array (* 2 index))))
466 (format *trace-output* "Profiler sample vector full (~a traces / ~a samples), doubling the size~%"
467 (samples-trace-count samples)
468 (truncate index 2))
469 (replace new-vector vector)
470 (setf vector new-vector
471 (samples-vector samples) new-vector)))
472 ;; For each sample, store the debug-info and the PC/offset into
473 ;; adjacent cells.
474 (setf (aref vector index) info
475 (aref vector (1+ index)) pc-or-offset)))
476 (incf (samples-index samples) 2))
478 (defun record-trace-start (samples)
479 ;; Mark the start of the trace.
480 (let ((vector (ensure-samples-vector samples)))
481 (declare (type simple-vector vector))
482 (setf (aref vector (samples-index samples))
483 'trace-start))
484 (incf (samples-index samples) 2))
486 ;;; List of thread currently profiled, or :ALL for all threads.
487 (defvar *profiled-threads* nil)
488 (declaim (type (or list (member :all)) *profiled-threads*))
490 ;;; Thread which runs the wallclock timers, if any.
491 (defvar *timer-thread* nil)
493 (defun profiled-threads ()
494 (let ((profiled-threads *profiled-threads*))
495 (if (eq :all profiled-threads)
496 (remove *timer-thread* (sb-thread:list-all-threads))
497 profiled-threads)))
499 (defun profiled-thread-p (thread)
500 (let ((profiled-threads *profiled-threads*))
501 (or (and (eq :all profiled-threads)
502 (not (eq *timer-thread* thread)))
503 (member thread profiled-threads :test #'eq))))
505 #+(or x86 x86-64)
506 (progn
507 ;; Ensure that only one thread at a time will be doing profiling stuff.
508 (defvar *profiler-lock* (sb-thread:make-mutex :name "Statistical Profiler"))
509 (defvar *distribution-lock* (sb-thread:make-mutex :name "Wallclock profiling lock"))
511 (define-alien-routine pthread-kill int (signal int) (os-thread unsigned-long))
513 ;;; A random thread will call this in response to either a timer firing,
514 ;;; This in turn will distribute the notice to those threads we are
515 ;;; interested using SIGPROF.
516 (defun thread-distribution-handler ()
517 (declare (optimize sb-c::merge-tail-calls))
518 (when *sampling*
519 #+sb-thread
520 (let ((lock *distribution-lock*))
521 ;; Don't flood the system with more interrupts if the last
522 ;; set is still being delivered.
523 (unless (sb-thread:mutex-value lock)
524 (sb-thread::with-system-mutex (lock)
525 (dolist (thread (profiled-threads))
526 ;; This may occasionally fail to deliver the signal, but that
527 ;; seems better then using kill_thread_safely with it's 1
528 ;; second backoff.
529 (let ((os-thread (sb-thread::thread-os-thread thread)))
530 (when os-thread
531 (pthread-kill os-thread sb-unix:sigprof)))))))
532 #-sb-thread
533 (unix-kill 0 sb-unix:sigprof)))
535 (defun sigprof-handler (signal code scp)
536 (declare (ignore signal code) (optimize speed (space 0))
537 (disable-package-locks sb-di::x86-call-context)
538 (muffle-conditions compiler-note)
539 (type system-area-pointer scp))
540 (let ((self sb-thread:*current-thread*)
541 (profiling *profiling*))
542 ;; Turn off allocation counter when it is not needed. Doing this in the
543 ;; signal handler means we don't have to worry about racing with the runtime
544 (unless (eq :alloc profiling)
545 (setf sb-vm::*alloc-signal* nil))
546 (when (and *sampling*
547 ;; Normal SIGPROF gets practically speaking delivered to threads
548 ;; depending on the run time they use, so we need to filter
549 ;; out those we don't care about. For :ALLOC and :TIME profiling
550 ;; only the interesting threads get SIGPROF in the first place.
552 ;; ...except that Darwin at least doesn't seem to work like we
553 ;; would want it to, which makes multithreaded :CPU profiling pretty
554 ;; pointless there -- though it may be that our mach magic is
555 ;; partially to blame?
556 (or (not (eq :cpu profiling)) (profiled-thread-p self)))
557 (sb-thread::with-system-mutex (*profiler-lock* :without-gcing t)
558 (let ((samples *samples*))
559 (when (and samples
560 (< (samples-trace-count samples)
561 (samples-max-samples samples)))
562 (with-alien ((scp (* os-context-t) :local scp))
563 (let* ((pc-ptr (sb-vm:context-pc scp))
564 (fp (sb-vm::context-register scp #.sb-vm::ebp-offset)))
565 ;; foreign code might not have a useful frame
566 ;; pointer in ebp/rbp, so make sure it looks
567 ;; reasonable before walking the stack
568 (unless (sb-di::control-stack-pointer-valid-p (sb-sys:int-sap fp))
569 (record samples pc-ptr)
570 (return-from sigprof-handler nil))
571 (incf (samples-trace-count samples))
572 (pushnew self (samples-sampled-threads samples))
573 (let ((fp (int-sap fp))
574 (ok t))
575 (declare (type system-area-pointer fp pc-ptr))
576 ;; FIXME: How annoying. The XC doesn't store enough
577 ;; type information about SB-DI::X86-CALL-CONTEXT,
578 ;; even if we declaim the ftype explicitly in
579 ;; src/code/debug-int. And for some reason that type
580 ;; information is needed for the inlined version to
581 ;; be compiled without boxing the returned saps. So
582 ;; we declare the correct ftype here manually, even
583 ;; if the compiler should be able to deduce this
584 ;; exact same information.
585 (declare (ftype (function (system-area-pointer)
586 (values (member nil t)
587 system-area-pointer
588 system-area-pointer))
589 sb-di::x86-call-context))
590 (record-trace-start samples)
591 (dotimes (i (samples-max-depth samples))
592 (record samples pc-ptr)
593 (setf (values ok pc-ptr fp)
594 (sb-di::x86-call-context fp))
595 (unless ok
596 (return))))))
597 ;; Reset thread-local allocation counter before interrupts
598 ;; are enabled.
599 (when (eq t sb-vm::*alloc-signal*)
600 (setf sb-vm:*alloc-signal* (1- (samples-alloc-interval samples)))))))))
601 nil))
603 ;; FIXME: On non-x86 platforms we don't yet walk the call stack deeper
604 ;; than one level.
605 #-(or x86 x86-64)
606 (defun sigprof-handler (signal code scp)
607 (declare (ignore signal code))
608 (sb-sys:without-interrupts
609 (let ((samples *samples*))
610 (when (and *sampling*
611 samples
612 (< (samples-trace-count samples)
613 (samples-max-samples samples)))
614 (sb-sys:without-gcing
615 (with-alien ((scp (* os-context-t) :local scp))
616 (locally (declare (optimize (inhibit-warnings 2)))
617 (incf (samples-trace-count samples))
618 (record-trace-start samples)
619 (let* ((pc-ptr (sb-vm:context-pc scp))
620 (fp (sb-vm::context-register scp #.sb-vm::cfp-offset))
621 (ra (sap-ref-word
622 (int-sap fp)
623 (* sb-vm::lra-save-offset sb-vm::n-word-bytes))))
624 (record samples pc-ptr)
625 (record samples (int-sap ra))))))))))
627 ;;; Return the start address of CODE.
628 (defun code-start (code)
629 (declare (type sb-kernel:code-component code))
630 (sap-int (sb-kernel:code-instructions code)))
632 ;;; Return start and end address of CODE as multiple values.
633 (defun code-bounds (code)
634 (declare (type sb-kernel:code-component code))
635 (let* ((start (code-start code))
636 (end (+ start (sb-kernel:%code-code-size code))))
637 (values start end)))
639 (defmacro with-profiling ((&key (sample-interval '*sample-interval*)
640 (alloc-interval '*alloc-interval*)
641 (max-samples '*max-samples*)
642 (reset nil)
643 (mode '*sampling-mode*)
644 (loop t)
645 (max-depth most-positive-fixnum)
646 show-progress
647 (threads '(list sb-thread:*current-thread*))
648 (report nil report-p))
649 &body body)
650 "Repeatedly evaluate BODY with statistical profiling turned on.
651 In multi-threaded operation, only the thread in which WITH-PROFILING
652 was evaluated will be profiled by default. If you want to profile
653 multiple threads, invoke the profiler with START-PROFILING.
655 The following keyword args are recognized:
657 :SAMPLE-INTERVAL <n>
658 Take a sample every <n> seconds. Default is *SAMPLE-INTERVAL*.
660 :ALLOC-INTERVAL <n>
661 Take a sample every time <n> allocation regions (approximately
662 8kB) have been allocated since the last sample. Default is
663 *ALLOC-INTERVAL*.
665 :MODE <mode>
666 If :CPU, run the profiler in CPU profiling mode. If :ALLOC, run the
667 profiler in allocation profiling mode. If :TIME, run the profiler
668 in wallclock profiling mode.
670 :MAX-SAMPLES <max>
671 Repeat evaluating body until <max> samples are taken.
672 Default is *MAX-SAMPLES*.
674 :MAX-DEPTH <max>
675 Maximum call stack depth that the profiler should consider. Only
676 has an effect on x86 and x86-64.
678 :REPORT <type>
679 If specified, call REPORT with :TYPE <type> at the end.
681 :RESET <bool>
682 It true, call RESET at the beginning.
684 :THREADS <list-form>
685 Form that evaluates to the list threads to profile, or :ALL to indicate
686 that all threads should be profiled. Defaults to the current
687 thread. (Note: START-PROFILING defaults to all threads.)
689 :THREADS has no effect on call-counting at the moment.
691 On some platforms (eg. Darwin) the signals used by the profiler are
692 not properly delivered to threads in proportion to their CPU usage
693 when doing :CPU profiling. If you see empty call graphs, or are obviously
694 missing several samples from certain threads, you may be falling afoul
695 of this.
697 :LOOP <bool>
698 If true (the default) repeatedly evaluate BODY. If false, evaluate
699 if only once."
700 (declare (type report-type report))
701 `(let* ((*sample-interval* ,sample-interval)
702 (*alloc-interval* ,alloc-interval)
703 (*sampling* nil)
704 (*sampling-mode* ,mode)
705 (*max-samples* ,max-samples))
706 ,@(when reset '((reset)))
707 (unwind-protect
708 (progn
709 (start-profiling :max-depth ,max-depth :threads ,threads)
710 (loop
711 (when (>= (samples-trace-count *samples*)
712 (samples-max-samples *samples*))
713 (return))
714 ,@(when show-progress
715 `((format t "~&===> ~d of ~d samples taken.~%"
716 (samples-trace-count *samples*)
717 (samples-max-samples *samples*))))
718 (let ((.last-index. (samples-index *samples*)))
719 ,@body
720 (when (= .last-index. (samples-index *samples*))
721 (warn "No sampling progress; possibly a profiler bug.")
722 (return)))
723 (unless ,loop
724 (return))))
725 (stop-profiling))
726 ,@(when report-p `((report :type ,report)))))
728 (defvar *timer* nil)
730 (defvar *old-alloc-interval* nil)
731 (defvar *old-sample-interval* nil)
733 (defun start-profiling (&key (max-samples *max-samples*)
734 (mode *sampling-mode*)
735 (sample-interval *sample-interval*)
736 (alloc-interval *alloc-interval*)
737 (max-depth most-positive-fixnum)
738 (threads :all)
739 (sampling t))
740 "Start profiling statistically in the current thread if not already profiling.
741 The following keyword args are recognized:
743 :SAMPLE-INTERVAL <n>
744 Take a sample every <n> seconds. Default is *SAMPLE-INTERVAL*.
746 :ALLOC-INTERVAL <n>
747 Take a sample every time <n> allocation regions (approximately
748 8kB) have been allocated since the last sample. Default is
749 *ALLOC-INTERVAL*.
751 :MODE <mode>
752 If :CPU, run the profiler in CPU profiling mode. If :ALLOC, run
753 the profiler in allocation profiling mode. If :TIME, run the profiler
754 in wallclock profiling mode.
756 :MAX-SAMPLES <max>
757 Maximum number of samples. Default is *MAX-SAMPLES*.
759 :MAX-DEPTH <max>
760 Maximum call stack depth that the profiler should consider. Only
761 has an effect on x86 and x86-64.
763 :THREADS <list>
764 List threads to profile, or :ALL to indicate that all threads should be
765 profiled. Defaults to :ALL. (Note: WITH-PROFILING defaults to the current
766 thread.)
768 :THREADS has no effect on call-counting at the moment.
770 On some platforms (eg. Darwin) the signals used by the profiler are
771 not properly delivered to threads in proportion to their CPU usage
772 when doing :CPU profiling. If you see empty call graphs, or are obviously
773 missing several samples from certain threads, you may be falling afoul
774 of this.
776 :SAMPLING <bool>
777 If true, the default, start sampling right away.
778 If false, START-SAMPLING can be used to turn sampling on."
779 #-gencgc
780 (when (eq mode :alloc)
781 (error "Allocation profiling is only supported for builds using the generational garbage collector."))
782 (unless *profiling*
783 (multiple-value-bind (secs usecs)
784 (multiple-value-bind (secs rest)
785 (truncate sample-interval)
786 (values secs (truncate (* rest 1000000))))
787 (setf *sampling* sampling
788 *samples* (make-samples :max-depth max-depth
789 :max-samples max-samples
790 :sample-interval sample-interval
791 :alloc-interval alloc-interval
792 :mode mode))
793 (enable-call-counting)
794 (setf *profiled-threads* threads)
795 (sb-sys:enable-interrupt sb-unix:sigprof #'sigprof-handler)
796 (ecase mode
797 (:alloc
798 (let ((alloc-signal (1- alloc-interval)))
799 #+sb-thread
800 (progn
801 (when (eq :all threads)
802 ;; Set the value new threads inherit.
803 (sb-thread::with-all-threads-lock
804 (setf sb-thread::*default-alloc-signal* alloc-signal)))
805 ;; Turn on allocation profiling in existing threads.
806 (dolist (thread (profiled-threads))
807 (sb-thread::%set-symbol-value-in-thread 'sb-vm::*alloc-signal* thread alloc-signal)))
808 #-sb-thread
809 (setf sb-vm:*alloc-signal* alloc-signal)))
810 (:cpu
811 (unix-setitimer :profile secs usecs secs usecs))
812 (:time
813 #+sb-thread
814 (let ((setup (sb-thread:make-semaphore :name "Timer thread setup semaphore")))
815 (setf *timer-thread*
816 (sb-thread:make-thread (lambda ()
817 (sb-thread:wait-on-semaphore setup)
818 (loop while (eq sb-thread:*current-thread* *timer-thread*)
819 do (sleep 1.0)))
820 :name "SB-SPROF wallclock timer thread"))
821 (sb-thread:signal-semaphore setup))
822 #-sb-thread
823 (setf *timer-thread* nil)
824 (setf *timer* (make-timer #'thread-distribution-handler :name "SB-PROF wallclock timer"
825 :thread *timer-thread*))
826 (schedule-timer *timer* sample-interval :repeat-interval sample-interval)))
827 (setq *profiling* mode)))
828 (values))
830 (defun stop-profiling ()
831 "Stop profiling if profiling."
832 (let ((profiling *profiling*))
833 (when profiling
834 ;; Even with the timers shut down we cannot be sure that there is no
835 ;; undelivered sigprof. The handler is also responsible for turning the
836 ;; *ALLOC-SIGNAL* off in individual threads.
837 (ecase profiling
838 (:alloc
839 #+sb-thread
840 (setf sb-thread::*default-alloc-signal* nil)
841 #-sb-thread
842 (setf sb-vm:*alloc-signal* nil))
843 (:cpu
844 (unix-setitimer :profile 0 0 0 0))
845 (:time
846 (unschedule-timer *timer*)
847 (setf *timer* nil
848 *timer-thread* nil)))
849 (disable-call-counting)
850 (setf *profiling* nil
851 *sampling* nil
852 *profiled-threads* nil)))
853 (values))
855 (defun reset ()
856 "Reset the profiler."
857 (stop-profiling)
858 (setq *sampling* nil)
859 (setq *samples* nil)
860 (values))
862 ;;; Make a NODE for debug-info INFO.
863 (defun make-node (info)
864 (flet ((clean-name (name)
865 (if (and (consp name)
866 (member (first name)
867 '(sb-c::xep sb-c::tl-xep sb-c::&more-processor
868 sb-c::varargs-entry
869 sb-c::top-level-form
870 sb-c::hairy-arg-processor
871 sb-c::&optional-processor)))
872 (second name)
873 name)))
874 (typecase info
875 (sb-kernel::code-component
876 (multiple-value-bind (start end)
877 (code-bounds info)
878 (values
879 (%make-node :name (or (sb-disassem::find-assembler-routine start)
880 (format nil "~a" info))
881 :debug-info info
882 :start-pc-or-offset start
883 :end-pc-or-offset end)
884 info)))
885 (sb-di::compiled-debug-fun
886 (let* ((name (sb-di::debug-fun-name info))
887 (cdf (sb-di::compiled-debug-fun-compiler-debug-fun info))
888 (start-offset (sb-c::compiled-debug-fun-start-pc cdf))
889 (end-offset (sb-c::compiled-debug-fun-elsewhere-pc cdf))
890 (component (sb-di::compiled-debug-fun-component info))
891 (start-pc (code-start component)))
892 ;; Call graphs are mostly useless unless we somehow
893 ;; distinguish a gazillion different (LAMBDA ())'s.
894 (when (equal name '(lambda ()))
895 (setf name (format nil "Unknown component: #x~x" start-pc)))
896 (values (%make-node :name (clean-name name)
897 :debug-info info
898 :start-pc-or-offset start-offset
899 :end-pc-or-offset end-offset)
900 component)))
901 (sb-di::debug-fun
902 (%make-node :name (clean-name (sb-di::debug-fun-name info))
903 :debug-info info))
905 (%make-node :name (coerce info 'string)
906 :debug-info info)))))
908 ;;; One function can have more than one COMPILED-DEBUG-FUNCTION with
909 ;;; the same name. Reduce the number of calls to Debug-Info by first
910 ;;; looking for a given PC in a red-black tree. If not found in the
911 ;;; tree, get debug info, and look for a node in a hash-table by
912 ;;; function name. If not found in the hash-table, make a new node.
914 (defvar *name->node*)
916 (defmacro with-lookup-tables (() &body body)
917 `(let ((*name->node* (make-hash-table :test 'equal)))
918 ,@body))
920 ;;; Find or make a new node for INFO. Value is the NODE found or
921 ;;; made; NIL if not enough information exists to make a NODE for INFO.
922 (defun lookup-node (info)
923 (when info
924 (multiple-value-bind (new key)
925 (make-node info)
926 (when (eql (node-name new) 'call-counter)
927 (return-from lookup-node (values nil nil)))
928 (let* ((key (cons (node-name new) key))
929 (found (gethash key *name->node*)))
930 (cond (found
931 (setf (node-start-pc-or-offset found)
932 (min (node-start-pc-or-offset found)
933 (node-start-pc-or-offset new)))
934 (setf (node-end-pc-or-offset found)
935 (max (node-end-pc-or-offset found)
936 (node-end-pc-or-offset new)))
937 found)
939 (let ((call-count-info (gethash (node-name new)
940 *encapsulations*)))
941 (when call-count-info
942 (setf (node-call-count new)
943 (car call-count-info))))
944 (setf (gethash key *name->node*) new)
945 new))))))
947 ;;; Return a list of all nodes created by LOOKUP-NODE.
948 (defun collect-nodes ()
949 (loop for node being the hash-values of *name->node*
950 collect node))
952 ;;; Value is a CALL-GRAPH for the current contents of *SAMPLES*.
953 (defun make-call-graph-1 (max-depth)
954 (let ((elsewhere-count 0)
955 visited-nodes)
956 (with-lookup-tables ()
957 (loop for i below (- (samples-index *samples*) 2) by 2
958 with depth = 0
959 for debug-info = (aref (samples-vector *samples*) i)
960 for next-info = (aref (samples-vector *samples*)
961 (+ i 2))
962 do (if (eq debug-info 'trace-start)
963 (setf depth 0)
964 (let ((callee (lookup-node debug-info))
965 (caller (unless (eq next-info 'trace-start)
966 (lookup-node next-info))))
967 (when (< depth max-depth)
968 (when (zerop depth)
969 (setf visited-nodes nil)
970 (cond (callee
971 (incf (node-accrued-count callee))
972 (incf (node-count callee)))
974 (incf elsewhere-count))))
975 (incf depth)
976 (when callee
977 (push callee visited-nodes))
978 (when caller
979 (unless (member caller visited-nodes)
980 (incf (node-accrued-count caller)))
981 (when callee
982 (let ((call (find callee (node-edges caller)
983 :key #'call-vertex)))
984 (pushnew caller (node-callers callee))
985 (if call
986 (unless (member caller visited-nodes)
987 (incf (call-count call)))
988 (push (make-call callee)
989 (node-edges caller))))))))))
990 (let ((sorted-nodes (sort (collect-nodes) #'> :key #'node-count)))
991 (loop for node in sorted-nodes and i from 1 do
992 (setf (node-index node) i))
993 (%make-call-graph :nsamples (samples-trace-count *samples*)
994 :sample-interval (if (eq (samples-mode *samples*)
995 :alloc)
996 (samples-alloc-interval *samples*)
997 (samples-sample-interval *samples*))
998 :sampling-mode (samples-mode *samples*)
999 :sampled-threads (samples-sampled-threads *samples*)
1000 :elsewhere-count elsewhere-count
1001 :vertices sorted-nodes)))))
1003 ;;; Reduce CALL-GRAPH to a dag, creating CYCLE structures for call
1004 ;;; cycles.
1005 (defun reduce-call-graph (call-graph)
1006 (let ((cycle-no 0))
1007 (flet ((make-one-cycle (vertices edges)
1008 (let* ((name (format nil "<Cycle ~d>" (incf cycle-no)))
1009 (count (loop for v in vertices sum (node-count v))))
1010 (make-cycle :name name
1011 :index cycle-no
1012 :count count
1013 :scc-vertices vertices
1014 :edges edges))))
1015 (reduce-graph call-graph #'make-one-cycle))))
1017 ;;; For all nodes in CALL-GRAPH, compute times including the time
1018 ;;; spent in functions called from them. Note that the call-graph
1019 ;;; vertices are in reverse topological order, children first, so we
1020 ;;; will have computed accrued counts of called functions before they
1021 ;;; are used to compute accrued counts for callers.
1022 (defun compute-accrued-counts (call-graph)
1023 (do-vertices (from call-graph)
1024 (setf (node-accrued-count from) (node-count from))
1025 (do-edges (call to from)
1026 (incf (node-accrued-count from)
1027 (round (* (/ (call-count call) (node-count to))
1028 (node-accrued-count to)))))))
1030 ;;; Return a CALL-GRAPH structure for the current contents of
1031 ;;; *SAMPLES*. The result contain a list of nodes sorted by self-time
1032 ;;; in the FLAT-NODES slot, and a dag in VERTICES, with call cycles
1033 ;;; reduced to CYCLE structures.
1034 (defun make-call-graph (max-depth)
1035 (stop-profiling)
1036 (show-progress "~&Computing call graph ")
1037 (let ((call-graph (without-gcing (make-call-graph-1 max-depth))))
1038 (setf (call-graph-flat-nodes call-graph)
1039 (copy-list (graph-vertices call-graph)))
1040 (show-progress "~&Finding cycles")
1041 #+nil
1042 (reduce-call-graph call-graph)
1043 (show-progress "~&Propagating counts")
1044 #+nil
1045 (compute-accrued-counts call-graph)
1046 call-graph))
1049 ;;;; Reporting
1051 (defun print-separator (&key (length 72) (char #\-))
1052 (format t "~&~V,,,V<~>~%" length char))
1054 (defun samples-percent (call-graph count)
1055 (if (> count 0)
1056 (* 100.0 (/ count (call-graph-nsamples call-graph)))
1059 (defun print-call-graph-header (call-graph)
1060 (let ((nsamples (call-graph-nsamples call-graph))
1061 (interval (call-graph-sample-interval call-graph))
1062 (ncycles (loop for v in (graph-vertices call-graph)
1063 count (scc-p v))))
1064 (if (eq (call-graph-sampling-mode call-graph) :alloc)
1065 (format t "~2&Number of samples: ~d~%~
1066 Alloc interval: ~a regions (approximately ~a kB)~%~
1067 Total sampling amount: ~a regions (approximately ~a kB)~%~
1068 Number of cycles: ~d~%~
1069 Sampled threads:~{~% ~S~}~2%"
1070 nsamples
1071 interval
1072 (truncate (* interval *alloc-region-size*) 1024)
1073 (* nsamples interval)
1074 (truncate (* nsamples interval *alloc-region-size*) 1024)
1075 ncycles
1076 (call-graph-sampled-threads call-graph))
1077 (format t "~2&Number of samples: ~d~%~
1078 Sample interval: ~f seconds~%~
1079 Total sampling time: ~f seconds~%~
1080 Number of cycles: ~d~%~
1081 Sampled threads:~{~% ~S~}~2%"
1082 nsamples
1083 interval
1084 (* nsamples interval)
1085 ncycles
1086 (call-graph-sampled-threads call-graph)))))
1088 (declaim (type (member :samples :cumulative-samples) *report-sort-by*))
1089 (defvar *report-sort-by* :samples
1090 "Method for sorting the flat report: either by :SAMPLES or by :CUMULATIVE-SAMPLES.")
1092 (declaim (type (member :descending :ascending) *report-sort-order*))
1093 (defvar *report-sort-order* :descending
1094 "Order for sorting the flat report: either :DESCENDING or :ASCENDING.")
1096 (defun print-flat (call-graph &key (stream *standard-output*) max
1097 min-percent (print-header t)
1098 (sort-by *report-sort-by*)
1099 (sort-order *report-sort-order*))
1100 (declare (type (member :descending :ascending) sort-order)
1101 (type (member :samples :cumulative-samples) sort-by))
1102 (let ((*standard-output* stream)
1103 (*print-pretty* nil)
1104 (total-count 0)
1105 (total-percent 0)
1106 (min-count (if min-percent
1107 (round (* (/ min-percent 100.0)
1108 (call-graph-nsamples call-graph)))
1109 0)))
1110 (when print-header
1111 (print-call-graph-header call-graph))
1112 (format t "~& Self Total Cumul~%")
1113 (format t "~& Nr Count % Count % Count % Calls Function~%")
1114 (print-separator)
1115 (let ((elsewhere-count (call-graph-elsewhere-count call-graph))
1116 (i 0)
1117 (nodes (stable-sort (copy-list (call-graph-flat-nodes call-graph))
1118 (let ((cmp (if (eq :descending sort-order) #'> #'<)))
1119 (multiple-value-bind (primary secondary)
1120 (if (eq :samples sort-by)
1121 (values #'node-count #'node-accrued-count)
1122 (values #'node-accrued-count #'node-count))
1123 (lambda (x y)
1124 (let ((cx (funcall primary x))
1125 (cy (funcall primary y)))
1126 (if (= cx cy)
1127 (funcall cmp (funcall secondary x) (funcall secondary y))
1128 (funcall cmp cx cy)))))))))
1129 (dolist (node nodes)
1130 (when (or (and max (> (incf i) max))
1131 (< (node-count node) min-count))
1132 (return))
1133 (let* ((count (node-count node))
1134 (percent (samples-percent call-graph count))
1135 (accrued-count (node-accrued-count node))
1136 (accrued-percent (samples-percent call-graph accrued-count)))
1137 (incf total-count count)
1138 (incf total-percent percent)
1139 (format t "~&~4d ~6d ~5,1f ~6d ~5,1f ~6d ~5,1f ~8@a ~s~%"
1140 (incf i)
1141 count
1142 percent
1143 accrued-count
1144 accrued-percent
1145 total-count
1146 total-percent
1147 (or (node-call-count node) "-")
1148 (node-name node))
1149 (finish-output)))
1150 (print-separator)
1151 (format t "~& ~6d ~5,1f~36a elsewhere~%"
1152 elsewhere-count
1153 (samples-percent call-graph elsewhere-count)
1154 ""))))
1156 (defun print-cycles (call-graph)
1157 (when (some #'cycle-p (graph-vertices call-graph))
1158 (format t "~& Cycle~%")
1159 (format t "~& Count % Parts~%")
1160 (do-vertices (node call-graph)
1161 (when (cycle-p node)
1162 (flet ((print-info (indent index count percent name)
1163 (format t "~&~6d ~5,1f ~11@t ~V@t ~s [~d]~%"
1164 count percent indent name index)))
1165 (print-separator)
1166 (format t "~&~6d ~5,1f ~a...~%"
1167 (node-count node)
1168 (samples-percent call-graph (cycle-count node))
1169 (node-name node))
1170 (dolist (v (vertex-scc-vertices node))
1171 (print-info 4 (node-index v) (node-count v)
1172 (samples-percent call-graph (node-count v))
1173 (node-name v))))))
1174 (print-separator)
1175 (format t "~2%")))
1177 (defun print-graph (call-graph &key (stream *standard-output*)
1178 max min-percent)
1179 (let ((*standard-output* stream)
1180 (*print-pretty* nil))
1181 (print-call-graph-header call-graph)
1182 (print-cycles call-graph)
1183 (flet ((find-call (from to)
1184 (find to (node-edges from) :key #'call-vertex))
1185 (print-info (indent index count percent name)
1186 (format t "~&~6d ~5,1f ~11@t ~V@t ~s [~d]~%"
1187 count percent indent name index)))
1188 (format t "~& Callers~%")
1189 (format t "~& Total. Function~%")
1190 (format t "~& Count % Count % Callees~%")
1191 (do-vertices (node call-graph)
1192 (print-separator)
1194 ;; Print caller information.
1195 (dolist (caller (node-callers node))
1196 (let ((call (find-call caller node)))
1197 (print-info 4 (node-index caller)
1198 (call-count call)
1199 (samples-percent call-graph (call-count call))
1200 (node-name caller))))
1201 ;; Print the node itself.
1202 (format t "~&~6d ~5,1f ~6d ~5,1f ~s [~d]~%"
1203 (node-count node)
1204 (samples-percent call-graph (node-count node))
1205 (node-accrued-count node)
1206 (samples-percent call-graph (node-accrued-count node))
1207 (node-name node)
1208 (node-index node))
1209 ;; Print callees.
1210 (do-edges (call called node)
1211 (print-info 4 (node-index called)
1212 (call-count call)
1213 (samples-percent call-graph (call-count call))
1214 (node-name called))))
1215 (print-separator)
1216 (format t "~2%")
1217 (print-flat call-graph :stream stream :max max
1218 :min-percent min-percent :print-header nil))))
1220 (defun report (&key (type :graph) max min-percent call-graph
1221 ((:sort-by *report-sort-by*) *report-sort-by*)
1222 ((:sort-order *report-sort-order*) *report-sort-order*)
1223 (stream *standard-output*) ((:show-progress *show-progress*)))
1224 "Report statistical profiling results. The following keyword
1225 args are recognized:
1227 :TYPE <type>
1228 Specifies the type of report to generate. If :FLAT, show
1229 flat report, if :GRAPH show a call graph and a flat report.
1230 If nil, don't print out a report.
1232 :STREAM <stream>
1233 Specify a stream to print the report on. Default is
1234 *STANDARD-OUTPUT*.
1236 :MAX <max>
1237 Don't show more than <max> entries in the flat report.
1239 :MIN-PERCENT <min-percent>
1240 Don't show functions taking less than <min-percent> of the
1241 total time in the flat report.
1243 :SORT-BY <column>
1244 If :SAMPLES, sort flat report by number of samples taken.
1245 If :CUMULATIVE-SAMPLES, sort flat report by cumulative number of samples
1246 taken (shows how much time each function spent on stack.) Default
1247 is *REPORT-SORT-BY*.
1249 :SORT-ORDER <order>
1250 If :DESCENDING, sort flat report in descending order. If :ASCENDING,
1251 sort flat report in ascending order. Default is *REPORT-SORT-ORDER*.
1253 :SHOW-PROGRESS <bool>
1254 If true, print progress messages while generating the call graph.
1256 :CALL-GRAPH <graph>
1257 Print a report from <graph> instead of the latest profiling
1258 results.
1260 Value of this function is a CALL-GRAPH object representing the
1261 resulting call-graph, or NIL if there are no samples (eg. right after
1262 calling RESET.)
1264 Profiling is stopped before the call graph is generated."
1265 (cond (*samples*
1266 (let ((graph (or call-graph (make-call-graph most-positive-fixnum))))
1267 (ecase type
1268 (:flat
1269 (print-flat graph :stream stream :max max :min-percent min-percent))
1270 (:graph
1271 (print-graph graph :stream stream :max max :min-percent min-percent))
1272 ((nil)))
1273 graph))
1275 (format stream "~&; No samples to report.~%")
1276 nil)))
1278 ;;; Interface to DISASSEMBLE
1280 (defun sample-pc-from-pc-or-offset (sample pc-or-offset)
1281 (etypecase sample
1282 ;; Assembly routines or foreign functions don't move around, so we've
1283 ;; stored a raw PC
1284 ((or sb-kernel:code-component string)
1285 pc-or-offset)
1286 ;; Lisp functions might move, so we've stored a offset from the
1287 ;; start of the code component.
1288 (sb-di::compiled-debug-fun
1289 (let* ((component (sb-di::compiled-debug-fun-component sample))
1290 (start-pc (code-start component)))
1291 (+ start-pc pc-or-offset)))))
1293 (defun add-disassembly-profile-note (chunk stream dstate)
1294 (declare (ignore chunk stream))
1295 (when *samples*
1296 (let* ((location (+ (sb-disassem::seg-virtual-location
1297 (sb-disassem:dstate-segment dstate))
1298 (sb-disassem::dstate-cur-offs dstate)))
1299 (samples (loop with index = (samples-index *samples*)
1300 for x from 0 below (- index 2) by 2
1301 for last-sample = nil then sample
1302 for sample = (aref (samples-vector *samples*) x)
1303 for pc-or-offset = (aref (samples-vector *samples*)
1304 (1+ x))
1305 when (and sample (eq last-sample 'trace-start))
1306 count (= location
1307 (sample-pc-from-pc-or-offset sample
1308 pc-or-offset)))))
1309 (unless (zerop samples)
1310 (sb-disassem::note (format nil "~A/~A samples"
1311 samples (samples-trace-count *samples*))
1312 dstate)))))
1314 (pushnew 'add-disassembly-profile-note sb-disassem::*default-dstate-hooks*)
1317 ;;;; Call counting
1319 ;;; The following functions tell sb-sprof to do call count profiling
1320 ;;; for the named functions in addition to normal statistical
1321 ;;; profiling. The benefit of this over using SB-PROFILE is that this
1322 ;;; encapsulation is a lot more lightweight, due to not needing to
1323 ;;; track cpu usage / consing. (For example, compiling asdf 20 times
1324 ;;; took 13s normally, 15s with call counting for all functions in
1325 ;;; SB-C, and 94s with SB-PROFILE profiling SB-C).
1327 (defun profile-call-counts (&rest names)
1328 "Mark the functions named by NAMES as being subject to call counting
1329 during statistical profiling. If a string is used as a name, it will
1330 be interpreted as a package name. In this case call counting will be
1331 done for all functions with names like X or (SETF X), where X is a symbol
1332 with the package as its home package."
1333 (dolist (name names)
1334 (if (stringp name)
1335 (let ((package (find-package name)))
1336 (do-symbols (symbol package)
1337 (when (eql (symbol-package symbol) package)
1338 (dolist (function-name (list symbol (list 'setf symbol)))
1339 (profile-call-counts-for-function function-name)))))
1340 (profile-call-counts-for-function name))))
1342 (defun profile-call-counts-for-function (function-name)
1343 (unless (gethash function-name *encapsulations*)
1344 (setf (gethash function-name *encapsulations*) nil)))
1346 (defun unprofile-call-counts ()
1347 "Clear all call counting information. Call counting will be done for no
1348 functions during statistical profiling."
1349 (clrhash *encapsulations*))
1351 ;;; Called when profiling is started to enable the call counting
1352 ;;; encapsulation. Wrap all the call counted functions
1353 (defun enable-call-counting ()
1354 (maphash (lambda (k v)
1355 (declare (ignore v))
1356 (enable-call-counting-for-function k))
1357 *encapsulations*))
1359 ;;; Called when profiling is stopped to disable the encapsulation. Restore
1360 ;;; the original functions.
1361 (defun disable-call-counting ()
1362 (maphash (lambda (k v)
1363 (when v
1364 (assert (cdr v))
1365 (without-package-locks
1366 (setf (fdefinition k) (cdr v)))
1367 (setf (cdr v) nil)))
1368 *encapsulations*))
1370 (defun enable-call-counting-for-function (function-name)
1371 (let ((info (gethash function-name *encapsulations*)))
1372 ;; We should never try to encapsulate an fdefn multiple times.
1373 (assert (or (null info)
1374 (null (cdr info))))
1375 (when (and (fboundp function-name)
1376 (or (not (symbolp function-name))
1377 (and (not (special-operator-p function-name))
1378 (not (macro-function function-name)))))
1379 (let* ((original-fun (fdefinition function-name))
1380 (info (cons 0 original-fun)))
1381 (setf (gethash function-name *encapsulations*) info)
1382 (without-package-locks
1383 (setf (fdefinition function-name)
1384 (sb-int:named-lambda call-counter (sb-int:&more more-context more-count)
1385 (declare (optimize speed (safety 0)))
1386 ;; 2^59 calls should be enough for anybody, and it
1387 ;; allows using fixnum arithmetic on x86-64. 2^32
1388 ;; isn't enough, so we can't do that on 32 bit platforms.
1389 (incf (the (unsigned-byte 59)
1390 (car info)))
1391 (multiple-value-call original-fun
1392 (sb-c:%more-arg-values more-context
1394 more-count)))))))))
1397 ;;; silly examples
1399 (defun test-0 (n &optional (depth 0))
1400 (declare (optimize (debug 3)))
1401 (when (< depth n)
1402 (dotimes (i n)
1403 (test-0 n (1+ depth))
1404 (test-0 n (1+ depth)))))
1406 (defun test ()
1407 (with-profiling (:reset t :max-samples 1000 :report :graph)
1408 (test-0 7)))
1411 ;;; provision
1412 (provide 'sb-sprof)
1414 ;;; end of file