a50f2f0ac76f2ad3c507f969ab48ccd4ca494cc7
[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_CLEAN"
160     , "MUT_VAR_DIRTY"
161
162     , "WEAK"
163   
164     , "TSO"
165
166     , "BLOCKED_FETCH"
167     , "FETCH_ME"
168
169     , "EVACUATED"
170 };
171
172 #endif /* DEBUG_HEAP_PROF */
173
174 /* -----------------------------------------------------------------------------
175  * Find the "closure identity", which is a unique pointer reresenting
176  * the band to which this closure's heap space is attributed in the
177  * heap profile.
178  * ------------------------------------------------------------------------- */
179 STATIC_INLINE void *
180 closureIdentity( StgClosure *p )
181 {
182     switch (RtsFlags.ProfFlags.doHeapProfile) {
183
184 #ifdef PROFILING
185     case HEAP_BY_CCS:
186         return p->header.prof.ccs;
187     case HEAP_BY_MOD:
188         return p->header.prof.ccs->cc->module;
189     case HEAP_BY_DESCR:
190         return get_itbl(p)->prof.closure_desc;
191     case HEAP_BY_TYPE:
192         return get_itbl(p)->prof.closure_type;
193     case HEAP_BY_RETAINER:
194         // AFAIK, the only closures in the heap which might not have a
195         // valid retainer set are DEAD_WEAK closures.
196         if (isRetainerSetFieldValid(p))
197             return retainerSetOf(p);
198         else
199             return NULL;
200
201 #else // DEBUG
202     case HEAP_BY_INFOPTR:
203         return (void *)((StgClosure *)p)->header.info; 
204     case HEAP_BY_CLOSURE_TYPE:
205         return type_names[get_itbl(p)->type];
206
207 #endif
208     default:
209         barf("closureIdentity");
210     }
211 }
212
213 /* --------------------------------------------------------------------------
214  * Profiling type predicates
215  * ----------------------------------------------------------------------- */
216 #ifdef PROFILING
217 STATIC_INLINE rtsBool
218 doingLDVProfiling( void )
219 {
220     return (RtsFlags.ProfFlags.doHeapProfile == HEAP_BY_LDV 
221             || RtsFlags.ProfFlags.bioSelector != NULL);
222 }
223
224 STATIC_INLINE rtsBool
225 doingRetainerProfiling( void )
226 {
227     return (RtsFlags.ProfFlags.doHeapProfile == HEAP_BY_RETAINER
228             || RtsFlags.ProfFlags.retainerSelector != NULL);
229 }
230 #endif /* PROFILING */
231
232 // Precesses a closure 'c' being destroyed whose size is 'size'.
233 // Make sure that LDV_recordDead() is not invoked on 'inherently used' closures
234 // such as TSO; they should not be involved in computing dragNew or voidNew.
235 // 
236 // Even though era is checked in both LdvCensusForDead() and 
237 // LdvCensusKillAll(), we still need to make sure that era is > 0 because 
238 // LDV_recordDead() may be called from elsewhere in the runtime system. E.g., 
239 // when a thunk is replaced by an indirection object.
240
241 #ifdef PROFILING
242 void
243 LDV_recordDead( StgClosure *c, nat size )
244 {
245     void *id;
246     nat t;
247     counter *ctr;
248
249     if (era > 0 && closureSatisfiesConstraints(c)) {
250         size -= sizeofW(StgProfHeader);
251         ASSERT(LDVW(c) != 0);
252         if ((LDVW((c)) & LDV_STATE_MASK) == LDV_STATE_CREATE) {
253             t = (LDVW((c)) & LDV_CREATE_MASK) >> LDV_SHIFT;
254             if (t < era) {
255                 if (RtsFlags.ProfFlags.bioSelector == NULL) {
256                     censuses[t].void_total   += (int)size;
257                     censuses[era].void_total -= (int)size;
258                 } else {
259                     id = closureIdentity(c);
260                     ctr = lookupHashTable(censuses[t].hash, (StgWord)id);
261                     ASSERT( ctr != NULL );
262                     ctr->c.ldv.void_total += (int)size;
263                     ctr = lookupHashTable(censuses[era].hash, (StgWord)id);
264                     if (ctr == NULL) {
265                         ctr = arenaAlloc(censuses[era].arena, sizeof(counter));
266                         initLDVCtr(ctr);
267                         insertHashTable(censuses[era].hash, (StgWord)id, ctr);
268                         ctr->identity = id;
269                         ctr->next = censuses[era].ctrs;
270                         censuses[era].ctrs = ctr;
271                     }
272                     ctr->c.ldv.void_total -= (int)size;
273                 }
274             }
275         } else {
276             t = LDVW((c)) & LDV_LAST_MASK;
277             if (t + 1 < era) {
278                 if (RtsFlags.ProfFlags.bioSelector == NULL) {
279                     censuses[t+1].drag_total += size;
280                     censuses[era].drag_total -= size;
281                 } else {
282                     void *id;
283                     id = closureIdentity(c);
284                     ctr = lookupHashTable(censuses[t+1].hash, (StgWord)id);
285                     ASSERT( ctr != NULL );
286                     ctr->c.ldv.drag_total += (int)size;
287                     ctr = lookupHashTable(censuses[era].hash, (StgWord)id);
288                     if (ctr == NULL) {
289                         ctr = arenaAlloc(censuses[era].arena, sizeof(counter));
290                         initLDVCtr(ctr);
291                         insertHashTable(censuses[era].hash, (StgWord)id, ctr);
292                         ctr->identity = id;
293                         ctr->next = censuses[era].ctrs;
294                         censuses[era].ctrs = ctr;
295                     }
296                     ctr->c.ldv.drag_total -= (int)size;
297                 }
298             }
299         }
300     }
301 }
302 #endif
303
304 /* --------------------------------------------------------------------------
305  * Initialize censuses[era];
306  * ----------------------------------------------------------------------- */
307 STATIC_INLINE void
308 initEra(Census *census)
309 {
310     census->hash  = allocHashTable();
311     census->ctrs  = NULL;
312     census->arena = newArena();
313
314     census->not_used   = 0;
315     census->used       = 0;
316     census->prim       = 0;
317     census->void_total = 0;
318     census->drag_total = 0;
319 }
320
321 /* --------------------------------------------------------------------------
322  * Increases era by 1 and initialize census[era].
323  * Reallocates gi[] and increases its size if needed.
324  * ----------------------------------------------------------------------- */
325 static void
326 nextEra( void )
327 {
328 #ifdef PROFILING
329     if (doingLDVProfiling()) { 
330         era++;
331
332         if (era == max_era) {
333             errorBelch("maximum number of censuses reached; use +RTS -i to reduce");
334             stg_exit(EXIT_FAILURE);
335         }
336         
337         if (era == n_censuses) {
338             n_censuses *= 2;
339             censuses = stgReallocBytes(censuses, sizeof(Census) * n_censuses,
340                                        "nextEra");
341         }
342     }
343 #endif /* PROFILING */
344
345     initEra( &censuses[era] );
346 }
347
348 /* -----------------------------------------------------------------------------
349  * DEBUG heap profiling, by info table
350  * -------------------------------------------------------------------------- */
351
352 #ifdef DEBUG_HEAP_PROF
353 FILE *hp_file;
354 static char *hp_filename;
355
356 void initProfiling1( void )
357 {
358 }
359
360 void initProfiling2( void )
361 {
362   if (RtsFlags.ProfFlags.doHeapProfile) {
363     /* Initialise the log file name */
364     hp_filename = stgMallocBytes(strlen(prog_name) + 6, "hpFileName");
365     sprintf(hp_filename, "%s.hp", prog_name);
366     
367     /* open the log file */
368     if ((hp_file = fopen(hp_filename, "w")) == NULL) {
369       debugBelch("Can't open profiling report file %s\n", 
370               hp_filename);
371       RtsFlags.ProfFlags.doHeapProfile = 0;
372       return;
373     }
374   }
375   
376   initHeapProfiling();
377 }
378
379 void endProfiling( void )
380 {
381   endHeapProfiling();
382 }
383 #endif /* DEBUG_HEAP_PROF */
384
385 static void
386 printSample(rtsBool beginSample, StgDouble sampleValue)
387 {
388     StgDouble fractionalPart, integralPart;
389     fractionalPart = modf(sampleValue, &integralPart);
390     fprintf(hp_file, "%s %d.%02d\n",
391             (beginSample ? "BEGIN_SAMPLE" : "END_SAMPLE"),
392             (int)integralPart, (int)(fractionalPart * 100));
393 }
394
395 /* --------------------------------------------------------------------------
396  * Initialize the heap profilier
397  * ----------------------------------------------------------------------- */
398 nat
399 initHeapProfiling(void)
400 {
401     if (! RtsFlags.ProfFlags.doHeapProfile) {
402         return 0;
403     }
404
405 #ifdef PROFILING
406     if (doingLDVProfiling() && doingRetainerProfiling()) {
407         errorBelch("cannot mix -hb and -hr");
408         stg_exit(EXIT_FAILURE);
409     }
410 #endif
411
412     // we only count eras if we're doing LDV profiling.  Otherwise era
413     // is fixed at zero.
414 #ifdef PROFILING
415     if (doingLDVProfiling()) {
416         era = 1;
417     } else
418 #endif
419     {
420         era = 0;
421     }
422
423     {   // max_era = 2^LDV_SHIFT
424         nat p;
425         max_era = 1;
426         for (p = 0; p < LDV_SHIFT; p++)
427             max_era *= 2;
428     }
429
430     n_censuses = 32;
431     censuses = stgMallocBytes(sizeof(Census) * n_censuses, "initHeapProfiling");
432
433     initEra( &censuses[era] );
434
435     /* initProfilingLogFile(); */
436     fprintf(hp_file, "JOB \"%s", prog_name);
437
438 #ifdef PROFILING
439     {
440         int count;
441         for(count = 1; count < prog_argc; count++)
442             fprintf(hp_file, " %s", prog_argv[count]);
443         fprintf(hp_file, " +RTS");
444         for(count = 0; count < rts_argc; count++)
445             fprintf(hp_file, " %s", rts_argv[count]);
446     }
447 #endif /* PROFILING */
448
449     fprintf(hp_file, "\"\n" );
450
451     fprintf(hp_file, "DATE \"%s\"\n", time_str());
452
453     fprintf(hp_file, "SAMPLE_UNIT \"seconds\"\n");
454     fprintf(hp_file, "VALUE_UNIT \"bytes\"\n");
455
456     printSample(rtsTrue, 0);
457     printSample(rtsFalse, 0);
458
459 #ifdef DEBUG_HEAP_PROF
460     DEBUG_LoadSymbols(prog_name);
461 #endif
462
463 #ifdef PROFILING
464     if (doingRetainerProfiling()) {
465         initRetainerProfiling();
466     }
467 #endif
468
469     return 0;
470 }
471
472 void
473 endHeapProfiling(void)
474 {
475     StgDouble seconds;
476
477     if (! RtsFlags.ProfFlags.doHeapProfile) {
478         return;
479     }
480
481 #ifdef PROFILING
482     if (doingRetainerProfiling()) {
483         endRetainerProfiling();
484     }
485 #endif
486
487 #ifdef PROFILING
488     if (doingLDVProfiling()) {
489         nat t;
490         LdvCensusKillAll();
491         aggregateCensusInfo();
492         for (t = 1; t < era; t++) {
493             dumpCensus( &censuses[t] );
494         }
495     }
496 #endif
497
498     seconds = mut_user_time();
499     printSample(rtsTrue, seconds);
500     printSample(rtsFalse, seconds);
501     fclose(hp_file);
502 }
503
504
505
506 #ifdef PROFILING
507 static size_t
508 buf_append(char *p, const char *q, char *end)
509 {
510     int m;
511
512     for (m = 0; p < end; p++, q++, m++) {
513         *p = *q;
514         if (*q == '\0') { break; }
515     }
516     return m;
517 }
518
519 static void
520 fprint_ccs(FILE *fp, CostCentreStack *ccs, nat max_length)
521 {
522     char buf[max_length+1], *p, *buf_end;
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         }
555     }
556     fprintf(fp, "%s", buf);
557 }
558 #endif /* PROFILING */
559
560 rtsBool
561 strMatchesSelector( char* str, char* sel )
562 {
563    char* p;
564    // debugBelch("str_matches_selector %s %s\n", str, sel);
565    while (1) {
566        // Compare str against wherever we've got to in sel.
567        p = str;
568        while (*p != '\0' && *sel != ',' && *sel != '\0' && *p == *sel) {
569            p++; sel++;
570        }
571        // Match if all of str used and have reached the end of a sel fragment.
572        if (*p == '\0' && (*sel == ',' || *sel == '\0'))
573            return rtsTrue;
574        
575        // No match.  Advance sel to the start of the next elem.
576        while (*sel != ',' && *sel != '\0') sel++;
577        if (*sel == ',') sel++;
578        
579        /* Run out of sel ?? */
580        if (*sel == '\0') return rtsFalse;
581    }
582 }
583
584 /* -----------------------------------------------------------------------------
585  * Figure out whether a closure should be counted in this census, by
586  * testing against all the specified constraints.
587  * -------------------------------------------------------------------------- */
588 rtsBool
589 closureSatisfiesConstraints( StgClosure* p )
590 {
591 #ifdef DEBUG_HEAP_PROF
592     (void)p;   /* keep gcc -Wall happy */
593     return rtsTrue;
594 #else
595    rtsBool b;
596
597    // The CCS has a selected field to indicate whether this closure is
598    // deselected by not being mentioned in the module, CC, or CCS
599    // selectors.
600    if (!p->header.prof.ccs->selected) {
601        return rtsFalse;
602    }
603
604    if (RtsFlags.ProfFlags.descrSelector) {
605        b = strMatchesSelector( (get_itbl((StgClosure *)p))->prof.closure_desc,
606                                  RtsFlags.ProfFlags.descrSelector );
607        if (!b) return rtsFalse;
608    }
609    if (RtsFlags.ProfFlags.typeSelector) {
610        b = strMatchesSelector( (get_itbl((StgClosure *)p))->prof.closure_type,
611                                 RtsFlags.ProfFlags.typeSelector );
612        if (!b) return rtsFalse;
613    }
614    if (RtsFlags.ProfFlags.retainerSelector) {
615        RetainerSet *rs;
616        nat i;
617        // We must check that the retainer set is valid here.  One
618        // reason it might not be valid is if this closure is a
619        // a newly deceased weak pointer (i.e. a DEAD_WEAK), since
620        // these aren't reached by the retainer profiler's traversal.
621        if (isRetainerSetFieldValid((StgClosure *)p)) {
622            rs = retainerSetOf((StgClosure *)p);
623            if (rs != NULL) {
624                for (i = 0; i < rs->num; i++) {
625                    b = strMatchesSelector( rs->element[i]->cc->label,
626                                            RtsFlags.ProfFlags.retainerSelector );
627                    if (b) return rtsTrue;
628                }
629            }
630        }
631        return rtsFalse;
632    }
633    return rtsTrue;
634 #endif /* PROFILING */
635 }
636
637 /* -----------------------------------------------------------------------------
638  * Aggregate the heap census info for biographical profiling
639  * -------------------------------------------------------------------------- */
640 #ifdef PROFILING
641 static void
642 aggregateCensusInfo( void )
643 {
644     HashTable *acc;
645     nat t;
646     counter *c, *d, *ctrs;
647     Arena *arena;
648
649     if (!doingLDVProfiling()) return;
650
651     // Aggregate the LDV counters when displaying by biography.
652     if (RtsFlags.ProfFlags.doHeapProfile == HEAP_BY_LDV) {
653         int void_total, drag_total;
654
655         // Now we compute void_total and drag_total for each census
656         void_total = 0;
657         drag_total = 0;
658         for (t = 1; t < era; t++) { // note: start at 1, not 0
659             void_total += censuses[t].void_total;
660             drag_total += censuses[t].drag_total;
661             censuses[t].void_total = void_total;
662             censuses[t].drag_total = drag_total;
663             ASSERT( censuses[t].void_total <= censuses[t].not_used );
664             ASSERT( censuses[t].drag_total <= censuses[t].used );
665         }
666         
667         return;
668     }
669
670     // otherwise... we're doing a heap profile that is restricted to
671     // some combination of lag, drag, void or use.  We've kept all the
672     // census info for all censuses so far, but we still need to
673     // aggregate the counters forwards.
674
675     arena = newArena();
676     acc = allocHashTable();
677     ctrs = NULL;
678
679     for (t = 1; t < era; t++) {
680
681         // first look through all the counters we're aggregating
682         for (c = ctrs; c != NULL; c = c->next) {
683             // if one of the totals is non-zero, then this closure
684             // type must be present in the heap at this census time...
685             d = lookupHashTable(censuses[t].hash, (StgWord)c->identity);
686
687             if (d == NULL) {
688                 // if this closure identity isn't present in the
689                 // census for this time period, then our running
690                 // totals *must* be zero.
691                 ASSERT(c->c.ldv.void_total == 0 && c->c.ldv.drag_total == 0);
692
693                 // debugCCS(c->identity);
694                 // debugBelch(" census=%d void_total=%d drag_total=%d\n",
695                 //         t, c->c.ldv.void_total, c->c.ldv.drag_total);
696             } else {
697                 d->c.ldv.void_total += c->c.ldv.void_total;
698                 d->c.ldv.drag_total += c->c.ldv.drag_total;
699                 c->c.ldv.void_total =  d->c.ldv.void_total;
700                 c->c.ldv.drag_total =  d->c.ldv.drag_total;
701
702                 ASSERT( c->c.ldv.void_total >= 0 );
703                 ASSERT( c->c.ldv.drag_total >= 0 );
704             }
705         }
706
707         // now look through the counters in this census to find new ones
708         for (c = censuses[t].ctrs; c != NULL; c = c->next) {
709             d = lookupHashTable(acc, (StgWord)c->identity);
710             if (d == NULL) {
711                 d = arenaAlloc( arena, sizeof(counter) );
712                 initLDVCtr(d);
713                 insertHashTable( acc, (StgWord)c->identity, d );
714                 d->identity = c->identity;
715                 d->next = ctrs;
716                 ctrs = d;
717                 d->c.ldv.void_total = c->c.ldv.void_total;
718                 d->c.ldv.drag_total = c->c.ldv.drag_total;
719             }
720             ASSERT( c->c.ldv.void_total >= 0 );
721             ASSERT( c->c.ldv.drag_total >= 0 );
722         }
723     }
724
725     freeHashTable(acc, NULL);
726     arenaFree(arena);
727 }
728 #endif
729
730 /* -----------------------------------------------------------------------------
731  * Print out the results of a heap census.
732  * -------------------------------------------------------------------------- */
733 static void
734 dumpCensus( Census *census )
735 {
736     counter *ctr;
737     int count;
738
739     printSample(rtsTrue, census->time);
740
741 #ifdef PROFILING
742     if (RtsFlags.ProfFlags.doHeapProfile == HEAP_BY_LDV) {
743       fprintf(hp_file, "VOID\t%lu\n", (unsigned long)(census->void_total) * sizeof(W_));
744         fprintf(hp_file, "LAG\t%lu\n", 
745                 (unsigned long)(census->not_used - census->void_total) * sizeof(W_));
746         fprintf(hp_file, "USE\t%lu\n", 
747                 (unsigned long)(census->used - census->drag_total) * sizeof(W_));
748         fprintf(hp_file, "INHERENT_USE\t%lu\n", 
749                 (unsigned long)(census->prim) * sizeof(W_));
750         fprintf(hp_file, "DRAG\t%lu\n",
751                 (unsigned long)(census->drag_total) * sizeof(W_));
752         printSample(rtsFalse, census->time);
753         return;
754     }
755 #endif
756
757     for (ctr = census->ctrs; ctr != NULL; ctr = ctr->next) {
758
759 #ifdef PROFILING
760         if (RtsFlags.ProfFlags.bioSelector != NULL) {
761             count = 0;
762             if (strMatchesSelector("lag", RtsFlags.ProfFlags.bioSelector))
763                 count += ctr->c.ldv.not_used - ctr->c.ldv.void_total;
764             if (strMatchesSelector("drag", RtsFlags.ProfFlags.bioSelector))
765                 count += ctr->c.ldv.drag_total;
766             if (strMatchesSelector("void", RtsFlags.ProfFlags.bioSelector))
767                 count += ctr->c.ldv.void_total;
768             if (strMatchesSelector("use", RtsFlags.ProfFlags.bioSelector))
769                 count += ctr->c.ldv.used - ctr->c.ldv.drag_total;
770         } else
771 #endif
772         {
773             count = ctr->c.resid;
774         }
775
776         ASSERT( count >= 0 );
777
778         if (count == 0) continue;
779
780 #ifdef DEBUG_HEAP_PROF
781         switch (RtsFlags.ProfFlags.doHeapProfile) {
782         case HEAP_BY_INFOPTR:
783             fprintf(hp_file, "%s", lookupGHCName(ctr->identity));
784             break;
785         case HEAP_BY_CLOSURE_TYPE:
786             fprintf(hp_file, "%s", (char *)ctr->identity);
787             break;
788         }
789 #endif
790         
791 #ifdef PROFILING
792         switch (RtsFlags.ProfFlags.doHeapProfile) {
793         case HEAP_BY_CCS:
794             fprint_ccs(hp_file, (CostCentreStack *)ctr->identity, 25);
795             break;
796         case HEAP_BY_MOD:
797         case HEAP_BY_DESCR:
798         case HEAP_BY_TYPE:
799             fprintf(hp_file, "%s", (char *)ctr->identity);
800             break;
801         case HEAP_BY_RETAINER:
802         {
803             RetainerSet *rs = (RetainerSet *)ctr->identity;
804
805             // it might be the distinguished retainer set rs_MANY:
806             if (rs == &rs_MANY) {
807                 fprintf(hp_file, "MANY");
808                 break;
809             }
810
811             // Mark this retainer set by negating its id, because it
812             // has appeared in at least one census.  We print the
813             // values of all such retainer sets into the log file at
814             // the end.  A retainer set may exist but not feature in
815             // any censuses if it arose as the intermediate retainer
816             // set for some closure during retainer set calculation.
817             if (rs->id > 0)
818                 rs->id = -(rs->id);
819
820             // report in the unit of bytes: * sizeof(StgWord)
821             printRetainerSetShort(hp_file, rs);
822             break;
823         }
824         default:
825             barf("dumpCensus; doHeapProfile");
826         }
827 #endif
828
829         fprintf(hp_file, "\t%lu\n", (unsigned long)count * sizeof(W_));
830     }
831
832     printSample(rtsFalse, census->time);
833 }
834
835 /* -----------------------------------------------------------------------------
836  * Code to perform a heap census.
837  * -------------------------------------------------------------------------- */
838 static void
839 heapCensusChain( Census *census, bdescr *bd )
840 {
841     StgPtr p;
842     StgInfoTable *info;
843     void *identity;
844     nat size;
845     counter *ctr;
846     nat real_size;
847     rtsBool prim;
848
849     for (; bd != NULL; bd = bd->link) {
850
851         // HACK: ignore pinned blocks, because they contain gaps.
852         // It's not clear exactly what we'd like to do here, since we
853         // can't tell which objects in the block are actually alive.
854         // Perhaps the whole block should be counted as SYSTEM memory.
855         if (bd->flags & BF_PINNED) {
856             continue;
857         }
858
859         p = bd->start;
860         while (p < bd->free) {
861             info = get_itbl((StgClosure *)p);
862             prim = rtsFalse;
863             
864             switch (info->type) {
865
866             case THUNK:
867                 size = thunk_sizeW_fromITBL(info);
868                 break;
869
870             case THUNK_1_1:
871             case THUNK_0_2:
872             case THUNK_2_0:
873                 size = sizeofW(StgThunkHeader) + 2;
874                 break;
875
876             case THUNK_1_0:
877             case THUNK_0_1:
878             case THUNK_SELECTOR:
879                 size = sizeofW(StgThunkHeader) + 1;
880                 break;
881
882             case CONSTR:
883             case FUN:
884             case IND_PERM:
885             case IND_OLDGEN:
886             case IND_OLDGEN_PERM:
887             case CAF_BLACKHOLE:
888             case SE_CAF_BLACKHOLE:
889             case SE_BLACKHOLE:
890             case BLACKHOLE:
891             case CONSTR_INTLIKE:
892             case CONSTR_CHARLIKE:
893             case FUN_1_0:
894             case FUN_0_1:
895             case FUN_1_1:
896             case FUN_0_2:
897             case FUN_2_0:
898             case CONSTR_1_0:
899             case CONSTR_0_1:
900             case CONSTR_1_1:
901             case CONSTR_0_2:
902             case CONSTR_2_0:
903                 size = sizeW_fromITBL(info);
904                 break;
905
906             case IND:
907                 // Special case/Delicate Hack: INDs don't normally
908                 // appear, since we're doing this heap census right
909                 // after GC.  However, GarbageCollect() also does
910                 // resurrectThreads(), which can update some
911                 // blackholes when it calls raiseAsync() on the
912                 // resurrected threads.  So we know that any IND will
913                 // be the size of a BLACKHOLE.
914                 size = BLACKHOLE_sizeW();
915                 break;
916
917             case BCO:
918                 prim = rtsTrue;
919                 size = bco_sizeW((StgBCO *)p);
920                 break;
921
922             case MVAR:
923             case WEAK:
924             case STABLE_NAME:
925             case MUT_VAR_CLEAN:
926             case MUT_VAR_DIRTY:
927                 prim = rtsTrue;
928                 size = sizeW_fromITBL(info);
929                 break;
930
931             case AP:
932                 size = ap_sizeW((StgAP *)p);
933                 break;
934
935             case PAP:
936                 size = pap_sizeW((StgPAP *)p);
937                 break;
938
939             case AP_STACK:
940                 size = ap_stack_sizeW((StgAP_STACK *)p);
941                 break;
942                 
943             case ARR_WORDS:
944                 prim = rtsTrue;
945                 size = arr_words_sizeW(stgCast(StgArrWords*,p));
946                 break;
947                 
948             case MUT_ARR_PTRS_CLEAN:
949             case MUT_ARR_PTRS_DIRTY:
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