1 /* -----------------------------------------------------------------------------
2 * $Id: ProfHeap.c,v 1.36 2002/05/07 04:58:15 sof 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"
33 /* -----------------------------------------------------------------------------
34 * era stores the current time period. It is the same as the
35 * number of censuses that have been performed.
38 * era must be no longer than LDV_SHIFT (15 or 30) bits.
40 * era is initialized to 1 in initHeapProfiling().
42 * max_era is initialized to 2^LDV_SHIFT in initHeapProfiling().
43 * When era reaches max_era, the profiling stops because a closure can
44 * store only up to (max_era - 1) as its creation or last use time.
45 * -------------------------------------------------------------------------- */
49 /* -----------------------------------------------------------------------------
52 * For most heap profiles each closure identity gets a simple count
53 * of live words in the heap at each census. However, if we're
54 * selecting by biography, then we have to keep the various
55 * lag/drag/void counters for each identity.
56 * -------------------------------------------------------------------------- */
57 typedef struct _counter {
62 int prim; // total size of 'inherently used' closures
63 int not_used; // total size of 'never used' closures
64 int used; // total size of 'used at least once' closures
65 int void_total; // current total size of 'destroyed without being used' closures
66 int drag_total; // current total size of 'used at least once and waiting to die'
69 struct _counter *next;
73 initLDVCtr( counter *ctr )
76 ctr->c.ldv.not_used = 0;
78 ctr->c.ldv.void_total = 0;
79 ctr->c.ldv.drag_total = 0;
83 double time; // the time in MUT time when the census is made
88 // for LDV profiling, when just displaying by LDV
96 Census *censuses = NULL;
100 static void aggregateCensusInfo( void );
103 static void dumpCensus( Census *census );
105 /* -----------------------------------------------------------------------------
106 Closure Type Profiling;
108 PROBABLY TOTALLY OUT OF DATE -- ToDo (SDM)
109 -------------------------------------------------------------------------- */
111 #ifdef DEBUG_HEAP_PROF
112 static char *type_names[] = {
118 , "CONSTR_NOCAF_STATIC"
156 , "MUT_ARR_PTRS_FROZEN"
170 #endif /* DEBUG_HEAP_PROF */
172 /* -----------------------------------------------------------------------------
173 * Find the "closure identity", which is a unique pointer reresenting
174 * the band to which this closure's heap space is attributed in the
176 * ------------------------------------------------------------------------- */
178 closureIdentity( StgClosure *p )
180 switch (RtsFlags.ProfFlags.doHeapProfile) {
184 return p->header.prof.ccs;
186 return p->header.prof.ccs->cc->module;
188 return get_itbl(p)->prof.closure_desc;
190 return get_itbl(p)->prof.closure_type;
191 case HEAP_BY_RETAINER:
192 // AFAIK, the only closures in the heap which might not have a
193 // valid retainer set are DEAD_WEAK closures.
194 if (isRetainerSetFieldValid(p))
195 return retainerSetOf(p);
200 case HEAP_BY_INFOPTR:
201 return (void *)((StgClosure *)p)->header.info;
202 case HEAP_BY_CLOSURE_TYPE:
203 return type_names[get_itbl(p)->type];
207 barf("closureIdentity");
211 /* --------------------------------------------------------------------------
212 * Profiling type predicates
213 * ----------------------------------------------------------------------- */
215 static inline rtsBool
216 doingLDVProfiling( void )
218 return (RtsFlags.ProfFlags.doHeapProfile == HEAP_BY_LDV
219 || RtsFlags.ProfFlags.bioSelector != NULL);
222 static inline rtsBool
223 doingRetainerProfiling( void )
225 return (RtsFlags.ProfFlags.doHeapProfile == HEAP_BY_RETAINER
226 || RtsFlags.ProfFlags.retainerSelector != NULL);
230 // Precesses a closure 'c' being destroyed whose size is 'size'.
231 // Make sure that LDV_recordDead() is not invoked on 'inherently used' closures
232 // such as TSO; they should not be involved in computing dragNew or voidNew.
234 // Even though era is checked in both LdvCensusForDead() and
235 // LdvCensusKillAll(), we still need to make sure that era is > 0 because
236 // LDV_recordDead() may be called from elsewhere in the runtime system. E.g.,
237 // when a thunk is replaced by an indirection object.
241 LDV_recordDead( StgClosure *c, nat size )
247 if (era > 0 && closureSatisfiesConstraints(c)) {
248 size -= sizeofW(StgProfHeader);
249 if ((LDVW((c)) & LDV_STATE_MASK) == LDV_STATE_CREATE) {
250 t = (LDVW((c)) & LDV_CREATE_MASK) >> LDV_SHIFT;
252 if (RtsFlags.ProfFlags.bioSelector == NULL) {
253 censuses[t].void_total += (int)size;
254 censuses[era].void_total -= (int)size;
256 id = closureIdentity(c);
257 ctr = lookupHashTable(censuses[t].hash, (StgWord)id);
258 ASSERT( ctr != NULL );
259 ctr->c.ldv.void_total += (int)size;
260 ctr = lookupHashTable(censuses[era].hash, (StgWord)id);
262 ctr = arenaAlloc(censuses[era].arena, sizeof(counter));
264 insertHashTable(censuses[era].hash, (StgWord)id, ctr);
266 ctr->next = censuses[era].ctrs;
267 censuses[era].ctrs = ctr;
269 ctr->c.ldv.void_total -= (int)size;
273 t = LDVW((c)) & LDV_LAST_MASK;
275 if (RtsFlags.ProfFlags.bioSelector == NULL) {
276 censuses[t+1].drag_total += size;
277 censuses[era].drag_total -= size;
280 id = closureIdentity(c);
281 ctr = lookupHashTable(censuses[t+1].hash, (StgWord)id);
282 ASSERT( ctr != NULL );
283 ctr->c.ldv.drag_total += (int)size;
284 ctr = lookupHashTable(censuses[era].hash, (StgWord)id);
286 ctr = arenaAlloc(censuses[era].arena, sizeof(counter));
288 insertHashTable(censuses[era].hash, (StgWord)id, ctr);
290 ctr->next = censuses[era].ctrs;
291 censuses[era].ctrs = ctr;
293 ctr->c.ldv.drag_total -= (int)size;
301 /* --------------------------------------------------------------------------
302 * Initialize censuses[era];
303 * ----------------------------------------------------------------------- */
305 initEra(Census *census)
307 census->hash = allocHashTable();
309 census->arena = newArena();
311 census->not_used = 0;
314 census->void_total = 0;
315 census->drag_total = 0;
318 /* --------------------------------------------------------------------------
319 * Increases era by 1 and initialize census[era].
320 * Reallocates gi[] and increases its size if needed.
321 * ----------------------------------------------------------------------- */
326 if (doingLDVProfiling()) {
329 if (era == max_era) {
330 barf("maximum number of censuses reached; use +RTS -i to reduce");
333 if (era == n_censuses) {
335 censuses = stgReallocBytes(censuses, sizeof(Census) * n_censuses,
341 initEra( &censuses[era] );
344 /* -----------------------------------------------------------------------------
345 * DEBUG heap profiling, by info table
346 * -------------------------------------------------------------------------- */
348 #ifdef DEBUG_HEAP_PROF
351 void initProfiling1( void )
355 void initProfiling2( void )
360 void endProfiling( void )
364 #endif /* DEBUG_HEAP_PROF */
366 /* --------------------------------------------------------------------------
367 * Initialize the heap profilier
368 * ----------------------------------------------------------------------- */
370 initHeapProfiling(void)
372 if (! RtsFlags.ProfFlags.doHeapProfile) {
377 if (doingLDVProfiling() && doingRetainerProfiling()) {
378 prog_belch("cannot mix -hb and -hr");
383 // we only count eras if we're doing LDV profiling. Otherwise era
386 if (doingLDVProfiling()) {
394 { // max_era = 2^LDV_SHIFT
397 for (p = 0; p < LDV_SHIFT; p++)
402 censuses = stgMallocBytes(sizeof(Census) * n_censuses, "initHeapProfiling");
404 initEra( &censuses[era] );
406 fprintf(hp_file, "JOB \"%s", prog_argv[0]);
411 for(count = 1; count < prog_argc; count++)
412 fprintf(hp_file, " %s", prog_argv[count]);
413 fprintf(hp_file, " +RTS ");
414 for(count = 0; count < rts_argc; count++)
415 fprintf(hp_file, "%s ", rts_argv[count]);
416 fprintf(hp_file, "\n");
418 #endif /* PROFILING */
420 fprintf(hp_file, "\"\n" );
422 fprintf(hp_file, "DATE \"%s\"\n", time_str());
424 fprintf(hp_file, "SAMPLE_UNIT \"seconds\"\n");
425 fprintf(hp_file, "VALUE_UNIT \"bytes\"\n");
427 fprintf(hp_file, "BEGIN_SAMPLE 0.00\n");
428 fprintf(hp_file, "END_SAMPLE 0.00\n");
430 #ifdef DEBUG_HEAP_PROF
431 DEBUG_LoadSymbols(prog_argv[0]);
435 if (doingRetainerProfiling()) {
436 initRetainerProfiling();
444 endHeapProfiling(void)
448 if (! RtsFlags.ProfFlags.doHeapProfile) {
453 if (doingRetainerProfiling()) {
454 endRetainerProfiling();
459 if (doingLDVProfiling()) {
462 aggregateCensusInfo();
463 for (t = 1; t < era; t++) {
464 dumpCensus( &censuses[t] );
469 seconds = mut_user_time();
470 fprintf(hp_file, "BEGIN_SAMPLE %0.2f\n", seconds);
471 fprintf(hp_file, "END_SAMPLE %0.2f\n", seconds);
479 fprint_ccs(FILE *fp, CostCentreStack *ccs, nat max_length)
481 char buf[max_length+1];
486 // MAIN on its own gets printed as "MAIN", otherwise we ignore MAIN.
487 if (ccs == CCS_MAIN) {
492 fprintf(fp, "(%d)", ccs->ccsID);
494 // keep printing components of the stack until we run out of space
495 // in the buffer. If we run out of space, end with "...".
496 for (; ccs != NULL && ccs != CCS_MAIN; ccs = ccs->prevStack) {
498 // CAF cost centres print as M.CAF, but we leave the module
499 // name out of all the others to save space.
500 if (!strcmp(ccs->cc->label,"CAF")) {
502 written = snprintf(buf+next_offset,
503 (int)max_length-3-(int)next_offset,
504 "%s.CAF", ccs->cc->module);
506 written = sprintf(buf+next_offset,
507 "%s.CAF", ccs->cc->module);
510 if (ccs->prevStack != NULL && ccs->prevStack != CCS_MAIN) {
516 written = snprintf(buf+next_offset,
517 (int)max_length-3-(int)next_offset,
518 template, ccs->cc->label);
520 written = sprintf(buf+next_offset,
521 template, ccs->cc->label);
525 if (next_offset+written >= max_length-4) {
526 sprintf(buf+max_length-4, "...");
529 next_offset += written;
532 fprintf(fp, "%s", buf);
537 strMatchesSelector( char* str, char* sel )
540 // fprintf(stderr, "str_matches_selector %s %s\n", str, sel);
542 // Compare str against wherever we've got to in sel.
544 while (*p != '\0' && *sel != ',' && *sel != '\0' && *p == *sel) {
547 // Match if all of str used and have reached the end of a sel fragment.
548 if (*p == '\0' && (*sel == ',' || *sel == '\0'))
551 // No match. Advance sel to the start of the next elem.
552 while (*sel != ',' && *sel != '\0') sel++;
553 if (*sel == ',') sel++;
555 /* Run out of sel ?? */
556 if (*sel == '\0') return rtsFalse;
560 /* -----------------------------------------------------------------------------
561 * Figure out whether a closure should be counted in this census, by
562 * testing against all the specified constraints.
563 * -------------------------------------------------------------------------- */
565 closureSatisfiesConstraints( StgClosure* p )
567 #ifdef DEBUG_HEAP_PROF
572 // The CCS has a selected field to indicate whether this closure is
573 // deselected by not being mentioned in the module, CC, or CCS
575 if (!p->header.prof.ccs->selected) {
579 if (RtsFlags.ProfFlags.descrSelector) {
580 b = strMatchesSelector( (get_itbl((StgClosure *)p))->prof.closure_desc,
581 RtsFlags.ProfFlags.descrSelector );
582 if (!b) return rtsFalse;
584 if (RtsFlags.ProfFlags.typeSelector) {
585 b = strMatchesSelector( (get_itbl((StgClosure *)p))->prof.closure_type,
586 RtsFlags.ProfFlags.typeSelector );
587 if (!b) return rtsFalse;
589 if (RtsFlags.ProfFlags.retainerSelector) {
592 rs = retainerSetOf((StgClosure *)p);
594 for (i = 0; i < rs->num; i++) {
595 b = strMatchesSelector( rs->element[i]->cc->label,
596 RtsFlags.ProfFlags.retainerSelector );
597 if (b) return rtsTrue;
603 #endif /* PROFILING */
606 /* -----------------------------------------------------------------------------
607 * Aggregate the heap census info for biographical profiling
608 * -------------------------------------------------------------------------- */
611 aggregateCensusInfo( void )
615 counter *c, *d, *ctrs;
618 if (!doingLDVProfiling()) return;
620 // Aggregate the LDV counters when displaying by biography.
621 if (RtsFlags.ProfFlags.doHeapProfile == HEAP_BY_LDV) {
622 int void_total, drag_total;
624 // Now we compute void_total and drag_total for each census
627 for (t = 1; t < era; t++) { // note: start at 1, not 0
628 void_total += censuses[t].void_total;
629 drag_total += censuses[t].drag_total;
630 censuses[t].void_total = void_total;
631 censuses[t].drag_total = drag_total;
632 ASSERT( censuses[t].void_total <= censuses[t].not_used );
633 ASSERT( censuses[t].drag_total <= censuses[t].used );
639 // otherwise... we're doing a heap profile that is restricted to
640 // some combination of lag, drag, void or use. We've kept all the
641 // census info for all censuses so far, but we still need to
642 // aggregate the counters forwards.
645 acc = allocHashTable();
648 for (t = 1; t < era; t++) {
650 // first look through all the counters we're aggregating
651 for (c = ctrs; c != NULL; c = c->next) {
652 // if one of the totals is non-zero, then this closure
653 // type must be present in the heap at this census time...
654 d = lookupHashTable(censuses[t].hash, (StgWord)c->identity);
657 // if this closure identity isn't present in the
658 // census for this time period, then our running
659 // totals *must* be zero.
660 ASSERT(c->c.ldv.void_total == 0 && c->c.ldv.drag_total == 0);
662 // fprintCCS(stderr,c->identity);
663 // fprintf(stderr," census=%d void_total=%d drag_total=%d\n",
664 // t, c->c.ldv.void_total, c->c.ldv.drag_total);
666 d->c.ldv.void_total += c->c.ldv.void_total;
667 d->c.ldv.drag_total += c->c.ldv.drag_total;
668 c->c.ldv.void_total = d->c.ldv.void_total;
669 c->c.ldv.drag_total = d->c.ldv.drag_total;
671 ASSERT( c->c.ldv.void_total >= 0 );
672 ASSERT( c->c.ldv.drag_total >= 0 );
676 // now look through the counters in this census to find new ones
677 for (c = censuses[t].ctrs; c != NULL; c = c->next) {
678 d = lookupHashTable(acc, (StgWord)c->identity);
680 d = arenaAlloc( arena, sizeof(counter) );
682 insertHashTable( acc, (StgWord)c->identity, d );
683 d->identity = c->identity;
686 d->c.ldv.void_total = c->c.ldv.void_total;
687 d->c.ldv.drag_total = c->c.ldv.drag_total;
689 ASSERT( c->c.ldv.void_total >= 0 );
690 ASSERT( c->c.ldv.drag_total >= 0 );
694 freeHashTable(acc, NULL);
699 /* -----------------------------------------------------------------------------
700 * Print out the results of a heap census.
701 * -------------------------------------------------------------------------- */
703 dumpCensus( Census *census )
708 fprintf(hp_file, "BEGIN_SAMPLE %0.2f\n", census->time);
711 if (RtsFlags.ProfFlags.doHeapProfile == HEAP_BY_LDV) {
712 fprintf(hp_file, "VOID\t%u\n", census->void_total * sizeof(W_));
713 fprintf(hp_file, "LAG\t%u\n",
714 (census->not_used - census->void_total) * sizeof(W_));
715 fprintf(hp_file, "USE\t%u\n",
716 (census->used - census->drag_total) * sizeof(W_));
717 fprintf(hp_file, "INHERENT_USE\t%u\n",
718 census->prim * sizeof(W_));
719 fprintf(hp_file, "DRAG\t%u\n", census->drag_total *
721 fprintf(hp_file, "END_SAMPLE %0.2f\n", census->time);
726 for (ctr = census->ctrs; ctr != NULL; ctr = ctr->next) {
729 if (RtsFlags.ProfFlags.bioSelector != NULL) {
731 if (strMatchesSelector("lag", RtsFlags.ProfFlags.bioSelector))
732 count += ctr->c.ldv.not_used - ctr->c.ldv.void_total;
733 if (strMatchesSelector("drag", RtsFlags.ProfFlags.bioSelector))
734 count += ctr->c.ldv.drag_total;
735 if (strMatchesSelector("void", RtsFlags.ProfFlags.bioSelector))
736 count += ctr->c.ldv.void_total;
737 if (strMatchesSelector("use", RtsFlags.ProfFlags.bioSelector))
738 count += ctr->c.ldv.used - ctr->c.ldv.drag_total;
742 count = ctr->c.resid;
745 ASSERT( count >= 0 );
747 if (count == 0) continue;
749 #ifdef DEBUG_HEAP_PROF
750 switch (RtsFlags.ProfFlags.doHeapProfile) {
751 case HEAP_BY_INFOPTR:
752 fprintf(hp_file, "%s", lookupGHCName(ctr->identity));
754 case HEAP_BY_CLOSURE_TYPE:
755 fprintf(hp_file, "%s", (char *)ctr->identity);
761 switch (RtsFlags.ProfFlags.doHeapProfile) {
763 fprint_ccs(hp_file, (CostCentreStack *)ctr->identity, 25);
768 fprintf(hp_file, "%s", (char *)ctr->identity);
770 case HEAP_BY_RETAINER:
772 RetainerSet *rs = (RetainerSet *)ctr->identity;
774 // it might be the distinguished retainer set rs_MANY:
775 if (rs == &rs_MANY) {
776 fprintf(hp_file, "MANY");
780 // Mark this retainer set by negating its id, because it
781 // has appeared in at least one census. We print the
782 // values of all such retainer sets into the log file at
783 // the end. A retainer set may exist but not feature in
784 // any censuses if it arose as the intermediate retainer
785 // set for some closure during retainer set calculation.
789 // report in the unit of bytes: * sizeof(StgWord)
790 printRetainerSetShort(hp_file, rs);
794 barf("dumpCensus; doHeapProfile");
798 fprintf(hp_file, "\t%d\n", count * sizeof(W_));
801 fprintf(hp_file, "END_SAMPLE %0.2f\n", census->time);
804 /* -----------------------------------------------------------------------------
805 * Code to perform a heap census.
806 * -------------------------------------------------------------------------- */
808 heapCensusChain( Census *census, bdescr *bd )
818 for (; bd != NULL; bd = bd->link) {
820 while (p < bd->free) {
821 info = get_itbl((StgClosure *)p);
824 switch (info->type) {
830 case IND_OLDGEN_PERM:
832 case SE_CAF_BLACKHOLE:
837 case CONSTR_CHARLIKE:
851 size = sizeW_fromITBL(info);
862 size = sizeW_fromITBL(info);
865 case THUNK_1_0: /* ToDo - shouldn't be here */
866 case THUNK_0_1: /* " ditto " */
868 size = sizeofW(StgHeader) + MIN_UPD_SIZE;
873 size = pap_sizeW((StgPAP *)p);
878 size = arr_words_sizeW(stgCast(StgArrWords*,p));
882 case MUT_ARR_PTRS_FROZEN:
884 size = mut_arr_ptrs_sizeW((StgMutArrPtrs *)p);
889 size = tso_sizeW((StgTSO *)p);
898 #ifdef DEBUG_HEAP_PROF
901 // subtract the profiling overhead
902 real_size = size - sizeofW(StgProfHeader);
905 if (closureSatisfiesConstraints((StgClosure*)p)) {
907 if (RtsFlags.ProfFlags.doHeapProfile == HEAP_BY_LDV) {
909 census->prim += real_size;
910 else if ((LDVW(p) & LDV_STATE_MASK) == LDV_STATE_CREATE)
911 census->not_used += real_size;
913 census->used += real_size;
917 identity = closureIdentity((StgClosure *)p);
919 if (identity != NULL) {
920 ctr = lookupHashTable( census->hash, (StgWord)identity );
923 if (RtsFlags.ProfFlags.bioSelector != NULL) {
925 ctr->c.ldv.prim += real_size;
926 else if ((LDVW(p) & LDV_STATE_MASK) == LDV_STATE_CREATE)
927 ctr->c.ldv.not_used += real_size;
929 ctr->c.ldv.used += real_size;
933 ctr->c.resid += real_size;
936 ctr = arenaAlloc( census->arena, sizeof(counter) );
938 insertHashTable( census->hash, (StgWord)identity, ctr );
939 ctr->identity = identity;
940 ctr->next = census->ctrs;
944 if (RtsFlags.ProfFlags.bioSelector != NULL) {
946 ctr->c.ldv.prim = real_size;
947 else if ((LDVW(p) & LDV_STATE_MASK) == LDV_STATE_CREATE)
948 ctr->c.ldv.not_used = real_size;
950 ctr->c.ldv.used = real_size;
954 ctr->c.resid = real_size;
972 census = &censuses[era];
973 census->time = mut_user_time();
975 // calculate retainer sets if necessary
977 if (doingRetainerProfiling()) {
983 stat_startHeapCensus();
986 // traverse the heap, collecting the census info
987 heapCensusChain( census, small_alloc_list );
988 if (RtsFlags.GcFlags.generations == 1) {
989 heapCensusChain( census, g0s0->to_blocks );
991 for (g = 0; g < RtsFlags.GcFlags.generations; g++) {
992 for (s = 0; s < generations[g].n_steps; s++) {
993 heapCensusChain( census, generations[g].steps[s].blocks );
994 // Are we interested in large objects? might be
995 // confusing to include the stack in a heap profile.
996 // heapCensusChain( census, generations[g].steps[s].large_objects );
1001 // dump out the census info
1003 // We can't generate any info for LDV profiling until
1004 // the end of the run...
1005 if (!doingLDVProfiling())
1006 dumpCensus( census );
1008 dumpCensus( census );
1012 // free our storage, unless we're keeping all the census info for
1013 // future restriction by biography.
1015 if (RtsFlags.ProfFlags.bioSelector == NULL)
1018 freeHashTable( census->hash, NULL/* don't free the elements */ );
1019 arenaFree( census->arena );
1020 census->hash = NULL;
1021 census->arena = NULL;
1024 // we're into the next time period now
1028 stat_endHeapCensus();
1032 #endif /* PROFILING || DEBUG_HEAP_PROF */