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