[project @ 2003-08-22 22:24:12 by sof]
[ghc-hetmet.git] / ghc / rts / ProfHeap.c
1 /* -----------------------------------------------------------------------------
2  * $Id: ProfHeap.c,v 1.47 2003/08/22 22:24:12 sof Exp $
3  *
4  * (c) The GHC Team, 1998-2003
5  *
6  * Support for heap profiling
7  *
8  * ---------------------------------------------------------------------------*/
9
10 #if defined(DEBUG) && !defined(PROFILING)
11 #define DEBUG_HEAP_PROF
12 #else
13 #undef DEBUG_HEAP_PROF
14 #endif
15
16 #if defined(PROFILING) || defined(DEBUG_HEAP_PROF)
17
18 #include "PosixSource.h"
19 #include "Rts.h"
20 #include "RtsUtils.h"
21 #include "RtsFlags.h"
22 #include "Profiling.h"
23 #include "Storage.h"
24 #include "ProfHeap.h"
25 #include "Stats.h"
26 #include "Hash.h"
27 #include "StrHash.h"
28 #include "RetainerProfile.h"
29 #include "LdvProfile.h"
30 #include "Arena.h"
31 #include "Printer.h"
32
33 #include <string.h>
34 #include <stdlib.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 nat 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     , "BLACKHOLE_BQ"
154     , "MVAR"
155
156     , "ARR_WORDS"
157
158     , "MUT_ARR_PTRS"
159     , "MUT_ARR_PTRS_FROZEN"
160     , "MUT_VAR"
161
162     , "WEAK"
163     , "FOREIGN"
164   
165     , "TSO"
166
167     , "BLOCKED_FETCH"
168     , "FETCH_ME"
169
170     , "EVACUATED"
171 };
172
173 #endif /* DEBUG_HEAP_PROF */
174
175 /* -----------------------------------------------------------------------------
176  * Find the "closure identity", which is a unique pointer reresenting
177  * the band to which this closure's heap space is attributed in the
178  * heap profile.
179  * ------------------------------------------------------------------------- */
180 static inline void *
181 closureIdentity( StgClosure *p )
182 {
183     switch (RtsFlags.ProfFlags.doHeapProfile) {
184
185 #ifdef PROFILING
186     case HEAP_BY_CCS:
187         return p->header.prof.ccs;
188     case HEAP_BY_MOD:
189         return p->header.prof.ccs->cc->module;
190     case HEAP_BY_DESCR:
191         return get_itbl(p)->prof.closure_desc;
192     case HEAP_BY_TYPE:
193         return get_itbl(p)->prof.closure_type;
194     case HEAP_BY_RETAINER:
195         // AFAIK, the only closures in the heap which might not have a
196         // valid retainer set are DEAD_WEAK closures.
197         if (isRetainerSetFieldValid(p))
198             return retainerSetOf(p);
199         else
200             return NULL;
201
202 #else // DEBUG
203     case HEAP_BY_INFOPTR:
204         return (void *)((StgClosure *)p)->header.info; 
205     case HEAP_BY_CLOSURE_TYPE:
206         return type_names[get_itbl(p)->type];
207
208 #endif
209     default:
210         barf("closureIdentity");
211     }
212 }
213
214 /* --------------------------------------------------------------------------
215  * Profiling type predicates
216  * ----------------------------------------------------------------------- */
217 #ifdef PROFILING
218 static inline rtsBool
219 doingLDVProfiling( void )
220 {
221     return (RtsFlags.ProfFlags.doHeapProfile == HEAP_BY_LDV 
222             || RtsFlags.ProfFlags.bioSelector != NULL);
223 }
224
225 static inline rtsBool
226 doingRetainerProfiling( void )
227 {
228     return (RtsFlags.ProfFlags.doHeapProfile == HEAP_BY_RETAINER
229             || RtsFlags.ProfFlags.retainerSelector != NULL);
230 }
231 #endif // PROFILING
232
233 // Precesses a closure 'c' being destroyed whose size is 'size'.
234 // Make sure that LDV_recordDead() is not invoked on 'inherently used' closures
235 // such as TSO; they should not be involved in computing dragNew or voidNew.
236 // 
237 // Even though era is checked in both LdvCensusForDead() and 
238 // LdvCensusKillAll(), we still need to make sure that era is > 0 because 
239 // LDV_recordDead() may be called from elsewhere in the runtime system. E.g., 
240 // when a thunk is replaced by an indirection object.
241
242 #ifdef PROFILING
243 void
244 LDV_recordDead( StgClosure *c, nat size )
245 {
246     void *id;
247     nat t;
248     counter *ctr;
249
250     if (era > 0 && closureSatisfiesConstraints(c)) {
251         size -= sizeofW(StgProfHeader);
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             prog_belch("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
355 void initProfiling1( void )
356 {
357 }
358
359 void initProfiling2( void )
360 {
361   initHeapProfiling();
362 }
363
364 void endProfiling( void )
365 {
366   endHeapProfiling();
367 }
368 #endif /* DEBUG_HEAP_PROF */
369
370 /* --------------------------------------------------------------------------
371  * Initialize the heap profilier
372  * ----------------------------------------------------------------------- */
373 nat
374 initHeapProfiling(void)
375 {
376     if (! RtsFlags.ProfFlags.doHeapProfile) {
377         return 0;
378     }
379
380 #ifdef PROFILING
381     if (doingLDVProfiling() && doingRetainerProfiling()) {
382         prog_belch("cannot mix -hb and -hr");
383         stg_exit(1);
384     }
385 #endif
386
387     // we only count eras if we're doing LDV profiling.  Otherwise era
388     // is fixed at zero.
389 #ifdef PROFILING
390     if (doingLDVProfiling()) {
391         era = 1;
392     } else
393 #endif
394     {
395         era = 0;
396     }
397
398     {   // max_era = 2^LDV_SHIFT
399         nat p;
400         max_era = 1;
401         for (p = 0; p < LDV_SHIFT; p++)
402             max_era *= 2;
403     }
404
405     n_censuses = 32;
406     censuses = stgMallocBytes(sizeof(Census) * n_censuses, "initHeapProfiling");
407
408     initEra( &censuses[era] );
409
410     fprintf(hp_file, "JOB \"%s", prog_name);
411
412 #ifdef PROFILING
413     {
414         int count;
415         for(count = 1; count < prog_argc; count++)
416             fprintf(hp_file, " %s", prog_argv[count]);
417         fprintf(hp_file, " +RTS ");
418         for(count = 0; count < rts_argc; count++)
419             fprintf(hp_file, "%s ", rts_argv[count]);
420         fprintf(hp_file, "\n");
421     }
422 #endif /* PROFILING */
423
424     fprintf(hp_file, "\"\n" );
425
426     fprintf(hp_file, "DATE \"%s\"\n", time_str());
427
428     fprintf(hp_file, "SAMPLE_UNIT \"seconds\"\n");
429     fprintf(hp_file, "VALUE_UNIT \"bytes\"\n");
430
431     fprintf(hp_file, "BEGIN_SAMPLE 0.00\n");
432     fprintf(hp_file, "END_SAMPLE 0.00\n");
433
434 #ifdef DEBUG_HEAP_PROF
435     DEBUG_LoadSymbols(prog_name);
436 #endif
437
438 #ifdef PROFILING
439     if (doingRetainerProfiling()) {
440         initRetainerProfiling();
441     }
442 #endif
443
444     return 0;
445 }
446
447 void
448 endHeapProfiling(void)
449 {
450     StgDouble seconds;
451
452     if (! RtsFlags.ProfFlags.doHeapProfile) {
453         return;
454     }
455
456 #ifdef PROFILING
457     if (doingRetainerProfiling()) {
458         endRetainerProfiling();
459     }
460 #endif
461
462 #ifdef PROFILING
463     if (doingLDVProfiling()) {
464         nat t;
465         LdvCensusKillAll();
466         aggregateCensusInfo();
467         for (t = 1; t < era; t++) {
468             dumpCensus( &censuses[t] );
469         }
470     }
471 #endif
472
473     seconds = mut_user_time();
474     fprintf(hp_file, "BEGIN_SAMPLE %0.2f\n", seconds);
475     fprintf(hp_file, "END_SAMPLE %0.2f\n", seconds);
476     fclose(hp_file);
477 }
478
479
480
481 #ifdef PROFILING
482 static size_t
483 buf_append(char *p, const char *q, char *end)
484 {
485     int m;
486
487     for (m = 0; p < end; p++, q++, m++) {
488         *p = *q;
489         if (*q == '\0') { break; }
490     }
491     return m;
492 }
493
494 static void
495 fprint_ccs(FILE *fp, CostCentreStack *ccs, nat max_length)
496 {
497     char buf[max_length+1], *p, *buf_end;
498     nat next_offset = 0;
499     nat written;
500
501     // MAIN on its own gets printed as "MAIN", otherwise we ignore MAIN.
502     if (ccs == CCS_MAIN) {
503         fprintf(fp, "MAIN");
504         return;
505     }
506
507     fprintf(fp, "(%d)", ccs->ccsID);
508
509     p = buf;
510     buf_end = buf + max_length + 1;
511
512     // keep printing components of the stack until we run out of space
513     // in the buffer.  If we run out of space, end with "...".
514     for (; ccs != NULL && ccs != CCS_MAIN; ccs = ccs->prevStack) {
515
516         // CAF cost centres print as M.CAF, but we leave the module
517         // name out of all the others to save space.
518         if (!strcmp(ccs->cc->label,"CAF")) {
519             p += buf_append(p, ccs->cc->module, buf_end);
520             p += buf_append(p, ".CAF", buf_end);
521         } else {
522             if (ccs->prevStack != NULL && ccs->prevStack != CCS_MAIN) {
523                 p += buf_append(p, "/", buf_end);
524             }
525             p += buf_append(p, ccs->cc->label, buf_end);
526         }
527         
528         if (p >= buf_end) {
529             sprintf(buf+max_length-4, "...");
530             break;
531         } else {
532             next_offset += written;
533         }
534     }
535     fprintf(fp, "%s", buf);
536 }
537 #endif // PROFILING
538
539 rtsBool
540 strMatchesSelector( char* str, char* sel )
541 {
542    char* p;
543    // fprintf(stderr, "str_matches_selector %s %s\n", str, sel);
544    while (1) {
545        // Compare str against wherever we've got to in sel.
546        p = str;
547        while (*p != '\0' && *sel != ',' && *sel != '\0' && *p == *sel) {
548            p++; sel++;
549        }
550        // Match if all of str used and have reached the end of a sel fragment.
551        if (*p == '\0' && (*sel == ',' || *sel == '\0'))
552            return rtsTrue;
553        
554        // No match.  Advance sel to the start of the next elem.
555        while (*sel != ',' && *sel != '\0') sel++;
556        if (*sel == ',') sel++;
557        
558        /* Run out of sel ?? */
559        if (*sel == '\0') return rtsFalse;
560    }
561 }
562
563 /* -----------------------------------------------------------------------------
564  * Figure out whether a closure should be counted in this census, by
565  * testing against all the specified constraints.
566  * -------------------------------------------------------------------------- */
567 rtsBool
568 closureSatisfiesConstraints( StgClosure* p )
569 {
570 #ifdef DEBUG_HEAP_PROF
571     return rtsTrue;
572 #else
573    rtsBool b;
574
575    // The CCS has a selected field to indicate whether this closure is
576    // deselected by not being mentioned in the module, CC, or CCS
577    // selectors.
578    if (!p->header.prof.ccs->selected) {
579        return rtsFalse;
580    }
581
582    if (RtsFlags.ProfFlags.descrSelector) {
583        b = strMatchesSelector( (get_itbl((StgClosure *)p))->prof.closure_desc,
584                                  RtsFlags.ProfFlags.descrSelector );
585        if (!b) return rtsFalse;
586    }
587    if (RtsFlags.ProfFlags.typeSelector) {
588        b = strMatchesSelector( (get_itbl((StgClosure *)p))->prof.closure_type,
589                                 RtsFlags.ProfFlags.typeSelector );
590        if (!b) return rtsFalse;
591    }
592    if (RtsFlags.ProfFlags.retainerSelector) {
593        RetainerSet *rs;
594        nat i;
595        // We must check that the retainer set is valid here.  One
596        // reason it might not be valid is if this closure is a
597        // a newly deceased weak pointer (i.e. a DEAD_WEAK), since
598        // these aren't reached by the retainer profiler's traversal.
599        if (isRetainerSetFieldValid((StgClosure *)p)) {
600            rs = retainerSetOf((StgClosure *)p);
601            if (rs != NULL) {
602                for (i = 0; i < rs->num; i++) {
603                    b = strMatchesSelector( rs->element[i]->cc->label,
604                                            RtsFlags.ProfFlags.retainerSelector );
605                    if (b) return rtsTrue;
606                }
607            }
608        }
609        return rtsFalse;
610    }
611    return rtsTrue;
612 #endif /* PROFILING */
613 }
614
615 /* -----------------------------------------------------------------------------
616  * Aggregate the heap census info for biographical profiling
617  * -------------------------------------------------------------------------- */
618 #ifdef PROFILING
619 static void
620 aggregateCensusInfo( void )
621 {
622     HashTable *acc;
623     nat t;
624     counter *c, *d, *ctrs;
625     Arena *arena;
626
627     if (!doingLDVProfiling()) return;
628
629     // Aggregate the LDV counters when displaying by biography.
630     if (RtsFlags.ProfFlags.doHeapProfile == HEAP_BY_LDV) {
631         int void_total, drag_total;
632
633         // Now we compute void_total and drag_total for each census
634         void_total = 0;
635         drag_total = 0;
636         for (t = 1; t < era; t++) { // note: start at 1, not 0
637             void_total += censuses[t].void_total;
638             drag_total += censuses[t].drag_total;
639             censuses[t].void_total = void_total;
640             censuses[t].drag_total = drag_total;
641             ASSERT( censuses[t].void_total <= censuses[t].not_used );
642             ASSERT( censuses[t].drag_total <= censuses[t].used );
643         }
644         
645         return;
646     }
647
648     // otherwise... we're doing a heap profile that is restricted to
649     // some combination of lag, drag, void or use.  We've kept all the
650     // census info for all censuses so far, but we still need to
651     // aggregate the counters forwards.
652
653     arena = newArena();
654     acc = allocHashTable();
655     ctrs = NULL;
656
657     for (t = 1; t < era; t++) {
658
659         // first look through all the counters we're aggregating
660         for (c = ctrs; c != NULL; c = c->next) {
661             // if one of the totals is non-zero, then this closure
662             // type must be present in the heap at this census time...
663             d = lookupHashTable(censuses[t].hash, (StgWord)c->identity);
664
665             if (d == NULL) {
666                 // if this closure identity isn't present in the
667                 // census for this time period, then our running
668                 // totals *must* be zero.
669                 ASSERT(c->c.ldv.void_total == 0 && c->c.ldv.drag_total == 0);
670
671                 // fprintCCS(stderr,c->identity);
672                 // fprintf(stderr," census=%d void_total=%d drag_total=%d\n",
673                 //         t, c->c.ldv.void_total, c->c.ldv.drag_total);
674             } else {
675                 d->c.ldv.void_total += c->c.ldv.void_total;
676                 d->c.ldv.drag_total += c->c.ldv.drag_total;
677                 c->c.ldv.void_total =  d->c.ldv.void_total;
678                 c->c.ldv.drag_total =  d->c.ldv.drag_total;
679
680                 ASSERT( c->c.ldv.void_total >= 0 );
681                 ASSERT( c->c.ldv.drag_total >= 0 );
682             }
683         }
684
685         // now look through the counters in this census to find new ones
686         for (c = censuses[t].ctrs; c != NULL; c = c->next) {
687             d = lookupHashTable(acc, (StgWord)c->identity);
688             if (d == NULL) {
689                 d = arenaAlloc( arena, sizeof(counter) );
690                 initLDVCtr(d);
691                 insertHashTable( acc, (StgWord)c->identity, d );
692                 d->identity = c->identity;
693                 d->next = ctrs;
694                 ctrs = d;
695                 d->c.ldv.void_total = c->c.ldv.void_total;
696                 d->c.ldv.drag_total = c->c.ldv.drag_total;
697             }
698             ASSERT( c->c.ldv.void_total >= 0 );
699             ASSERT( c->c.ldv.drag_total >= 0 );
700         }
701     }
702
703     freeHashTable(acc, NULL);
704     arenaFree(arena);
705 }
706 #endif
707
708 /* -----------------------------------------------------------------------------
709  * Print out the results of a heap census.
710  * -------------------------------------------------------------------------- */
711 static void
712 dumpCensus( Census *census )
713 {
714     counter *ctr;
715     int count;
716
717     fprintf(hp_file, "BEGIN_SAMPLE %0.2f\n", census->time);
718
719 #ifdef PROFILING
720     if (RtsFlags.ProfFlags.doHeapProfile == HEAP_BY_LDV) {
721         fprintf(hp_file, "VOID\t%u\n", census->void_total * sizeof(W_));
722         fprintf(hp_file, "LAG\t%u\n", 
723                 (census->not_used - census->void_total) * sizeof(W_));
724         fprintf(hp_file, "USE\t%u\n", 
725                 (census->used - census->drag_total) * sizeof(W_));
726         fprintf(hp_file, "INHERENT_USE\t%u\n", 
727                 census->prim * sizeof(W_));
728         fprintf(hp_file, "DRAG\t%u\n", census->drag_total *
729                 sizeof(W_));
730         fprintf(hp_file, "END_SAMPLE %0.2f\n", census->time);
731         return;
732     }
733 #endif
734
735     for (ctr = census->ctrs; ctr != NULL; ctr = ctr->next) {
736
737 #ifdef PROFILING
738         if (RtsFlags.ProfFlags.bioSelector != NULL) {
739             count = 0;
740             if (strMatchesSelector("lag", RtsFlags.ProfFlags.bioSelector))
741                 count += ctr->c.ldv.not_used - ctr->c.ldv.void_total;
742             if (strMatchesSelector("drag", RtsFlags.ProfFlags.bioSelector))
743                 count += ctr->c.ldv.drag_total;
744             if (strMatchesSelector("void", RtsFlags.ProfFlags.bioSelector))
745                 count += ctr->c.ldv.void_total;
746             if (strMatchesSelector("use", RtsFlags.ProfFlags.bioSelector))
747                 count += ctr->c.ldv.used - ctr->c.ldv.drag_total;
748         } else
749 #endif
750         {
751             count = ctr->c.resid;
752         }
753
754         ASSERT( count >= 0 );
755
756         if (count == 0) continue;
757
758 #ifdef DEBUG_HEAP_PROF
759         switch (RtsFlags.ProfFlags.doHeapProfile) {
760         case HEAP_BY_INFOPTR:
761             fprintf(hp_file, "%s", lookupGHCName(ctr->identity));
762             break;
763         case HEAP_BY_CLOSURE_TYPE:
764             fprintf(hp_file, "%s", (char *)ctr->identity);
765             break;
766         }
767 #endif
768         
769 #ifdef PROFILING
770         switch (RtsFlags.ProfFlags.doHeapProfile) {
771         case HEAP_BY_CCS:
772             fprint_ccs(hp_file, (CostCentreStack *)ctr->identity, 25);
773             break;
774         case HEAP_BY_MOD:
775         case HEAP_BY_DESCR:
776         case HEAP_BY_TYPE:
777             fprintf(hp_file, "%s", (char *)ctr->identity);
778             break;
779         case HEAP_BY_RETAINER:
780         {
781             RetainerSet *rs = (RetainerSet *)ctr->identity;
782
783             // it might be the distinguished retainer set rs_MANY:
784             if (rs == &rs_MANY) {
785                 fprintf(hp_file, "MANY");
786                 break;
787             }
788
789             // Mark this retainer set by negating its id, because it
790             // has appeared in at least one census.  We print the
791             // values of all such retainer sets into the log file at
792             // the end.  A retainer set may exist but not feature in
793             // any censuses if it arose as the intermediate retainer
794             // set for some closure during retainer set calculation.
795             if (rs->id > 0)
796                 rs->id = -(rs->id);
797
798             // report in the unit of bytes: * sizeof(StgWord)
799             printRetainerSetShort(hp_file, rs);
800             break;
801         }
802         default:
803             barf("dumpCensus; doHeapProfile");
804         }
805 #endif
806
807         fprintf(hp_file, "\t%d\n", count * sizeof(W_));
808     }
809
810     fprintf(hp_file, "END_SAMPLE %0.2f\n", census->time);
811 }
812
813 /* -----------------------------------------------------------------------------
814  * Code to perform a heap census.
815  * -------------------------------------------------------------------------- */
816 static void
817 heapCensusChain( Census *census, bdescr *bd )
818 {
819     StgPtr p;
820     StgInfoTable *info;
821     void *identity;
822     nat size;
823     counter *ctr;
824     nat real_size;
825     rtsBool prim;
826
827     for (; bd != NULL; bd = bd->link) {
828         p = bd->start;
829         while (p < bd->free) {
830             info = get_itbl((StgClosure *)p);
831             prim = rtsFalse;
832             
833             switch (info->type) {
834
835             case CONSTR:
836             case FUN:
837             case THUNK:
838             case IND_PERM:
839             case IND_OLDGEN:
840             case IND_OLDGEN_PERM:
841             case CAF_BLACKHOLE:
842             case SE_CAF_BLACKHOLE:
843             case SE_BLACKHOLE:
844             case BLACKHOLE:
845             case BLACKHOLE_BQ:
846             case CONSTR_INTLIKE:
847             case CONSTR_CHARLIKE:
848             case FUN_1_0:
849             case FUN_0_1:
850             case FUN_1_1:
851             case FUN_0_2:
852             case FUN_2_0:
853             case THUNK_1_1:
854             case THUNK_0_2:
855             case THUNK_2_0:
856             case CONSTR_1_0:
857             case CONSTR_0_1:
858             case CONSTR_1_1:
859             case CONSTR_0_2:
860             case CONSTR_2_0:
861                 size = sizeW_fromITBL(info);
862                 break;
863                 
864             case BCO:
865                 prim = rtsTrue;
866                 size = bco_sizeW((StgBCO *)p);
867                 break;
868
869             case MVAR:
870             case WEAK:
871             case FOREIGN:
872             case STABLE_NAME:
873             case MUT_VAR:
874             case MUT_CONS:
875                 prim = rtsTrue;
876                 size = sizeW_fromITBL(info);
877                 break;
878
879             case THUNK_1_0:             /* ToDo - shouldn't be here */
880             case THUNK_0_1:             /* "  ditto  " */
881             case THUNK_SELECTOR:
882                 size = sizeofW(StgHeader) + MIN_UPD_SIZE;
883                 break;
884
885             case AP:
886             case PAP:
887                 size = pap_sizeW((StgPAP *)p);
888                 break;
889
890             case AP_STACK:
891                 size = ap_stack_sizeW((StgAP_STACK *)p);
892                 break;
893                 
894             case ARR_WORDS:
895                 prim = rtsTrue;
896                 size = arr_words_sizeW(stgCast(StgArrWords*,p));
897                 break;
898                 
899             case MUT_ARR_PTRS:
900             case MUT_ARR_PTRS_FROZEN:
901                 prim = rtsTrue;
902                 size = mut_arr_ptrs_sizeW((StgMutArrPtrs *)p);
903                 break;
904                 
905             case TSO:
906                 prim = rtsTrue;
907 #ifdef DEBUG_HEAP_PROF
908                 size = tso_sizeW((StgTSO *)p);
909                 break;
910 #else
911                 if (RtsFlags.ProfFlags.includeTSOs) {
912                     size = tso_sizeW((StgTSO *)p);
913                     break;
914                 } else {
915                     // Skip this TSO and move on to the next object
916                     p += tso_sizeW((StgTSO *)p);
917                     continue;
918                 }
919 #endif
920
921             default:
922                 barf("heapCensus");
923             }
924             
925             identity = NULL;
926
927 #ifdef DEBUG_HEAP_PROF
928             real_size = size;
929 #else
930             // subtract the profiling overhead
931             real_size = size - sizeofW(StgProfHeader);
932 #endif
933
934             if (closureSatisfiesConstraints((StgClosure*)p)) {
935 #ifdef PROFILING
936                 if (RtsFlags.ProfFlags.doHeapProfile == HEAP_BY_LDV) {
937                     if (prim)
938                         census->prim += real_size;
939                     else if ((LDVW(p) & LDV_STATE_MASK) == LDV_STATE_CREATE)
940                         census->not_used += real_size;
941                     else
942                         census->used += real_size;
943                 } else
944 #endif
945                 {
946                     identity = closureIdentity((StgClosure *)p);
947
948                     if (identity != NULL) {
949                         ctr = lookupHashTable( census->hash, (StgWord)identity );
950                         if (ctr != NULL) {
951 #ifdef PROFILING
952                             if (RtsFlags.ProfFlags.bioSelector != NULL) {
953                                 if (prim)
954                                     ctr->c.ldv.prim += real_size;
955                                 else if ((LDVW(p) & LDV_STATE_MASK) == LDV_STATE_CREATE)
956                                     ctr->c.ldv.not_used += real_size;
957                                 else
958                                     ctr->c.ldv.used += real_size;
959                             } else
960 #endif
961                             {
962                                 ctr->c.resid += real_size;
963                             }
964                         } else {
965                             ctr = arenaAlloc( census->arena, sizeof(counter) );
966                             initLDVCtr(ctr);
967                             insertHashTable( census->hash, (StgWord)identity, ctr );
968                             ctr->identity = identity;
969                             ctr->next = census->ctrs;
970                             census->ctrs = ctr;
971
972 #ifdef PROFILING
973                             if (RtsFlags.ProfFlags.bioSelector != NULL) {
974                                 if (prim)
975                                     ctr->c.ldv.prim = real_size;
976                                 else if ((LDVW(p) & LDV_STATE_MASK) == LDV_STATE_CREATE)
977                                     ctr->c.ldv.not_used = real_size;
978                                 else
979                                     ctr->c.ldv.used = real_size;
980                             } else
981 #endif
982                             {
983                                 ctr->c.resid = real_size;
984                             }
985                         }
986                     }
987                 }
988             }
989
990             p += size;
991         }
992     }
993 }
994
995 void
996 heapCensus( void )
997 {
998   nat g, s;
999   Census *census;
1000
1001   census = &censuses[era];
1002   census->time  = mut_user_time();
1003     
1004   // calculate retainer sets if necessary
1005 #ifdef PROFILING
1006   if (doingRetainerProfiling()) {
1007       retainerProfile();
1008   }
1009 #endif
1010
1011 #ifdef PROFILING
1012   stat_startHeapCensus();
1013 #endif
1014
1015   // Traverse the heap, collecting the census info
1016
1017   // First the small_alloc_list: we have to fix the free pointer at
1018   // the end by calling tidyAllocatedLists() first.
1019   tidyAllocateLists();
1020   heapCensusChain( census, small_alloc_list );
1021
1022   // Now traverse the heap in each generation/step.
1023   if (RtsFlags.GcFlags.generations == 1) {
1024       heapCensusChain( census, g0s0->to_blocks );
1025   } else {
1026       for (g = 0; g < RtsFlags.GcFlags.generations; g++) {
1027           for (s = 0; s < generations[g].n_steps; s++) {
1028               heapCensusChain( census, generations[g].steps[s].blocks );
1029               // Are we interested in large objects?  might be
1030               // confusing to include the stack in a heap profile.
1031               heapCensusChain( census, generations[g].steps[s].large_objects );
1032           }
1033       }
1034   }
1035
1036   // dump out the census info
1037 #ifdef PROFILING
1038     // We can't generate any info for LDV profiling until
1039     // the end of the run...
1040     if (!doingLDVProfiling())
1041         dumpCensus( census );
1042 #else
1043     dumpCensus( census );
1044 #endif
1045
1046
1047   // free our storage, unless we're keeping all the census info for
1048   // future restriction by biography.
1049 #ifdef PROFILING
1050   if (RtsFlags.ProfFlags.bioSelector == NULL)
1051 #endif
1052   {
1053       freeHashTable( census->hash, NULL/* don't free the elements */ );
1054       arenaFree( census->arena );
1055       census->hash = NULL;
1056       census->arena = NULL;
1057   }
1058
1059   // we're into the next time period now
1060   nextEra();
1061
1062 #ifdef PROFILING
1063   stat_endHeapCensus();
1064 #endif
1065 }    
1066
1067 #endif /* PROFILING || DEBUG_HEAP_PROF */
1068