ProfHeap.c 37.1 KB
Newer Older
1
/* ----------------------------------------------------------------------------
2
 *
3
 * (c) The GHC Team, 1998-2003
4 5 6
 *
 * Support for heap profiling
 *
7
 * --------------------------------------------------------------------------*/
8

9
#include "PosixSource.h"
10
#include "Rts.h"
11

Simon Marlow's avatar
Simon Marlow committed
12
#include "Capability.h"
13
#include "RtsFlags.h"
14
#include "RtsUtils.h"
15
#include "Profiling.h"
16 17
#include "ProfHeap.h"
#include "Stats.h"
18
#include "Hash.h"
19
#include "RetainerProfile.h"
Simon Marlow's avatar
Simon Marlow committed
20
#include "LdvProfile.h"
21
#include "Arena.h"
22
#include "Printer.h"
23
#include "Trace.h"
24
#include "sm/GCThread.h"
25

26
#include <fs_rts.h>
27 28
#include <string.h>

29 30 31
FILE *hp_file;
static char *hp_filename; /* heap profile (hp2ps style) log file */

32
/* -----------------------------------------------------------------------------
33 34
 * era stores the current time period.  It is the same as the
 * number of censuses that have been performed.
35
 *
36 37 38
 * RESTRICTION:
 *   era must be no longer than LDV_SHIFT (15 or 30) bits.
 * Invariants:
39
 *   era is initialized to 1 in initHeapProfiling().
40
 *
41 42 43
 * max_era is initialized to 2^LDV_SHIFT in initHeapProfiling().
 * When era reaches max_era, the profiling stops because a closure can
 * store only up to (max_era - 1) as its creation or last use time.
44
 * -------------------------------------------------------------------------- */
45
unsigned int era;
46
static uint32_t max_era;
47

48
/* -----------------------------------------------------------------------------
49 50 51 52 53 54 55
 * Counters
 *
 * For most heap profiles each closure identity gets a simple count
 * of live words in the heap at each census.  However, if we're
 * selecting by biography, then we have to keep the various
 * lag/drag/void counters for each identity.
 * -------------------------------------------------------------------------- */
56
typedef struct _counter {
57
    const void *identity;
58
    union {
59
        ssize_t resid;
60
        struct {
61 62 63 64 65 66
            // Total sizes of:
            ssize_t prim;     // 'inherently used' closures
            ssize_t not_used; // 'never used' closures
            ssize_t used;     // 'used at least once' closures
            ssize_t void_total;  // 'destroyed without being used' closures
            ssize_t drag_total;  // 'used at least once and waiting to die'
67
        } ldv;
68 69 70
    } c;
    struct _counter *next;
} counter;
71

72
STATIC_INLINE void
73 74 75 76 77 78 79 80 81
initLDVCtr( counter *ctr )
{
    ctr->c.ldv.prim = 0;
    ctr->c.ldv.not_used = 0;
    ctr->c.ldv.used = 0;
    ctr->c.ldv.void_total = 0;
    ctr->c.ldv.drag_total = 0;
}

82 83 84 85 86 87 88
typedef struct {
    double      time;    // the time in MUT time when the census is made
    HashTable * hash;
    counter   * ctrs;
    Arena     * arena;

    // for LDV profiling, when just displaying by LDV
89 90 91 92 93
    ssize_t    prim;
    ssize_t    not_used;
    ssize_t    used;
    ssize_t    void_total;
    ssize_t    drag_total;
94 95
} Census;

96
static Census *censuses = NULL;
97
static uint32_t n_censuses = 0;
98

99
#if defined(PROFILING)
100 101 102 103 104
static void aggregateCensusInfo( void );
#endif

static void dumpCensus( Census *census );

Ben Gamari's avatar
Ben Gamari committed
105
static bool closureSatisfiesConstraints( const StgClosure* p );
106

107
/* ----------------------------------------------------------------------------
Edward Z. Yang's avatar
Edward Z. Yang committed
108
 * Find the "closure identity", which is a unique pointer representing
109 110 111
 * the band to which this closure's heap space is attributed in the
 * heap profile.
 * ------------------------------------------------------------------------- */
112
static const void *
113
closureIdentity( const StgClosure *p )
114 115 116
{
    switch (RtsFlags.ProfFlags.doHeapProfile) {

117
#if defined(PROFILING)
118
    case HEAP_BY_CCS:
119
        return p->header.prof.ccs;
120
    case HEAP_BY_MOD:
121
        return p->header.prof.ccs->cc->module;
122
    case HEAP_BY_DESCR:
123
        return GET_PROF_DESC(get_itbl(p));
124
    case HEAP_BY_TYPE:
125
        return GET_PROF_TYPE(get_itbl(p));
126
    case HEAP_BY_RETAINER:
127 128 129 130 131 132
        // AFAIK, the only closures in the heap which might not have a
        // valid retainer set are DEAD_WEAK closures.
        if (isRetainerSetFieldValid(p))
            return retainerSetOf(p);
        else
            return NULL;
133
#endif
134

135
    case HEAP_BY_CLOSURE_TYPE:
136
    {
137
        const StgInfoTable *info;
138 139 140 141 142 143 144 145
        info = get_itbl(p);
        switch (info->type) {
        case CONSTR:
        case CONSTR_1_0:
        case CONSTR_0_1:
        case CONSTR_2_0:
        case CONSTR_1_1:
        case CONSTR_0_2:
Simon Marlow's avatar
Simon Marlow committed
146
        case CONSTR_NOCAF:
147 148
            return GET_CON_DESC(itbl_to_con_itbl(info));
        default:
149
            return closure_type_names[info->type];
150 151
        }
    }
152

153
    default:
154
        barf("closureIdentity");
155 156 157
    }
}

158 159 160
/* --------------------------------------------------------------------------
 * Profiling type predicates
 * ----------------------------------------------------------------------- */
161
#if defined(PROFILING)
Ben Gamari's avatar
Ben Gamari committed
162
STATIC_INLINE bool
163
doingLDVProfiling( void )
164
{
165 166
    return (RtsFlags.ProfFlags.doHeapProfile == HEAP_BY_LDV
            || RtsFlags.ProfFlags.bioSelector != NULL);
167 168
}

Ben Gamari's avatar
Ben Gamari committed
169
bool
170
doingRetainerProfiling( void )
171
{
172
    return (RtsFlags.ProfFlags.doHeapProfile == HEAP_BY_RETAINER
173
            || RtsFlags.ProfFlags.retainerSelector != NULL);
174
}
175
#endif /* PROFILING */
176

177
// Processes a closure 'c' being destroyed whose size is 'size'.
178 179
// Make sure that LDV_recordDead() is not invoked on 'inherently used' closures
// such as TSO; they should not be involved in computing dragNew or voidNew.
180 181 182 183
//
// Even though era is checked in both LdvCensusForDead() and
// LdvCensusKillAll(), we still need to make sure that era is > 0 because
// LDV_recordDead() may be called from elsewhere in the runtime system. E.g.,
184
// when a thunk is replaced by an indirection object.
185

186
#if defined(PROFILING)
187
void
188
LDV_recordDead( const StgClosure *c, uint32_t size )
189
{
190
    const void *id;
191
    uint32_t t;
192 193
    counter *ctr;

194
    if (era > 0 && closureSatisfiesConstraints(c)) {
195 196 197 198 199 200
        size -= sizeofW(StgProfHeader);
        ASSERT(LDVW(c) != 0);
        if ((LDVW((c)) & LDV_STATE_MASK) == LDV_STATE_CREATE) {
            t = (LDVW((c)) & LDV_CREATE_MASK) >> LDV_SHIFT;
            if (t < era) {
                if (RtsFlags.ProfFlags.bioSelector == NULL) {
201 202
                    censuses[t].void_total   += size;
                    censuses[era].void_total -= size;
203
                    ASSERT(censuses[t].void_total <= censuses[t].not_used);
204 205 206
                } else {
                    id = closureIdentity(c);
                    ctr = lookupHashTable(censuses[t].hash, (StgWord)id);
207 208 209
                    if (ctr == NULL)
                        barf("LDV_recordDead: Failed to find counter for closure %p", c);

210
                    ctr->c.ldv.void_total += size;
211 212 213 214 215 216 217 218 219
                    ctr = lookupHashTable(censuses[era].hash, (StgWord)id);
                    if (ctr == NULL) {
                        ctr = arenaAlloc(censuses[era].arena, sizeof(counter));
                        initLDVCtr(ctr);
                        insertHashTable(censuses[era].hash, (StgWord)id, ctr);
                        ctr->identity = id;
                        ctr->next = censuses[era].ctrs;
                        censuses[era].ctrs = ctr;
                    }
220
                    ctr->c.ldv.void_total -= size;
221 222 223 224 225 226 227 228 229
                }
            }
        } else {
            t = LDVW((c)) & LDV_LAST_MASK;
            if (t + 1 < era) {
                if (RtsFlags.ProfFlags.bioSelector == NULL) {
                    censuses[t+1].drag_total += size;
                    censuses[era].drag_total -= size;
                } else {
230
                    const void *id;
231 232 233
                    id = closureIdentity(c);
                    ctr = lookupHashTable(censuses[t+1].hash, (StgWord)id);
                    ASSERT( ctr != NULL );
234
                    ctr->c.ldv.drag_total += size;
235 236 237 238 239 240 241 242 243
                    ctr = lookupHashTable(censuses[era].hash, (StgWord)id);
                    if (ctr == NULL) {
                        ctr = arenaAlloc(censuses[era].arena, sizeof(counter));
                        initLDVCtr(ctr);
                        insertHashTable(censuses[era].hash, (StgWord)id, ctr);
                        ctr->identity = id;
                        ctr->next = censuses[era].ctrs;
                        censuses[era].ctrs = ctr;
                    }
244
                    ctr->c.ldv.drag_total -= size;
245 246 247
                }
            }
        }
248 249
    }
}
250
#endif
251

252 253 254
/* --------------------------------------------------------------------------
 * Initialize censuses[era];
 * ----------------------------------------------------------------------- */
255

256
STATIC_INLINE void
257
initEra(Census *census)
258
{
259 260 261 262 263 264 265 266 267
    census->hash  = allocHashTable();
    census->ctrs  = NULL;
    census->arena = newArena();

    census->not_used   = 0;
    census->used       = 0;
    census->prim       = 0;
    census->void_total = 0;
    census->drag_total = 0;
268 269
}

270 271 272
STATIC_INLINE void
freeEra(Census *census)
{
273 274
    arenaFree(census->arena);
    freeHashTable(census->hash, NULL);
275 276
}

277 278 279 280
/* --------------------------------------------------------------------------
 * Increases era by 1 and initialize census[era].
 * Reallocates gi[] and increases its size if needed.
 * ----------------------------------------------------------------------- */
281

282
static void
283
nextEra( void )
284
{
285
#if defined(PROFILING)
286 287 288 289
    if (doingLDVProfiling()) {
        era++;

        if (era == max_era) {
290
            errorBelch("Maximum number of censuses reached.");
Ben Gamari's avatar
Ben Gamari committed
291
            if (rtsConfig.rts_opts_suggestions == true) {
292 293 294 295 296 297
                if (rtsConfig.rts_opts_enabled == RtsOptsAll)  {
                    errorBelch("Use `+RTS -i' to reduce censuses.");
                } else  {
                    errorBelch("Relink with -rtsopts and "
                               "use `+RTS -i' to reduce censuses.");
                }
298
            }
299 300 301 302 303 304 305 306
            stg_exit(EXIT_FAILURE);
        }

        if (era == n_censuses) {
            n_censuses *= 2;
            censuses = stgReallocBytes(censuses, sizeof(Census) * n_censuses,
                                       "nextEra");
        }
307
    }
308
#endif /* PROFILING */
309

310
    initEra( &censuses[era] );
311 312
}

313 314 315
/* ----------------------------------------------------------------------------
 * Heap profiling by info table
 * ------------------------------------------------------------------------- */
316

317 318 319 320 321 322 323 324 325 326 327 328
static void
printEscapedString(const char* string)
{
    for (const char* p = string; *p != '\0'; ++p) {
        if (*p == '\"') {
            // Escape every " as ""
            fputc('"', hp_file);
        }
        fputc(*p, hp_file);
    }
}

329
static void
Ben Gamari's avatar
Ben Gamari committed
330
printSample(bool beginSample, StgDouble sampleValue)
331
{
332
    fprintf(hp_file, "%s %f\n",
333
            (beginSample ? "BEGIN_SAMPLE" : "END_SAMPLE"),
334
            sampleValue);
335 336 337
    if (!beginSample) {
        fflush(hp_file);
    }
338 339
}

340 341 342
static void
dumpCostCentresToEventLog(void)
{
343
#if defined(PROFILING)
344 345 346 347 348 349 350 351 352
    CostCentre *cc, *next;
    for (cc = CC_LIST; cc != NULL; cc = next) {
        next = cc->link;
        traceHeapProfCostCentre(cc->ccID, cc->label, cc->module,
                                cc->srcloc, cc->is_caf);
    }
#endif
}

353 354 355 356
void freeHeapProfiling (void)
{
}

357 358 359
/* --------------------------------------------------------------------------
 * Initialize the heap profilier
 * ----------------------------------------------------------------------- */
360
void
361 362 363
initHeapProfiling(void)
{
    if (! RtsFlags.ProfFlags.doHeapProfile) {
364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387
        return;
    }

    char *prog;

    prog = stgMallocBytes(strlen(prog_name) + 1, "initHeapProfiling");
    strcpy(prog, prog_name);
#if defined(mingw32_HOST_OS)
    // on Windows, drop the .exe suffix if there is one
    {
        char *suff;
        suff = strrchr(prog,'.');
        if (suff != NULL && !strcmp(suff,".exe")) {
            *suff = '\0';
        }
    }
#endif

  if (RtsFlags.ProfFlags.doHeapProfile) {
    /* Initialise the log file name */
    hp_filename = stgMallocBytes(strlen(prog) + 6, "hpFileName");
    sprintf(hp_filename, "%s.hp", prog);

    /* open the log file */
388
    if ((hp_file = __rts_fopen(hp_filename, "w+")) == NULL) {
389 390 391 392 393
      debugBelch("Can't open profiling report file %s\n",
              hp_filename);
      RtsFlags.ProfFlags.doHeapProfile = 0;
      stgFree(prog);
      return;
394
    }
395 396 397
  }

  stgFree(prog);
398

399
#if defined(PROFILING)
400
    if (doingLDVProfiling() && doingRetainerProfiling()) {
401 402
        errorBelch("cannot mix -hb and -hr");
        stg_exit(EXIT_FAILURE);
403
    }
404
#if defined(THREADED_RTS)
405
    // See #12019.
406 407 408 409 410
    if (doingLDVProfiling() && RtsFlags.ParFlags.nCapabilities > 1) {
        errorBelch("-hb cannot be used with multiple capabilities");
        stg_exit(EXIT_FAILURE);
    }
#endif
411 412
#endif

413 414
    // we only count eras if we're doing LDV profiling.  Otherwise era
    // is fixed at zero.
415
#if defined(PROFILING)
416
    if (doingLDVProfiling()) {
417
        era = 1;
418 419 420
    } else
#endif
    {
421
        era = 0;
422 423
    }

Ian Lynagh's avatar
Ian Lynagh committed
424
    // max_era = 2^LDV_SHIFT
425
    max_era = 1 << LDV_SHIFT;
426 427 428 429

    n_censuses = 32;
    censuses = stgMallocBytes(sizeof(Census) * n_censuses, "initHeapProfiling");

430 431
    initEra( &censuses[era] );

432
    /* initProfilingLogFile(); */
433 434
    fprintf(hp_file, "JOB \"");
    printEscapedString(prog_name);
435

436
#if defined(PROFILING)
437 438 439 440 441 442 443 444
    for (int i = 1; i < prog_argc; ++i) {
        fputc(' ', hp_file);
        printEscapedString(prog_argv[i]);
    }
    fprintf(hp_file, " +RTS");
    for (int i = 0; i < rts_argc; ++i) {
        fputc(' ', hp_file);
        printEscapedString(rts_argv[i]);
445
    }
446
#endif /* PROFILING */
447 448 449

    fprintf(hp_file, "\"\n" );

450
    fprintf(hp_file, "DATE \"%s\"\n", time_str());
451

452 453
    fprintf(hp_file, "SAMPLE_UNIT \"seconds\"\n");
    fprintf(hp_file, "VALUE_UNIT \"bytes\"\n");
454

Ben Gamari's avatar
Ben Gamari committed
455 456
    printSample(true, 0);
    printSample(false, 0);
457

458
#if defined(PROFILING)
459
    if (doingRetainerProfiling()) {
460
        initRetainerProfiling();
461
    }
462 463
#endif

464 465
    traceHeapProfBegin(0);
    dumpCostCentresToEventLog();
466 467 468 469 470 471 472 473 474 475 476
}

void
endHeapProfiling(void)
{
    StgDouble seconds;

    if (! RtsFlags.ProfFlags.doHeapProfile) {
        return;
    }

477
#if defined(PROFILING)
478
    if (doingRetainerProfiling()) {
479
        endRetainerProfiling();
480 481 482
    }
#endif

483
#if defined(PROFILING)
484
    if (doingLDVProfiling()) {
485
        uint32_t t;
486 487 488 489 490
        LdvCensusKillAll();
        aggregateCensusInfo();
        for (t = 1; t < era; t++) {
            dumpCensus( &censuses[t] );
        }
491
    }
492
#endif
493

494
#if defined(PROFILING)
495
    if (doingLDVProfiling()) {
496
        uint32_t t;
497 498 499 500 501 502
        if (RtsFlags.ProfFlags.bioSelector != NULL) {
            for (t = 1; t <= era; t++) {
                freeEra( &censuses[t] );
            }
        } else {
            freeEra( &censuses[era] );
503
        }
504 505
    } else {
        freeEra( &censuses[0] );
506
    }
507 508 509 510
#else
    freeEra( &censuses[0] );
#endif

511 512
    stgFree(censuses);

513
    seconds = mut_user_time();
Ben Gamari's avatar
Ben Gamari committed
514 515
    printSample(true, seconds);
    printSample(false, seconds);
516
    fclose(hp_file);
517 518 519 520
}



521
#if defined(PROFILING)
522 523 524 525 526 527
static size_t
buf_append(char *p, const char *q, char *end)
{
    int m;

    for (m = 0; p < end; p++, q++, m++) {
528 529
        *p = *q;
        if (*q == '\0') { break; }
530 531 532 533
    }
    return m;
}

534
static void
535
fprint_ccs(FILE *fp, CostCentreStack *ccs, uint32_t max_length)
536
{
537
    char buf[max_length+1], *p, *buf_end;
538 539 540

    // MAIN on its own gets printed as "MAIN", otherwise we ignore MAIN.
    if (ccs == CCS_MAIN) {
541 542
        fprintf(fp, "MAIN");
        return;
543
    }
544

thomie's avatar
thomie committed
545
    fprintf(fp, "(%" FMT_Int ")", ccs->ccsID);
546

547 548 549
    p = buf;
    buf_end = buf + max_length + 1;

550 551 552
    // keep printing components of the stack until we run out of space
    // in the buffer.  If we run out of space, end with "...".
    for (; ccs != NULL && ccs != CCS_MAIN; ccs = ccs->prevStack) {
553

554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569
        // CAF cost centres print as M.CAF, but we leave the module
        // name out of all the others to save space.
        if (!strcmp(ccs->cc->label,"CAF")) {
            p += buf_append(p, ccs->cc->module, buf_end);
            p += buf_append(p, ".CAF", buf_end);
        } else {
            p += buf_append(p, ccs->cc->label, buf_end);
            if (ccs->prevStack != NULL && ccs->prevStack != CCS_MAIN) {
                p += buf_append(p, "/", buf_end);
            }
        }

        if (p >= buf_end) {
            sprintf(buf+max_length-4, "...");
            break;
        }
570 571
    }
    fprintf(fp, "%s", buf);
572 573
}

Ben Gamari's avatar
Ben Gamari committed
574
bool
Ben Gamari's avatar
Ben Gamari committed
575
strMatchesSelector( const char* str, const char* sel )
576
{
Ben Gamari's avatar
Ben Gamari committed
577
   const char* p;
578
   // debugBelch("str_matches_selector %s %s\n", str, sel);
579
   while (1) {
580 581 582
       // Compare str against wherever we've got to in sel.
       p = str;
       while (*p != '\0' && *sel != ',' && *sel != '\0' && *p == *sel) {
583
           p++; sel++;
584 585 586
       }
       // Match if all of str used and have reached the end of a sel fragment.
       if (*p == '\0' && (*sel == ',' || *sel == '\0'))
Ben Gamari's avatar
Ben Gamari committed
587
           return true;
588

589 590 591
       // No match.  Advance sel to the start of the next elem.
       while (*sel != ',' && *sel != '\0') sel++;
       if (*sel == ',') sel++;
592

593
       /* Run out of sel ?? */
Ben Gamari's avatar
Ben Gamari committed
594
       if (*sel == '\0') return false;
595 596 597
   }
}

598 599
#endif /* PROFILING */

600 601 602 603
/* -----------------------------------------------------------------------------
 * Figure out whether a closure should be counted in this census, by
 * testing against all the specified constraints.
 * -------------------------------------------------------------------------- */
Ben Gamari's avatar
Ben Gamari committed
604
static bool
605
closureSatisfiesConstraints( const StgClosure* p )
606
{
607
#if !defined(PROFILING)
608
    (void)p;   /* keep gcc -Wall happy */
Ben Gamari's avatar
Ben Gamari committed
609
    return true;
610
#else
Ben Gamari's avatar
Ben Gamari committed
611
   bool b;
612 613 614 615 616

   // The CCS has a selected field to indicate whether this closure is
   // deselected by not being mentioned in the module, CC, or CCS
   // selectors.
   if (!p->header.prof.ccs->selected) {
Ben Gamari's avatar
Ben Gamari committed
617
       return false;
618
   }
619

620
   if (RtsFlags.ProfFlags.descrSelector) {
Simon Marlow's avatar
Simon Marlow committed
621
       b = strMatchesSelector( (GET_PROF_DESC(get_itbl((StgClosure *)p))),
622
                                 RtsFlags.ProfFlags.descrSelector );
Ben Gamari's avatar
Ben Gamari committed
623
       if (!b) return false;
624 625
   }
   if (RtsFlags.ProfFlags.typeSelector) {
Simon Marlow's avatar
Simon Marlow committed
626
       b = strMatchesSelector( (GET_PROF_TYPE(get_itbl((StgClosure *)p))),
627
                                RtsFlags.ProfFlags.typeSelector );
Ben Gamari's avatar
Ben Gamari committed
628
       if (!b) return false;
629
   }
630 631
   if (RtsFlags.ProfFlags.retainerSelector) {
       RetainerSet *rs;
632
       uint32_t i;
633 634 635 636 637
       // We must check that the retainer set is valid here.  One
       // reason it might not be valid is if this closure is a
       // a newly deceased weak pointer (i.e. a DEAD_WEAK), since
       // these aren't reached by the retainer profiler's traversal.
       if (isRetainerSetFieldValid((StgClosure *)p)) {
638 639 640 641 642
           rs = retainerSetOf((StgClosure *)p);
           if (rs != NULL) {
               for (i = 0; i < rs->num; i++) {
                   b = strMatchesSelector( rs->element[i]->cc->label,
                                           RtsFlags.ProfFlags.retainerSelector );
Ben Gamari's avatar
Ben Gamari committed
643
                   if (b) return true;
644 645
               }
           }
646
       }
Ben Gamari's avatar
Ben Gamari committed
647
       return false;
648
   }
Ben Gamari's avatar
Ben Gamari committed
649
   return true;
650
#endif /* PROFILING */
651
}
652

653 654 655
/* -----------------------------------------------------------------------------
 * Aggregate the heap census info for biographical profiling
 * -------------------------------------------------------------------------- */
656
#if defined(PROFILING)
657 658 659 660
static void
aggregateCensusInfo( void )
{
    HashTable *acc;
661
    uint32_t t;
662 663 664 665 666 667 668
    counter *c, *d, *ctrs;
    Arena *arena;

    if (!doingLDVProfiling()) return;

    // Aggregate the LDV counters when displaying by biography.
    if (RtsFlags.ProfFlags.doHeapProfile == HEAP_BY_LDV) {
669
        long void_total, drag_total;
670

671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699
        // Now we compute void_total and drag_total for each census
        // After the program has finished, the void_total field of
        // each census contains the count of words that were *created*
        // in this era and were eventually void.  Conversely, if a
        // void closure was destroyed in this era, it will be
        // represented by a negative count of words in void_total.
        //
        // To get the count of live words that are void at each
        // census, just propagate the void_total count forwards:

        void_total = 0;
        drag_total = 0;
        for (t = 1; t < era; t++) { // note: start at 1, not 0
            void_total += censuses[t].void_total;
            drag_total += censuses[t].drag_total;
            censuses[t].void_total = void_total;
            censuses[t].drag_total = drag_total;

            ASSERT( censuses[t].void_total <= censuses[t].not_used );
            // should be true because: void_total is the count of
            // live words that are void at this census, which *must*
            // be less than the number of live words that have not
            // been used yet.

            ASSERT( censuses[t].drag_total <= censuses[t].used );
            // similar reasoning as above.
        }

        return;
700 701 702 703 704 705 706 707 708 709 710 711 712
    }

    // otherwise... we're doing a heap profile that is restricted to
    // some combination of lag, drag, void or use.  We've kept all the
    // census info for all censuses so far, but we still need to
    // aggregate the counters forwards.

    arena = newArena();
    acc = allocHashTable();
    ctrs = NULL;

    for (t = 1; t < era; t++) {

713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754
        // first look through all the counters we're aggregating
        for (c = ctrs; c != NULL; c = c->next) {
            // if one of the totals is non-zero, then this closure
            // type must be present in the heap at this census time...
            d = lookupHashTable(censuses[t].hash, (StgWord)c->identity);

            if (d == NULL) {
                // if this closure identity isn't present in the
                // census for this time period, then our running
                // totals *must* be zero.
                ASSERT(c->c.ldv.void_total == 0 && c->c.ldv.drag_total == 0);

                // debugCCS(c->identity);
                // debugBelch(" census=%d void_total=%d drag_total=%d\n",
                //         t, c->c.ldv.void_total, c->c.ldv.drag_total);
            } else {
                d->c.ldv.void_total += c->c.ldv.void_total;
                d->c.ldv.drag_total += c->c.ldv.drag_total;
                c->c.ldv.void_total =  d->c.ldv.void_total;
                c->c.ldv.drag_total =  d->c.ldv.drag_total;

                ASSERT( c->c.ldv.void_total >= 0 );
                ASSERT( c->c.ldv.drag_total >= 0 );
            }
        }

        // now look through the counters in this census to find new ones
        for (c = censuses[t].ctrs; c != NULL; c = c->next) {
            d = lookupHashTable(acc, (StgWord)c->identity);
            if (d == NULL) {
                d = arenaAlloc( arena, sizeof(counter) );
                initLDVCtr(d);
                insertHashTable( acc, (StgWord)c->identity, d );
                d->identity = c->identity;
                d->next = ctrs;
                ctrs = d;
                d->c.ldv.void_total = c->c.ldv.void_total;
                d->c.ldv.drag_total = c->c.ldv.drag_total;
            }
            ASSERT( c->c.ldv.void_total >= 0 );
            ASSERT( c->c.ldv.drag_total >= 0 );
        }
755 756 757 758 759 760 761
    }

    freeHashTable(acc, NULL);
    arenaFree(arena);
}
#endif

762 763 764 765 766 767 768
/* -----------------------------------------------------------------------------
 * Print out the results of a heap census.
 * -------------------------------------------------------------------------- */
static void
dumpCensus( Census *census )
{
    counter *ctr;
769
    ssize_t count;
770

Ben Gamari's avatar
Ben Gamari committed
771
    printSample(true, census->time);
772
    traceHeapProfSampleBegin(era);
773

774
#if defined(PROFILING)
775 776
    /* change typecast to uint64_t to remove
     * print formatting warning. See #12636 */
777
    if (RtsFlags.ProfFlags.doHeapProfile == HEAP_BY_LDV) {
778 779 780 781 782 783 784 785 786 787 788 789 790
        fprintf(hp_file, "VOID\t%" FMT_Word64 "\n",
                (uint64_t)(census->void_total *
                                     sizeof(W_)));
        fprintf(hp_file, "LAG\t%" FMT_Word64 "\n",
                (uint64_t)((census->not_used - census->void_total) *
                                     sizeof(W_)));
        fprintf(hp_file, "USE\t%" FMT_Word64 "\n",
                (uint64_t)((census->used - census->drag_total) *
                                     sizeof(W_)));
        fprintf(hp_file, "INHERENT_USE\t%" FMT_Word64 "\n",
                (uint64_t)(census->prim * sizeof(W_)));
        fprintf(hp_file, "DRAG\t%" FMT_Word64 "\n",
                (uint64_t)(census->drag_total * sizeof(W_)));
Ben Gamari's avatar
Ben Gamari committed
791
        printSample(false, census->time);
792
        return;
793 794 795
    }
#endif

796
    for (ctr = census->ctrs; ctr != NULL; ctr = ctr->next) {
797

798
#if defined(PROFILING)
799 800 801 802 803 804 805 806 807 808 809
        if (RtsFlags.ProfFlags.bioSelector != NULL) {
            count = 0;
            if (strMatchesSelector("lag", RtsFlags.ProfFlags.bioSelector))
                count += ctr->c.ldv.not_used - ctr->c.ldv.void_total;
            if (strMatchesSelector("drag", RtsFlags.ProfFlags.bioSelector))
                count += ctr->c.ldv.drag_total;
            if (strMatchesSelector("void", RtsFlags.ProfFlags.bioSelector))
                count += ctr->c.ldv.void_total;
            if (strMatchesSelector("use", RtsFlags.ProfFlags.bioSelector))
                count += ctr->c.ldv.used - ctr->c.ldv.drag_total;
        } else
810
#endif
811 812 813
        {
            count = ctr->c.resid;
        }
814

815
        ASSERT( count >= 0 );
816

817
        if (count == 0) continue;
818

819 820 821
        switch (RtsFlags.ProfFlags.doHeapProfile) {
        case HEAP_BY_CLOSURE_TYPE:
            fprintf(hp_file, "%s", (char *)ctr->identity);
822 823
            traceHeapProfSampleString(0, (char *)ctr->identity,
                                      count * sizeof(W_));
824
            break;
825
#if defined(PROFILING)
826
        case HEAP_BY_CCS:
827 828 829 830
            fprint_ccs(hp_file, (CostCentreStack *)ctr->identity,
                       RtsFlags.ProfFlags.ccsLength);
            traceHeapProfSampleCostCentre(0, (CostCentreStack *)ctr->identity,
                                          count * sizeof(W_));
831 832 833 834 835
            break;
        case HEAP_BY_MOD:
        case HEAP_BY_DESCR:
        case HEAP_BY_TYPE:
            fprintf(hp_file, "%s", (char *)ctr->identity);
836 837
            traceHeapProfSampleString(0, (char *)ctr->identity,
                                      count * sizeof(W_));
838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861
            break;
        case HEAP_BY_RETAINER:
        {
            RetainerSet *rs = (RetainerSet *)ctr->identity;

            // it might be the distinguished retainer set rs_MANY:
            if (rs == &rs_MANY) {
                fprintf(hp_file, "MANY");
                break;
            }

            // Mark this retainer set by negating its id, because it
            // has appeared in at least one census.  We print the
            // values of all such retainer sets into the log file at
            // the end.  A retainer set may exist but not feature in
            // any censuses if it arose as the intermediate retainer
            // set for some closure during retainer set calculation.
            if (rs->id > 0)
                rs->id = -(rs->id);

            // report in the unit of bytes: * sizeof(StgWord)
            printRetainerSetShort(hp_file, rs, RtsFlags.ProfFlags.ccsLength);
            break;
        }
862
#endif
863 864 865
        default:
            barf("dumpCensus; doHeapProfile");
        }
866

867
        fprintf(hp_file, "\t%" FMT_Word "\n", (W_)count * sizeof(W_));
868 869
    }

870
    traceHeapProfSampleEnd(era);
Ben Gamari's avatar
Ben Gamari committed
871
    printSample(false, census->time);
872 873
}

874

875
static void heapProfObject(Census *census, StgClosure *p, size_t size,
Ben Gamari's avatar
Ben Gamari committed
876
                           bool prim
877
#if !defined(PROFILING)
878 879 880 881
                           STG_UNUSED
#endif
                           )
{
882
    const void *identity;
883
    size_t real_size;
884 885 886 887
    counter *ctr;

            identity = NULL;

888
#if defined(PROFILING)
889 890
            // subtract the profiling overhead
            real_size = size - sizeofW(StgProfHeader);
891
#else
892
            real_size = size;
893 894
#endif

895
            if (closureSatisfiesConstraints((StgClosure*)p)) {
896
#if defined(PROFILING)
897 898 899 900 901 902 903 904
                if (RtsFlags.ProfFlags.doHeapProfile == HEAP_BY_LDV) {
                    if (prim)
                        census->prim += real_size;
                    else if ((LDVW(p) & LDV_STATE_MASK) == LDV_STATE_CREATE)
                        census->not_used += real_size;
                    else
                        census->used += real_size;
                } else
905
#endif
906 907
                {
                    identity = closureIdentity((StgClosure *)p);
908

909
                    if (identity != NULL) {
910
                        ctr = lookupHashTable(census->hash, (StgWord)identity);
911
                        if (ctr != NULL) {
912
#if defined(PROFILING)
913 914 915 916 917 918 919 920
                            if (RtsFlags.ProfFlags.bioSelector != NULL) {
                                if (prim)
                                    ctr->c.ldv.prim += real_size;
                                else if ((LDVW(p) & LDV_STATE_MASK) == LDV_STATE_CREATE)
                                    ctr->c.ldv.not_used += real_size;
                                else
                                    ctr->c.ldv.used += real_size;
                            } else
921
#endif
922 923 924 925 926 927 928 929 930 931
                            {
                                ctr->c.resid += real_size;
                            }
                        } else {
                            ctr = arenaAlloc( census->arena, sizeof(counter) );
                            initLDVCtr(ctr);
                            insertHashTable( census->hash, (StgWord)identity, ctr );
                            ctr->identity = identity;
                            ctr->next = census->ctrs;
                            census->ctrs = ctr;
932

933
#if defined(PROFILING)
934 935 936 937 938 939 940 941
                            if (RtsFlags.ProfFlags.bioSelector != NULL) {
                                if (prim)
                                    ctr->c.ldv.prim = real_size;
                                else if ((LDVW(p) & LDV_STATE_MASK) == LDV_STATE_CREATE)
                                    ctr->c.ldv.not_used = real_size;
                                else
                                    ctr->c.ldv.used = real_size;
                            } else
942
#endif
943 944 945 946 947 948 949
                            {
                                ctr->c.resid = real_size;
                            }
                        }
                    }
                }
            }
950 951
}

gcampax's avatar
gcampax committed
952 953 954 955 956 957 958 959 960 961 962 963 964 965
// Compact objects require special handling code because they
// are not stored consecutively in memory (rather, each object
// is a list of objects), and that would break the while loop
// below. But we know that each block holds at most one object
// so we don't need the loop.
//
// See Note [Compact Normal Forms] for details.
static void
heapCensusCompactList(Census *census, bdescr *bd)
{
    for (; bd != NULL; bd = bd->link) {
        StgCompactNFDataBlock *block = (StgCompactNFDataBlock*)bd->start;
        StgCompactNFData *str = block->owner;
        heapProfObject(census, (StgClosure*)str,
Ben Gamari's avatar
Ben Gamari committed
966
                       compact_nfdata_full_sizeW(str), true);
gcampax's avatar
gcampax committed
967 968 969
    }
}

970 971 972 973
/* -----------------------------------------------------------------------------
 * Code to perform a heap census.
 * -------------------------------------------------------------------------- */
static void
974
heapCensusChain( Census *census, bdescr *bd )
975 976
{
    StgPtr p;
977
    const StgInfoTable *info;
978
    size_t size;
Ben Gamari's avatar
Ben Gamari committed
979
    bool prim;
980

981
    for (; bd != NULL; bd = bd->link) {
982

983
        // HACK: pretend a pinned block is just one big ARR_WORDS
984
        // owned by CCS_PINNED.  These blocks can be full of holes due
985 986 987 988
        // to alignment constraints so we can't traverse the memory
        // and do a proper census.
        if (bd->flags & BF_PINNED) {
            StgClosure arr;
989
            SET_HDR(&arr, &stg_ARR_WORDS_info, CCS_PINNED);
Ben Gamari's avatar
Ben Gamari committed
990
            heapProfObject(census, &arr, bd->blocks * BLOCK_SIZE_W, true);
991 992
            continue;
        }
993

994
        p = bd->start;
995

996
        while (p < bd->free) {
997
            info = get_itbl((const StgClosure *)p);
Ben Gamari's avatar
Ben Gamari committed
998
            prim = false;
999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025

            switch (info->type) {

            case THUNK:
                size = thunk_sizeW_fromITBL(info);
                break;

            case THUNK_1_1:
            case THUNK_0_2:
            case THUNK_2_0:
                size = sizeofW(StgThunkHeader) + 2;
                break;

            case THUNK_1_0:
            case THUNK_0_1:
            case THUNK_SELECTOR:
                size = sizeofW(StgThunkHeader) + 1;
                break;

            case FUN:
            case BLACKHOLE:
            case BLOCKING_QUEUE:
            case FUN_1_0:
            case FUN_0_1:
            case FUN_1_1:
            case FUN_0_2:
            case FUN_2_0:
Simon Marlow's avatar
Simon Marlow committed
1026 1027
            case CONSTR:
            case CONSTR_NOCAF:
1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047
            case CONSTR_1_0:
            case CONSTR_0_1:
            case CONSTR_1_1:
            case CONSTR_0_2:
            case CONSTR_2_0:
                size = sizeW_fromITBL(info);
                break;

            case IND:
                // Special case/Delicate Hack: INDs don't normally
                // appear, since we're doing this heap census right
                // after GC.  However, GarbageCollect() also does
                // resurrectThreads(), which can update some
                // blackholes when it calls raiseAsync() on the
                // resurrected threads.  So we know that any IND will
                // be the size of a BLACKHOLE.
                size = BLACKHOLE_sizeW();
                break;

            case BCO:
Ben Gamari's avatar
Ben Gamari committed
1048
                prim = true;
1049 1050
                size = bco_sizeW((StgBCO *)p);
                break;
1051

1052 1053
            case MVAR_CLEAN:
            case MVAR_DIRTY:
1054 1055
            case TVAR:
            case WEAK:
1056 1057 1058 1059
            case PRIM:
            case MUT_PRIM:
            case MUT_VAR_CLEAN:
            case MUT_VAR_DIRTY:
Ben Gamari's avatar
Ben Gamari committed
1060
                prim = true;
1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076
                size = sizeW_fromITBL(info);
                break;

            case AP:
                size = ap_sizeW((StgAP *)p);
                break;

            case PAP:
                size = pap_sizeW((StgPAP *)p);
                break;

            case AP_STACK:
                size = ap_stack_sizeW((StgAP_STACK *)p);
                break;

            case ARR_WORDS:
Ben Gamari's avatar
Ben Gamari committed
1077
                prim = true;
1078
                size = arr_words_sizeW((StgArrBytes*)p);
1079 1080 1081 1082
                break;

            case MUT_ARR_PTRS_CLEAN:
            case MUT_ARR_PTRS_DIRTY:
1083 1084
            case MUT_ARR_PTRS_FROZEN_CLEAN:
            case MUT_ARR_PTRS_FROZEN_DIRTY:
Ben Gamari's avatar
Ben Gamari committed
1085
                prim = true;
1086 1087 1088 1089 1090
                size = mut_arr_ptrs_sizeW((StgMutArrPtrs *)p);
                break;

            case SMALL_MUT_ARR_PTRS_CLEAN:
            case SMALL_MUT_ARR_PTRS_DIRTY:
1091 1092
            case SMALL_MUT_ARR_PTRS_FROZEN_CLEAN:
            case SMALL_MUT_ARR_PTRS_FROZEN_DIRTY:
Ben Gamari's avatar
Ben Gamari committed
1093
                prim = true;
1094 1095 1096 1097
                size = small_mut_arr_ptrs_sizeW((StgSmallMutArrPtrs *)p);
                break;

            case TSO:
Ben Gamari's avatar
Ben Gamari committed
1098
                prim = true;
1099
#if defined(PROFILING)
1100
                if (RtsFlags.ProfFlags.includeTSOs) {
1101
                    size = sizeofW(StgTSO);
1102 1103 1104
                    break;
                } else {
                    // Skip this TSO and move on to the next object
1105
                    p += sizeofW(StgTSO);
1106 1107
                    continue;
                }
1108
#else
1109
                size = sizeofW(StgTSO);
1110
                break;
1111 1112
#endif

1113
            case STACK:
Ben Gamari's avatar
Ben Gamari committed
1114
                prim = true;
1115
#if defined(PROFILING)
1116
                if (RtsFlags.ProfFlags.includeTSOs) {
1117 1118
                    size = stack_sizeW((StgStack*)p);
                    break;
1119 1120
                } else {
                    // Skip this TSO and move on to the next object
1121
                    p += stack_sizeW((StgStack*)p);
1122 1123
                    continue;
                }
1124 1125
#else
                size = stack_sizeW((StgStack*)p);
1126
                break;
1127 1128 1129
#endif

            case TREC_CHUNK:
Ben Gamari's avatar
Ben Gamari committed
1130
                prim = true;
1131 1132 1133
                size = sizeofW(StgTRecChunk);
                break;

gcampax's avatar
gcampax committed
1134 1135 1136 1137
            case COMPACT_NFDATA:
                barf("heapCensus, found compact object in the wrong list");
                break;

1138 1139 1140 1141
            default:
                barf("heapCensus, unknown object: %d", info->type);
            }

1142
            heapProfObject(census,(StgClosure*)p,size,prim);
1143

1144
            p += size;
1145 1146
            /* skip over slop */
            while (p < bd->free && !*p) p++; // skip slop
1147
        }
1148 1149
    }
}
1150

Simon Marlow's avatar
Simon Marlow committed
1151
void heapCensus (Time t)
1152
{
1153
  uint32_t g, n;
1154
  Census *census;
1155
  gen_workspace *ws;
1156 1157

  census = &censuses[era];
Ian Lynagh's avatar
Ian Lynagh committed
1158
  census->time  = mut_user_time_until(t);
1159

1160
  // calculate retainer sets if necessary
1161
#if defined(PROFILING)
1162 1163
  if (doingRetainerProfiling()) {
      retainerProfile();
1164 1165 1166
  }
#endif

1167
#if defined(PROFILING)
1168
  stat_startHeapCensus();
1169
#endif
1170

1171
  // Traverse the heap, collecting the census info
1172 1173 1174 1175 1176
  for (g = 0; g < RtsFlags.GcFlags.generations; g++) {
      heapCensusChain( census, generations[g].blocks );
      // Are we interested in large objects?  might be
      // confusing to include the stack in a heap profile.
      heapCensusChain( census, generations[g].large_objects );
gcampax's avatar
gcampax committed
1177
      heapCensusCompactList ( census, generations[g].compact_objects );
1178 1179 1180 1181 1182 1183 1184

      for (n = 0; n < n_capabilities; n++) {
          ws = &gc_threads[n]->gens[g];
          heapCensusChain(census, ws->todo_bd);
          heapCensusChain(census, ws->part_list);
          heapCensusChain(census, ws->scavd_list);
      }
1185 1186
  }

1187
  // dump out the census info
1188
#if defined(PROFILING)
1189 1190 1191
    // We can't generate any info for LDV profiling until
    // the end of the run...
    if (!doingLDVProfiling())
1192
        dumpCensus( census );
1193 1194 1195
#else
    dumpCensus( census );
#endif
1196

1197 1198 1199

  // free our storage, unless we're keeping all the census info for
  // future restriction by biography.
1200
#if defined(PROFILING)
1201 1202
  if (RtsFlags.ProfFlags.bioSelector == NULL)
  {
1203
      freeEra(census);
1204 1205 1206
      census->hash = NULL;
      census->arena = NULL;
  }
1207
#endif
1208 1209 1210

  // we're into the next time period now
  nextEra();
1211

1212
#if defined(PROFILING)
1213
  stat_endHeapCensus();
1214
#endif
1215
}