1 /* -----------------------------------------------------------------------------
2 * $Id: ProfHeap.c,v 1.29 2001/11/28 15:01:02 simonmar Exp $
4 * (c) The GHC Team, 1998-2000
6 * Support for heap profiling
8 * ---------------------------------------------------------------------------*/
10 #if defined(DEBUG) && !defined(PROFILING)
11 #define DEBUG_HEAP_PROF
13 #undef DEBUG_HEAP_PROF
16 #if defined(PROFILING) || defined(DEBUG_HEAP_PROF)
18 #include "PosixSource.h"
22 #include "Profiling.h"
28 #include "RetainerProfile.h"
29 #include "LdvProfile.h"
32 #ifdef DEBUG_HEAP_PROF
34 static void fprint_data(FILE *fp);
37 /* -----------------------------------------------------------------------------
38 * era stores the current time period. It is the same as the
39 * number of censuses that have been performed.
42 * era must be no longer than LDV_SHIFT (15 or 30) bits.
44 * era is initialized to 0 in initHeapProfiling().
46 * max_era is initialized to 2^LDV_SHIFT in initHeapProfiling().
47 * When era reaches max_era, the profiling stops because a closure can
48 * store only up to (max_era - 1) as its creation or last use time.
49 * -------------------------------------------------------------------------- */
53 /* -----------------------------------------------------------------------------
56 * For most heap profiles each closure identity gets a simple count
57 * of live words in the heap at each census. However, if we're
58 * selecting by biography, then we have to keep the various
59 * lag/drag/void counters for each identity.
60 * -------------------------------------------------------------------------- */
61 typedef struct _counter {
66 int prim; // total size of 'inherently used' closures
67 int not_used; // total size of 'never used' closures
68 int used; // total size of 'used at least once' closures
69 int void_total; // current total size of 'destroyed without being used' closures
70 int drag_total; // current total size of 'used at least once and waiting to die'
73 struct _counter *next;
77 initLDVCtr( counter *ctr )
80 ctr->c.ldv.not_used = 0;
82 ctr->c.ldv.void_total = 0;
83 ctr->c.ldv.drag_total = 0;
87 double time; // the time in MUT time when the census is made
92 // for LDV profiling, when just displaying by LDV
100 Census *censuses = NULL;
104 static void aggregateCensusInfo( void );
107 static void dumpCensus( Census *census );
109 /* -----------------------------------------------------------------------------
110 Closure Type Profiling;
112 PROBABLY TOTALLY OUT OF DATE -- ToDo (SDM)
113 -------------------------------------------------------------------------- */
115 #ifdef DEBUG_HEAP_PROF
116 static char *type_names[] = {
122 , "CONSTR_NOCAF_STATIC"
160 , "MUT_ARR_PTRS_FROZEN"
174 #endif /* DEBUG_HEAP_PROF */
176 /* -----------------------------------------------------------------------------
177 * Find the "closure identity", which is a unique pointer reresenting
178 * the band to which this closure's heap space is attributed in the
180 * ------------------------------------------------------------------------- */
182 closureIdentity( StgClosure *p )
184 switch (RtsFlags.ProfFlags.doHeapProfile) {
188 return ((StgClosure *)p)->header.prof.ccs;
190 return ((StgClosure *)p)->header.prof.ccs->cc->module;
192 return (get_itbl((StgClosure *)p))->prof.closure_desc;
194 return (get_itbl((StgClosure *)p))->prof.closure_type;
195 case HEAP_BY_RETAINER:
196 return retainerSetOf((StgClosure *)p);
198 case HEAP_BY_INFOPTR:
199 return (void *)((StgClosure *)p)->header.info;
200 case HEAP_BY_CLOSURE_TYPE:
201 return type_names[get_itbl(p)->type];
204 barf("closureIdentity");
208 /* --------------------------------------------------------------------------
209 * Profiling type predicates
210 * ----------------------------------------------------------------------- */
212 static inline rtsBool
213 doingLDVProfiling( void )
215 return (RtsFlags.ProfFlags.doHeapProfile == HEAP_BY_LDV
216 || RtsFlags.ProfFlags.bioSelector != NULL);
219 static inline rtsBool
220 doingRetainerProfiling( void )
222 return (RtsFlags.ProfFlags.doHeapProfile == HEAP_BY_RETAINER
223 || RtsFlags.ProfFlags.retainerSelector != NULL);
227 // Precesses a closure 'c' being destroyed whose size is 'size'.
228 // Make sure that LDV_recordDead() is not invoked on 'inherently used' closures
229 // such as TSO; they should not be involved in computing dragNew or voidNew.
231 // Even though era is checked in both LdvCensusForDead() and
232 // LdvCensusKillAll(), we still need to make sure that era is > 0 because
233 // LDV_recordDead() may be called from elsewhere in the runtime system. E.g.,
234 // when a thunk is replaced by an indirection object.
238 LDV_recordDead( StgClosure *c, nat size )
244 if (era > 0 && closureSatisfiesConstraints(c)) {
245 size -= sizeofW(StgProfHeader);
246 if ((LDVW((c)) & LDV_STATE_MASK) == LDV_STATE_CREATE) {
247 t = (LDVW((c)) & LDV_CREATE_MASK) >> LDV_SHIFT;
249 if (RtsFlags.ProfFlags.bioSelector == NULL) {
250 censuses[t].void_total += (int)size;
251 censuses[era].void_total -= (int)size;
253 id = closureIdentity(c);
254 ctr = lookupHashTable(censuses[t].hash, (StgWord)id);
255 ASSERT( ctr != NULL );
256 ctr->c.ldv.void_total += (int)size;
257 ctr = lookupHashTable(censuses[era].hash, (StgWord)id);
259 ctr = arenaAlloc(censuses[era].arena, sizeof(counter));
261 insertHashTable(censuses[era].hash, (StgWord)id, ctr);
263 ctr->next = censuses[era].ctrs;
264 censuses[era].ctrs = ctr;
266 ctr->c.ldv.void_total -= (int)size;
270 t = LDVW((c)) & LDV_LAST_MASK;
272 if (RtsFlags.ProfFlags.bioSelector == NULL) {
273 censuses[t+1].drag_total += size;
274 censuses[era].drag_total -= size;
277 id = closureIdentity(c);
278 ctr = lookupHashTable(censuses[t+1].hash, (StgWord)id);
279 ASSERT( ctr != NULL );
280 ctr->c.ldv.drag_total += (int)size;
281 ctr = lookupHashTable(censuses[era].hash, (StgWord)id);
283 ctr = arenaAlloc(censuses[era].arena, sizeof(counter));
285 insertHashTable(censuses[era].hash, (StgWord)id, ctr);
287 ctr->next = censuses[era].ctrs;
288 censuses[era].ctrs = ctr;
290 ctr->c.ldv.drag_total -= (int)size;
298 /* --------------------------------------------------------------------------
299 * Initialize censuses[era];
300 * ----------------------------------------------------------------------- */
302 initEra(Census *census)
304 census->hash = allocHashTable();
306 census->arena = newArena();
308 census->not_used = 0;
311 census->void_total = 0;
312 census->drag_total = 0;
315 /* --------------------------------------------------------------------------
316 * Increases era by 1 and initialize census[era].
317 * Reallocates gi[] and increases its size if needed.
318 * ----------------------------------------------------------------------- */
323 if (doingLDVProfiling()) {
326 if (era == max_era) {
327 barf("maximum number of censuses reached; use +RTS -i to reduce");
330 if (era == n_censuses) {
332 censuses = stgReallocBytes(censuses, sizeof(Census) * n_censuses,
338 initEra( &censuses[era] );
341 /* -------------------------------------------------------------------------- */
343 #ifdef DEBUG_HEAP_PROF
346 void initProfiling1( void )
350 void initProfiling2( void )
355 void endProfiling( void )
359 #endif /* DEBUG_HEAP_PROF */
362 initHeapProfiling(void)
364 if (! RtsFlags.ProfFlags.doHeapProfile) {
368 // we only count eras if we're doing LDV profiling. Otherwise era
371 if (doingLDVProfiling()) {
379 { // max_era = 2^LDV_SHIFT
382 for (p = 0; p < LDV_SHIFT; p++)
387 censuses = stgMallocBytes(sizeof(Census) * n_censuses, "initHeapProfiling");
389 initEra( &censuses[era] );
391 fprintf(hp_file, "JOB \"%s", prog_argv[0]);
396 for(count = 1; count < prog_argc; count++)
397 fprintf(hp_file, " %s", prog_argv[count]);
398 fprintf(hp_file, " +RTS ");
399 for(count = 0; count < rts_argc; count++)
400 fprintf(hp_file, "%s ", rts_argv[count]);
401 fprintf(hp_file, "\n");
403 #endif /* PROFILING */
405 fprintf(hp_file, "\"\n" );
407 fprintf(hp_file, "DATE \"%s\"\n", time_str());
409 fprintf(hp_file, "SAMPLE_UNIT \"seconds\"\n");
410 fprintf(hp_file, "VALUE_UNIT \"bytes\"\n");
412 fprintf(hp_file, "BEGIN_SAMPLE 0.00\n");
413 fprintf(hp_file, "END_SAMPLE 0.00\n");
415 #ifdef DEBUG_HEAP_PROF
416 DEBUG_LoadSymbols(prog_argv[0]);
420 if (doingRetainerProfiling()) {
421 initRetainerProfiling();
429 endHeapProfiling(void)
433 if (! RtsFlags.ProfFlags.doHeapProfile) {
438 if (doingRetainerProfiling()) {
439 endRetainerProfiling();
445 // We do not need to perform a major garbage collection because all the
446 // closures created since the last census will not affect the profiling
447 // statistics anyhow.
448 if (RtsFlags.ProfFlags.doHeapProfile == HEAP_BY_LDV)
453 if (RtsFlags.ProfFlags.bioSelector != NULL) {
455 aggregateCensusInfo();
456 for (t = 1; t < era; t++) {
457 dumpCensus( &censuses[t] );
462 seconds = mut_user_time();
463 fprintf(hp_file, "BEGIN_SAMPLE %0.2f\n", seconds);
464 fprintf(hp_file, "END_SAMPLE %0.2f\n", seconds);
472 fprint_ccs(FILE *fp, CostCentreStack *ccs, nat max_length)
474 char buf[max_length+1];
479 // MAIN on its own gets printed as "MAIN", otherwise we ignore MAIN.
480 if (ccs == CCS_MAIN) {
485 // keep printing components of the stack until we run out of space
486 // in the buffer. If we run out of space, end with "...".
487 for (; ccs != NULL && ccs != CCS_MAIN; ccs = ccs->prevStack) {
489 // CAF cost centres print as M.CAF, but we leave the module
490 // name out of all the others to save space.
491 if (!strcmp(ccs->cc->label,"CAF")) {
492 written = snprintf(buf+next_offset,
493 (int)max_length-3-(int)next_offset,
494 "%s.CAF", ccs->cc->module);
496 if (ccs->prevStack != NULL && ccs->prevStack != CCS_MAIN) {
501 written = snprintf(buf+next_offset,
502 (int)max_length-3-(int)next_offset,
503 template, ccs->cc->label);
506 if (next_offset+written >= max_length-4) {
507 sprintf(buf+max_length-4, "...");
510 next_offset += written;
513 fprintf(fp, "%s", buf);
517 str_matches_selector( char* str, char* sel )
520 // fprintf(stderr, "str_matches_selector %s %s\n", str, sel);
522 // Compare str against wherever we've got to in sel.
524 while (*p != '\0' && *sel != ',' && *sel != '\0' && *p == *sel) {
527 // Match if all of str used and have reached the end of a sel fragment.
528 if (*p == '\0' && (*sel == ',' || *sel == '\0'))
531 // No match. Advance sel to the start of the next elem.
532 while (*sel != ',' && *sel != '\0') sel++;
533 if (*sel == ',') sel++;
535 /* Run out of sel ?? */
536 if (*sel == '\0') return rtsFalse;
540 // Figure out whether a closure should be counted in this census, by
541 // testing against all the specified constraints.
543 closureSatisfiesConstraints( StgClosure* p )
546 if (RtsFlags.ProfFlags.modSelector) {
547 b = str_matches_selector( ((StgClosure *)p)->header.prof.ccs->cc->module,
548 RtsFlags.ProfFlags.modSelector );
549 if (!b) return rtsFalse;
551 if (RtsFlags.ProfFlags.descrSelector) {
552 b = str_matches_selector( (get_itbl((StgClosure *)p))->prof.closure_desc,
553 RtsFlags.ProfFlags.descrSelector );
554 if (!b) return rtsFalse;
556 if (RtsFlags.ProfFlags.typeSelector) {
557 b = str_matches_selector( (get_itbl((StgClosure *)p))->prof.closure_type,
558 RtsFlags.ProfFlags.typeSelector );
559 if (!b) return rtsFalse;
561 if (RtsFlags.ProfFlags.ccSelector) {
562 b = str_matches_selector( ((StgClosure *)p)->header.prof.ccs->cc->label,
563 RtsFlags.ProfFlags.ccSelector );
564 if (!b) return rtsFalse;
566 if (RtsFlags.ProfFlags.retainerSelector) {
569 rs = retainerSetOf((StgClosure *)p);
571 for (i = 0; i < rs->num; i++) {
572 b = str_matches_selector( rs->element[i]->cc->label,
573 RtsFlags.ProfFlags.retainerSelector );
574 if (b) return rtsTrue;
581 #endif /* PROFILING */
583 /* -----------------------------------------------------------------------------
584 * Aggregate the heap census info for biographical profiling
585 * -------------------------------------------------------------------------- */
588 aggregateCensusInfo( void )
592 counter *c, *d, *ctrs;
595 if (!doingLDVProfiling()) return;
597 // Aggregate the LDV counters when displaying by biography.
598 if (RtsFlags.ProfFlags.doHeapProfile == HEAP_BY_LDV) {
599 int void_total, drag_total;
601 // Now we compute void_total and drag_total for each census
604 for (t = 1; t < era; t++) { // note: start at 1, not 0
605 void_total += censuses[t].void_total;
606 drag_total += censuses[t].drag_total;
607 censuses[t].void_total = void_total;
608 censuses[t].drag_total = drag_total;
609 ASSERT( censuses[t].void_total < censuses[t].not_used );
610 ASSERT( censuses[t].drag_total < censuses[t].used );
613 for (t = 1; t < era; t++) { // note: start at 1, not 0
614 fprintf(hp_file, "MARK %f\n", censuses[t].time);
615 fprintf(hp_file, "BEGIN_SAMPLE %f\n", censuses[t].time);
616 fprintf(hp_file, "VOID\t%u\n", censuses[t].void_total * sizeof(W_));
617 fprintf(hp_file, "LAG\t%u\n",
618 (censuses[t].not_used - censuses[t].void_total)
620 fprintf(hp_file, "USE\t%u\n",
621 (censuses[t].used - censuses[t].drag_total) * sizeof(W_));
622 fprintf(hp_file, "INHERENT_USE\t%u\n",
623 censuses[t].prim * sizeof(W_));
624 fprintf(hp_file, "DRAG\t%u\n", censuses[t].drag_total * sizeof(W_));
625 fprintf(hp_file, "END_SAMPLE %f\n", censuses[t].time);
631 // otherwise... we're doing a heap profile that is restricted to
632 // some combination of lag, drag, void or use. We've kept all the
633 // census info for all censuses so far, but we still need to
634 // aggregate the counters forwards.
637 acc = allocHashTable();
640 for (t = 1; t < era; t++) {
642 // first look through all the counters we're aggregating
643 for (c = ctrs; c != NULL; c = c->next) {
644 // if one of the totals is non-zero, then this closure
645 // type must be present in the heap at this census time...
646 d = lookupHashTable(censuses[t].hash, (StgWord)c->identity);
649 // if this closure identity isn't present in the
650 // census for this time period, then our running
651 // totals *must* be zero.
652 ASSERT(c->c.ldv.void_total == 0 && c->c.ldv.drag_total == 0);
654 // fprintCCS(stderr,c->identity);
655 // fprintf(stderr," census=%d void_total=%d drag_total=%d\n",
656 // t, c->c.ldv.void_total, c->c.ldv.drag_total);
658 d->c.ldv.void_total += c->c.ldv.void_total;
659 d->c.ldv.drag_total += c->c.ldv.drag_total;
660 c->c.ldv.void_total = d->c.ldv.void_total;
661 c->c.ldv.drag_total = d->c.ldv.drag_total;
663 ASSERT( c->c.ldv.void_total >= 0 );
664 ASSERT( c->c.ldv.drag_total >= 0 );
668 // now look through the counters in this census to find new ones
669 for (c = censuses[t].ctrs; c != NULL; c = c->next) {
670 d = lookupHashTable(acc, (StgWord)c->identity);
672 d = arenaAlloc( arena, sizeof(counter) );
674 insertHashTable( acc, (StgWord)c->identity, d );
675 d->identity = c->identity;
678 d->c.ldv.void_total = c->c.ldv.void_total;
679 d->c.ldv.drag_total = c->c.ldv.drag_total;
681 ASSERT( c->c.ldv.void_total >= 0 );
682 ASSERT( c->c.ldv.drag_total >= 0 );
686 freeHashTable(acc, NULL);
691 /* -----------------------------------------------------------------------------
692 * Print out the results of a heap census.
693 * -------------------------------------------------------------------------- */
695 dumpCensus( Census *census )
700 fprintf(hp_file, "BEGIN_SAMPLE %0.2f\n", census->time);
702 for (ctr = census->ctrs; ctr != NULL; ctr = ctr->next) {
705 if (RtsFlags.ProfFlags.bioSelector != NULL) {
707 if (str_matches_selector("lag", RtsFlags.ProfFlags.bioSelector))
708 count += ctr->c.ldv.not_used - ctr->c.ldv.void_total;
709 if (str_matches_selector("drag", RtsFlags.ProfFlags.bioSelector))
710 count += ctr->c.ldv.drag_total;
711 if (str_matches_selector("void", RtsFlags.ProfFlags.bioSelector))
712 count += ctr->c.ldv.void_total;
713 if (str_matches_selector("use", RtsFlags.ProfFlags.bioSelector))
714 count += ctr->c.ldv.used - ctr->c.ldv.drag_total;
718 count = ctr->c.resid;
721 ASSERT( count >= 0 );
723 if (count == 0) continue;
725 #ifdef DEBUG_HEAP_PROF
726 switch (RtsFlags.ProfFlags.doHeapProfile) {
727 case HEAP_BY_INFOPTR:
728 fprint_data(hp_file);
730 case HEAP_BY_CLOSURE_TYPE:
731 fprint_closure_types(hp_file);
737 switch (RtsFlags.ProfFlags.doHeapProfile) {
739 fprint_ccs(hp_file, (CostCentreStack *)ctr->identity, 30);
744 fprintf(hp_file, "%s", (char *)ctr->identity);
746 case HEAP_BY_RETAINER:
748 RetainerSet *rs = (RetainerSet *)ctr->identity;
750 // it might be the distinguished retainer set rs_MANY:
751 if (rs == &rs_MANY) {
752 fprintf(hp_file, "MANY");
756 // Mark this retainer set by negating its id, because it
757 // has appeared in at least one census. We print the
758 // values of all such retainer sets into the log file at
759 // the end. A retainer set may exist but not feature in
760 // any censuses if it arose as the intermediate retainer
761 // set for some closure during retainer set calculation.
765 // report in the unit of bytes: * sizeof(StgWord)
766 printRetainerSetShort(hp_file, rs);
770 barf("dumpCensus; doHeapProfile");
774 fprintf(hp_file, "\t%d\n", count * sizeof(W_));
777 fprintf(hp_file, "END_SAMPLE %0.2f\n", census->time);
780 /* -----------------------------------------------------------------------------
781 * Code to perform a heap census.
782 * -------------------------------------------------------------------------- */
784 heapCensusChain( Census *census, bdescr *bd )
794 for (; bd != NULL; bd = bd->link) {
796 while (p < bd->free) {
797 info = get_itbl((StgClosure *)p);
800 switch (info->type) {
806 case IND_OLDGEN_PERM:
808 case SE_CAF_BLACKHOLE:
813 case CONSTR_CHARLIKE:
827 size = sizeW_fromITBL(info);
838 size = sizeW_fromITBL(info);
841 case THUNK_1_0: /* ToDo - shouldn't be here */
842 case THUNK_0_1: /* " ditto " */
844 size = sizeofW(StgHeader) + MIN_UPD_SIZE;
849 size = pap_sizeW((StgPAP *)p);
854 size = arr_words_sizeW(stgCast(StgArrWords*,p));
858 case MUT_ARR_PTRS_FROZEN:
860 size = mut_arr_ptrs_sizeW((StgMutArrPtrs *)p);
865 size = tso_sizeW((StgTSO *)p);
874 #ifdef DEBUG_HEAP_PROF
877 // subtract the profiling overhead
878 real_size = size - sizeofW(StgProfHeader);
881 if (closureSatisfiesConstraints((StgClosure*)p)) {
883 if (RtsFlags.ProfFlags.doHeapProfile == HEAP_BY_LDV) {
885 census->prim += real_size;
886 else if ((LDVW(p) & LDV_STATE_MASK) == LDV_STATE_CREATE)
887 census->not_used += real_size;
889 census->used += real_size;
893 identity = closureIdentity((StgClosure *)p);
895 if (identity != NULL) {
896 ctr = lookupHashTable( census->hash, (StgWord)identity );
899 if (RtsFlags.ProfFlags.bioSelector != NULL) {
901 ctr->c.ldv.prim += real_size;
902 else if ((LDVW(p) & LDV_STATE_MASK) == LDV_STATE_CREATE)
903 ctr->c.ldv.not_used += real_size;
905 ctr->c.ldv.used += real_size;
909 ctr->c.resid += real_size;
912 ctr = arenaAlloc( census->arena, sizeof(counter) );
914 insertHashTable( census->hash, (StgWord)identity, ctr );
915 ctr->identity = identity;
916 ctr->next = census->ctrs;
920 if (RtsFlags.ProfFlags.bioSelector != NULL) {
922 ctr->c.ldv.prim = real_size;
923 else if ((LDVW(p) & LDV_STATE_MASK) == LDV_STATE_CREATE)
924 ctr->c.ldv.not_used = real_size;
926 ctr->c.ldv.used = real_size;
930 ctr->c.resid = real_size;
948 census = &censuses[era];
949 census->time = mut_user_time();
951 // calculate retainer sets if necessary
953 if (doingRetainerProfiling()) {
958 stat_startHeapCensus();
960 // traverse the heap, collecting the census info
961 heapCensusChain( census, small_alloc_list );
962 if (RtsFlags.GcFlags.generations == 1) {
963 heapCensusChain( census, g0s0->to_blocks );
965 for (g = 0; g < RtsFlags.GcFlags.generations; g++) {
966 for (s = 0; s < generations[g].n_steps; s++) {
967 heapCensusChain( census, generations[g].steps[s].blocks );
968 // Are we interested in large objects? might be
969 // confusing to include the stack in a heap profile.
970 // heapCensusChain( census, generations[g].steps[s].large_objects );
975 // dump out the census info
977 // We can't generate any info for LDV profiling until
978 // the end of the run...
979 if (!doingLDVProfiling())
980 dumpCensus( census );
982 dumpCensus( census );
986 // free our storage, unless we're keeping all the census info for
987 // future restriction by biography.
989 if (RtsFlags.ProfFlags.bioSelector == NULL)
992 freeHashTable( census->hash, NULL/* don't free the elements */ );
993 arenaFree( census->arena );
995 census->arena = NULL;
998 // we're into the next time period now
1001 stat_endHeapCensus();
1004 #endif /* PROFILING || DEBUG_HEAP_PROF */