1 /* -----------------------------------------------------------------------------
2 * $Id: ProfHeap.c,v 1.31 2001/11/28 17:45:13 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"
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 0 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 ((StgClosure *)p)->header.prof.ccs;
186 return ((StgClosure *)p)->header.prof.ccs->cc->module;
188 return (get_itbl((StgClosure *)p))->prof.closure_desc;
190 return (get_itbl((StgClosure *)p))->prof.closure_type;
191 case HEAP_BY_RETAINER:
192 return retainerSetOf((StgClosure *)p);
194 case HEAP_BY_INFOPTR:
195 return (void *)((StgClosure *)p)->header.info;
196 case HEAP_BY_CLOSURE_TYPE:
197 return type_names[get_itbl(p)->type];
200 barf("closureIdentity");
204 /* --------------------------------------------------------------------------
205 * Profiling type predicates
206 * ----------------------------------------------------------------------- */
208 static inline rtsBool
209 doingLDVProfiling( void )
211 return (RtsFlags.ProfFlags.doHeapProfile == HEAP_BY_LDV
212 || RtsFlags.ProfFlags.bioSelector != NULL);
215 static inline rtsBool
216 doingRetainerProfiling( void )
218 return (RtsFlags.ProfFlags.doHeapProfile == HEAP_BY_RETAINER
219 || RtsFlags.ProfFlags.retainerSelector != NULL);
223 // Precesses a closure 'c' being destroyed whose size is 'size'.
224 // Make sure that LDV_recordDead() is not invoked on 'inherently used' closures
225 // such as TSO; they should not be involved in computing dragNew or voidNew.
227 // Even though era is checked in both LdvCensusForDead() and
228 // LdvCensusKillAll(), we still need to make sure that era is > 0 because
229 // LDV_recordDead() may be called from elsewhere in the runtime system. E.g.,
230 // when a thunk is replaced by an indirection object.
234 LDV_recordDead( StgClosure *c, nat size )
240 if (era > 0 && closureSatisfiesConstraints(c)) {
241 size -= sizeofW(StgProfHeader);
242 if ((LDVW((c)) & LDV_STATE_MASK) == LDV_STATE_CREATE) {
243 t = (LDVW((c)) & LDV_CREATE_MASK) >> LDV_SHIFT;
245 if (RtsFlags.ProfFlags.bioSelector == NULL) {
246 censuses[t].void_total += (int)size;
247 censuses[era].void_total -= (int)size;
249 id = closureIdentity(c);
250 ctr = lookupHashTable(censuses[t].hash, (StgWord)id);
251 ASSERT( ctr != NULL );
252 ctr->c.ldv.void_total += (int)size;
253 ctr = lookupHashTable(censuses[era].hash, (StgWord)id);
255 ctr = arenaAlloc(censuses[era].arena, sizeof(counter));
257 insertHashTable(censuses[era].hash, (StgWord)id, ctr);
259 ctr->next = censuses[era].ctrs;
260 censuses[era].ctrs = ctr;
262 ctr->c.ldv.void_total -= (int)size;
266 t = LDVW((c)) & LDV_LAST_MASK;
268 if (RtsFlags.ProfFlags.bioSelector == NULL) {
269 censuses[t+1].drag_total += size;
270 censuses[era].drag_total -= size;
273 id = closureIdentity(c);
274 ctr = lookupHashTable(censuses[t+1].hash, (StgWord)id);
275 ASSERT( ctr != NULL );
276 ctr->c.ldv.drag_total += (int)size;
277 ctr = lookupHashTable(censuses[era].hash, (StgWord)id);
279 ctr = arenaAlloc(censuses[era].arena, sizeof(counter));
281 insertHashTable(censuses[era].hash, (StgWord)id, ctr);
283 ctr->next = censuses[era].ctrs;
284 censuses[era].ctrs = ctr;
286 ctr->c.ldv.drag_total -= (int)size;
294 /* --------------------------------------------------------------------------
295 * Initialize censuses[era];
296 * ----------------------------------------------------------------------- */
298 initEra(Census *census)
300 census->hash = allocHashTable();
302 census->arena = newArena();
304 census->not_used = 0;
307 census->void_total = 0;
308 census->drag_total = 0;
311 /* --------------------------------------------------------------------------
312 * Increases era by 1 and initialize census[era].
313 * Reallocates gi[] and increases its size if needed.
314 * ----------------------------------------------------------------------- */
319 if (doingLDVProfiling()) {
322 if (era == max_era) {
323 barf("maximum number of censuses reached; use +RTS -i to reduce");
326 if (era == n_censuses) {
328 censuses = stgReallocBytes(censuses, sizeof(Census) * n_censuses,
334 initEra( &censuses[era] );
337 /* -----------------------------------------------------------------------------
338 * DEBUG heap profiling, by info table
339 * -------------------------------------------------------------------------- */
341 #ifdef DEBUG_HEAP_PROF
344 void initProfiling1( void )
348 void initProfiling2( void )
353 void endProfiling( void )
357 #endif /* DEBUG_HEAP_PROF */
359 /* --------------------------------------------------------------------------
360 * Initialize the heap profilier
361 * ----------------------------------------------------------------------- */
363 initHeapProfiling(void)
365 if (! RtsFlags.ProfFlags.doHeapProfile) {
369 // we only count eras if we're doing LDV profiling. Otherwise era
372 if (doingLDVProfiling()) {
380 { // max_era = 2^LDV_SHIFT
383 for (p = 0; p < LDV_SHIFT; p++)
388 censuses = stgMallocBytes(sizeof(Census) * n_censuses, "initHeapProfiling");
390 initEra( &censuses[era] );
392 fprintf(hp_file, "JOB \"%s", prog_argv[0]);
397 for(count = 1; count < prog_argc; count++)
398 fprintf(hp_file, " %s", prog_argv[count]);
399 fprintf(hp_file, " +RTS ");
400 for(count = 0; count < rts_argc; count++)
401 fprintf(hp_file, "%s ", rts_argv[count]);
402 fprintf(hp_file, "\n");
404 #endif /* PROFILING */
406 fprintf(hp_file, "\"\n" );
408 fprintf(hp_file, "DATE \"%s\"\n", time_str());
410 fprintf(hp_file, "SAMPLE_UNIT \"seconds\"\n");
411 fprintf(hp_file, "VALUE_UNIT \"bytes\"\n");
413 fprintf(hp_file, "BEGIN_SAMPLE 0.00\n");
414 fprintf(hp_file, "END_SAMPLE 0.00\n");
416 #ifdef DEBUG_HEAP_PROF
417 DEBUG_LoadSymbols(prog_argv[0]);
421 if (doingRetainerProfiling()) {
422 initRetainerProfiling();
430 endHeapProfiling(void)
434 if (! RtsFlags.ProfFlags.doHeapProfile) {
439 if (doingRetainerProfiling()) {
440 endRetainerProfiling();
446 // We do not need to perform a major garbage collection because all the
447 // closures created since the last census will not affect the profiling
448 // statistics anyhow.
449 if (RtsFlags.ProfFlags.doHeapProfile == HEAP_BY_LDV)
454 if (doingLDVProfiling()) {
456 aggregateCensusInfo();
457 for (t = 1; t < era; t++) {
458 dumpCensus( &censuses[t] );
463 seconds = mut_user_time();
464 fprintf(hp_file, "BEGIN_SAMPLE %0.2f\n", seconds);
465 fprintf(hp_file, "END_SAMPLE %0.2f\n", seconds);
473 fprint_ccs(FILE *fp, CostCentreStack *ccs, nat max_length)
475 char buf[max_length+1];
480 // MAIN on its own gets printed as "MAIN", otherwise we ignore MAIN.
481 if (ccs == CCS_MAIN) {
486 // keep printing components of the stack until we run out of space
487 // in the buffer. If we run out of space, end with "...".
488 for (; ccs != NULL && ccs != CCS_MAIN; ccs = ccs->prevStack) {
490 // CAF cost centres print as M.CAF, but we leave the module
491 // name out of all the others to save space.
492 if (!strcmp(ccs->cc->label,"CAF")) {
493 written = snprintf(buf+next_offset,
494 (int)max_length-3-(int)next_offset,
495 "%s.CAF", ccs->cc->module);
497 if (ccs->prevStack != NULL && ccs->prevStack != CCS_MAIN) {
502 written = snprintf(buf+next_offset,
503 (int)max_length-3-(int)next_offset,
504 template, ccs->cc->label);
507 if (next_offset+written >= max_length-4) {
508 sprintf(buf+max_length-4, "...");
511 next_offset += written;
514 fprintf(fp, "%s", buf);
518 str_matches_selector( char* str, char* sel )
521 // fprintf(stderr, "str_matches_selector %s %s\n", str, sel);
523 // Compare str against wherever we've got to in sel.
525 while (*p != '\0' && *sel != ',' && *sel != '\0' && *p == *sel) {
528 // Match if all of str used and have reached the end of a sel fragment.
529 if (*p == '\0' && (*sel == ',' || *sel == '\0'))
532 // No match. Advance sel to the start of the next elem.
533 while (*sel != ',' && *sel != '\0') sel++;
534 if (*sel == ',') sel++;
536 /* Run out of sel ?? */
537 if (*sel == '\0') return rtsFalse;
542 /* -----------------------------------------------------------------------------
543 * Figure out whether a closure should be counted in this census, by
544 * testing against all the specified constraints.
545 * -------------------------------------------------------------------------- */
547 closureSatisfiesConstraints( StgClosure* p )
549 #ifdef DEBUG_HEAP_PROF
553 if (RtsFlags.ProfFlags.modSelector) {
554 b = str_matches_selector( ((StgClosure *)p)->header.prof.ccs->cc->module,
555 RtsFlags.ProfFlags.modSelector );
556 if (!b) return rtsFalse;
558 if (RtsFlags.ProfFlags.descrSelector) {
559 b = str_matches_selector( (get_itbl((StgClosure *)p))->prof.closure_desc,
560 RtsFlags.ProfFlags.descrSelector );
561 if (!b) return rtsFalse;
563 if (RtsFlags.ProfFlags.typeSelector) {
564 b = str_matches_selector( (get_itbl((StgClosure *)p))->prof.closure_type,
565 RtsFlags.ProfFlags.typeSelector );
566 if (!b) return rtsFalse;
568 if (RtsFlags.ProfFlags.ccSelector) {
569 b = str_matches_selector( ((StgClosure *)p)->header.prof.ccs->cc->label,
570 RtsFlags.ProfFlags.ccSelector );
571 if (!b) return rtsFalse;
573 if (RtsFlags.ProfFlags.retainerSelector) {
576 rs = retainerSetOf((StgClosure *)p);
578 for (i = 0; i < rs->num; i++) {
579 b = str_matches_selector( rs->element[i]->cc->label,
580 RtsFlags.ProfFlags.retainerSelector );
581 if (b) return rtsTrue;
587 #endif /* PROFILING */
590 /* -----------------------------------------------------------------------------
591 * Aggregate the heap census info for biographical profiling
592 * -------------------------------------------------------------------------- */
595 aggregateCensusInfo( void )
599 counter *c, *d, *ctrs;
602 if (!doingLDVProfiling()) return;
604 // Aggregate the LDV counters when displaying by biography.
605 if (RtsFlags.ProfFlags.doHeapProfile == HEAP_BY_LDV) {
606 int void_total, drag_total;
608 // Now we compute void_total and drag_total for each census
611 for (t = 1; t < era; t++) { // note: start at 1, not 0
612 void_total += censuses[t].void_total;
613 drag_total += censuses[t].drag_total;
614 censuses[t].void_total = void_total;
615 censuses[t].drag_total = drag_total;
616 ASSERT( censuses[t].void_total < censuses[t].not_used );
617 ASSERT( censuses[t].drag_total < censuses[t].used );
623 // otherwise... we're doing a heap profile that is restricted to
624 // some combination of lag, drag, void or use. We've kept all the
625 // census info for all censuses so far, but we still need to
626 // aggregate the counters forwards.
629 acc = allocHashTable();
632 for (t = 1; t < era; t++) {
634 // first look through all the counters we're aggregating
635 for (c = ctrs; c != NULL; c = c->next) {
636 // if one of the totals is non-zero, then this closure
637 // type must be present in the heap at this census time...
638 d = lookupHashTable(censuses[t].hash, (StgWord)c->identity);
641 // if this closure identity isn't present in the
642 // census for this time period, then our running
643 // totals *must* be zero.
644 ASSERT(c->c.ldv.void_total == 0 && c->c.ldv.drag_total == 0);
646 // fprintCCS(stderr,c->identity);
647 // fprintf(stderr," census=%d void_total=%d drag_total=%d\n",
648 // t, c->c.ldv.void_total, c->c.ldv.drag_total);
650 d->c.ldv.void_total += c->c.ldv.void_total;
651 d->c.ldv.drag_total += c->c.ldv.drag_total;
652 c->c.ldv.void_total = d->c.ldv.void_total;
653 c->c.ldv.drag_total = d->c.ldv.drag_total;
655 ASSERT( c->c.ldv.void_total >= 0 );
656 ASSERT( c->c.ldv.drag_total >= 0 );
660 // now look through the counters in this census to find new ones
661 for (c = censuses[t].ctrs; c != NULL; c = c->next) {
662 d = lookupHashTable(acc, (StgWord)c->identity);
664 d = arenaAlloc( arena, sizeof(counter) );
666 insertHashTable( acc, (StgWord)c->identity, d );
667 d->identity = c->identity;
670 d->c.ldv.void_total = c->c.ldv.void_total;
671 d->c.ldv.drag_total = c->c.ldv.drag_total;
673 ASSERT( c->c.ldv.void_total >= 0 );
674 ASSERT( c->c.ldv.drag_total >= 0 );
678 freeHashTable(acc, NULL);
683 /* -----------------------------------------------------------------------------
684 * Print out the results of a heap census.
685 * -------------------------------------------------------------------------- */
687 dumpCensus( Census *census )
692 fprintf(hp_file, "BEGIN_SAMPLE %0.2f\n", census->time);
695 if (RtsFlags.ProfFlags.doHeapProfile == HEAP_BY_LDV) {
696 fprintf(hp_file, "VOID\t%u\n", census->void_total * sizeof(W_));
697 fprintf(hp_file, "LAG\t%u\n",
698 (census->not_used - census->void_total) * sizeof(W_));
699 fprintf(hp_file, "USE\t%u\n",
700 (census->used - census->drag_total) * sizeof(W_));
701 fprintf(hp_file, "INHERENT_USE\t%u\n",
702 census->prim * sizeof(W_));
703 fprintf(hp_file, "DRAG\t%u\n", census->drag_total *
705 fprintf(hp_file, "END_SAMPLE %0.2f\n", census->time);
710 for (ctr = census->ctrs; ctr != NULL; ctr = ctr->next) {
713 if (RtsFlags.ProfFlags.bioSelector != NULL) {
715 if (str_matches_selector("lag", RtsFlags.ProfFlags.bioSelector))
716 count += ctr->c.ldv.not_used - ctr->c.ldv.void_total;
717 if (str_matches_selector("drag", RtsFlags.ProfFlags.bioSelector))
718 count += ctr->c.ldv.drag_total;
719 if (str_matches_selector("void", RtsFlags.ProfFlags.bioSelector))
720 count += ctr->c.ldv.void_total;
721 if (str_matches_selector("use", RtsFlags.ProfFlags.bioSelector))
722 count += ctr->c.ldv.used - ctr->c.ldv.drag_total;
726 count = ctr->c.resid;
729 ASSERT( count >= 0 );
731 if (count == 0) continue;
733 #ifdef DEBUG_HEAP_PROF
734 switch (RtsFlags.ProfFlags.doHeapProfile) {
735 case HEAP_BY_INFOPTR:
736 fprintf(hp_file, "%s", lookupGHCName(ctr->identity));
738 case HEAP_BY_CLOSURE_TYPE:
739 fprintf(hp_file, "%s", (char *)ctr->identity);
745 switch (RtsFlags.ProfFlags.doHeapProfile) {
747 fprint_ccs(hp_file, (CostCentreStack *)ctr->identity, 30);
752 fprintf(hp_file, "%s", (char *)ctr->identity);
754 case HEAP_BY_RETAINER:
756 RetainerSet *rs = (RetainerSet *)ctr->identity;
758 // it might be the distinguished retainer set rs_MANY:
759 if (rs == &rs_MANY) {
760 fprintf(hp_file, "MANY");
764 // Mark this retainer set by negating its id, because it
765 // has appeared in at least one census. We print the
766 // values of all such retainer sets into the log file at
767 // the end. A retainer set may exist but not feature in
768 // any censuses if it arose as the intermediate retainer
769 // set for some closure during retainer set calculation.
773 // report in the unit of bytes: * sizeof(StgWord)
774 printRetainerSetShort(hp_file, rs);
778 barf("dumpCensus; doHeapProfile");
782 fprintf(hp_file, "\t%d\n", count * sizeof(W_));
785 fprintf(hp_file, "END_SAMPLE %0.2f\n", census->time);
788 /* -----------------------------------------------------------------------------
789 * Code to perform a heap census.
790 * -------------------------------------------------------------------------- */
792 heapCensusChain( Census *census, bdescr *bd )
802 for (; bd != NULL; bd = bd->link) {
804 while (p < bd->free) {
805 info = get_itbl((StgClosure *)p);
808 switch (info->type) {
814 case IND_OLDGEN_PERM:
816 case SE_CAF_BLACKHOLE:
821 case CONSTR_CHARLIKE:
835 size = sizeW_fromITBL(info);
846 size = sizeW_fromITBL(info);
849 case THUNK_1_0: /* ToDo - shouldn't be here */
850 case THUNK_0_1: /* " ditto " */
852 size = sizeofW(StgHeader) + MIN_UPD_SIZE;
857 size = pap_sizeW((StgPAP *)p);
862 size = arr_words_sizeW(stgCast(StgArrWords*,p));
866 case MUT_ARR_PTRS_FROZEN:
868 size = mut_arr_ptrs_sizeW((StgMutArrPtrs *)p);
873 size = tso_sizeW((StgTSO *)p);
882 #ifdef DEBUG_HEAP_PROF
885 // subtract the profiling overhead
886 real_size = size - sizeofW(StgProfHeader);
889 if (closureSatisfiesConstraints((StgClosure*)p)) {
891 if (RtsFlags.ProfFlags.doHeapProfile == HEAP_BY_LDV) {
893 census->prim += real_size;
894 else if ((LDVW(p) & LDV_STATE_MASK) == LDV_STATE_CREATE)
895 census->not_used += real_size;
897 census->used += real_size;
901 identity = closureIdentity((StgClosure *)p);
903 if (identity != NULL) {
904 ctr = lookupHashTable( census->hash, (StgWord)identity );
907 if (RtsFlags.ProfFlags.bioSelector != NULL) {
909 ctr->c.ldv.prim += real_size;
910 else if ((LDVW(p) & LDV_STATE_MASK) == LDV_STATE_CREATE)
911 ctr->c.ldv.not_used += real_size;
913 ctr->c.ldv.used += real_size;
917 ctr->c.resid += real_size;
920 ctr = arenaAlloc( census->arena, sizeof(counter) );
922 insertHashTable( census->hash, (StgWord)identity, ctr );
923 ctr->identity = identity;
924 ctr->next = census->ctrs;
928 if (RtsFlags.ProfFlags.bioSelector != NULL) {
930 ctr->c.ldv.prim = real_size;
931 else if ((LDVW(p) & LDV_STATE_MASK) == LDV_STATE_CREATE)
932 ctr->c.ldv.not_used = real_size;
934 ctr->c.ldv.used = real_size;
938 ctr->c.resid = real_size;
956 census = &censuses[era];
957 census->time = mut_user_time();
959 // calculate retainer sets if necessary
961 if (doingRetainerProfiling()) {
967 stat_startHeapCensus();
970 // traverse the heap, collecting the census info
971 heapCensusChain( census, small_alloc_list );
972 if (RtsFlags.GcFlags.generations == 1) {
973 heapCensusChain( census, g0s0->to_blocks );
975 for (g = 0; g < RtsFlags.GcFlags.generations; g++) {
976 for (s = 0; s < generations[g].n_steps; s++) {
977 heapCensusChain( census, generations[g].steps[s].blocks );
978 // Are we interested in large objects? might be
979 // confusing to include the stack in a heap profile.
980 // heapCensusChain( census, generations[g].steps[s].large_objects );
985 // dump out the census info
987 // We can't generate any info for LDV profiling until
988 // the end of the run...
989 if (!doingLDVProfiling())
990 dumpCensus( census );
992 dumpCensus( census );
996 // free our storage, unless we're keeping all the census info for
997 // future restriction by biography.
999 if (RtsFlags.ProfFlags.bioSelector == NULL)
1002 freeHashTable( census->hash, NULL/* don't free the elements */ );
1003 arenaFree( census->arena );
1004 census->hash = NULL;
1005 census->arena = NULL;
1008 // we're into the next time period now
1012 stat_endHeapCensus();
1016 #endif /* PROFILING || DEBUG_HEAP_PROF */