[project @ 2006-01-17 16:03:47 by simonmar]
[ghc-hetmet.git] / ghc / rts / ProfHeap.c
1 /* -----------------------------------------------------------------------------
2  *
3  * (c) The GHC Team, 1998-2003
4  *
5  * Support for heap profiling
6  *
7  * ---------------------------------------------------------------------------*/
8
9 #if defined(DEBUG) && !defined(PROFILING)
10 #define DEBUG_HEAP_PROF
11 #else
12 #undef DEBUG_HEAP_PROF
13 #endif
14
15 #if defined(PROFILING) || defined(DEBUG_HEAP_PROF)
16
17 #include "PosixSource.h"
18 #include "Rts.h"
19 #include "RtsUtils.h"
20 #include "RtsFlags.h"
21 #include "Profiling.h"
22 #include "Storage.h"
23 #include "ProfHeap.h"
24 #include "Stats.h"
25 #include "Hash.h"
26 #include "RetainerProfile.h"
27 #include "LdvProfile.h"
28 #include "Arena.h"
29 #include "Printer.h"
30
31 #include <string.h>
32 #include <stdlib.h>
33 #include <math.h>
34
35 /* -----------------------------------------------------------------------------
36  * era stores the current time period.  It is the same as the
37  * number of censuses that have been performed.
38  *
39  * RESTRICTION:
40  *   era must be no longer than LDV_SHIFT (15 or 30) bits.
41  * Invariants:
42  *   era is initialized to 1 in initHeapProfiling().
43  *
44  * max_era is initialized to 2^LDV_SHIFT in initHeapProfiling().
45  * When era reaches max_era, the profiling stops because a closure can
46  * store only up to (max_era - 1) as its creation or last use time.
47  * -------------------------------------------------------------------------- */
48 unsigned int era;
49 static nat max_era;
50
51 /* -----------------------------------------------------------------------------
52  * Counters
53  *
54  * For most heap profiles each closure identity gets a simple count
55  * of live words in the heap at each census.  However, if we're
56  * selecting by biography, then we have to keep the various
57  * lag/drag/void counters for each identity.
58  * -------------------------------------------------------------------------- */
59 typedef struct _counter {
60     void *identity;
61     union {
62         nat resid;
63         struct {
64             int prim;     // total size of 'inherently used' closures
65             int not_used; // total size of 'never used' closures
66             int used;     // total size of 'used at least once' closures
67             int void_total;  // current total size of 'destroyed without being used' closures
68             int drag_total;  // current total size of 'used at least once and waiting to die'
69         } ldv;
70     } c;
71     struct _counter *next;
72 } counter;
73
74 STATIC_INLINE void
75 initLDVCtr( counter *ctr )
76 {
77     ctr->c.ldv.prim = 0;
78     ctr->c.ldv.not_used = 0;
79     ctr->c.ldv.used = 0;
80     ctr->c.ldv.void_total = 0;
81     ctr->c.ldv.drag_total = 0;
82 }
83
84 typedef struct {
85     double      time;    // the time in MUT time when the census is made
86     HashTable * hash;
87     counter   * ctrs;
88     Arena     * arena;
89
90     // for LDV profiling, when just displaying by LDV
91     int       prim;
92     int       not_used;
93     int       used;
94     int       void_total;
95     int       drag_total;
96 } Census;
97
98 static Census *censuses = NULL;
99 static nat n_censuses = 0;
100
101 #ifdef PROFILING
102 static void aggregateCensusInfo( void );
103 #endif
104
105 static void dumpCensus( Census *census );
106
107 /* -----------------------------------------------------------------------------
108    Closure Type Profiling;
109
110    PROBABLY TOTALLY OUT OF DATE -- ToDo (SDM)
111    -------------------------------------------------------------------------- */
112
113 #ifdef DEBUG_HEAP_PROF
114 static char *type_names[] = {
115       "INVALID_OBJECT"
116     , "CONSTR"
117     , "CONSTR_INTLIKE"
118     , "CONSTR_CHARLIKE"
119     , "CONSTR_STATIC"
120     , "CONSTR_NOCAF_STATIC"
121
122     , "FUN"
123     , "FUN_STATIC"
124
125     , "THUNK"
126     , "THUNK_STATIC"
127     , "THUNK_SELECTOR"
128
129     , "BCO"
130     , "AP_STACK"
131     , "AP"
132
133     , "PAP"
134
135     , "IND"
136     , "IND_OLDGEN"
137     , "IND_PERM"
138     , "IND_OLDGEN_PERM"
139     , "IND_STATIC"
140
141     , "RET_BCO"
142     , "RET_SMALL"
143     , "RET_VEC_SMALL"
144     , "RET_BIG"
145     , "RET_VEC_BIG"
146     , "RET_DYN"
147     , "UPDATE_FRAME"
148     , "CATCH_FRAME"
149     , "STOP_FRAME"
150
151     , "BLACKHOLE"
152     , "MVAR"
153
154     , "ARR_WORDS"
155
156     , "MUT_ARR_PTRS_CLEAN"
157     , "MUT_ARR_PTRS_DIRTY"
158     , "MUT_ARR_PTRS_FROZEN"
159     , "MUT_VAR"
160
161     , "WEAK"
162   
163     , "TSO"
164
165     , "BLOCKED_FETCH"
166     , "FETCH_ME"
167
168     , "EVACUATED"
169 };
170
171 #endif /* DEBUG_HEAP_PROF */
172
173 /* -----------------------------------------------------------------------------
174  * Find the "closure identity", which is a unique pointer reresenting
175  * the band to which this closure's heap space is attributed in the
176  * heap profile.
177  * ------------------------------------------------------------------------- */
178 STATIC_INLINE void *
179 closureIdentity( StgClosure *p )
180 {
181     switch (RtsFlags.ProfFlags.doHeapProfile) {
182
183 #ifdef PROFILING
184     case HEAP_BY_CCS:
185         return p->header.prof.ccs;
186     case HEAP_BY_MOD:
187         return p->header.prof.ccs->cc->module;
188     case HEAP_BY_DESCR:
189         return get_itbl(p)->prof.closure_desc;
190     case HEAP_BY_TYPE:
191         return get_itbl(p)->prof.closure_type;
192     case HEAP_BY_RETAINER:
193         // AFAIK, the only closures in the heap which might not have a
194         // valid retainer set are DEAD_WEAK closures.
195         if (isRetainerSetFieldValid(p))
196             return retainerSetOf(p);
197         else
198             return NULL;
199
200 #else // DEBUG
201     case HEAP_BY_INFOPTR:
202         return (void *)((StgClosure *)p)->header.info; 
203     case HEAP_BY_CLOSURE_TYPE:
204         return type_names[get_itbl(p)->type];
205
206 #endif
207     default:
208         barf("closureIdentity");
209     }
210 }
211
212 /* --------------------------------------------------------------------------
213  * Profiling type predicates
214  * ----------------------------------------------------------------------- */
215 #ifdef PROFILING
216 STATIC_INLINE rtsBool
217 doingLDVProfiling( void )
218 {
219     return (RtsFlags.ProfFlags.doHeapProfile == HEAP_BY_LDV 
220             || RtsFlags.ProfFlags.bioSelector != NULL);
221 }
222
223 STATIC_INLINE rtsBool
224 doingRetainerProfiling( void )
225 {
226     return (RtsFlags.ProfFlags.doHeapProfile == HEAP_BY_RETAINER
227             || RtsFlags.ProfFlags.retainerSelector != NULL);
228 }
229 #endif /* PROFILING */
230
231 // Precesses a closure 'c' being destroyed whose size is 'size'.
232 // Make sure that LDV_recordDead() is not invoked on 'inherently used' closures
233 // such as TSO; they should not be involved in computing dragNew or voidNew.
234 // 
235 // Even though era is checked in both LdvCensusForDead() and 
236 // LdvCensusKillAll(), we still need to make sure that era is > 0 because 
237 // LDV_recordDead() may be called from elsewhere in the runtime system. E.g., 
238 // when a thunk is replaced by an indirection object.
239
240 #ifdef PROFILING
241 void
242 LDV_recordDead( StgClosure *c, nat size )
243 {
244     void *id;
245     nat t;
246     counter *ctr;
247
248     if (era > 0 && closureSatisfiesConstraints(c)) {
249         size -= sizeofW(StgProfHeader);
250         ASSERT(LDVW(c) != 0);
251         if ((LDVW((c)) & LDV_STATE_MASK) == LDV_STATE_CREATE) {
252             t = (LDVW((c)) & LDV_CREATE_MASK) >> LDV_SHIFT;
253             if (t < era) {
254                 if (RtsFlags.ProfFlags.bioSelector == NULL) {
255                     censuses[t].void_total   += (int)size;
256                     censuses[era].void_total -= (int)size;
257                 } else {
258                     id = closureIdentity(c);
259                     ctr = lookupHashTable(censuses[t].hash, (StgWord)id);
260                     ASSERT( ctr != NULL );
261                     ctr->c.ldv.void_total += (int)size;
262                     ctr = lookupHashTable(censuses[era].hash, (StgWord)id);
263                     if (ctr == NULL) {
264                         ctr = arenaAlloc(censuses[era].arena, sizeof(counter));
265                         initLDVCtr(ctr);
266                         insertHashTable(censuses[era].hash, (StgWord)id, ctr);
267                         ctr->identity = id;
268                         ctr->next = censuses[era].ctrs;
269                         censuses[era].ctrs = ctr;
270                     }
271                     ctr->c.ldv.void_total -= (int)size;
272                 }
273             }
274         } else {
275             t = LDVW((c)) & LDV_LAST_MASK;
276             if (t + 1 < era) {
277                 if (RtsFlags.ProfFlags.bioSelector == NULL) {
278                     censuses[t+1].drag_total += size;
279                     censuses[era].drag_total -= size;
280                 } else {
281                     void *id;
282                     id = closureIdentity(c);
283                     ctr = lookupHashTable(censuses[t+1].hash, (StgWord)id);
284                     ASSERT( ctr != NULL );
285                     ctr->c.ldv.drag_total += (int)size;
286                     ctr = lookupHashTable(censuses[era].hash, (StgWord)id);
287                     if (ctr == NULL) {
288                         ctr = arenaAlloc(censuses[era].arena, sizeof(counter));
289                         initLDVCtr(ctr);
290                         insertHashTable(censuses[era].hash, (StgWord)id, ctr);
291                         ctr->identity = id;
292                         ctr->next = censuses[era].ctrs;
293                         censuses[era].ctrs = ctr;
294                     }
295                     ctr->c.ldv.drag_total -= (int)size;
296                 }
297             }
298         }
299     }
300 }
301 #endif
302
303 /* --------------------------------------------------------------------------
304  * Initialize censuses[era];
305  * ----------------------------------------------------------------------- */
306 STATIC_INLINE void
307 initEra(Census *census)
308 {
309     census->hash  = allocHashTable();
310     census->ctrs  = NULL;
311     census->arena = newArena();
312
313     census->not_used   = 0;
314     census->used       = 0;
315     census->prim       = 0;
316     census->void_total = 0;
317     census->drag_total = 0;
318 }
319
320 /* --------------------------------------------------------------------------
321  * Increases era by 1 and initialize census[era].
322  * Reallocates gi[] and increases its size if needed.
323  * ----------------------------------------------------------------------- */
324 static void
325 nextEra( void )
326 {
327 #ifdef PROFILING
328     if (doingLDVProfiling()) { 
329         era++;
330
331         if (era == max_era) {
332             errorBelch("maximum number of censuses reached; use +RTS -i to reduce");
333             stg_exit(EXIT_FAILURE);
334         }
335         
336         if (era == n_censuses) {
337             n_censuses *= 2;
338             censuses = stgReallocBytes(censuses, sizeof(Census) * n_censuses,
339                                        "nextEra");
340         }
341     }
342 #endif /* PROFILING */
343
344     initEra( &censuses[era] );
345 }
346
347 /* -----------------------------------------------------------------------------
348  * DEBUG heap profiling, by info table
349  * -------------------------------------------------------------------------- */
350
351 #ifdef DEBUG_HEAP_PROF
352 FILE *hp_file;
353 static char *hp_filename;
354
355 void initProfiling1( void )
356 {
357 }
358
359 void initProfiling2( void )
360 {
361   if (RtsFlags.ProfFlags.doHeapProfile) {
362     /* Initialise the log file name */
363     hp_filename = stgMallocBytes(strlen(prog_name) + 6, "hpFileName");
364     sprintf(hp_filename, "%s.hp", prog_name);
365     
366     /* open the log file */
367     if ((hp_file = fopen(hp_filename, "w")) == NULL) {
368       debugBelch("Can't open profiling report file %s\n", 
369               hp_filename);
370       RtsFlags.ProfFlags.doHeapProfile = 0;
371       return;
372     }
373   }
374   
375   initHeapProfiling();
376 }
377
378 void endProfiling( void )
379 {
380   endHeapProfiling();
381 }
382 #endif /* DEBUG_HEAP_PROF */
383
384 static void
385 printSample(rtsBool beginSample, StgDouble sampleValue)
386 {
387     StgDouble fractionalPart, integralPart;
388     fractionalPart = modf(sampleValue, &integralPart);
389     fprintf(hp_file, "%s %d.%02d\n",
390             (beginSample ? "BEGIN_SAMPLE" : "END_SAMPLE"),
391             (int)integralPart, (int)(fractionalPart * 100 + 0.5));
392 }
393
394 /* --------------------------------------------------------------------------
395  * Initialize the heap profilier
396  * ----------------------------------------------------------------------- */
397 nat
398 initHeapProfiling(void)
399 {
400     if (! RtsFlags.ProfFlags.doHeapProfile) {
401         return 0;
402     }
403
404 #ifdef PROFILING
405     if (doingLDVProfiling() && doingRetainerProfiling()) {
406         errorBelch("cannot mix -hb and -hr");
407         stg_exit(EXIT_FAILURE);
408     }
409 #endif
410
411     // we only count eras if we're doing LDV profiling.  Otherwise era
412     // is fixed at zero.
413 #ifdef PROFILING
414     if (doingLDVProfiling()) {
415         era = 1;
416     } else
417 #endif
418     {
419         era = 0;
420     }
421
422     {   // max_era = 2^LDV_SHIFT
423         nat p;
424         max_era = 1;
425         for (p = 0; p < LDV_SHIFT; p++)
426             max_era *= 2;
427     }
428
429     n_censuses = 32;
430     censuses = stgMallocBytes(sizeof(Census) * n_censuses, "initHeapProfiling");
431
432     initEra( &censuses[era] );
433
434     /* initProfilingLogFile(); */
435     fprintf(hp_file, "JOB \"%s", prog_name);
436
437 #ifdef PROFILING
438     {
439         int count;
440         for(count = 1; count < prog_argc; count++)
441             fprintf(hp_file, " %s", prog_argv[count]);
442         fprintf(hp_file, " +RTS");
443         for(count = 0; count < rts_argc; count++)
444             fprintf(hp_file, " %s", rts_argv[count]);
445     }
446 #endif /* PROFILING */
447
448     fprintf(hp_file, "\"\n" );
449
450     fprintf(hp_file, "DATE \"%s\"\n", time_str());
451
452     fprintf(hp_file, "SAMPLE_UNIT \"seconds\"\n");
453     fprintf(hp_file, "VALUE_UNIT \"bytes\"\n");
454
455     printSample(rtsTrue, 0);
456     printSample(rtsFalse, 0);
457
458 #ifdef DEBUG_HEAP_PROF
459     DEBUG_LoadSymbols(prog_name);
460 #endif
461
462 #ifdef PROFILING
463     if (doingRetainerProfiling()) {
464         initRetainerProfiling();
465     }
466 #endif
467
468     return 0;
469 }
470
471 void
472 endHeapProfiling(void)
473 {
474     StgDouble seconds;
475
476     if (! RtsFlags.ProfFlags.doHeapProfile) {
477         return;
478     }
479
480 #ifdef PROFILING
481     if (doingRetainerProfiling()) {
482         endRetainerProfiling();
483     }
484 #endif
485
486 #ifdef PROFILING
487     if (doingLDVProfiling()) {
488         nat t;
489         LdvCensusKillAll();
490         aggregateCensusInfo();
491         for (t = 1; t < era; t++) {
492             dumpCensus( &censuses[t] );
493         }
494     }
495 #endif
496
497     seconds = mut_user_time();
498     printSample(rtsTrue, seconds);
499     printSample(rtsFalse, seconds);
500     fclose(hp_file);
501 }
502
503
504
505 #ifdef PROFILING
506 static size_t
507 buf_append(char *p, const char *q, char *end)
508 {
509     int m;
510
511     for (m = 0; p < end; p++, q++, m++) {
512         *p = *q;
513         if (*q == '\0') { break; }
514     }
515     return m;
516 }
517
518 static void
519 fprint_ccs(FILE *fp, CostCentreStack *ccs, nat max_length)
520 {
521     char buf[max_length+1], *p, *buf_end;
522     nat next_offset = 0;
523     nat written;
524
525     // MAIN on its own gets printed as "MAIN", otherwise we ignore MAIN.
526     if (ccs == CCS_MAIN) {
527         fprintf(fp, "MAIN");
528         return;
529     }
530
531     fprintf(fp, "(%ld)", ccs->ccsID);
532
533     p = buf;
534     buf_end = buf + max_length + 1;
535
536     // keep printing components of the stack until we run out of space
537     // in the buffer.  If we run out of space, end with "...".
538     for (; ccs != NULL && ccs != CCS_MAIN; ccs = ccs->prevStack) {
539
540         // CAF cost centres print as M.CAF, but we leave the module
541         // name out of all the others to save space.
542         if (!strcmp(ccs->cc->label,"CAF")) {
543             p += buf_append(p, ccs->cc->module, buf_end);
544             p += buf_append(p, ".CAF", buf_end);
545         } else {
546             if (ccs->prevStack != NULL && ccs->prevStack != CCS_MAIN) {
547                 p += buf_append(p, "/", buf_end);
548             }
549             p += buf_append(p, ccs->cc->label, buf_end);
550         }
551         
552         if (p >= buf_end) {
553             sprintf(buf+max_length-4, "...");
554             break;
555         } else {
556             next_offset += written;
557         }
558     }
559     fprintf(fp, "%s", buf);
560 }
561 #endif /* PROFILING */
562
563 rtsBool
564 strMatchesSelector( char* str, char* sel )
565 {
566    char* p;
567    // debugBelch("str_matches_selector %s %s\n", str, sel);
568    while (1) {
569        // Compare str against wherever we've got to in sel.
570        p = str;
571        while (*p != '\0' && *sel != ',' && *sel != '\0' && *p == *sel) {
572            p++; sel++;
573        }
574        // Match if all of str used and have reached the end of a sel fragment.
575        if (*p == '\0' && (*sel == ',' || *sel == '\0'))
576            return rtsTrue;
577        
578        // No match.  Advance sel to the start of the next elem.
579        while (*sel != ',' && *sel != '\0') sel++;
580        if (*sel == ',') sel++;
581        
582        /* Run out of sel ?? */
583        if (*sel == '\0') return rtsFalse;
584    }
585 }
586
587 /* -----------------------------------------------------------------------------
588  * Figure out whether a closure should be counted in this census, by
589  * testing against all the specified constraints.
590  * -------------------------------------------------------------------------- */
591 rtsBool
592 closureSatisfiesConstraints( StgClosure* p )
593 {
594 #ifdef DEBUG_HEAP_PROF
595     (void)p;   /* keep gcc -Wall happy */
596     return rtsTrue;
597 #else
598    rtsBool b;
599
600    // The CCS has a selected field to indicate whether this closure is
601    // deselected by not being mentioned in the module, CC, or CCS
602    // selectors.
603    if (!p->header.prof.ccs->selected) {
604        return rtsFalse;
605    }
606
607    if (RtsFlags.ProfFlags.descrSelector) {
608        b = strMatchesSelector( (get_itbl((StgClosure *)p))->prof.closure_desc,
609                                  RtsFlags.ProfFlags.descrSelector );
610        if (!b) return rtsFalse;
611    }
612    if (RtsFlags.ProfFlags.typeSelector) {
613        b = strMatchesSelector( (get_itbl((StgClosure *)p))->prof.closure_type,
614                                 RtsFlags.ProfFlags.typeSelector );
615        if (!b) return rtsFalse;
616    }
617    if (RtsFlags.ProfFlags.retainerSelector) {
618        RetainerSet *rs;
619        nat i;
620        // We must check that the retainer set is valid here.  One
621        // reason it might not be valid is if this closure is a
622        // a newly deceased weak pointer (i.e. a DEAD_WEAK), since
623        // these aren't reached by the retainer profiler's traversal.
624        if (isRetainerSetFieldValid((StgClosure *)p)) {
625            rs = retainerSetOf((StgClosure *)p);
626            if (rs != NULL) {
627                for (i = 0; i < rs->num; i++) {
628                    b = strMatchesSelector( rs->element[i]->cc->label,
629                                            RtsFlags.ProfFlags.retainerSelector );
630                    if (b) return rtsTrue;
631                }
632            }
633        }
634        return rtsFalse;
635    }
636    return rtsTrue;
637 #endif /* PROFILING */
638 }
639
640 /* -----------------------------------------------------------------------------
641  * Aggregate the heap census info for biographical profiling
642  * -------------------------------------------------------------------------- */
643 #ifdef PROFILING
644 static void
645 aggregateCensusInfo( void )
646 {
647     HashTable *acc;
648     nat t;
649     counter *c, *d, *ctrs;
650     Arena *arena;
651
652     if (!doingLDVProfiling()) return;
653
654     // Aggregate the LDV counters when displaying by biography.
655     if (RtsFlags.ProfFlags.doHeapProfile == HEAP_BY_LDV) {
656         int void_total, drag_total;
657
658         // Now we compute void_total and drag_total for each census
659         void_total = 0;
660         drag_total = 0;
661         for (t = 1; t < era; t++) { // note: start at 1, not 0
662             void_total += censuses[t].void_total;
663             drag_total += censuses[t].drag_total;
664             censuses[t].void_total = void_total;
665             censuses[t].drag_total = drag_total;
666             ASSERT( censuses[t].void_total <= censuses[t].not_used );
667             ASSERT( censuses[t].drag_total <= censuses[t].used );
668         }
669         
670         return;
671     }
672
673     // otherwise... we're doing a heap profile that is restricted to
674     // some combination of lag, drag, void or use.  We've kept all the
675     // census info for all censuses so far, but we still need to
676     // aggregate the counters forwards.
677
678     arena = newArena();
679     acc = allocHashTable();
680     ctrs = NULL;
681
682     for (t = 1; t < era; t++) {
683
684         // first look through all the counters we're aggregating
685         for (c = ctrs; c != NULL; c = c->next) {
686             // if one of the totals is non-zero, then this closure
687             // type must be present in the heap at this census time...
688             d = lookupHashTable(censuses[t].hash, (StgWord)c->identity);
689
690             if (d == NULL) {
691                 // if this closure identity isn't present in the
692                 // census for this time period, then our running
693                 // totals *must* be zero.
694                 ASSERT(c->c.ldv.void_total == 0 && c->c.ldv.drag_total == 0);
695
696                 // debugCCS(c->identity);
697                 // debugBelch(" census=%d void_total=%d drag_total=%d\n",
698                 //         t, c->c.ldv.void_total, c->c.ldv.drag_total);
699             } else {
700                 d->c.ldv.void_total += c->c.ldv.void_total;
701                 d->c.ldv.drag_total += c->c.ldv.drag_total;
702                 c->c.ldv.void_total =  d->c.ldv.void_total;
703                 c->c.ldv.drag_total =  d->c.ldv.drag_total;
704
705                 ASSERT( c->c.ldv.void_total >= 0 );
706                 ASSERT( c->c.ldv.drag_total >= 0 );
707             }
708         }
709
710         // now look through the counters in this census to find new ones
711         for (c = censuses[t].ctrs; c != NULL; c = c->next) {
712             d = lookupHashTable(acc, (StgWord)c->identity);
713             if (d == NULL) {
714                 d = arenaAlloc( arena, sizeof(counter) );
715                 initLDVCtr(d);
716                 insertHashTable( acc, (StgWord)c->identity, d );
717                 d->identity = c->identity;
718                 d->next = ctrs;
719                 ctrs = d;
720                 d->c.ldv.void_total = c->c.ldv.void_total;
721                 d->c.ldv.drag_total = c->c.ldv.drag_total;
722             }
723             ASSERT( c->c.ldv.void_total >= 0 );
724             ASSERT( c->c.ldv.drag_total >= 0 );
725         }
726     }
727
728     freeHashTable(acc, NULL);
729     arenaFree(arena);
730 }
731 #endif
732
733 /* -----------------------------------------------------------------------------
734  * Print out the results of a heap census.
735  * -------------------------------------------------------------------------- */
736 static void
737 dumpCensus( Census *census )
738 {
739     counter *ctr;
740     int count;
741
742     printSample(rtsTrue, census->time);
743
744 #ifdef PROFILING
745     if (RtsFlags.ProfFlags.doHeapProfile == HEAP_BY_LDV) {
746       fprintf(hp_file, "VOID\t%lu\n", (unsigned long)(census->void_total) * sizeof(W_));
747         fprintf(hp_file, "LAG\t%lu\n", 
748                 (unsigned long)(census->not_used - census->void_total) * sizeof(W_));
749         fprintf(hp_file, "USE\t%lu\n", 
750                 (unsigned long)(census->used - census->drag_total) * sizeof(W_));
751         fprintf(hp_file, "INHERENT_USE\t%lu\n", 
752                 (unsigned long)(census->prim) * sizeof(W_));
753         fprintf(hp_file, "DRAG\t%lu\n",
754                 (unsigned long)(census->drag_total) * sizeof(W_));
755         printSample(rtsFalse, census->time);
756         return;
757     }
758 #endif
759
760     for (ctr = census->ctrs; ctr != NULL; ctr = ctr->next) {
761
762 #ifdef PROFILING
763         if (RtsFlags.ProfFlags.bioSelector != NULL) {
764             count = 0;
765             if (strMatchesSelector("lag", RtsFlags.ProfFlags.bioSelector))
766                 count += ctr->c.ldv.not_used - ctr->c.ldv.void_total;
767             if (strMatchesSelector("drag", RtsFlags.ProfFlags.bioSelector))
768                 count += ctr->c.ldv.drag_total;
769             if (strMatchesSelector("void", RtsFlags.ProfFlags.bioSelector))
770                 count += ctr->c.ldv.void_total;
771             if (strMatchesSelector("use", RtsFlags.ProfFlags.bioSelector))
772                 count += ctr->c.ldv.used - ctr->c.ldv.drag_total;
773         } else
774 #endif
775         {
776             count = ctr->c.resid;
777         }
778
779         ASSERT( count >= 0 );
780
781         if (count == 0) continue;
782
783 #ifdef DEBUG_HEAP_PROF
784         switch (RtsFlags.ProfFlags.doHeapProfile) {
785         case HEAP_BY_INFOPTR:
786             fprintf(hp_file, "%s", lookupGHCName(ctr->identity));
787             break;
788         case HEAP_BY_CLOSURE_TYPE:
789             fprintf(hp_file, "%s", (char *)ctr->identity);
790             break;
791         }
792 #endif
793         
794 #ifdef PROFILING
795         switch (RtsFlags.ProfFlags.doHeapProfile) {
796         case HEAP_BY_CCS:
797             fprint_ccs(hp_file, (CostCentreStack *)ctr->identity, 25);
798             break;
799         case HEAP_BY_MOD:
800         case HEAP_BY_DESCR:
801         case HEAP_BY_TYPE:
802             fprintf(hp_file, "%s", (char *)ctr->identity);
803             break;
804         case HEAP_BY_RETAINER:
805         {
806             RetainerSet *rs = (RetainerSet *)ctr->identity;
807
808             // it might be the distinguished retainer set rs_MANY:
809             if (rs == &rs_MANY) {
810                 fprintf(hp_file, "MANY");
811                 break;
812             }
813
814             // Mark this retainer set by negating its id, because it
815             // has appeared in at least one census.  We print the
816             // values of all such retainer sets into the log file at
817             // the end.  A retainer set may exist but not feature in
818             // any censuses if it arose as the intermediate retainer
819             // set for some closure during retainer set calculation.
820             if (rs->id > 0)
821                 rs->id = -(rs->id);
822
823             // report in the unit of bytes: * sizeof(StgWord)
824             printRetainerSetShort(hp_file, rs);
825             break;
826         }
827         default:
828             barf("dumpCensus; doHeapProfile");
829         }
830 #endif
831
832         fprintf(hp_file, "\t%lu\n", (unsigned long)count * sizeof(W_));
833     }
834
835     printSample(rtsFalse, census->time);
836 }
837
838 /* -----------------------------------------------------------------------------
839  * Code to perform a heap census.
840  * -------------------------------------------------------------------------- */
841 static void
842 heapCensusChain( Census *census, bdescr *bd )
843 {
844     StgPtr p;
845     StgInfoTable *info;
846     void *identity;
847     nat size;
848     counter *ctr;
849     nat real_size;
850     rtsBool prim;
851
852     for (; bd != NULL; bd = bd->link) {
853
854         // HACK: ignore pinned blocks, because they contain gaps.
855         // It's not clear exactly what we'd like to do here, since we
856         // can't tell which objects in the block are actually alive.
857         // Perhaps the whole block should be counted as SYSTEM memory.
858         if (bd->flags & BF_PINNED) {
859             continue;
860         }
861
862         p = bd->start;
863         while (p < bd->free) {
864             info = get_itbl((StgClosure *)p);
865             prim = rtsFalse;
866             
867             switch (info->type) {
868
869             case THUNK:
870                 size = thunk_sizeW_fromITBL(info);
871                 break;
872
873             case THUNK_1_1:
874             case THUNK_0_2:
875             case THUNK_2_0:
876                 size = sizeofW(StgHeader) + stg_max(MIN_UPD_SIZE,2);
877                 break;
878
879             case THUNK_1_0:
880             case THUNK_0_1:
881             case THUNK_SELECTOR:
882                 size = sizeofW(StgHeader) + stg_max(MIN_UPD_SIZE,1);
883                 break;
884
885             case CONSTR:
886             case FUN:
887             case IND_PERM:
888             case IND_OLDGEN:
889             case IND_OLDGEN_PERM:
890             case CAF_BLACKHOLE:
891             case SE_CAF_BLACKHOLE:
892             case SE_BLACKHOLE:
893             case BLACKHOLE:
894             case CONSTR_INTLIKE:
895             case CONSTR_CHARLIKE:
896             case FUN_1_0:
897             case FUN_0_1:
898             case FUN_1_1:
899             case FUN_0_2:
900             case FUN_2_0:
901             case CONSTR_1_0:
902             case CONSTR_0_1:
903             case CONSTR_1_1:
904             case CONSTR_0_2:
905             case CONSTR_2_0:
906                 size = sizeW_fromITBL(info);
907                 break;
908                 
909             case IND:
910                 // Special case/Delicate Hack: INDs don't normally
911                 // appear, since we're doing this heap census right
912                 // after GC.  However, GarbageCollect() also does
913                 // resurrectThreads(), which can update some
914                 // blackholes when it calls raiseAsync() on the
915                 // resurrected threads.  So we know that any IND will
916                 // be the size of a BLACKHOLE.
917                 size = BLACKHOLE_sizeW();
918                 break;
919
920             case BCO:
921                 prim = rtsTrue;
922                 size = bco_sizeW((StgBCO *)p);
923                 break;
924
925             case MVAR:
926             case WEAK:
927             case STABLE_NAME:
928             case MUT_VAR:
929                 prim = rtsTrue;
930                 size = sizeW_fromITBL(info);
931                 break;
932
933             case AP:
934                 size = ap_sizeW((StgAP *)p);
935                 break;
936
937             case PAP:
938                 size = pap_sizeW((StgPAP *)p);
939                 break;
940
941             case AP_STACK:
942                 size = ap_stack_sizeW((StgAP_STACK *)p);
943                 break;
944                 
945             case ARR_WORDS:
946                 prim = rtsTrue;
947                 size = arr_words_sizeW(stgCast(StgArrWords*,p));
948                 break;
949                 
950             case MUT_ARR_PTRS_CLEAN:
951             case MUT_ARR_PTRS_DIRTY:
952             case MUT_ARR_PTRS_FROZEN:
953             case MUT_ARR_PTRS_FROZEN0:
954                 prim = rtsTrue;
955                 size = mut_arr_ptrs_sizeW((StgMutArrPtrs *)p);
956                 break;
957                 
958             case TSO:
959                 prim = rtsTrue;
960 #ifdef DEBUG_HEAP_PROF
961                 size = tso_sizeW((StgTSO *)p);
962                 break;
963 #else
964                 if (RtsFlags.ProfFlags.includeTSOs) {
965                     size = tso_sizeW((StgTSO *)p);
966                     break;
967                 } else {
968                     // Skip this TSO and move on to the next object
969                     p += tso_sizeW((StgTSO *)p);
970                     continue;
971                 }
972 #endif
973
974             case TREC_HEADER: 
975                 prim = rtsTrue;
976                 size = sizeofW(StgTRecHeader);
977                 break;
978
979             case TVAR_WAIT_QUEUE:
980                 prim = rtsTrue;
981                 size = sizeofW(StgTVarWaitQueue);
982                 break;
983                 
984             case TVAR:
985                 prim = rtsTrue;
986                 size = sizeofW(StgTVar);
987                 break;
988                 
989             case TREC_CHUNK:
990                 prim = rtsTrue;
991                 size = sizeofW(StgTRecChunk);
992                 break;
993
994             default:
995                 barf("heapCensus, unknown object: %d", info->type);
996             }
997             
998             identity = NULL;
999
1000 #ifdef DEBUG_HEAP_PROF
1001             real_size = size;
1002 #else
1003             // subtract the profiling overhead
1004             real_size = size - sizeofW(StgProfHeader);
1005 #endif
1006
1007             if (closureSatisfiesConstraints((StgClosure*)p)) {
1008 #ifdef PROFILING
1009                 if (RtsFlags.ProfFlags.doHeapProfile == HEAP_BY_LDV) {
1010                     if (prim)
1011                         census->prim += real_size;
1012                     else if ((LDVW(p) & LDV_STATE_MASK) == LDV_STATE_CREATE)
1013                         census->not_used += real_size;
1014                     else
1015                         census->used += real_size;
1016                 } else
1017 #endif
1018                 {
1019                     identity = closureIdentity((StgClosure *)p);
1020
1021                     if (identity != NULL) {
1022                         ctr = lookupHashTable( census->hash, (StgWord)identity );
1023                         if (ctr != NULL) {
1024 #ifdef PROFILING
1025                             if (RtsFlags.ProfFlags.bioSelector != NULL) {
1026                                 if (prim)
1027                                     ctr->c.ldv.prim += real_size;
1028                                 else if ((LDVW(p) & LDV_STATE_MASK) == LDV_STATE_CREATE)
1029                                     ctr->c.ldv.not_used += real_size;
1030                                 else
1031                                     ctr->c.ldv.used += real_size;
1032                             } else
1033 #endif
1034                             {
1035                                 ctr->c.resid += real_size;
1036                             }
1037                         } else {
1038                             ctr = arenaAlloc( census->arena, sizeof(counter) );
1039                             initLDVCtr(ctr);
1040                             insertHashTable( census->hash, (StgWord)identity, ctr );
1041                             ctr->identity = identity;
1042                             ctr->next = census->ctrs;
1043                             census->ctrs = ctr;
1044
1045 #ifdef PROFILING
1046                             if (RtsFlags.ProfFlags.bioSelector != NULL) {
1047                                 if (prim)
1048                                     ctr->c.ldv.prim = real_size;
1049                                 else if ((LDVW(p) & LDV_STATE_MASK) == LDV_STATE_CREATE)
1050                                     ctr->c.ldv.not_used = real_size;
1051                                 else
1052                                     ctr->c.ldv.used = real_size;
1053                             } else
1054 #endif
1055                             {
1056                                 ctr->c.resid = real_size;
1057                             }
1058                         }
1059                     }
1060                 }
1061             }
1062
1063             p += size;
1064         }
1065     }
1066 }
1067
1068 void
1069 heapCensus( void )
1070 {
1071   nat g, s;
1072   Census *census;
1073
1074   census = &censuses[era];
1075   census->time  = mut_user_time();
1076     
1077   // calculate retainer sets if necessary
1078 #ifdef PROFILING
1079   if (doingRetainerProfiling()) {
1080       retainerProfile();
1081   }
1082 #endif
1083
1084 #ifdef PROFILING
1085   stat_startHeapCensus();
1086 #endif
1087
1088   // Traverse the heap, collecting the census info
1089
1090   // First the small_alloc_list: we have to fix the free pointer at
1091   // the end by calling tidyAllocatedLists() first.
1092   tidyAllocateLists();
1093   heapCensusChain( census, small_alloc_list );
1094
1095   // Now traverse the heap in each generation/step.
1096   if (RtsFlags.GcFlags.generations == 1) {
1097       heapCensusChain( census, g0s0->blocks );
1098   } else {
1099       for (g = 0; g < RtsFlags.GcFlags.generations; g++) {
1100           for (s = 0; s < generations[g].n_steps; s++) {
1101               heapCensusChain( census, generations[g].steps[s].blocks );
1102               // Are we interested in large objects?  might be
1103               // confusing to include the stack in a heap profile.
1104               heapCensusChain( census, generations[g].steps[s].large_objects );
1105           }
1106       }
1107   }
1108
1109   // dump out the census info
1110 #ifdef PROFILING
1111     // We can't generate any info for LDV profiling until
1112     // the end of the run...
1113     if (!doingLDVProfiling())
1114         dumpCensus( census );
1115 #else
1116     dumpCensus( census );
1117 #endif
1118
1119
1120   // free our storage, unless we're keeping all the census info for
1121   // future restriction by biography.
1122 #ifdef PROFILING
1123   if (RtsFlags.ProfFlags.bioSelector == NULL)
1124 #endif
1125   {
1126       freeHashTable( census->hash, NULL/* don't free the elements */ );
1127       arenaFree( census->arena );
1128       census->hash = NULL;
1129       census->arena = NULL;
1130   }
1131
1132   // we're into the next time period now
1133   nextEra();
1134
1135 #ifdef PROFILING
1136   stat_endHeapCensus();
1137 #endif
1138 }    
1139
1140 #endif /* PROFILING || DEBUG_HEAP_PROF */
1141