fix long-standing debug-name confusion
[sbcl.git] / contrib / sb-sprof / sb-sprof.lisp
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.
29
30 ;;; Statistical profiler.
31
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.
44
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?
99
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))
108
109 (in-package #:sb-sprof)
110
111 \f
112 ;;;; Graph Utilities
113
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))
121
122 (defstruct edge
123   (vertex (sb-impl::missing-arg) :type vertex))
124
125 (defstruct graph
126   (vertices () :type list))
127
128 (declaim (inline scc-p))
129 (defun scc-p (vertex)
130   (not (null (vertex-scc-vertices vertex))))
131
132 (defmacro do-vertices ((vertex graph) &body body)
133   `(dolist (,vertex (graph-vertices ,graph))
134      ,@body))
135
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)))
140
141 (defun self-cycle-p (vertex)
142   (do-edges (e to vertex)
143     (when (eq to vertex)
144       (return t))))
145
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))))
152
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))
169                      rx
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)))
198
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))))
213
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))))))
234 \f
235 ;;;; The Profiler
236
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))
241
242 (defconstant +unknown-address+ 0
243   "Constant representing an address that cannot be determined.")
244
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))
262
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)))
291
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)))
295
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))
302
303 (defvar *sample-interval* 0.01
304   "Default number of seconds between samples.")
305 (declaim (type number *sample-interval*))
306
307 (defvar *alloc-interval* 4
308   "Default number of allocation region openings between samples.")
309 (declaim (type number *alloc-interval*))
310
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*))
316
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.
326                          10
327                          ;; Each sample takes two cells in the vector
328                          2))
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))
338
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))))
342
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))))
346
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)))))
351
352 (deftype report-type ()
353   '(member nil :flat :graph))
354
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*))
359
360 (defvar *alloc-region-size*
361   #-gencgc
362   (get-page-size)
363   #+gencgc
364   (max sb-vm:gencgc-alloc-granularity sb-vm:gencgc-card-bytes))
365 (declaim (type number *alloc-region-size*))
366
367 (defvar *samples* nil)
368 (declaim (type (or null samples) *samples*))
369
370 (defvar *profiling* nil)
371 (declaim (type (member nil :alloc :cpu :time) *profiling*))
372 (defvar *sampling* nil)
373 (declaim (type boolean *sampling*))
374
375 (defvar *show-progress* nil)
376
377 (defvar *old-sampling* nil)
378
379 ;; Call count encapsulation information
380 (defvar *encapsulations* (make-hash-table :test 'equal))
381
382 (defun turn-off-sampling ()
383   (setq *old-sampling* *sampling*)
384   (setq *sampling* nil))
385
386 (defun turn-on-sampling ()
387   (setq *sampling* *old-sampling*))
388
389 (defun show-progress (format-string &rest args)
390   (when *show-progress*
391     (apply #'format t format-string args)
392     (finish-output)))
393
394 (defun start-sampling ()
395   "Switch on statistical sampling."
396   (setq *sampling* t))
397
398 (defun stop-sampling ()
399   "Switch off statistical sampling."
400   (setq *sampling* nil))
401
402 (defmacro with-sampling ((&optional (on t)) &body body)
403   "Evaluate body with statistical sampling turned on or off."
404   `(let ((*sampling* ,on)
405          (sb-vm:*alloc-signal* sb-vm:*alloc-signal*))
406      ,@body))
407
408 ;;; Return something serving as debug info for address PC.
409 (declaim (inline debug-info))
410 (defun debug-info (pc)
411   (declare (type system-area-pointer pc)
412            (muffle-conditions compiler-note))
413   (let ((ptr (sb-di::component-ptr-from-pc pc)))
414     (cond ((sap= ptr (int-sap 0))
415            (let ((name (sap-foreign-symbol pc)))
416              (if name
417                  (values (format nil "foreign function ~a" name)
418                          (sap-int pc))
419                  (values nil (sap-int pc)))))
420           (t
421            (let* ((code (sb-di::component-from-component-ptr ptr))
422                   (code-header-len (* (sb-kernel:get-header-data code)
423                                       sb-vm:n-word-bytes))
424                   (pc-offset (- (sap-int pc)
425                                 (- (sb-kernel:get-lisp-obj-address code)
426                                    sb-vm:other-pointer-lowtag)
427                                 code-header-len))
428                   (df (sb-di::debug-fun-from-pc code pc-offset)))
429              (cond ((typep df 'sb-di::bogus-debug-fun)
430                     (values code (sap-int pc)))
431                    (df
432                     ;; The code component might be moved by the GC. Store
433                     ;; a PC offset, and reconstruct the data in
434                     ;; SAMPLE-PC-FROM-PC-OR-OFFSET.
435                     (values df pc-offset))
436                    (t
437                     (values nil 0))))))))
438
439 (defun ensure-samples-vector (samples)
440   (let ((vector (samples-vector samples))
441         (index (samples-index samples)))
442     ;; Allocate a new sample vector if the old one is full
443     (if (= (length vector) index)
444         (let ((new-vector (make-array (* 2 index))))
445           (format *trace-output* "Profiler sample vector full (~a traces / ~a samples), doubling the size~%"
446                   (samples-trace-count samples)
447                   (truncate index 2))
448           (replace new-vector vector)
449           (setf (samples-vector samples) new-vector))
450         vector)))
451
452 (declaim (inline record))
453 (defun record (samples pc)
454   (declare (type system-area-pointer pc)
455            (muffle-conditions compiler-note))
456   (multiple-value-bind (info pc-or-offset)
457       (debug-info pc)
458     (let ((vector (ensure-samples-vector samples))
459           (index (samples-index samples)))
460       (declare (type simple-vector vector))
461       ;; Allocate a new sample vector if the old one is full
462       (when (= (length vector) index)
463         (let ((new-vector (make-array (* 2 index))))
464           (format *trace-output* "Profiler sample vector full (~a traces / ~a samples), doubling the size~%"
465                   (samples-trace-count samples)
466                   (truncate index 2))
467           (replace new-vector vector)
468           (setf vector new-vector
469                 (samples-vector samples) new-vector)))
470       ;; For each sample, store the debug-info and the PC/offset into
471       ;; adjacent cells.
472       (setf (aref vector index) info
473             (aref vector (1+ index)) pc-or-offset)))
474   (incf (samples-index samples) 2))
475
476 (defun record-trace-start (samples)
477   ;; Mark the start of the trace.
478   (let ((vector (ensure-samples-vector samples)))
479     (declare (type simple-vector vector))
480     (setf (aref vector (samples-index samples))
481           'trace-start))
482   (incf (samples-index samples) 2))
483
484 ;;; List of thread currently profiled, or :ALL for all threads.
485 (defvar *profiled-threads* nil)
486 (declaim (type (or list (member :all)) *profiled-threads*))
487
488 ;;; Thread which runs the wallclock timers, if any.
489 (defvar *timer-thread* nil)
490
491 (defun profiled-threads ()
492   (let ((profiled-threads *profiled-threads*))
493     (remove *timer-thread*
494             (if (eq :all profiled-threads)
495                 (sb-thread:list-all-threads)
496                 profiled-threads))))
497
498 (defun profiled-thread-p (thread)
499   (let ((profiled-threads *profiled-threads*))
500     (or (and (eq :all profiled-threads)
501              (not (eq *timer-thread* thread)))
502         (member thread profiled-threads :test #'eq))))
503
504 #+(or x86 x86-64)
505 (progn
506   ;; Ensure that only one thread at a time will be doing profiling stuff.
507   (defvar *profiler-lock* (sb-thread:make-mutex :name "Statistical Profiler"))
508   (defvar *distribution-lock* (sb-thread:make-mutex :name "Wallclock profiling lock"))
509
510   (declaim (inline pthread-kill))
511   (define-alien-routine pthread-kill int (os-thread unsigned-long) (signal int))
512
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 speed (space 0)))
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)))
534
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.
551                  ;;
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))
602
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))))))))))
626
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)))
631
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)))
638
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.
654
655    The following keyword args are recognized:
656
657    :SAMPLE-INTERVAL <n>
658      Take a sample every <n> seconds. Default is *SAMPLE-INTERVAL*.
659
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*.
664
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.
669
670    :MAX-SAMPLES <max>
671      Repeat evaluating body until <max> samples are taken.
672      Default is *MAX-SAMPLES*.
673
674    :MAX-DEPTH <max>
675      Maximum call stack depth that the profiler should consider. Only
676      has an effect on x86 and x86-64.
677
678    :REPORT <type>
679      If specified, call REPORT with :TYPE <type> at the end.
680
681    :RESET <bool>
682      It true, call RESET at the beginning.
683
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.)
688
689      :THREADS has no effect on call-counting at the moment.
690
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.
696
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)))))
727
728 (defvar *timer* nil)
729
730 (defvar *old-alloc-interval* nil)
731 (defvar *old-sample-interval* nil)
732
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:
742
743    :SAMPLE-INTERVAL <n>
744      Take a sample every <n> seconds.  Default is *SAMPLE-INTERVAL*.
745
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*.
750
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.
755
756    :MAX-SAMPLES <max>
757      Maximum number of samples.  Default is *MAX-SAMPLES*.
758
759    :MAX-DEPTH <max>
760      Maximum call stack depth that the profiler should consider. Only
761      has an effect on x86 and x86-64.
762
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.)
767
768      :THREADS has no effect on call-counting at the moment.
769
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.
775
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))
829
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))
854
855 (defun reset ()
856   "Reset the profiler."
857   (stop-profiling)
858   (setq *sampling* nil)
859   (setq *samples* nil)
860   (values))
861
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::top-level-form
869                               sb-c::&optional-processor)))
870                (second name)
871                name)))
872     (typecase info
873       (sb-kernel::code-component
874        (multiple-value-bind (start end)
875            (code-bounds info)
876          (values
877           (%make-node :name (or (sb-disassem::find-assembler-routine start)
878                                 (format nil "~a" info))
879                       :debug-info info
880                       :start-pc-or-offset start
881                       :end-pc-or-offset end)
882           info)))
883       (sb-di::compiled-debug-fun
884        (let* ((name (sb-di::debug-fun-name info))
885               (cdf (sb-di::compiled-debug-fun-compiler-debug-fun info))
886               (start-offset (sb-c::compiled-debug-fun-start-pc cdf))
887               (end-offset (sb-c::compiled-debug-fun-elsewhere-pc cdf))
888               (component (sb-di::compiled-debug-fun-component info))
889               (start-pc (code-start component)))
890          ;; Call graphs are mostly useless unless we somehow
891          ;; distinguish a gazillion different (LAMBDA ())'s.
892          (when (equal name '(lambda ()))
893            (setf name (format nil "Unknown component: #x~x" start-pc)))
894          (values (%make-node :name (clean-name name)
895                              :debug-info info
896                              :start-pc-or-offset start-offset
897                              :end-pc-or-offset end-offset)
898                  component)))
899       (sb-di::debug-fun
900        (%make-node :name (clean-name (sb-di::debug-fun-name info))
901                    :debug-info info))
902       (t
903        (%make-node :name (coerce info 'string)
904                    :debug-info info)))))
905
906 ;;; One function can have more than one COMPILED-DEBUG-FUNCTION with
907 ;;; the same name.  Reduce the number of calls to Debug-Info by first
908 ;;; looking for a given PC in a red-black tree.  If not found in the
909 ;;; tree, get debug info, and look for a node in a hash-table by
910 ;;; function name.  If not found in the hash-table, make a new node.
911
912 (defvar *name->node*)
913
914 (defmacro with-lookup-tables (() &body body)
915   `(let ((*name->node* (make-hash-table :test 'equal)))
916      ,@body))
917
918 ;;; Find or make a new node for INFO.  Value is the NODE found or
919 ;;; made; NIL if not enough information exists to make a NODE for INFO.
920 (defun lookup-node (info)
921   (when info
922     (multiple-value-bind (new key)
923         (make-node info)
924       (when (eql (node-name new) 'call-counter)
925         (return-from lookup-node (values nil nil)))
926       (let* ((key (cons (node-name new) key))
927              (found (gethash key *name->node*)))
928         (cond (found
929                (setf (node-start-pc-or-offset found)
930                      (min (node-start-pc-or-offset found)
931                           (node-start-pc-or-offset new)))
932                (setf (node-end-pc-or-offset found)
933                      (max (node-end-pc-or-offset found)
934                           (node-end-pc-or-offset new)))
935                found)
936               (t
937                (let ((call-count-info (gethash (node-name new)
938                                                *encapsulations*)))
939                  (when call-count-info
940                    (setf (node-call-count new)
941                          (car call-count-info))))
942                (setf (gethash key *name->node*) new)
943                new))))))
944
945 ;;; Return a list of all nodes created by LOOKUP-NODE.
946 (defun collect-nodes ()
947   (loop for node being the hash-values of *name->node*
948         collect node))
949
950 ;;; Value is a CALL-GRAPH for the current contents of *SAMPLES*.
951 (defun make-call-graph-1 (max-depth)
952   (let ((elsewhere-count 0)
953         visited-nodes)
954     (with-lookup-tables ()
955       (loop for i below (- (samples-index *samples*) 2) by 2
956             with depth = 0
957             for debug-info = (aref (samples-vector *samples*) i)
958             for next-info = (aref (samples-vector *samples*)
959                                   (+ i 2))
960             do (if (eq debug-info 'trace-start)
961                    (setf depth 0)
962                    (let ((callee (lookup-node debug-info))
963                          (caller (unless (eq next-info 'trace-start)
964                                    (lookup-node next-info))))
965                      (when (< depth max-depth)
966                        (when (zerop depth)
967                          (setf visited-nodes nil)
968                          (cond (callee
969                                 (incf (node-accrued-count callee))
970                                 (incf (node-count callee)))
971                                (t
972                                 (incf elsewhere-count))))
973                        (incf depth)
974                        (when callee
975                          (push callee visited-nodes))
976                        (when caller
977                          (unless (member caller visited-nodes)
978                            (incf (node-accrued-count caller)))
979                          (when callee
980                            (let ((call (find callee (node-edges caller)
981                                              :key #'call-vertex)))
982                              (pushnew caller (node-callers callee))
983                              (if call
984                                  (unless (member caller visited-nodes)
985                                    (incf (call-count call)))
986                                  (push (make-call callee)
987                                        (node-edges caller))))))))))
988       (let ((sorted-nodes (sort (collect-nodes) #'> :key #'node-count)))
989         (loop for node in sorted-nodes and i from 1 do
990               (setf (node-index node) i))
991         (%make-call-graph :nsamples (samples-trace-count *samples*)
992                           :sample-interval (if (eq (samples-mode *samples*)
993                                                    :alloc)
994                                                (samples-alloc-interval *samples*)
995                                                (samples-sample-interval *samples*))
996                           :sampling-mode (samples-mode *samples*)
997                           :sampled-threads (samples-sampled-threads *samples*)
998                           :elsewhere-count elsewhere-count
999                           :vertices sorted-nodes)))))
1000
1001 ;;; Reduce CALL-GRAPH to a dag, creating CYCLE structures for call
1002 ;;; cycles.
1003 (defun reduce-call-graph (call-graph)
1004   (let ((cycle-no 0))
1005     (flet ((make-one-cycle (vertices edges)
1006              (let* ((name (format nil "<Cycle ~d>" (incf cycle-no)))
1007                     (count (loop for v in vertices sum (node-count v))))
1008                (make-cycle :name name
1009                            :index cycle-no
1010                            :count count
1011                            :scc-vertices vertices
1012                            :edges edges))))
1013       (reduce-graph call-graph #'make-one-cycle))))
1014
1015 ;;; For all nodes in CALL-GRAPH, compute times including the time
1016 ;;; spent in functions called from them.  Note that the call-graph
1017 ;;; vertices are in reverse topological order, children first, so we
1018 ;;; will have computed accrued counts of called functions before they
1019 ;;; are used to compute accrued counts for callers.
1020 (defun compute-accrued-counts (call-graph)
1021   (do-vertices (from call-graph)
1022     (setf (node-accrued-count from) (node-count from))
1023     (do-edges (call to from)
1024       (incf (node-accrued-count from)
1025             (round (* (/ (call-count call) (node-count to))
1026                       (node-accrued-count to)))))))
1027
1028 ;;; Return a CALL-GRAPH structure for the current contents of
1029 ;;; *SAMPLES*.  The result contain a list of nodes sorted by self-time
1030 ;;; in the FLAT-NODES slot, and a dag in VERTICES, with call cycles
1031 ;;; reduced to CYCLE structures.
1032 (defun make-call-graph (max-depth)
1033   (stop-profiling)
1034   (show-progress "~&Computing call graph ")
1035   (let ((call-graph (without-gcing (make-call-graph-1 max-depth))))
1036     (setf (call-graph-flat-nodes call-graph)
1037           (copy-list (graph-vertices call-graph)))
1038     (show-progress "~&Finding cycles")
1039     #+nil
1040     (reduce-call-graph call-graph)
1041     (show-progress "~&Propagating counts")
1042     #+nil
1043     (compute-accrued-counts call-graph)
1044     call-graph))
1045
1046 \f
1047 ;;;; Reporting
1048
1049 (defun print-separator (&key (length 72) (char #\-))
1050   (format t "~&~V,,,V<~>~%" length char))
1051
1052 (defun samples-percent (call-graph count)
1053   (if (> count 0)
1054       (* 100.0 (/ count (call-graph-nsamples call-graph)))
1055       0))
1056
1057 (defun print-call-graph-header (call-graph)
1058   (let ((nsamples (call-graph-nsamples call-graph))
1059         (interval (call-graph-sample-interval call-graph))
1060         (ncycles (loop for v in (graph-vertices call-graph)
1061                        count (scc-p v))))
1062     (if (eq (call-graph-sampling-mode call-graph) :alloc)
1063         (format t "~2&Number of samples:     ~d~%~
1064                       Alloc interval:        ~a regions (approximately ~a kB)~%~
1065                       Total sampling amount: ~a regions (approximately ~a kB)~%~
1066                       Number of cycles:      ~d~%~
1067                       Sampled threads:~{~%   ~S~}~2%"
1068                 nsamples
1069                 interval
1070                 (truncate (* interval *alloc-region-size*) 1024)
1071                 (* nsamples interval)
1072                 (truncate (* nsamples interval *alloc-region-size*) 1024)
1073                 ncycles
1074                 (call-graph-sampled-threads call-graph))
1075         (format t "~2&Number of samples:   ~d~%~
1076                       Sample interval:     ~f seconds~%~
1077                       Total sampling time: ~f seconds~%~
1078                       Number of cycles:    ~d~%~
1079                       Sampled threads:~{~% ~S~}~2%"
1080                 nsamples
1081                 interval
1082                 (* nsamples interval)
1083                 ncycles
1084                 (call-graph-sampled-threads call-graph)))))
1085
1086 (declaim (type (member :samples :cumulative-samples) *report-sort-by*))
1087 (defvar *report-sort-by* :samples
1088   "Method for sorting the flat report: either by :SAMPLES or by :CUMULATIVE-SAMPLES.")
1089
1090 (declaim (type (member :descending :ascending) *report-sort-order*))
1091 (defvar *report-sort-order* :descending
1092   "Order for sorting the flat report: either :DESCENDING or :ASCENDING.")
1093
1094 (defun print-flat (call-graph &key (stream *standard-output*) max
1095                    min-percent (print-header t)
1096                    (sort-by *report-sort-by*)
1097                    (sort-order *report-sort-order*))
1098   (declare (type (member :descending :ascending) sort-order)
1099            (type (member :samples :cumulative-samples) sort-by))
1100   (let ((*standard-output* stream)
1101         (*print-pretty* nil)
1102         (total-count 0)
1103         (total-percent 0)
1104         (min-count (if min-percent
1105                        (round (* (/ min-percent 100.0)
1106                                  (call-graph-nsamples call-graph)))
1107                        0)))
1108     (when print-header
1109       (print-call-graph-header call-graph))
1110     (format t "~&           Self        Total        Cumul~%")
1111     (format t "~&  Nr  Count     %  Count     %  Count     %    Calls  Function~%")
1112     (print-separator)
1113     (let ((elsewhere-count (call-graph-elsewhere-count call-graph))
1114           (i 0)
1115           (nodes (stable-sort (copy-list (call-graph-flat-nodes call-graph))
1116                               (let ((cmp (if (eq :descending sort-order) #'> #'<)))
1117                                 (multiple-value-bind (primary secondary)
1118                                     (if (eq :samples sort-by)
1119                                         (values #'node-count #'node-accrued-count)
1120                                         (values #'node-accrued-count #'node-count))
1121                                   (lambda (x y)
1122                                     (let ((cx (funcall primary x))
1123                                           (cy (funcall primary y)))
1124                                       (if (= cx cy)
1125                                           (funcall cmp (funcall secondary x) (funcall secondary y))
1126                                           (funcall cmp cx cy)))))))))
1127       (dolist (node nodes)
1128         (when (or (and max (> (incf i) max))
1129                   (< (node-count node) min-count))
1130           (return))
1131         (let* ((count (node-count node))
1132                (percent (samples-percent call-graph count))
1133                (accrued-count (node-accrued-count node))
1134                (accrued-percent (samples-percent call-graph accrued-count)))
1135           (incf total-count count)
1136           (incf total-percent percent)
1137           (format t "~&~4d ~6d ~5,1f ~6d ~5,1f ~6d ~5,1f ~8@a  ~s~%"
1138                   (incf i)
1139                   count
1140                   percent
1141                   accrued-count
1142                   accrued-percent
1143                   total-count
1144                   total-percent
1145                   (or (node-call-count node) "-")
1146                   (node-name node))
1147           (finish-output)))
1148       (print-separator)
1149       (format t "~&     ~6d ~5,1f~36a elsewhere~%"
1150               elsewhere-count
1151               (samples-percent call-graph elsewhere-count)
1152               ""))))
1153
1154 (defun print-cycles (call-graph)
1155   (when (some #'cycle-p (graph-vertices call-graph))
1156     (format t "~&                            Cycle~%")
1157     (format t "~& Count     %                   Parts~%")
1158     (do-vertices (node call-graph)
1159       (when (cycle-p node)
1160         (flet ((print-info (indent index count percent name)
1161                  (format t "~&~6d ~5,1f ~11@t ~V@t  ~s [~d]~%"
1162                          count percent indent name index)))
1163           (print-separator)
1164           (format t "~&~6d ~5,1f                ~a...~%"
1165                   (node-count node)
1166                   (samples-percent call-graph (cycle-count node))
1167                   (node-name node))
1168           (dolist (v (vertex-scc-vertices node))
1169             (print-info 4 (node-index v) (node-count v)
1170                         (samples-percent call-graph (node-count v))
1171                         (node-name v))))))
1172     (print-separator)
1173     (format t "~2%")))
1174
1175 (defun print-graph (call-graph &key (stream *standard-output*)
1176                     max min-percent)
1177   (let ((*standard-output* stream)
1178         (*print-pretty* nil))
1179     (print-call-graph-header call-graph)
1180     (print-cycles call-graph)
1181     (flet ((find-call (from to)
1182              (find to (node-edges from) :key #'call-vertex))
1183            (print-info (indent index count percent name)
1184              (format t "~&~6d ~5,1f ~11@t ~V@t  ~s [~d]~%"
1185                      count percent indent name index)))
1186       (format t "~&                               Callers~%")
1187       (format t "~&                 Total.     Function~%")
1188       (format t "~& Count     %  Count     %      Callees~%")
1189       (do-vertices (node call-graph)
1190         (print-separator)
1191         ;;
1192         ;; Print caller information.
1193         (dolist (caller (node-callers node))
1194           (let ((call (find-call caller node)))
1195             (print-info 4 (node-index caller)
1196                         (call-count call)
1197                         (samples-percent call-graph (call-count call))
1198                         (node-name caller))))
1199         ;; Print the node itself.
1200         (format t "~&~6d ~5,1f ~6d ~5,1f   ~s [~d]~%"
1201                 (node-count node)
1202                 (samples-percent call-graph (node-count node))
1203                 (node-accrued-count node)
1204                 (samples-percent call-graph (node-accrued-count node))
1205                 (node-name node)
1206                 (node-index node))
1207         ;; Print callees.
1208         (do-edges (call called node)
1209           (print-info 4 (node-index called)
1210                       (call-count call)
1211                       (samples-percent call-graph (call-count call))
1212                       (node-name called))))
1213       (print-separator)
1214       (format t "~2%")
1215       (print-flat call-graph :stream stream :max max
1216                   :min-percent min-percent :print-header nil))))
1217
1218 (defun report (&key (type :graph) max min-percent call-graph
1219                ((:sort-by *report-sort-by*) *report-sort-by*)
1220                ((:sort-order *report-sort-order*) *report-sort-order*)
1221                (stream *standard-output*) ((:show-progress *show-progress*)))
1222   "Report statistical profiling results.  The following keyword
1223    args are recognized:
1224
1225    :TYPE <type>
1226       Specifies the type of report to generate.  If :FLAT, show
1227       flat report, if :GRAPH show a call graph and a flat report.
1228       If nil, don't print out a report.
1229
1230    :STREAM <stream>
1231       Specify a stream to print the report on.  Default is
1232       *STANDARD-OUTPUT*.
1233
1234    :MAX <max>
1235       Don't show more than <max> entries in the flat report.
1236
1237    :MIN-PERCENT <min-percent>
1238       Don't show functions taking less than <min-percent> of the
1239       total time in the flat report.
1240
1241    :SORT-BY <column>
1242       If :SAMPLES, sort flat report by number of samples taken.
1243       If :CUMULATIVE-SAMPLES, sort flat report by cumulative number of samples
1244       taken (shows how much time each function spent on stack.) Default
1245       is *REPORT-SORT-BY*.
1246
1247    :SORT-ORDER <order>
1248       If :DESCENDING, sort flat report in descending order. If :ASCENDING,
1249       sort flat report in ascending order. Default is *REPORT-SORT-ORDER*.
1250
1251    :SHOW-PROGRESS <bool>
1252      If true, print progress messages while generating the call graph.
1253
1254    :CALL-GRAPH <graph>
1255      Print a report from <graph> instead of the latest profiling
1256      results.
1257
1258 Value of this function is a CALL-GRAPH object representing the
1259 resulting call-graph, or NIL if there are no samples (eg. right after
1260 calling RESET.)
1261
1262 Profiling is stopped before the call graph is generated."
1263   (cond (*samples*
1264          (let ((graph (or call-graph (make-call-graph most-positive-fixnum))))
1265            (ecase type
1266              (:flat
1267               (print-flat graph :stream stream :max max :min-percent min-percent))
1268              (:graph
1269               (print-graph graph :stream stream :max max :min-percent min-percent))
1270              ((nil)))
1271            graph))
1272         (t
1273          (format stream "~&; No samples to report.~%")
1274          nil)))
1275
1276 ;;; Interface to DISASSEMBLE
1277
1278 (defun sample-pc-from-pc-or-offset (sample pc-or-offset)
1279   (etypecase sample
1280     ;; Assembly routines or foreign functions don't move around, so we've
1281     ;; stored a raw PC
1282     ((or sb-kernel:code-component string)
1283      pc-or-offset)
1284     ;; Lisp functions might move, so we've stored a offset from the
1285     ;; start of the code component.
1286     (sb-di::compiled-debug-fun
1287      (let* ((component (sb-di::compiled-debug-fun-component sample))
1288             (start-pc (code-start component)))
1289        (+ start-pc pc-or-offset)))))
1290
1291 (defun add-disassembly-profile-note (chunk stream dstate)
1292   (declare (ignore chunk stream))
1293   (when *samples*
1294     (let* ((location (+ (sb-disassem::seg-virtual-location
1295                          (sb-disassem:dstate-segment dstate))
1296                         (sb-disassem::dstate-cur-offs dstate)))
1297            (samples (loop with index = (samples-index *samples*)
1298                           for x from 0 below (- index 2) by 2
1299                           for last-sample = nil then sample
1300                           for sample = (aref (samples-vector *samples*) x)
1301                           for pc-or-offset = (aref (samples-vector *samples*)
1302                                                    (1+ x))
1303                           when (and sample (eq last-sample 'trace-start))
1304                           count (= location
1305                                    (sample-pc-from-pc-or-offset sample
1306                                                                 pc-or-offset)))))
1307       (unless (zerop samples)
1308         (sb-disassem::note (format nil "~A/~A samples"
1309                                    samples (samples-trace-count *samples*))
1310                            dstate)))))
1311
1312 (pushnew 'add-disassembly-profile-note sb-disassem::*default-dstate-hooks*)
1313
1314 \f
1315 ;;;; Call counting
1316
1317 ;;; The following functions tell sb-sprof to do call count profiling
1318 ;;; for the named functions in addition to normal statistical
1319 ;;; profiling.  The benefit of this over using SB-PROFILE is that this
1320 ;;; encapsulation is a lot more lightweight, due to not needing to
1321 ;;; track cpu usage / consing. (For example, compiling asdf 20 times
1322 ;;; took 13s normally, 15s with call counting for all functions in
1323 ;;; SB-C, and 94s with SB-PROFILE profiling SB-C).
1324
1325 (defun profile-call-counts (&rest names)
1326   "Mark the functions named by NAMES as being subject to call counting
1327 during statistical profiling. If a string is used as a name, it will
1328 be interpreted as a package name. In this case call counting will be
1329 done for all functions with names like X or (SETF X), where X is a symbol
1330 with the package as its home package."
1331   (dolist (name names)
1332     (if (stringp name)
1333         (let ((package (find-package name)))
1334           (do-symbols (symbol package)
1335             (when (eql (symbol-package symbol) package)
1336               (dolist (function-name (list symbol (list 'setf symbol)))
1337                 (profile-call-counts-for-function function-name)))))
1338         (profile-call-counts-for-function name))))
1339
1340 (defun profile-call-counts-for-function (function-name)
1341   (unless (gethash function-name *encapsulations*)
1342     (setf (gethash function-name *encapsulations*) nil)))
1343
1344 (defun unprofile-call-counts ()
1345   "Clear all call counting information. Call counting will be done for no
1346 functions during statistical profiling."
1347   (clrhash *encapsulations*))
1348
1349 ;;; Called when profiling is started to enable the call counting
1350 ;;; encapsulation. Wrap all the call counted functions
1351 (defun enable-call-counting ()
1352   (maphash (lambda (k v)
1353              (declare (ignore v))
1354              (enable-call-counting-for-function k))
1355            *encapsulations*))
1356
1357 ;;; Called when profiling is stopped to disable the encapsulation. Restore
1358 ;;; the original functions.
1359 (defun disable-call-counting ()
1360   (maphash (lambda (k v)
1361              (when v
1362                (assert (cdr v))
1363                (without-package-locks
1364                  (setf (fdefinition k) (cdr v)))
1365                (setf (cdr v) nil)))
1366            *encapsulations*))
1367
1368 (defun enable-call-counting-for-function (function-name)
1369   (let ((info (gethash function-name *encapsulations*)))
1370     ;; We should never try to encapsulate an fdefn multiple times.
1371     (assert (or (null info)
1372                 (null (cdr info))))
1373     (when (and (fboundp function-name)
1374                (or (not (symbolp function-name))
1375                    (and (not (special-operator-p function-name))
1376                         (not (macro-function function-name)))))
1377       (let* ((original-fun (fdefinition function-name))
1378              (info (cons 0 original-fun)))
1379         (setf (gethash function-name *encapsulations*) info)
1380         (without-package-locks
1381           (setf (fdefinition function-name)
1382                 (sb-int:named-lambda call-counter (sb-int:&more more-context more-count)
1383                   (declare (optimize speed (safety 0)))
1384                   ;; 2^59 calls should be enough for anybody, and it
1385                   ;; allows using fixnum arithmetic on x86-64. 2^32
1386                   ;; isn't enough, so we can't do that on 32 bit platforms.
1387                   (incf (the (unsigned-byte 59)
1388                           (car info)))
1389                   (multiple-value-call original-fun
1390                     (sb-c:%more-arg-values more-context
1391                                            0
1392                                            more-count)))))))))
1393
1394 \f
1395 ;;; silly examples
1396
1397 (defun test-0 (n &optional (depth 0))
1398   (declare (optimize (debug 3)))
1399   (when (< depth n)
1400     (dotimes (i n)
1401       (test-0 n (1+ depth))
1402       (test-0 n (1+ depth)))))
1403
1404 (defun test ()
1405   (with-profiling (:reset t :max-samples 1000 :report :graph)
1406     (test-0 7)))
1407
1408
1409 ;;; provision
1410 (provide 'sb-sprof)
1411
1412 ;;; end of file