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