[project @ 2005-04-05 12:19:54 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 "StrHash.h"
27 #include "RetainerProfile.h"
28 #include "LdvProfile.h"
29 #include "Arena.h"
30 #include "Printer.h"
31
32 #include <string.h>
33 #include <stdlib.h>
34 #include <math.h>
35
36 /* -----------------------------------------------------------------------------
37  * era stores the current time period.  It is the same as the
38  * number of censuses that have been performed.
39  *
40  * RESTRICTION:
41  *   era must be no longer than LDV_SHIFT (15 or 30) bits.
42  * Invariants:
43  *   era is initialized to 1 in initHeapProfiling().
44  *
45  * max_era is initialized to 2^LDV_SHIFT in initHeapProfiling().
46  * When era reaches max_era, the profiling stops because a closure can
47  * store only up to (max_era - 1) as its creation or last use time.
48  * -------------------------------------------------------------------------- */
49 unsigned int era;
50 static nat max_era;
51
52 /* -----------------------------------------------------------------------------
53  * Counters
54  *
55  * For most heap profiles each closure identity gets a simple count
56  * of live words in the heap at each census.  However, if we're
57  * selecting by biography, then we have to keep the various
58  * lag/drag/void counters for each identity.
59  * -------------------------------------------------------------------------- */
60 typedef struct _counter {
61     void *identity;
62     union {
63         nat resid;
64         struct {
65             int prim;     // total size of 'inherently used' closures
66             int not_used; // total size of 'never used' closures
67             int used;     // total size of 'used at least once' closures
68             int void_total;  // current total size of 'destroyed without being used' closures
69             int drag_total;  // current total size of 'used at least once and waiting to die'
70         } ldv;
71     } c;
72     struct _counter *next;
73 } counter;
74
75 STATIC_INLINE void
76 initLDVCtr( counter *ctr )
77 {
78     ctr->c.ldv.prim = 0;
79     ctr->c.ldv.not_used = 0;
80     ctr->c.ldv.used = 0;
81     ctr->c.ldv.void_total = 0;
82     ctr->c.ldv.drag_total = 0;
83 }
84
85 typedef struct {
86     double      time;    // the time in MUT time when the census is made
87     HashTable * hash;
88     counter   * ctrs;
89     Arena     * arena;
90
91     // for LDV profiling, when just displaying by LDV
92     int       prim;
93     int       not_used;
94     int       used;
95     int       void_total;
96     int       drag_total;
97 } Census;
98
99 static Census *censuses = NULL;
100 static nat n_censuses = 0;
101
102 #ifdef PROFILING
103 static void aggregateCensusInfo( void );
104 #endif
105
106 static void dumpCensus( Census *census );
107
108 /* -----------------------------------------------------------------------------
109    Closure Type Profiling;
110
111    PROBABLY TOTALLY OUT OF DATE -- ToDo (SDM)
112    -------------------------------------------------------------------------- */
113
114 #ifdef DEBUG_HEAP_PROF
115 static char *type_names[] = {
116       "INVALID_OBJECT"
117     , "CONSTR"
118     , "CONSTR_INTLIKE"
119     , "CONSTR_CHARLIKE"
120     , "CONSTR_STATIC"
121     , "CONSTR_NOCAF_STATIC"
122
123     , "FUN"
124     , "FUN_STATIC"
125
126     , "THUNK"
127     , "THUNK_STATIC"
128     , "THUNK_SELECTOR"
129
130     , "BCO"
131     , "AP_STACK"
132     , "AP"
133
134     , "PAP"
135
136     , "IND"
137     , "IND_OLDGEN"
138     , "IND_PERM"
139     , "IND_OLDGEN_PERM"
140     , "IND_STATIC"
141
142     , "RET_BCO"
143     , "RET_SMALL"
144     , "RET_VEC_SMALL"
145     , "RET_BIG"
146     , "RET_VEC_BIG"
147     , "RET_DYN"
148     , "UPDATE_FRAME"
149     , "CATCH_FRAME"
150     , "STOP_FRAME"
151
152     , "BLACKHOLE"
153     , "MVAR"
154
155     , "ARR_WORDS"
156
157     , "MUT_ARR_PTRS"
158     , "MUT_ARR_PTRS_FROZEN"
159     , "MUT_VAR"
160
161     , "WEAK"
162     , "FOREIGN"
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 + 0.5));
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(1);
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     nat next_offset = 0;
524     nat written;
525
526     // MAIN on its own gets printed as "MAIN", otherwise we ignore MAIN.
527     if (ccs == CCS_MAIN) {
528         fprintf(fp, "MAIN");
529         return;
530     }
531
532     fprintf(fp, "(%ld)", ccs->ccsID);
533
534     p = buf;
535     buf_end = buf + max_length + 1;
536
537     // keep printing components of the stack until we run out of space
538     // in the buffer.  If we run out of space, end with "...".
539     for (; ccs != NULL && ccs != CCS_MAIN; ccs = ccs->prevStack) {
540
541         // CAF cost centres print as M.CAF, but we leave the module
542         // name out of all the others to save space.
543         if (!strcmp(ccs->cc->label,"CAF")) {
544             p += buf_append(p, ccs->cc->module, buf_end);
545             p += buf_append(p, ".CAF", buf_end);
546         } else {
547             if (ccs->prevStack != NULL && ccs->prevStack != CCS_MAIN) {
548                 p += buf_append(p, "/", buf_end);
549             }
550             p += buf_append(p, ccs->cc->label, buf_end);
551         }
552         
553         if (p >= buf_end) {
554             sprintf(buf+max_length-4, "...");
555             break;
556         } else {
557             next_offset += written;
558         }
559     }
560     fprintf(fp, "%s", buf);
561 }
562 #endif /* PROFILING */
563
564 rtsBool
565 strMatchesSelector( char* str, char* sel )
566 {
567    char* p;
568    // debugBelch("str_matches_selector %s %s\n", str, sel);
569    while (1) {
570        // Compare str against wherever we've got to in sel.
571        p = str;
572        while (*p != '\0' && *sel != ',' && *sel != '\0' && *p == *sel) {
573            p++; sel++;
574        }
575        // Match if all of str used and have reached the end of a sel fragment.
576        if (*p == '\0' && (*sel == ',' || *sel == '\0'))
577            return rtsTrue;
578        
579        // No match.  Advance sel to the start of the next elem.
580        while (*sel != ',' && *sel != '\0') sel++;
581        if (*sel == ',') sel++;
582        
583        /* Run out of sel ?? */
584        if (*sel == '\0') return rtsFalse;
585    }
586 }
587
588 /* -----------------------------------------------------------------------------
589  * Figure out whether a closure should be counted in this census, by
590  * testing against all the specified constraints.
591  * -------------------------------------------------------------------------- */
592 rtsBool
593 closureSatisfiesConstraints( StgClosure* p )
594 {
595 #ifdef DEBUG_HEAP_PROF
596     (void)p;   /* keep gcc -Wall happy */
597     return rtsTrue;
598 #else
599    rtsBool b;
600
601    // The CCS has a selected field to indicate whether this closure is
602    // deselected by not being mentioned in the module, CC, or CCS
603    // selectors.
604    if (!p->header.prof.ccs->selected) {
605        return rtsFalse;
606    }
607
608    if (RtsFlags.ProfFlags.descrSelector) {
609        b = strMatchesSelector( (get_itbl((StgClosure *)p))->prof.closure_desc,
610                                  RtsFlags.ProfFlags.descrSelector );
611        if (!b) return rtsFalse;
612    }
613    if (RtsFlags.ProfFlags.typeSelector) {
614        b = strMatchesSelector( (get_itbl((StgClosure *)p))->prof.closure_type,
615                                 RtsFlags.ProfFlags.typeSelector );
616        if (!b) return rtsFalse;
617    }
618    if (RtsFlags.ProfFlags.retainerSelector) {
619        RetainerSet *rs;
620        nat i;
621        // We must check that the retainer set is valid here.  One
622        // reason it might not be valid is if this closure is a
623        // a newly deceased weak pointer (i.e. a DEAD_WEAK), since
624        // these aren't reached by the retainer profiler's traversal.
625        if (isRetainerSetFieldValid((StgClosure *)p)) {
626            rs = retainerSetOf((StgClosure *)p);
627            if (rs != NULL) {
628                for (i = 0; i < rs->num; i++) {
629                    b = strMatchesSelector( rs->element[i]->cc->label,
630                                            RtsFlags.ProfFlags.retainerSelector );
631                    if (b) return rtsTrue;
632                }
633            }
634        }
635        return rtsFalse;
636    }
637    return rtsTrue;
638 #endif /* PROFILING */
639 }
640
641 /* -----------------------------------------------------------------------------
642  * Aggregate the heap census info for biographical profiling
643  * -------------------------------------------------------------------------- */
644 #ifdef PROFILING
645 static void
646 aggregateCensusInfo( void )
647 {
648     HashTable *acc;
649     nat t;
650     counter *c, *d, *ctrs;
651     Arena *arena;
652
653     if (!doingLDVProfiling()) return;
654
655     // Aggregate the LDV counters when displaying by biography.
656     if (RtsFlags.ProfFlags.doHeapProfile == HEAP_BY_LDV) {
657         int void_total, drag_total;
658
659         // Now we compute void_total and drag_total for each census
660         void_total = 0;
661         drag_total = 0;
662         for (t = 1; t < era; t++) { // note: start at 1, not 0
663             void_total += censuses[t].void_total;
664             drag_total += censuses[t].drag_total;
665             censuses[t].void_total = void_total;
666             censuses[t].drag_total = drag_total;
667             ASSERT( censuses[t].void_total <= censuses[t].not_used );
668             ASSERT( censuses[t].drag_total <= censuses[t].used );
669         }
670         
671         return;
672     }
673
674     // otherwise... we're doing a heap profile that is restricted to
675     // some combination of lag, drag, void or use.  We've kept all the
676     // census info for all censuses so far, but we still need to
677     // aggregate the counters forwards.
678
679     arena = newArena();
680     acc = allocHashTable();
681     ctrs = NULL;
682
683     for (t = 1; t < era; t++) {
684
685         // first look through all the counters we're aggregating
686         for (c = ctrs; c != NULL; c = c->next) {
687             // if one of the totals is non-zero, then this closure
688             // type must be present in the heap at this census time...
689             d = lookupHashTable(censuses[t].hash, (StgWord)c->identity);
690
691             if (d == NULL) {
692                 // if this closure identity isn't present in the
693                 // census for this time period, then our running
694                 // totals *must* be zero.
695                 ASSERT(c->c.ldv.void_total == 0 && c->c.ldv.drag_total == 0);
696
697                 // debugCCS(c->identity);
698                 // debugBelch(" census=%d void_total=%d drag_total=%d\n",
699                 //         t, c->c.ldv.void_total, c->c.ldv.drag_total);
700             } else {
701                 d->c.ldv.void_total += c->c.ldv.void_total;
702                 d->c.ldv.drag_total += c->c.ldv.drag_total;
703                 c->c.ldv.void_total =  d->c.ldv.void_total;
704                 c->c.ldv.drag_total =  d->c.ldv.drag_total;
705
706                 ASSERT( c->c.ldv.void_total >= 0 );
707                 ASSERT( c->c.ldv.drag_total >= 0 );
708             }
709         }
710
711         // now look through the counters in this census to find new ones
712         for (c = censuses[t].ctrs; c != NULL; c = c->next) {
713             d = lookupHashTable(acc, (StgWord)c->identity);
714             if (d == NULL) {
715                 d = arenaAlloc( arena, sizeof(counter) );
716                 initLDVCtr(d);
717                 insertHashTable( acc, (StgWord)c->identity, d );
718                 d->identity = c->identity;
719                 d->next = ctrs;
720                 ctrs = d;
721                 d->c.ldv.void_total = c->c.ldv.void_total;
722                 d->c.ldv.drag_total = c->c.ldv.drag_total;
723             }
724             ASSERT( c->c.ldv.void_total >= 0 );
725             ASSERT( c->c.ldv.drag_total >= 0 );
726         }
727     }
728
729     freeHashTable(acc, NULL);
730     arenaFree(arena);
731 }
732 #endif
733
734 /* -----------------------------------------------------------------------------
735  * Print out the results of a heap census.
736  * -------------------------------------------------------------------------- */
737 static void
738 dumpCensus( Census *census )
739 {
740     counter *ctr;
741     int count;
742
743     printSample(rtsTrue, census->time);
744
745 #ifdef PROFILING
746     if (RtsFlags.ProfFlags.doHeapProfile == HEAP_BY_LDV) {
747         fprintf(hp_file, "VOID\t%lu\n", census->void_total * sizeof(W_));
748         fprintf(hp_file, "LAG\t%lu\n", 
749                 (census->not_used - census->void_total) * sizeof(W_));
750         fprintf(hp_file, "USE\t%lu\n", 
751                 (census->used - census->drag_total) * sizeof(W_));
752         fprintf(hp_file, "INHERENT_USE\t%lu\n", 
753                 census->prim * sizeof(W_));
754         fprintf(hp_file, "DRAG\t%lu\n", census->drag_total *
755                 sizeof(W_));
756         printSample(rtsFalse, census->time);
757         return;
758     }
759 #endif
760
761     for (ctr = census->ctrs; ctr != NULL; ctr = ctr->next) {
762
763 #ifdef PROFILING
764         if (RtsFlags.ProfFlags.bioSelector != NULL) {
765             count = 0;
766             if (strMatchesSelector("lag", RtsFlags.ProfFlags.bioSelector))
767                 count += ctr->c.ldv.not_used - ctr->c.ldv.void_total;
768             if (strMatchesSelector("drag", RtsFlags.ProfFlags.bioSelector))
769                 count += ctr->c.ldv.drag_total;
770             if (strMatchesSelector("void", RtsFlags.ProfFlags.bioSelector))
771                 count += ctr->c.ldv.void_total;
772             if (strMatchesSelector("use", RtsFlags.ProfFlags.bioSelector))
773                 count += ctr->c.ldv.used - ctr->c.ldv.drag_total;
774         } else
775 #endif
776         {
777             count = ctr->c.resid;
778         }
779
780         ASSERT( count >= 0 );
781
782         if (count == 0) continue;
783
784 #ifdef DEBUG_HEAP_PROF
785         switch (RtsFlags.ProfFlags.doHeapProfile) {
786         case HEAP_BY_INFOPTR:
787             fprintf(hp_file, "%s", lookupGHCName(ctr->identity));
788             break;
789         case HEAP_BY_CLOSURE_TYPE:
790             fprintf(hp_file, "%s", (char *)ctr->identity);
791             break;
792         }
793 #endif
794         
795 #ifdef PROFILING
796         switch (RtsFlags.ProfFlags.doHeapProfile) {
797         case HEAP_BY_CCS:
798             fprint_ccs(hp_file, (CostCentreStack *)ctr->identity, 25);
799             break;
800         case HEAP_BY_MOD:
801         case HEAP_BY_DESCR:
802         case HEAP_BY_TYPE:
803             fprintf(hp_file, "%s", (char *)ctr->identity);
804             break;
805         case HEAP_BY_RETAINER:
806         {
807             RetainerSet *rs = (RetainerSet *)ctr->identity;
808
809             // it might be the distinguished retainer set rs_MANY:
810             if (rs == &rs_MANY) {
811                 fprintf(hp_file, "MANY");
812                 break;
813             }
814
815             // Mark this retainer set by negating its id, because it
816             // has appeared in at least one census.  We print the
817             // values of all such retainer sets into the log file at
818             // the end.  A retainer set may exist but not feature in
819             // any censuses if it arose as the intermediate retainer
820             // set for some closure during retainer set calculation.
821             if (rs->id > 0)
822                 rs->id = -(rs->id);
823
824             // report in the unit of bytes: * sizeof(StgWord)
825             printRetainerSetShort(hp_file, rs);
826             break;
827         }
828         default:
829             barf("dumpCensus; doHeapProfile");
830         }
831 #endif
832
833         fprintf(hp_file, "\t%ld\n", count * sizeof(W_));
834     }
835
836     printSample(rtsFalse, census->time);
837 }
838
839 /* -----------------------------------------------------------------------------
840  * Code to perform a heap census.
841  * -------------------------------------------------------------------------- */
842 static void
843 heapCensusChain( Census *census, bdescr *bd )
844 {
845     StgPtr p;
846     StgInfoTable *info;
847     void *identity;
848     nat size;
849     counter *ctr;
850     nat real_size;
851     rtsBool prim;
852
853     for (; bd != NULL; bd = bd->link) {
854
855         // HACK: ignore pinned blocks, because they contain gaps.
856         // It's not clear exactly what we'd like to do here, since we
857         // can't tell which objects in the block are actually alive.
858         // Perhaps the whole block should be counted as SYSTEM memory.
859         if (bd->flags & BF_PINNED) {
860             continue;
861         }
862
863         p = bd->start;
864         while (p < bd->free) {
865             info = get_itbl((StgClosure *)p);
866             prim = rtsFalse;
867             
868             switch (info->type) {
869
870             case CONSTR:
871             case FUN:
872             case THUNK:
873             case IND_PERM:
874             case IND_OLDGEN:
875             case IND_OLDGEN_PERM:
876             case CAF_BLACKHOLE:
877             case SE_CAF_BLACKHOLE:
878             case SE_BLACKHOLE:
879             case BLACKHOLE:
880             case CONSTR_INTLIKE:
881             case CONSTR_CHARLIKE:
882             case FUN_1_0:
883             case FUN_0_1:
884             case FUN_1_1:
885             case FUN_0_2:
886             case FUN_2_0:
887             case THUNK_1_1:
888             case THUNK_0_2:
889             case THUNK_2_0:
890             case CONSTR_1_0:
891             case CONSTR_0_1:
892             case CONSTR_1_1:
893             case CONSTR_0_2:
894             case CONSTR_2_0:
895                 size = sizeW_fromITBL(info);
896                 break;
897                 
898             case BCO:
899                 prim = rtsTrue;
900                 size = bco_sizeW((StgBCO *)p);
901                 break;
902
903             case MVAR:
904             case WEAK:
905             case FOREIGN:
906             case STABLE_NAME:
907             case MUT_VAR:
908                 prim = rtsTrue;
909                 size = sizeW_fromITBL(info);
910                 break;
911
912             case THUNK_1_0:             /* ToDo - shouldn't be here */
913             case THUNK_0_1:             /* "  ditto  " */
914             case THUNK_SELECTOR:
915                 size = sizeofW(StgHeader) + MIN_UPD_SIZE;
916                 break;
917
918             case AP:
919             case PAP:
920                 size = pap_sizeW((StgPAP *)p);
921                 break;
922
923             case AP_STACK:
924                 size = ap_stack_sizeW((StgAP_STACK *)p);
925                 break;
926                 
927             case ARR_WORDS:
928                 prim = rtsTrue;
929                 size = arr_words_sizeW(stgCast(StgArrWords*,p));
930                 break;
931                 
932             case MUT_ARR_PTRS:
933             case MUT_ARR_PTRS_FROZEN:
934                 prim = rtsTrue;
935                 size = mut_arr_ptrs_sizeW((StgMutArrPtrs *)p);
936                 break;
937                 
938             case TSO:
939                 prim = rtsTrue;
940 #ifdef DEBUG_HEAP_PROF
941                 size = tso_sizeW((StgTSO *)p);
942                 break;
943 #else
944                 if (RtsFlags.ProfFlags.includeTSOs) {
945                     size = tso_sizeW((StgTSO *)p);
946                     break;
947                 } else {
948                     // Skip this TSO and move on to the next object
949                     p += tso_sizeW((StgTSO *)p);
950                     continue;
951                 }
952 #endif
953
954             default:
955                 barf("heapCensus");
956             }
957             
958             identity = NULL;
959
960 #ifdef DEBUG_HEAP_PROF
961             real_size = size;
962 #else
963             // subtract the profiling overhead
964             real_size = size - sizeofW(StgProfHeader);
965 #endif
966
967             if (closureSatisfiesConstraints((StgClosure*)p)) {
968 #ifdef PROFILING
969                 if (RtsFlags.ProfFlags.doHeapProfile == HEAP_BY_LDV) {
970                     if (prim)
971                         census->prim += real_size;
972                     else if ((LDVW(p) & LDV_STATE_MASK) == LDV_STATE_CREATE)
973                         census->not_used += real_size;
974                     else
975                         census->used += real_size;
976                 } else
977 #endif
978                 {
979                     identity = closureIdentity((StgClosure *)p);
980
981                     if (identity != NULL) {
982                         ctr = lookupHashTable( census->hash, (StgWord)identity );
983                         if (ctr != NULL) {
984 #ifdef PROFILING
985                             if (RtsFlags.ProfFlags.bioSelector != NULL) {
986                                 if (prim)
987                                     ctr->c.ldv.prim += real_size;
988                                 else if ((LDVW(p) & LDV_STATE_MASK) == LDV_STATE_CREATE)
989                                     ctr->c.ldv.not_used += real_size;
990                                 else
991                                     ctr->c.ldv.used += real_size;
992                             } else
993 #endif
994                             {
995                                 ctr->c.resid += real_size;
996                             }
997                         } else {
998                             ctr = arenaAlloc( census->arena, sizeof(counter) );
999                             initLDVCtr(ctr);
1000                             insertHashTable( census->hash, (StgWord)identity, ctr );
1001                             ctr->identity = identity;
1002                             ctr->next = census->ctrs;
1003                             census->ctrs = ctr;
1004
1005 #ifdef PROFILING
1006                             if (RtsFlags.ProfFlags.bioSelector != NULL) {
1007                                 if (prim)
1008                                     ctr->c.ldv.prim = real_size;
1009                                 else if ((LDVW(p) & LDV_STATE_MASK) == LDV_STATE_CREATE)
1010                                     ctr->c.ldv.not_used = real_size;
1011                                 else
1012                                     ctr->c.ldv.used = real_size;
1013                             } else
1014 #endif
1015                             {
1016                                 ctr->c.resid = real_size;
1017                             }
1018                         }
1019                     }
1020                 }
1021             }
1022
1023             p += size;
1024         }
1025     }
1026 }
1027
1028 void
1029 heapCensus( void )
1030 {
1031   nat g, s;
1032   Census *census;
1033
1034   census = &censuses[era];
1035   census->time  = mut_user_time();
1036     
1037   // calculate retainer sets if necessary
1038 #ifdef PROFILING
1039   if (doingRetainerProfiling()) {
1040       retainerProfile();
1041   }
1042 #endif
1043
1044 #ifdef PROFILING
1045   stat_startHeapCensus();
1046 #endif
1047
1048   // Traverse the heap, collecting the census info
1049
1050   // First the small_alloc_list: we have to fix the free pointer at
1051   // the end by calling tidyAllocatedLists() first.
1052   tidyAllocateLists();
1053   heapCensusChain( census, small_alloc_list );
1054
1055   // Now traverse the heap in each generation/step.
1056   if (RtsFlags.GcFlags.generations == 1) {
1057       heapCensusChain( census, g0s0->to_blocks );
1058   } else {
1059       for (g = 0; g < RtsFlags.GcFlags.generations; g++) {
1060           for (s = 0; s < generations[g].n_steps; s++) {
1061               heapCensusChain( census, generations[g].steps[s].blocks );
1062               // Are we interested in large objects?  might be
1063               // confusing to include the stack in a heap profile.
1064               heapCensusChain( census, generations[g].steps[s].large_objects );
1065           }
1066       }
1067   }
1068
1069   // dump out the census info
1070 #ifdef PROFILING
1071     // We can't generate any info for LDV profiling until
1072     // the end of the run...
1073     if (!doingLDVProfiling())
1074         dumpCensus( census );
1075 #else
1076     dumpCensus( census );
1077 #endif
1078
1079
1080   // free our storage, unless we're keeping all the census info for
1081   // future restriction by biography.
1082 #ifdef PROFILING
1083   if (RtsFlags.ProfFlags.bioSelector == NULL)
1084 #endif
1085   {
1086       freeHashTable( census->hash, NULL/* don't free the elements */ );
1087       arenaFree( census->arena );
1088       census->hash = NULL;
1089       census->arena = NULL;
1090   }
1091
1092   // we're into the next time period now
1093   nextEra();
1094
1095 #ifdef PROFILING
1096   stat_endHeapCensus();
1097 #endif
1098 }    
1099
1100 #endif /* PROFILING || DEBUG_HEAP_PROF */
1101