RetainerProfile.c 72.5 KB
Newer Older
1 2 3 4 5 6 7 8 9
/* -----------------------------------------------------------------------------
 *
 * (c) The GHC Team, 2001
 * Author: Sungwoo Park
 *
 * Retainer profiling.
 *
 * ---------------------------------------------------------------------------*/

Ben Gamari's avatar
Ben Gamari committed
10
#if defined(PROFILING)
11

12
// Turn off inlining when debugging - it obfuscates things
Ben Gamari's avatar
Ben Gamari committed
13
#if defined(DEBUG)
14 15 16 17 18
#define INLINE
#else
#define INLINE inline
#endif

Simon Marlow's avatar
Simon Marlow committed
19
#include "PosixSource.h"
20
#include "Rts.h"
Simon Marlow's avatar
Simon Marlow committed
21

22 23 24 25 26 27
#include "RtsUtils.h"
#include "RetainerProfile.h"
#include "RetainerSet.h"
#include "Schedule.h"
#include "Printer.h"
#include "Weak.h"
Simon Marlow's avatar
Simon Marlow committed
28
#include "sm/Sanity.h"
29 30 31
#include "Profiling.h"
#include "Stats.h"
#include "ProfHeap.h"
32
#include "Apply.h"
David Feuer's avatar
David Feuer committed
33 34
#include "StablePtr.h" /* markStablePtrTable */
#include "StableName.h" /* rememberOldStableNameAddresses */
Simon Marlow's avatar
Simon Marlow committed
35
#include "sm/Storage.h" // for END_OF_STATIC_LIST
36

37 38
/* Note [What is a retainer?]
   ~~~~~~~~~~~~~~~~~~~~~~~~~~
39 40
Retainer profiling is a profiling technique that gives information why
objects can't be freed and lists the consumers that hold pointers to
41
the heap objects. It does not list all the objects that keep references
42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
to the other, because then we would keep too much information that will
make the report unusable, for example the cons element of the list would keep
all the tail cells. As a result we are keeping only the objects of the
certain types, see 'isRetainer()' function for more discussion.

More formal definition of the retainer can be given the following way.

An object p is a retainer object of the object l, if all requirements
hold:

  1. p can be a retainer (see `isRetainer()`)
  2. l is reachable from p
  3. There are no other retainers on the path from p to l.

Exact algorithm and additional information can be found the historical
document 'docs/storage-mgt/rp.tex'. Details that are related to the
RTS implementation may be out of date, but the general
information about the retainers is still applicable.
60 61 62
*/


63 64 65 66 67 68 69 70 71
/*
  Note: what to change in order to plug-in a new retainer profiling scheme?
    (1) type retainer in ../includes/StgRetainerProf.h
    (2) retainer function R(), i.e., getRetainerFrom()
    (3) the two hashing functions, hashKeySingleton() and hashKeyAddElement(),
        in RetainerSet.h, if needed.
    (4) printRetainer() and printRetainerSetShort() in RetainerSet.c.
 */

72 73
// TODO: Change references to c_child_r in comments to 'data'.

74 75 76 77
/* -----------------------------------------------------------------------------
 * Declarations...
 * -------------------------------------------------------------------------- */

78
static uint32_t retainerGeneration;  // generation
79

80 81 82
static uint32_t numObjectVisited;    // total number of objects visited
static uint32_t timesAnyObjectVisited;  // number of times any objects are
                                        // visited
83

84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111
/** Note [Profiling heap traversal visited bit]
 *
 * If the RTS is compiled with profiling enabled StgProfHeader can be used by
 * profiling code to store per-heap object information.
 *
 * When using the generic heap traversal code we use this field to store
 * profiler specific information. However we reserve the LSB of the *entire*
 * 'trav' union (which will overlap with the other fields) for the generic
 * traversal code. We use the bit to decide whether we've already visited this
 * closure in this pass or not. We do this as the heap may contain cyclic
 * references, it being a graph and all, so we would likely just infinite loop
 * if we didn't.
 *
 * We assume that at least the LSB of the largest field in the corresponding
 * union is insignificant. This is true at least for the word aligned pointers
 * which the retainer profiler currently stores there and should be maintained
 * by new users of the 'trav' union.
 *
 * Now the way the traversal works is that the interpretation of the "visited?"
 * bit depends on the value of the global 'flip' variable. We don't want to have
 * to do another pass over the heap just to reset the bit to zero so instead on
 * each traversal (i.e. each run of the profiling code) we invert the value of
 * the global 'flip' variable. We interpret this as resetting all the "visited?"
 * flags on the heap.
 *
 * There is one exception to this rule, namely: static objects. There we do just
 * go over the heap and reset the bit manually. See
 * 'resetStaticObjectForRetainerProfiling'.
112
 */
113
StgWord flip = 0;     // flip bit
114 115
                      // must be 0 if DEBUG_RETAINER is on (for static closures)

116 117
#define setTravDataToZero(c) \
  (c)->header.prof.hp.trav.lsb = flip
118

Ben Gamari's avatar
Ben Gamari committed
119
#if defined(DEBUG_RETAINER)
120
static uint32_t sumOfNewCost;        // sum of the cost of each object, computed
121
                                // when the object is first visited
122
static uint32_t sumOfNewCostExtra;   // for those objects not visited during
123
                                // retainer profiling, e.g., MUT_VAR
124
static uint32_t costArray[N_CLOSURE_TYPES];
125

126
uint32_t sumOfCostLinear;            // sum of the costs of all object, computed
127 128
                                // when linearly traversing the heap after
                                // retainer profiling
129
uint32_t costArrayLinear[N_CLOSURE_TYPES];
130 131 132 133 134 135 136 137 138 139 140 141 142
#endif

/* -----------------------------------------------------------------------------
 * Retainer stack - header
 *   Note:
 *     Although the retainer stack implementation could be separated *
 *     from the retainer profiling engine, there does not seem to be
 *     any advantage in doing that; retainer stack is an integral part
 *     of retainer profiling engine and cannot be use elsewhere at
 *     all.
 * -------------------------------------------------------------------------- */

typedef enum {
143 144
    // Object with fixed layout. Keeps an information about that
    // element was processed. (stackPos.next.step)
145
    posTypeStep,
146 147
    // Description of the pointers-first heap object. Keeps information
    // about layout. (stackPos.next.ptrs)
148
    posTypePtrs,
149
    // Keeps SRT bitmap (stackPos.next.srt)
150
    posTypeSRT,
151 152 153
    // Keeps a new object that was not inspected yet. Keeps a parent
    // element (stackPos.next.parent)
    posTypeFresh
154 155 156 157 158 159 160 161
} nextPosType;

typedef union {
    // fixed layout or layout specified by a field in the closure
    StgWord step;

    // layout.payload
    struct {
162 163 164
        // See StgClosureInfo in InfoTables.h
        StgHalfWord pos;
        StgHalfWord ptrs;
165
        StgPtr payload;
166 167 168 169
    } ptrs;

    // SRT
    struct {
170
        StgClosure *srt;
171 172 173
    } srt;
} nextPos;

174 175
// Tagged stack element, that keeps information how to process
// the next element in the traverse stack.
176 177 178 179 180
typedef struct {
    nextPosType type;
    nextPos next;
} stackPos;

181 182 183 184 185 186 187
typedef union {
     /**
      * Most recent retainer for the corresponding closure on the stack.
      */
    retainer c_child_r;
} stackData;

188 189
// Element in the traverse stack, keeps the element, information
// how to continue processing the element, and it's retainer set.
190 191
typedef struct {
    stackPos info;
192 193 194
    StgClosure *c;
    StgClosure *cp; // parent of 'c'
    stackData data;
195 196
} stackElement;

197
typedef struct {
198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214
/*
  Invariants:
    firstStack points to the first block group.
    currentStack points to the block group currently being used.
    currentStack->free == stackLimit.
    stackTop points to the topmost byte in the stack of currentStack.
    Unless the whole stack is empty, stackTop must point to the topmost
    object (or byte) in the whole stack. Thus, it is only when the whole stack
    is empty that stackTop == stackLimit (not during the execution of push()
    and pop()).
    stackBottom == currentStack->start.
    stackLimit == currentStack->start + BLOCK_SIZE_W * currentStack->blocks.
  Note:
    When a current stack becomes empty, stackTop is set to point to
    the topmost element on the previous block group so as to satisfy
    the invariants described above.
 */
215 216 217
    bdescr *firstStack;
    bdescr *currentStack;
    stackElement *stackBottom, *stackTop, *stackLimit;
218 219 220 221 222 223 224

/*
  currentStackBoundary is used to mark the current stack chunk.
  If stackTop == currentStackBoundary, it means that the current stack chunk
  is empty. It is the responsibility of the user to keep currentStackBoundary
  valid all the time if it is to be employed.
 */
225
    stackElement *currentStackBoundary;
226

227
#if defined(DEBUG_RETAINER)
228 229 230 231 232 233 234 235 236
/*
  stackSize records the current size of the stack.
  maxStackSize records its high water mark.
  Invariants:
    stackSize <= maxStackSize
  Note:
    stackSize is just an estimate measure of the depth of the graph. The reason
    is that some heap objects have only a single child and may not result
    in a new element being pushed onto the stack. Therefore, at the end of
237
    retainer profiling, maxStackSize is some value no greater
238 239
    than the actual depth of the graph.
 */
240
    int stackSize, maxStackSize;
241
#endif
242 243
} traverseState;

244 245 246 247 248 249 250 251 252 253 254 255 256 257 258
/* Callback called when heap traversal visits a closure.
 *
 * Before this callback is called the profiling header of the visited closure
 * 'c' is zero'd with 'setTravDataToZero' if this closure hasn't been visited in
 * this run yet. See Note [Profiling heap traversal visited bit].
 *
 * Return 'true' when this is not the first visit to this element. The generic
 * traversal code will then skip traversing the children.
 */
typedef bool (*visitClosure_cb) (
    const StgClosure *c,
    const StgClosure *cp,
    const stackData data,
    stackData *child_data);

259 260 261
traverseState g_retainerTraverseState;


262
static void retainStack(traverseState *, StgClosure *, stackData, StgPtr, StgPtr);
263
static void retainClosure(traverseState *, StgClosure *, StgClosure *, retainer);
264
static void retainPushClosure(traverseState *, StgClosure *, StgClosure *, stackData);
265 266 267 268 269 270 271
static void retainActualPush(traverseState *, stackElement *);

#if defined(DEBUG_RETAINER)
static void belongToHeap(StgPtr p);
static uint32_t checkHeapSanityForRetainerProfiling( void );
#endif

272 273 274 275 276 277 278 279 280

// number of blocks allocated for one stack
#define BLOCKS_IN_STACK 1

/* -----------------------------------------------------------------------------
 * Add a new block group to the stack.
 * Invariants:
 *  currentStack->link == s.
 * -------------------------------------------------------------------------- */
281
static INLINE void
282
newStackBlock( traverseState *ts, bdescr *bd )
283
{
284 285 286 287 288
    ts->currentStack = bd;
    ts->stackTop     = (stackElement *)(bd->start + BLOCK_SIZE_W * bd->blocks);
    ts->stackBottom  = (stackElement *)bd->start;
    ts->stackLimit   = (stackElement *)ts->stackTop;
    bd->free     = (StgPtr)ts->stackLimit;
289 290 291 292 293 294 295
}

/* -----------------------------------------------------------------------------
 * Return to the previous block group.
 * Invariants:
 *   s->link == currentStack.
 * -------------------------------------------------------------------------- */
296
static INLINE void
297
returnToOldStack( traverseState *ts, bdescr *bd )
298
{
299 300 301 302 303
    ts->currentStack = bd;
    ts->stackTop = (stackElement *)bd->free;
    ts->stackBottom = (stackElement *)bd->start;
    ts->stackLimit = (stackElement *)(bd->start + BLOCK_SIZE_W * bd->blocks);
    bd->free = (StgPtr)ts->stackLimit;
304 305 306 307 308 309
}

/* -----------------------------------------------------------------------------
 *  Initializes the traverse stack.
 * -------------------------------------------------------------------------- */
static void
310
initializeTraverseStack( traverseState *ts )
311
{
312 313
    if (ts->firstStack != NULL) {
        freeChain(ts->firstStack);
314 315
    }

316 317 318
    ts->firstStack = allocGroup(BLOCKS_IN_STACK);
    ts->firstStack->link = NULL;
    ts->firstStack->u.back = NULL;
319

320
    newStackBlock(ts, ts->firstStack);
321 322 323 324 325 326 327 328
}

/* -----------------------------------------------------------------------------
 * Frees all the block groups in the traverse stack.
 * Invariants:
 *   firstStack != NULL
 * -------------------------------------------------------------------------- */
static void
329
closeTraverseStack( traverseState *ts )
330
{
331 332
    freeChain(ts->firstStack);
    ts->firstStack = NULL;
333 334 335
}

/* -----------------------------------------------------------------------------
Ben Gamari's avatar
Ben Gamari committed
336
 * Returns true if the whole stack is empty.
337
 * -------------------------------------------------------------------------- */
Ben Gamari's avatar
Ben Gamari committed
338
static INLINE bool
339
isEmptyRetainerStack( traverseState *ts )
340
{
341
    return (ts->firstStack == ts->currentStack) && ts->stackTop == ts->stackLimit;
342 343
}

sof's avatar
sof committed
344 345 346
/* -----------------------------------------------------------------------------
 * Returns size of stack
 * -------------------------------------------------------------------------- */
347
W_
348
retainerStackBlocks( void )
sof's avatar
sof committed
349 350
{
    bdescr* bd;
351
    W_ res = 0;
352
    traverseState *ts = &g_retainerTraverseState;
sof's avatar
sof committed
353

354
    for (bd = ts->firstStack; bd != NULL; bd = bd->link)
sof's avatar
sof committed
355 356 357 358 359
      res += bd->blocks;

    return res;
}

360
/* -----------------------------------------------------------------------------
Ben Gamari's avatar
Ben Gamari committed
361
 * Returns true if stackTop is at the stack boundary of the current stack,
362 363
 * i.e., if the current stack chunk is empty.
 * -------------------------------------------------------------------------- */
Ben Gamari's avatar
Ben Gamari committed
364
static INLINE bool
365
isOnBoundary( traverseState *ts )
366
{
367
    return ts->stackTop == ts->currentStackBoundary;
368 369 370 371 372 373 374
}

/* -----------------------------------------------------------------------------
 * Initializes *info from ptrs and payload.
 * Invariants:
 *   payload[] begins with ptrs pointers followed by non-pointers.
 * -------------------------------------------------------------------------- */
375
static INLINE void
376
init_ptrs( stackPos *info, uint32_t ptrs, StgPtr payload )
377 378 379 380 381 382 383 384 385 386
{
    info->type              = posTypePtrs;
    info->next.ptrs.pos     = 0;
    info->next.ptrs.ptrs    = ptrs;
    info->next.ptrs.payload = payload;
}

/* -----------------------------------------------------------------------------
 * Find the next object from *info.
 * -------------------------------------------------------------------------- */
387
static INLINE StgClosure *
388 389 390
find_ptrs( stackPos *info )
{
    if (info->next.ptrs.pos < info->next.ptrs.ptrs) {
391
        return (StgClosure *)info->next.ptrs.payload[info->next.ptrs.pos++];
392
    } else {
393
        return NULL;
394 395 396 397 398 399
    }
}

/* -----------------------------------------------------------------------------
 *  Initializes *info from SRT information stored in *infoTable.
 * -------------------------------------------------------------------------- */
400
static INLINE void
401
init_srt_fun( stackPos *info, const StgFunInfoTable *infoTable )
402
{
403 404 405
    info->type = posTypeSRT;
    if (infoTable->i.srt) {
        info->next.srt.srt = (StgClosure*)GET_FUN_SRT(infoTable);
406
    } else {
407
        info->next.srt.srt = NULL;
408
    }
409 410
}

411
static INLINE void
412
init_srt_thunk( stackPos *info, const StgThunkInfoTable *infoTable )
413
{
Ömer Sinan Ağacan's avatar
Ömer Sinan Ağacan committed
414
    info->type = posTypeSRT;
415 416
    if (infoTable->i.srt) {
        info->next.srt.srt = (StgClosure*)GET_SRT(infoTable);
417
    } else {
418
        info->next.srt.srt = NULL;
419
    }
420 421 422 423 424
}

/* -----------------------------------------------------------------------------
 * Find the next object from *info.
 * -------------------------------------------------------------------------- */
425
static INLINE StgClosure *
426 427 428
find_srt( stackPos *info )
{
    StgClosure *c;
429
    if (info->type == posTypeSRT) {
430 431 432
        c = info->next.srt.srt;
        info->next.srt.srt = NULL;
        return c;
433 434 435
    }
}

436 437 438 439
/* -----------------------------------------------------------------------------
 * Pushes an element onto traverse stack
 * -------------------------------------------------------------------------- */
static void
440
retainActualPush(traverseState *ts, stackElement *se) {
441
    bdescr *nbd;      // Next Block Descriptor
442
    if (ts->stackTop - 1 < ts->stackBottom) {
443 444 445 446 447
#if defined(DEBUG_RETAINER)
        // debugBelch("push() to the next stack.\n");
#endif
        // currentStack->free is updated when the active stack is switched
        // to the next stack.
448
        ts->currentStack->free = (StgPtr)ts->stackTop;
449

450
        if (ts->currentStack->link == NULL) {
451 452
            nbd = allocGroup(BLOCKS_IN_STACK);
            nbd->link = NULL;
453 454
            nbd->u.back = ts->currentStack;
            ts->currentStack->link = nbd;
455
        } else
456
            nbd = ts->currentStack->link;
457

458
        newStackBlock(ts, nbd);
459 460 461
    }

    // adjust stackTop (acutal push)
462
    ts->stackTop--;
463 464 465 466
    // If the size of stackElement was huge, we would better replace the
    // following statement by either a memcpy() call or a switch statement
    // on the type of the element. Currently, the size of stackElement is
    // small enough (5 words) that this direct assignment seems to be enough.
467
    *ts->stackTop = *se;
468 469

#if defined(DEBUG_RETAINER)
470 471 472 473
    ts->stackSize++;
    if (ts->stackSize > ts->maxStackSize) ts->maxStackSize = ts->stackSize;
    ASSERT(ts->stackSize >= 0);
    debugBelch("stackSize = %d\n", ts->stackSize);
474
#endif
475

476 477 478 479 480 481
}

/* Push an object onto traverse stack. This method can be used anytime
 * instead of calling retainClosure(), it exists in order to use an
 * explicit stack instead of direct recursion.
 *
482
 *  *cp - object's parent
483 484 485 486
 *  *c - closure
 *  c_child_r - closure retainer.
 */
static INLINE void
487
retainPushClosure( traverseState *ts, StgClosure *c, StgClosure *cp, stackData data) {
488 489 490
    stackElement se;

    se.c = c;
491 492
    se.cp = cp;
    se.data = data;
493 494
    se.info.type = posTypeFresh;

495
    retainActualPush(ts, &se);
496 497
};

498 499 500 501
/* -----------------------------------------------------------------------------
 *  push() pushes a stackElement representing the next child of *c
 *  onto the traverse stack. If *c has no child, *first_child is set
 *  to NULL and nothing is pushed onto the stack. If *c has only one
502
 *  child, *c_child is set to that child and nothing is pushed onto
503 504 505 506 507 508
 *  the stack.  If *c has more than two children, *first_child is set
 *  to the first child and a stackElement representing the second
 *  child is pushed onto the stack.

 *  Invariants:
 *     *c_child_r is the most recent retainer of *c's children.
509
 *     *c is not any of TSO, AP, PAP, AP_STACK, which means that
510 511 512
 *        there cannot be any stack objects.
 *  Note: SRTs are considered to  be children as well.
 * -------------------------------------------------------------------------- */
513
static INLINE void
514
push( traverseState *ts, StgClosure *c, stackData data, StgClosure **first_child )
515 516 517 518
{
    stackElement se;
    bdescr *nbd;      // Next Block Descriptor

Ben Gamari's avatar
Ben Gamari committed
519
#if defined(DEBUG_RETAINER)
520
    debugBelch("push(): stackTop = 0x%x, currentStackBoundary = 0x%x\n", ts->stackTop, ts->currentStackBoundary);
521 522 523
#endif

    ASSERT(get_itbl(c)->type != TSO);
524
    ASSERT(get_itbl(c)->type != AP_STACK);
525 526 527 528 529 530

    //
    // fill in se
    //

    se.c = c;
531 532
    se.data = data;
    // Note: se.cp ommitted on purpose, only retainPushClosure uses that.
533 534 535

    // fill in se.info
    switch (get_itbl(c)->type) {
536
        // no child, no SRT
537 538 539
    case CONSTR_0_1:
    case CONSTR_0_2:
    case ARR_WORDS:
gcampax's avatar
gcampax committed
540
    case COMPACT_NFDATA:
541 542
        *first_child = NULL;
        return;
543

544
        // one child (fixed), no SRT
545 546
    case MUT_VAR_CLEAN:
    case MUT_VAR_DIRTY:
547 548
        *first_child = ((StgMutVar *)c)->var;
        return;
549
    case THUNK_SELECTOR:
550 551
        *first_child = ((StgSelector *)c)->selectee;
        return;
552
    case BLACKHOLE:
553 554
        *first_child = ((StgInd *)c)->indirectee;
        return;
555 556
    case CONSTR_1_0:
    case CONSTR_1_1:
557 558
        *first_child = c->payload[0];
        return;
559

560 561 562
        // For CONSTR_2_0 and MVAR, we use se.info.step to record the position
        // of the next child. We do not write a separate initialization code.
        // Also we do not have to initialize info.type;
563

564 565
        // two children (fixed), no SRT
        // need to push a stackElement, but nothing to store in se.info
566
    case CONSTR_2_0:
567
        *first_child = c->payload[0];         // return the first pointer
568 569
        se.info.type = posTypeStep;
        se.info.next.step = 2;            // 2 = second
570
        break;
571

572 573
        // three children (fixed), no SRT
        // need to push a stackElement
574 575
    case MVAR_CLEAN:
    case MVAR_DIRTY:
576 577 578
        // head must be TSO and the head of a linked list of TSOs.
        // Shoule it be a child? Seems to be yes.
        *first_child = (StgClosure *)((StgMVar *)c)->head;
579
        se.info.type = posTypeStep;
580 581 582 583
        se.info.next.step = 2;            // 2 = second
        break;

        // three children (fixed), no SRT
584
    case WEAK:
585
        *first_child = ((StgWeak *)c)->key;
586
        se.info.type = posTypeStep;
587 588
        se.info.next.step = 2;
        break;
589

590
        // layout.payload.ptrs, no SRT
591
    case TVAR:
592
    case CONSTR:
Simon Marlow's avatar
Simon Marlow committed
593
    case CONSTR_NOCAF:
594
    case PRIM:
595
    case MUT_PRIM:
596
    case BCO:
597 598 599 600 601 602 603 604
        init_ptrs(&se.info, get_itbl(c)->layout.payload.ptrs,
                  (StgPtr)c->payload);
        *first_child = find_ptrs(&se.info);
        if (*first_child == NULL)
            return;   // no child
        break;

        // StgMutArrPtr.ptrs, no SRT
605 606
    case MUT_ARR_PTRS_CLEAN:
    case MUT_ARR_PTRS_DIRTY:
607 608
    case MUT_ARR_PTRS_FROZEN_CLEAN:
    case MUT_ARR_PTRS_FROZEN_DIRTY:
609 610 611 612 613 614 615 616
        init_ptrs(&se.info, ((StgMutArrPtrs *)c)->ptrs,
                  (StgPtr)(((StgMutArrPtrs *)c)->payload));
        *first_child = find_ptrs(&se.info);
        if (*first_child == NULL)
            return;
        break;

        // StgMutArrPtr.ptrs, no SRT
617 618
    case SMALL_MUT_ARR_PTRS_CLEAN:
    case SMALL_MUT_ARR_PTRS_DIRTY:
619 620
    case SMALL_MUT_ARR_PTRS_FROZEN_CLEAN:
    case SMALL_MUT_ARR_PTRS_FROZEN_DIRTY:
621 622 623 624 625 626
        init_ptrs(&se.info, ((StgSmallMutArrPtrs *)c)->ptrs,
                  (StgPtr)(((StgSmallMutArrPtrs *)c)->payload));
        *first_child = find_ptrs(&se.info);
        if (*first_child == NULL)
            return;
        break;
627

628
    // layout.payload.ptrs, SRT
629
    case FUN_STATIC:
630 631
    case FUN:           // *c is a heap object.
    case FUN_2_0:
632 633 634 635 636 637
        init_ptrs(&se.info, get_itbl(c)->layout.payload.ptrs, (StgPtr)c->payload);
        *first_child = find_ptrs(&se.info);
        if (*first_child == NULL)
            // no child from ptrs, so check SRT
            goto fun_srt_only;
        break;
638

639 640
    case THUNK:
    case THUNK_2_0:
641 642 643 644 645 646 647 648 649
        init_ptrs(&se.info, get_itbl(c)->layout.payload.ptrs,
                  (StgPtr)((StgThunk *)c)->payload);
        *first_child = find_ptrs(&se.info);
        if (*first_child == NULL)
            // no child from ptrs, so check SRT
            goto thunk_srt_only;
        break;

        // 1 fixed child, SRT
650 651
    case FUN_1_0:
    case FUN_1_1:
652 653 654 655
        *first_child = c->payload[0];
        ASSERT(*first_child != NULL);
        init_srt_fun(&se.info, get_fun_itbl(c));
        break;
656

657 658
    case THUNK_1_0:
    case THUNK_1_1:
659 660 661 662
        *first_child = ((StgThunk *)c)->payload[0];
        ASSERT(*first_child != NULL);
        init_srt_thunk(&se.info, get_thunk_itbl(c));
        break;
663

664
    case FUN_0_1:      // *c is a heap object.
665
    case FUN_0_2:
666 667
    fun_srt_only:
        init_srt_fun(&se.info, get_fun_itbl(c));
668 669 670 671
        *first_child = find_srt(&se.info);
        if (*first_child == NULL)
            return;     // no child
        break;
672 673 674

    // SRT only
    case THUNK_STATIC:
675
        ASSERT(get_itbl(c)->srt != 0);
676 677
    case THUNK_0_1:
    case THUNK_0_2:
678 679
    thunk_srt_only:
        init_srt_thunk(&se.info, get_thunk_itbl(c));
680 681 682 683 684
        *first_child = find_srt(&se.info);
        if (*first_child == NULL)
            return;     // no child
        break;

685
    case TREC_CHUNK:
686
        *first_child = (StgClosure *)((StgTRecChunk *)c)->prev_chunk;
687
        se.info.type = posTypeStep;
688 689
        se.info.next.step = 0;  // entry no.
        break;
690

691
        // cannot appear
692
    case PAP:
693 694
    case AP:
    case AP_STACK:
695
    case TSO:
696
    case STACK:
697
    case IND_STATIC:
698
        // stack objects
699 700
    case UPDATE_FRAME:
    case CATCH_FRAME:
701
    case UNDERFLOW_FRAME:
702 703 704 705
    case STOP_FRAME:
    case RET_BCO:
    case RET_SMALL:
    case RET_BIG:
706
        // invalid objects
707 708 709
    case IND:
    case INVALID_OBJECT:
    default:
710
        barf("Invalid object *c in push(): %d", get_itbl(c)->type);
711
        return;
712 713
    }

714 715 716 717
    // se.cp has to be initialized when type==posTypeFresh. We don't do that
    // here though. So type must be !=posTypeFresh.
    ASSERT(se.info.type != posTypeFresh);

718
    retainActualPush(ts, &se);
719 720 721 722 723 724 725 726 727 728 729 730
}

/* -----------------------------------------------------------------------------
 *  popOff() and popOffReal(): Pop a stackElement off the traverse stack.
 *  Invariants:
 *    stackTop cannot be equal to stackLimit unless the whole stack is
 *    empty, in which case popOff() is not allowed.
 *  Note:
 *    You can think of popOffReal() as a part of popOff() which is
 *    executed at the end of popOff() in necessary. Since popOff() is
 *    likely to be executed quite often while popOffReal() is not, we
 *    separate popOffReal() from popOff(), which is declared as an
731
 *    INLINE function (for the sake of execution speed).  popOffReal()
732 733 734
 *    is called only within popOff() and nowhere else.
 * -------------------------------------------------------------------------- */
static void
735
popOffReal(traverseState *ts)
736 737 738
{
    bdescr *pbd;    // Previous Block Descriptor

Ben Gamari's avatar
Ben Gamari committed
739
#if defined(DEBUG_RETAINER)
740
    debugBelch("pop() to the previous stack.\n");
741 742
#endif

743 744
    ASSERT(ts->stackTop + 1 == ts->stackLimit);
    ASSERT(ts->stackBottom == (stackElement *)ts->currentStack->start);
745

746
    if (ts->firstStack == ts->currentStack) {
747
        // The stack is completely empty.
748 749
        ts->stackTop++;
        ASSERT(ts->stackTop == ts->stackLimit);
Ben Gamari's avatar
Ben Gamari committed
750
#if defined(DEBUG_RETAINER)
751 752 753 754
        ts->stackSize--;
        if (ts->stackSize > ts->maxStackSize) ts->maxStackSize = ts->stackSize;
        ASSERT(ts->stackSize >= 0);
        debugBelch("stackSize = %d\n", ts->stackSize);
755
#endif
756
        return;
757 758 759 760
    }

    // currentStack->free is updated when the active stack is switched back
    // to the previous stack.
761
    ts->currentStack->free = (StgPtr)ts->stackLimit;
762 763

    // find the previous block descriptor
764
    pbd = ts->currentStack->u.back;
765 766
    ASSERT(pbd != NULL);

767
    returnToOldStack(ts, pbd);
768

Ben Gamari's avatar
Ben Gamari committed
769
#if defined(DEBUG_RETAINER)
770 771 772 773
    ts->stackSize--;
    if (ts->stackSize > ts->maxStackSize) ts->maxStackSize = ts->stackSize;
    ASSERT(ts->stackSize >= 0);
    debugBelch("stackSize = %d\n", ts->stackSize);
774 775 776
#endif
}

777
static INLINE void
778
popOff(traverseState *ts) {
Ben Gamari's avatar
Ben Gamari committed
779
#if defined(DEBUG_RETAINER)
780
    debugBelch("\tpopOff(): stackTop = 0x%x, currentStackBoundary = 0x%x\n", ts->stackTop, ts->currentStackBoundary);
781 782
#endif

783 784
    ASSERT(ts->stackTop != ts->stackLimit);
    ASSERT(!isEmptyRetainerStack(ts));
785 786

    // <= (instead of <) is wrong!
787 788
    if (ts->stackTop + 1 < ts->stackLimit) {
        ts->stackTop++;
Ben Gamari's avatar
Ben Gamari committed
789
#if defined(DEBUG_RETAINER)
790 791 792 793
        ts->stackSize--;
        if (ts->stackSize > ts->maxStackSize) ts->maxStackSize = ts->stackSize;
        ASSERT(ts->stackSize >= 0);
        debugBelch("stackSize = %d\n", ts->stackSize);
794
#endif
795
        return;
796 797
    }

798
    popOffReal(ts);
799 800 801 802 803
}

/* -----------------------------------------------------------------------------
 *  Finds the next object to be considered for retainer profiling and store
 *  its pointer to *c.
804 805 806
 *  If the unprocessed object was stored in the stack (posTypeFresh), the
 *  this object is returned as-is. Otherwise Test if the topmost stack
 *  element indicates that more objects are left,
807
 *  and if so, retrieve the first object and store its pointer to *c. Also,
808 809 810
 *  set *cp and *data appropriately, both of which are stored in the stack
 *  element.  The topmost stack element then is overwritten so as for it to now
 *  denote the next object.
811 812
 *  If the topmost stack element indicates no more objects are left, pop
 *  off the stack element until either an object can be retrieved or
Ben Gamari's avatar
Ben Gamari committed
813
 *  the current stack chunk becomes empty, indicated by true returned by
814 815 816 817 818
 *  isOnBoundary(), in which case *c is set to NULL.
 *  Note:
 *    It is okay to call this function even when the current stack chunk
 *    is empty.
 * -------------------------------------------------------------------------- */
819
static INLINE void
820
pop( traverseState *ts, StgClosure **c, StgClosure **cp, stackData *data )
821 822 823
{
    stackElement *se;

Ben Gamari's avatar
Ben Gamari committed
824
#if defined(DEBUG_RETAINER)
825
    debugBelch("pop(): stackTop = 0x%x, currentStackBoundary = 0x%x\n", ts->stackTop, ts->currentStackBoundary);
826 827 828
#endif

    do {
829
        if (isOnBoundary(ts)) {     // if the current stack chunk is depleted
830 831 832 833
            *c = NULL;
            return;
        }

834
        se = ts->stackTop;
835

836 837
        // If this is a top-level element, you should pop that out.
        if (se->info.type == posTypeFresh) {
838
            *cp = se->cp;
839
            *c = se->c;
840
            *data = se->data;
841
            popOff(ts);
842 843 844
            return;
        }

845 846 847 848 849 850
        switch (get_itbl(se->c)->type) {
            // two children (fixed), no SRT
            // nothing in se.info
        case CONSTR_2_0:
            *c = se->c->payload[1];
            *cp = se->c;
851
            *data = se->data;
852
            popOff(ts);
853 854 855 856
            return;

            // three children (fixed), no SRT
            // need to push a stackElement
857 858
        case MVAR_CLEAN:
        case MVAR_DIRTY:
859 860 861 862 863 864
            if (se->info.next.step == 2) {
                *c = (StgClosure *)((StgMVar *)se->c)->tail;
                se->info.next.step++;             // move to the next step
                // no popOff
            } else {
                *c = ((StgMVar *)se->c)->value;
865
                popOff(ts);
866 867
            }
            *cp = se->c;
868
            *data = se->data;
869 870 871 872 873 874 875 876 877 878
            return;

            // three children (fixed), no SRT
        case WEAK:
            if (se->info.next.step == 2) {
                *c = ((StgWeak *)se->c)->value;
                se->info.next.step++;
                // no popOff
            } else {
                *c = ((StgWeak *)se->c)->finalizer;
879
                popOff(ts);
880 881
            }
            *cp = se->c;
882
            *data = se->data;
883 884 885 886 887 888 889 890 891
            return;

        case TREC_CHUNK: {
            // These are pretty complicated: we have N entries, each
            // of which contains 3 fields that we want to follow.  So
            // we divide the step counter: the 2 low bits indicate
            // which field, and the rest of the bits indicate the
            // entry number (starting from zero).
            TRecEntry *entry;
892 893
            uint32_t entry_no = se->info.next.step >> 2;
            uint32_t field_no = se->info.next.step & 3;
894 895
            if (entry_no == ((StgTRecChunk *)se->c)->next_entry_idx) {
                *c = NULL;
896
                popOff(ts);
897
                break;
898 899 900 901 902 903 904 905 906 907
            }
            entry = &((StgTRecChunk *)se->c)->entries[entry_no];
            if (field_no == 0) {
                *c = (StgClosure *)entry->tvar;
            } else if (field_no == 1) {
                *c = entry->expected_value;
            } else {
                *c = entry->new_value;
            }
            *cp = se->c;
908
            *data = se->data;
909 910 911
            se->info.next.step++;
            return;
        }
912

913 914
        case TVAR:
        case CONSTR:
915 916 917 918 919 920
        case PRIM:
        case MUT_PRIM:
        case BCO:
            // StgMutArrPtr.ptrs, no SRT
        case MUT_ARR_PTRS_CLEAN:
        case MUT_ARR_PTRS_DIRTY:
921 922
        case MUT_ARR_PTRS_FROZEN_CLEAN:
        case MUT_ARR_PTRS_FROZEN_DIRTY:
923 924 925 926
        case SMALL_MUT_ARR_PTRS_CLEAN:
        case SMALL_MUT_ARR_PTRS_DIRTY:
        case SMALL_MUT_ARR_PTRS_FROZEN_CLEAN:
        case SMALL_MUT_ARR_PTRS_FROZEN_DIRTY:
927 928
            *c = find_ptrs(&se->info);
            if (*c == NULL) {
929
                popOff(ts);
930 931 932
                break;
            }
            *cp = se->c;
933
            *data = se->data;
934 935 936 937
            return;

            // layout.payload.ptrs, SRT
        case FUN:         // always a heap object
938
        case FUN_STATIC:
939 940 941 942 943
        case FUN_2_0:
            if (se->info.type == posTypePtrs) {
                *c = find_ptrs(&se->info);
                if (*c != NULL) {
                    *cp = se->c;
944
                    *data = se->data;
945 946 947 948 949 950 951 952 953 954 955 956
                    return;
                }
                init_srt_fun(&se->info, get_fun_itbl(se->c));
            }
            goto do_srt;

        case THUNK:
        case THUNK_2_0:
            if (se->info.type == posTypePtrs) {
                *c = find_ptrs(&se->info);
                if (*c != NULL) {
                    *cp = se->c;
957
                    *data = se->data;
958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977
                    return;
                }
                init_srt_thunk(&se->info, get_thunk_itbl(se->c));
            }
            goto do_srt;

            // SRT
        do_srt:
        case THUNK_STATIC:
        case FUN_0_1:
        case FUN_0_2:
        case THUNK_0_1:
        case THUNK_0_2:
        case FUN_1_0:
        case FUN_1_1:
        case THUNK_1_0:
        case THUNK_1_1:
            *c = find_srt(&se->info);
            if (*c != NULL) {
                *cp = se->c;
978
                *data = se->data;
979 980
                return;
            }
981
            popOff(ts);
982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997
            break;

            // no child (fixed), no SRT
        case CONSTR_0_1:
        case CONSTR_0_2:
        case ARR_WORDS:
            // one child (fixed), no SRT
        case MUT_VAR_CLEAN:
        case MUT_VAR_DIRTY:
        case THUNK_SELECTOR:
        case CONSTR_1_1:
            // cannot appear
        case PAP:
        case AP:
        case AP_STACK:
        case TSO:
998 999
        case STACK:
        case IND_STATIC:
Simon Marlow's avatar
Simon Marlow committed
1000
        case CONSTR_NOCAF:
1001
            // stack objects
1002
        case UPDATE_FRAME:
1003
        case CATCH_FRAME:
1004 1005
        case UNDERFLOW_FRAME:
        case STOP_FRAME:
1006 1007 1008 1009 1010 1011 1012
        case RET_BCO:
        case RET_SMALL:
        case RET_BIG:
            // invalid objects
        case IND:
        case INVALID_OBJECT:
        default:
1013
            barf("Invalid object *c in pop(): %d", get_itbl(se->c)->type);
1014 1015
            return;
        }
Ben Gamari's avatar
Ben Gamari committed
1016
    } while (true);
1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035
}

/* -----------------------------------------------------------------------------
 * RETAINER PROFILING ENGINE
 * -------------------------------------------------------------------------- */

void
initRetainerProfiling( void )
{
    initializeAllRetainerSet();
    retainerGeneration = 0;
}

/* -----------------------------------------------------------------------------
 *  This function must be called before f-closing prof_file.
 * -------------------------------------------------------------------------- */
void
endRetainerProfiling( void )
{
Ben Gamari's avatar
Ben Gamari committed
1036
#if defined(SECOND_APPROACH)
1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054
    outputAllRetainerSet(prof_file);
#endif
}

/* -----------------------------------------------------------------------------
 *  Returns the actual pointer to the retainer set of the closure *c.
 *  It may adjust RSET(c) subject to flip.
 *  Side effects:
 *    RSET(c) is initialized to NULL if its current value does not
 *    conform to flip.
 *  Note:
 *    Even though this function has side effects, they CAN be ignored because
 *    subsequent calls to retainerSetOf() always result in the same return value
 *    and retainerSetOf() is the only way to retrieve retainerSet of a given
 *    closure.
 *    We have to perform an XOR (^) operation each time a closure is examined.
 *    The reason is that we do not know when a closure is visited last.
 * -------------------------------------------------------------------------- */
1055
static INLINE void
1056
maybeInitTravData( StgClosure *c )
1057
{
1058 1059
    if (!isTravDataValid(c)) {
        setTravDataToZero(c);
1060 1061 1062 1063
    }
}

/* -----------------------------------------------------------------------------
Ben Gamari's avatar
Ben Gamari committed
1064
 * Returns true if *c is a retainer.
1065 1066 1067 1068 1069 1070
 * In general the retainers are the objects that may be the roots of the
 * collection. Basically this roots represents programmers threads
 * (TSO) with their stack and thunks.
 *
 * In addition we mark all mutable objects as a retainers, the reason for
 * that decision is lost in time.
1071
 * -------------------------------------------------------------------------- */
Ben Gamari's avatar
Ben Gamari committed
1072
static INLINE bool
1073 1074 1075
isRetainer( StgClosure *c )
{
    switch (get_itbl(c)->type) {
1076 1077 1078 1079
        //
        //  True case
        //
        // TSOs MUST be retainers: they constitute the set of roots.
1080
    case TSO:
1081
    case STACK:
1082

1083
        // mutable objects
1084
    case MUT_PRIM:
1085 1086
    case MVAR_CLEAN:
    case MVAR_DIRTY:
1087
    case TVAR:
1088 1089
    case MUT_VAR_CLEAN:
    case MUT_VAR_DIRTY:
1090 1091
    case MUT_ARR_PTRS_CLEAN:
    case MUT_ARR_PTRS_DIRTY:
1092 1093 1094
    case SMALL_MUT_ARR_PTRS_CLEAN:
    case SMALL_MUT_ARR_PTRS_DIRTY:
    case BLOCKING_QUEUE:
1095

1096
        // thunks are retainers.
1097 1098 1099 1100 1101 1102 1103
    case THUNK:
    case THUNK_1_0:
    case THUNK_0_1:
    case THUNK_2_0:
    case THUNK_1_1:
    case THUNK_0_2:
    case THUNK_SELECTOR:
1104 1105
    case AP:
    case AP_STACK:
1106

1107
        // Static thunks, or CAFS, are obviously retainers.
1108 1109
    case THUNK_STATIC:

1110 1111
        // WEAK objects are roots; there is separate code in which traversing
        // begins from WEAK objects.
1112
    case WEAK:
Ben Gamari's avatar
Ben Gamari committed
1113
        return true;
1114

1115 1116 1117
        //
        // False case
        //
1118

1119
        // constructors
1120
    case CONSTR:
Simon Marlow's avatar
Simon Marlow committed
1121
    case CONSTR_NOCAF:
1122 1123 1124 1125 1126
    case CONSTR_1_0:
    case CONSTR_0_1:
    case CONSTR_2_0:
    case CONSTR_1_1:
    case CONSTR_0_2:
1127
        // functions
1128 1129 1130 1131 1132 1133
    case FUN:
    case FUN_1_0:
    case FUN_0_1:
    case FUN_2_0:
    case FUN_1_1:
    case FUN_0_2:
1134
        // partial applications
1135
    case PAP:
1136
        // indirection
Ian Lynagh's avatar
Ian Lynagh committed
1137 1138 1139 1140
    // IND_STATIC used to be an error, but at the moment it can happen
    // as isAlive doesn't look through IND_STATIC as it ignores static
    // closures. See trac #3956 for a program that hit this error.
    case IND_STATIC:
1141
    case BLACKHOLE:
1142
    case WHITEHOLE:
1143
        // static objects
1144
    case FUN_STATIC:
1145
        // misc