RetainerProfile.c 61.6 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 119 120 121 122 123 124 125 126 127 128 129

/* -----------------------------------------------------------------------------
 * 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 {
130 131
    // Object with fixed layout. Keeps an information about that
    // element was processed. (stackPos.next.step)
132
    posTypeStep,
133 134
    // Description of the pointers-first heap object. Keeps information
    // about layout. (stackPos.next.ptrs)
135
    posTypePtrs,
136
    // Keeps SRT bitmap (stackPos.next.srt)
137
    posTypeSRT,
138 139 140
    // Keeps a new object that was not inspected yet. Keeps a parent
    // element (stackPos.next.parent)
    posTypeFresh
141 142 143 144 145 146 147 148
} nextPosType;

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

    // layout.payload
    struct {
149 150 151
        // See StgClosureInfo in InfoTables.h
        StgHalfWord pos;
        StgHalfWord ptrs;
152
        StgPtr payload;
153 154 155 156
    } ptrs;

    // SRT
    struct {
157
        StgClosure *srt;
158 159 160
    } srt;
} nextPos;

161 162
// Tagged stack element, that keeps information how to process
// the next element in the traverse stack.
163 164 165 166 167
typedef struct {
    nextPosType type;
    nextPos next;
} stackPos;

168 169 170 171 172 173 174
typedef union {
     /**
      * Most recent retainer for the corresponding closure on the stack.
      */
    retainer c_child_r;
} stackData;

175 176
// Element in the traverse stack, keeps the element, information
// how to continue processing the element, and it's retainer set.
177 178
typedef struct {
    stackPos info;
179 180 181
    StgClosure *c;
    StgClosure *cp; // parent of 'c'
    stackData data;
182 183
} stackElement;

184
typedef struct {
185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201
/*
  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.
 */
202 203 204
    bdescr *firstStack;
    bdescr *currentStack;
    stackElement *stackBottom, *stackTop, *stackLimit;
205 206 207 208 209 210 211

/*
  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.
 */
212
    stackElement *currentStackBoundary;
213

214
#if defined(DEBUG_RETAINER)
215 216 217 218 219 220 221 222 223
/*
  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
224
    retainer profiling, maxStackSize is some value no greater
225 226
    than the actual depth of the graph.
 */
227
    int stackSize, maxStackSize;
228
#endif
229 230
} traverseState;

231 232 233 234 235 236 237 238 239 240 241 242 243 244 245
/* 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);

246 247 248
traverseState g_retainerTraverseState;


249
static void retainStack(traverseState *, StgClosure *, stackData, StgPtr, StgPtr);
250
static void retainClosure(traverseState *, StgClosure *, StgClosure *, retainer);
251
static void retainPushClosure(traverseState *, StgClosure *, StgClosure *, stackData);
252 253
static void retainActualPush(traverseState *, stackElement *);

254 255 256 257 258 259 260 261 262

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

/* -----------------------------------------------------------------------------
 * Add a new block group to the stack.
 * Invariants:
 *  currentStack->link == s.
 * -------------------------------------------------------------------------- */
263
static INLINE void
264
newStackBlock( traverseState *ts, bdescr *bd )
265
{
266 267 268 269 270
    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;
271 272 273 274 275 276 277
}

/* -----------------------------------------------------------------------------
 * Return to the previous block group.
 * Invariants:
 *   s->link == currentStack.
 * -------------------------------------------------------------------------- */
278
static INLINE void
279
returnToOldStack( traverseState *ts, bdescr *bd )
280
{
281 282 283 284 285
    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;
286 287 288 289 290 291
}

/* -----------------------------------------------------------------------------
 *  Initializes the traverse stack.
 * -------------------------------------------------------------------------- */
static void
292
initializeTraverseStack( traverseState *ts )
293
{
294 295
    if (ts->firstStack != NULL) {
        freeChain(ts->firstStack);
296 297
    }

298 299 300
    ts->firstStack = allocGroup(BLOCKS_IN_STACK);
    ts->firstStack->link = NULL;
    ts->firstStack->u.back = NULL;
301

302
    newStackBlock(ts, ts->firstStack);
303 304 305 306 307 308 309 310
}

/* -----------------------------------------------------------------------------
 * Frees all the block groups in the traverse stack.
 * Invariants:
 *   firstStack != NULL
 * -------------------------------------------------------------------------- */
static void
311
closeTraverseStack( traverseState *ts )
312
{
313 314
    freeChain(ts->firstStack);
    ts->firstStack = NULL;
315 316 317
}

/* -----------------------------------------------------------------------------
Ben Gamari's avatar
Ben Gamari committed
318
 * Returns true if the whole stack is empty.
319
 * -------------------------------------------------------------------------- */
Ben Gamari's avatar
Ben Gamari committed
320
static INLINE bool
321
isEmptyRetainerStack( traverseState *ts )
322
{
323
    return (ts->firstStack == ts->currentStack) && ts->stackTop == ts->stackLimit;
324 325
}

sof's avatar
sof committed
326 327 328
/* -----------------------------------------------------------------------------
 * Returns size of stack
 * -------------------------------------------------------------------------- */
329
W_
330
retainerStackBlocks( void )
sof's avatar
sof committed
331 332
{
    bdescr* bd;
333
    W_ res = 0;
334
    traverseState *ts = &g_retainerTraverseState;
sof's avatar
sof committed
335

336
    for (bd = ts->firstStack; bd != NULL; bd = bd->link)
sof's avatar
sof committed
337 338 339 340 341
      res += bd->blocks;

    return res;
}

342
/* -----------------------------------------------------------------------------
Ben Gamari's avatar
Ben Gamari committed
343
 * Returns true if stackTop is at the stack boundary of the current stack,
344 345
 * i.e., if the current stack chunk is empty.
 * -------------------------------------------------------------------------- */
Ben Gamari's avatar
Ben Gamari committed
346
static INLINE bool
347
isOnBoundary( traverseState *ts )
348
{
349
    return ts->stackTop == ts->currentStackBoundary;
350 351 352 353 354 355 356
}

/* -----------------------------------------------------------------------------
 * Initializes *info from ptrs and payload.
 * Invariants:
 *   payload[] begins with ptrs pointers followed by non-pointers.
 * -------------------------------------------------------------------------- */
357
static INLINE void
358
init_ptrs( stackPos *info, uint32_t ptrs, StgPtr payload )
359 360 361 362 363 364 365 366 367 368
{
    info->type              = posTypePtrs;
    info->next.ptrs.pos     = 0;
    info->next.ptrs.ptrs    = ptrs;
    info->next.ptrs.payload = payload;
}

/* -----------------------------------------------------------------------------
 * Find the next object from *info.
 * -------------------------------------------------------------------------- */
369
static INLINE StgClosure *
370 371 372
find_ptrs( stackPos *info )
{
    if (info->next.ptrs.pos < info->next.ptrs.ptrs) {
373
        return (StgClosure *)info->next.ptrs.payload[info->next.ptrs.pos++];
374
    } else {
375
        return NULL;
376 377 378 379 380 381
    }
}

/* -----------------------------------------------------------------------------
 *  Initializes *info from SRT information stored in *infoTable.
 * -------------------------------------------------------------------------- */
382
static INLINE void
383
init_srt_fun( stackPos *info, const StgFunInfoTable *infoTable )
384
{
385 386 387
    info->type = posTypeSRT;
    if (infoTable->i.srt) {
        info->next.srt.srt = (StgClosure*)GET_FUN_SRT(infoTable);
388
    } else {
389
        info->next.srt.srt = NULL;
390
    }
391 392
}

393
static INLINE void
394
init_srt_thunk( stackPos *info, const StgThunkInfoTable *infoTable )
395
{
Ömer Sinan Ağacan's avatar
Ömer Sinan Ağacan committed
396
    info->type = posTypeSRT;
397 398
    if (infoTable->i.srt) {
        info->next.srt.srt = (StgClosure*)GET_SRT(infoTable);
399
    } else {
400
        info->next.srt.srt = NULL;
401
    }
402 403 404 405 406
}

/* -----------------------------------------------------------------------------
 * Find the next object from *info.
 * -------------------------------------------------------------------------- */
407
static INLINE StgClosure *
408 409 410
find_srt( stackPos *info )
{
    StgClosure *c;
411
    if (info->type == posTypeSRT) {
412 413 414
        c = info->next.srt.srt;
        info->next.srt.srt = NULL;
        return c;
415 416 417
    }
}

418 419 420 421
/* -----------------------------------------------------------------------------
 * Pushes an element onto traverse stack
 * -------------------------------------------------------------------------- */
static void
422
retainActualPush(traverseState *ts, stackElement *se) {
423
    bdescr *nbd;      // Next Block Descriptor
424
    if (ts->stackTop - 1 < ts->stackBottom) {
425 426 427 428 429
#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.
430
        ts->currentStack->free = (StgPtr)ts->stackTop;
431

432
        if (ts->currentStack->link == NULL) {
433 434
            nbd = allocGroup(BLOCKS_IN_STACK);
            nbd->link = NULL;
435 436
            nbd->u.back = ts->currentStack;
            ts->currentStack->link = nbd;
437
        } else
438
            nbd = ts->currentStack->link;
439

440
        newStackBlock(ts, nbd);
441 442 443
    }

    // adjust stackTop (acutal push)
444
    ts->stackTop--;
445 446 447 448
    // 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.
449
    *ts->stackTop = *se;
450 451

#if defined(DEBUG_RETAINER)
452 453 454 455
    ts->stackSize++;
    if (ts->stackSize > ts->maxStackSize) ts->maxStackSize = ts->stackSize;
    ASSERT(ts->stackSize >= 0);
    debugBelch("stackSize = %d\n", ts->stackSize);
456
#endif
457

458 459 460 461 462 463
}

/* 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.
 *
464
 *  *cp - object's parent
465 466 467 468
 *  *c - closure
 *  c_child_r - closure retainer.
 */
static INLINE void
469
retainPushClosure( traverseState *ts, StgClosure *c, StgClosure *cp, stackData data) {
470 471 472
    stackElement se;

    se.c = c;
473 474
    se.cp = cp;
    se.data = data;
475 476
    se.info.type = posTypeFresh;

477
    retainActualPush(ts, &se);
478 479
};

480 481 482 483
/* -----------------------------------------------------------------------------
 *  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
484
 *  child, *c_child is set to that child and nothing is pushed onto
485 486 487 488 489 490
 *  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.
491
 *     *c is not any of TSO, AP, PAP, AP_STACK, which means that
492 493 494
 *        there cannot be any stack objects.
 *  Note: SRTs are considered to  be children as well.
 * -------------------------------------------------------------------------- */
495
static INLINE void
496
push( traverseState *ts, StgClosure *c, stackData data, StgClosure **first_child )
497 498 499 500
{
    stackElement se;
    bdescr *nbd;      // Next Block Descriptor

Ben Gamari's avatar
Ben Gamari committed
501
#if defined(DEBUG_RETAINER)
502
    debugBelch("push(): stackTop = 0x%x, currentStackBoundary = 0x%x\n", ts->stackTop, ts->currentStackBoundary);
503 504 505
#endif

    ASSERT(get_itbl(c)->type != TSO);
506
    ASSERT(get_itbl(c)->type != AP_STACK);
507 508 509 510 511 512

    //
    // fill in se
    //

    se.c = c;
513 514
    se.data = data;
    // Note: se.cp ommitted on purpose, only retainPushClosure uses that.
515 516 517

    // fill in se.info
    switch (get_itbl(c)->type) {
518
        // no child, no SRT
519 520 521
    case CONSTR_0_1:
    case CONSTR_0_2:
    case ARR_WORDS:
gcampax's avatar
gcampax committed
522
    case COMPACT_NFDATA:
523 524
        *first_child = NULL;
        return;
525

526
        // one child (fixed), no SRT
527 528
    case MUT_VAR_CLEAN:
    case MUT_VAR_DIRTY:
529 530
        *first_child = ((StgMutVar *)c)->var;
        return;
531
    case THUNK_SELECTOR:
532 533
        *first_child = ((StgSelector *)c)->selectee;
        return;
534
    case BLACKHOLE:
535 536
        *first_child = ((StgInd *)c)->indirectee;
        return;
537 538
    case CONSTR_1_0:
    case CONSTR_1_1:
539 540
        *first_child = c->payload[0];
        return;
541

542 543 544
        // 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;
545

546 547
        // two children (fixed), no SRT
        // need to push a stackElement, but nothing to store in se.info
548
    case CONSTR_2_0:
549
        *first_child = c->payload[0];         // return the first pointer
550 551
        se.info.type = posTypeStep;
        se.info.next.step = 2;            // 2 = second
552
        break;
553

554 555
        // three children (fixed), no SRT
        // need to push a stackElement
556 557
    case MVAR_CLEAN:
    case MVAR_DIRTY:
558 559 560
        // 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;
561
        se.info.type = posTypeStep;
562 563 564 565
        se.info.next.step = 2;            // 2 = second
        break;

        // three children (fixed), no SRT
566
    case WEAK:
567
        *first_child = ((StgWeak *)c)->key;
568
        se.info.type = posTypeStep;
569 570
        se.info.next.step = 2;
        break;
571

572
        // layout.payload.ptrs, no SRT
573
    case TVAR:
574
    case CONSTR:
Simon Marlow's avatar
Simon Marlow committed
575
    case CONSTR_NOCAF:
576
    case PRIM:
577
    case MUT_PRIM:
578
    case BCO:
579 580 581 582 583 584 585 586
        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
587 588
    case MUT_ARR_PTRS_CLEAN:
    case MUT_ARR_PTRS_DIRTY:
589 590
    case MUT_ARR_PTRS_FROZEN_CLEAN:
    case MUT_ARR_PTRS_FROZEN_DIRTY:
591 592 593 594 595 596 597 598
        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
599 600
    case SMALL_MUT_ARR_PTRS_CLEAN:
    case SMALL_MUT_ARR_PTRS_DIRTY:
601 602
    case SMALL_MUT_ARR_PTRS_FROZEN_CLEAN:
    case SMALL_MUT_ARR_PTRS_FROZEN_DIRTY:
603 604 605 606 607 608
        init_ptrs(&se.info, ((StgSmallMutArrPtrs *)c)->ptrs,
                  (StgPtr)(((StgSmallMutArrPtrs *)c)->payload));
        *first_child = find_ptrs(&se.info);
        if (*first_child == NULL)
            return;
        break;
609

610
    // layout.payload.ptrs, SRT
611
    case FUN_STATIC:
612 613
    case FUN:           // *c is a heap object.
    case FUN_2_0:
614 615 616 617 618 619
        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;
620

621 622
    case THUNK:
    case THUNK_2_0:
623 624 625 626 627 628 629 630 631
        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
632 633
    case FUN_1_0:
    case FUN_1_1:
634 635 636 637
        *first_child = c->payload[0];
        ASSERT(*first_child != NULL);
        init_srt_fun(&se.info, get_fun_itbl(c));
        break;
638

639 640
    case THUNK_1_0:
    case THUNK_1_1:
641 642 643 644
        *first_child = ((StgThunk *)c)->payload[0];
        ASSERT(*first_child != NULL);
        init_srt_thunk(&se.info, get_thunk_itbl(c));
        break;
645

646
    case FUN_0_1:      // *c is a heap object.
647
    case FUN_0_2:
648 649
    fun_srt_only:
        init_srt_fun(&se.info, get_fun_itbl(c));
650 651 652 653
        *first_child = find_srt(&se.info);
        if (*first_child == NULL)
            return;     // no child
        break;
654 655 656

    // SRT only
    case THUNK_STATIC:
657
        ASSERT(get_itbl(c)->srt != 0);
658 659
    case THUNK_0_1:
    case THUNK_0_2:
660 661
    thunk_srt_only:
        init_srt_thunk(&se.info, get_thunk_itbl(c));
662 663 664 665 666
        *first_child = find_srt(&se.info);
        if (*first_child == NULL)
            return;     // no child
        break;

667
    case TREC_CHUNK:
668
        *first_child = (StgClosure *)((StgTRecChunk *)c)->prev_chunk;
669
        se.info.type = posTypeStep;
670 671
        se.info.next.step = 0;  // entry no.
        break;
672

673
        // cannot appear
674
    case PAP:
675 676
    case AP:
    case AP_STACK:
677
    case TSO:
678
    case STACK:
679
    case IND_STATIC:
680
        // stack objects
681 682
    case UPDATE_FRAME:
    case CATCH_FRAME:
683
    case UNDERFLOW_FRAME:
684 685 686 687
    case STOP_FRAME:
    case RET_BCO:
    case RET_SMALL:
    case RET_BIG:
688
        // invalid objects
689 690 691
    case IND:
    case INVALID_OBJECT:
    default:
692
        barf("Invalid object *c in push(): %d", get_itbl(c)->type);
693
        return;
694 695
    }

696 697 698 699
    // 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);

700
    retainActualPush(ts, &se);
701 702 703 704 705 706 707 708 709 710 711 712
}

/* -----------------------------------------------------------------------------
 *  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
713
 *    INLINE function (for the sake of execution speed).  popOffReal()
714 715 716
 *    is called only within popOff() and nowhere else.
 * -------------------------------------------------------------------------- */
static void
717
popOffReal(traverseState *ts)
718 719 720
{
    bdescr *pbd;    // Previous Block Descriptor

Ben Gamari's avatar
Ben Gamari committed
721
#if defined(DEBUG_RETAINER)
722
    debugBelch("pop() to the previous stack.\n");
723 724
#endif

725 726
    ASSERT(ts->stackTop + 1 == ts->stackLimit);
    ASSERT(ts->stackBottom == (stackElement *)ts->currentStack->start);
727

728
    if (ts->firstStack == ts->currentStack) {
729
        // The stack is completely empty.
730 731
        ts->stackTop++;
        ASSERT(ts->stackTop == ts->stackLimit);
Ben Gamari's avatar
Ben Gamari committed
732
#if defined(DEBUG_RETAINER)
733 734 735 736
        ts->stackSize--;
        if (ts->stackSize > ts->maxStackSize) ts->maxStackSize = ts->stackSize;
        ASSERT(ts->stackSize >= 0);
        debugBelch("stackSize = %d\n", ts->stackSize);
737
#endif
738
        return;
739 740 741 742
    }

    // currentStack->free is updated when the active stack is switched back
    // to the previous stack.
743
    ts->currentStack->free = (StgPtr)ts->stackLimit;
744 745

    // find the previous block descriptor
746
    pbd = ts->currentStack->u.back;
747 748
    ASSERT(pbd != NULL);

749
    returnToOldStack(ts, pbd);
750

Ben Gamari's avatar
Ben Gamari committed
751
#if defined(DEBUG_RETAINER)
752 753 754 755
    ts->stackSize--;
    if (ts->stackSize > ts->maxStackSize) ts->maxStackSize = ts->stackSize;
    ASSERT(ts->stackSize >= 0);
    debugBelch("stackSize = %d\n", ts->stackSize);
756 757 758
#endif
}

759
static INLINE void
760
popOff(traverseState *ts) {
Ben Gamari's avatar
Ben Gamari committed
761
#if defined(DEBUG_RETAINER)
762
    debugBelch("\tpopOff(): stackTop = 0x%x, currentStackBoundary = 0x%x\n", ts->stackTop, ts->currentStackBoundary);
763 764
#endif

765 766
    ASSERT(ts->stackTop != ts->stackLimit);
    ASSERT(!isEmptyRetainerStack(ts));
767 768

    // <= (instead of <) is wrong!
769 770
    if (ts->stackTop + 1 < ts->stackLimit) {
        ts->stackTop++;
Ben Gamari's avatar
Ben Gamari committed
771
#if defined(DEBUG_RETAINER)
772 773 774 775
        ts->stackSize--;
        if (ts->stackSize > ts->maxStackSize) ts->maxStackSize = ts->stackSize;
        ASSERT(ts->stackSize >= 0);
        debugBelch("stackSize = %d\n", ts->stackSize);
776
#endif
777
        return;
778 779
    }

780
    popOffReal(ts);
781 782 783 784 785
}

/* -----------------------------------------------------------------------------
 *  Finds the next object to be considered for retainer profiling and store
 *  its pointer to *c.
786 787 788
 *  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,
789
 *  and if so, retrieve the first object and store its pointer to *c. Also,
790 791 792
 *  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.
793 794
 *  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
795
 *  the current stack chunk becomes empty, indicated by true returned by
796 797 798 799 800
 *  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.
 * -------------------------------------------------------------------------- */
801
static INLINE void
802
pop( traverseState *ts, StgClosure **c, StgClosure **cp, stackData *data )
803 804 805
{
    stackElement *se;

Ben Gamari's avatar
Ben Gamari committed
806
#if defined(DEBUG_RETAINER)
807
    debugBelch("pop(): stackTop = 0x%x, currentStackBoundary = 0x%x\n", ts->stackTop, ts->currentStackBoundary);
808 809
#endif

810 811 812 813
    // Is this the last internal element? If so instead of modifying the current
    // stackElement in place we actually remove it from the stack.
    bool last = false;

814
    do {
815
        if (isOnBoundary(ts)) {     // if the current stack chunk is depleted
816 817 818 819
            *c = NULL;
            return;
        }

820 821
        // Note: Below every `break`, where the loop condition is true, must be
        // accompanied by a popOff() otherwise this is an infinite loop.
822
        se = ts->stackTop;
823

824 825
        // If this is a top-level element, you should pop that out.
        if (se->info.type == posTypeFresh) {
826
            *cp = se->cp;
827
            *c = se->c;
828
            *data = se->data;
829
            popOff(ts);
830 831 832
            return;
        }

833 834
        // Note: The first ptr of all of these was already returned as
        // *fist_child in push(), so we always start with the second field.
835 836 837 838 839
        switch (get_itbl(se->c)->type) {
            // two children (fixed), no SRT
            // nothing in se.info
        case CONSTR_2_0:
            *c = se->c->payload[1];
840 841
            last = true;
            goto out;
842 843 844

            // three children (fixed), no SRT
            // need to push a stackElement
845 846
        case MVAR_CLEAN:
        case MVAR_DIRTY:
847 848 849 850 851 852
            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;
853
                last = true;
854
            }
855
            goto out;
856 857 858 859 860 861 862 863 864

            // 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;
865
                last = true;
866
            }
867
            goto out;
868 869 870 871 872 873 874 875

        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;
876 877
            uint32_t entry_no = se->info.next.step >> 2;
            uint32_t field_no = se->info.next.step & 3;
878 879
            if (entry_no == ((StgTRecChunk *)se->c)->next_entry_idx) {
                *c = NULL;
880
                popOff(ts);
881
                break; // this breaks out of the switch not the loop
882 883 884 885 886 887 888 889 890 891
            }
            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;
            }
            se->info.next.step++;
892
            goto out;
893
        }
894

895 896
        case TVAR:
        case CONSTR:
897 898 899 900 901 902
        case PRIM:
        case MUT_PRIM:
        case BCO:
            // StgMutArrPtr.ptrs, no SRT
        case MUT_ARR_PTRS_CLEAN:
        case MUT_ARR_PTRS_DIRTY:
903 904
        case MUT_ARR_PTRS_FROZEN_CLEAN:
        case MUT_ARR_PTRS_FROZEN_DIRTY:
905 906 907 908
        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:
909 910
            *c = find_ptrs(&se->info);
            if (*c == NULL) {
911
                popOff(ts);
912
                break; // this breaks out of the switch not the loop
913
            }
914
            goto out;
915 916 917

            // layout.payload.ptrs, SRT
        case FUN:         // always a heap object
918
        case FUN_STATIC:
919 920 921 922
        case FUN_2_0:
            if (se->info.type == posTypePtrs) {
                *c = find_ptrs(&se->info);
                if (*c != NULL) {
923
                    goto out;
924 925 926 927 928 929 930 931 932 933
                }
                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) {
934
                    goto out;
935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951
                }
                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);
952 953 954
            if(*c == NULL) {
                popOff(ts);
                break; // this breaks out of the switch not the loop
955
            }
956
            goto out;
957 958 959 960 961 962 963 964 965 966 967 968 969 970 971

            // 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:
972 973
        case STACK:
        case IND_STATIC:
Simon Marlow's avatar
Simon Marlow committed
974
        case CONSTR_NOCAF:
975
            // stack objects
976
        case UPDATE_FRAME:
977
        case CATCH_FRAME:
978 979
        case UNDERFLOW_FRAME:
        case STOP_FRAME:
980 981 982 983 984 985 986
        case RET_BCO:
        case RET_SMALL:
        case RET_BIG:
            // invalid objects
        case IND:
        case INVALID_OBJECT:
        default:
987
            barf("Invalid object *c in pop(): %d", get_itbl(se->c)->type);
988 989
            return;
        }
990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003
    } while (*c == NULL);

out:

    ASSERT(*c != NULL);

    *cp = se->c;
    *data = se->data;

    if(last)
        popOff(ts);

    return;

1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039
}

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

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

/* -----------------------------------------------------------------------------
 *  This function must be called before f-closing prof_file.
 * -------------------------------------------------------------------------- */
void
endRetainerProfiling( void )
{
    outputAllRetainerSet(prof_file);
}

/* -----------------------------------------------------------------------------
 *  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.
 * -------------------------------------------------------------------------- */
1040
static INLINE void
1041
maybeInitTravData( StgClosure *c )
1042
{
1043 1044
    if (!isTravDataValid(c)) {
        setTravDataToZero(c);
1045 1046 1047 1048
    }
}

/* -----------------------------------------------------------------------------
Ben Gamari's avatar
Ben Gamari committed
1049
 * Returns true if *c is a retainer.
1050 1051 1052 1053 1054 1055
 * 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.
1056
 * -------------------------------------------------------------------------- */
Ben Gamari's avatar
Ben Gamari committed
1057
static INLINE bool
1058 1059 1060
isRetainer( StgClosure *c )
{
    switch (get_itbl(c)->type) {
1061 1062 1063 1064
        //
        //  True case
        //
        // TSOs MUST be retainers: they constitute the set of roots.
1065
    case TSO:
1066
    case STACK:
1067

1068
        // mutable objects
1069
    case MUT_PRIM:
1070 1071
    case MVAR_CLEAN:
    case MVAR_DIRTY:
1072
    case TVAR:
1073 1074
    case MUT_VAR_CLEAN:
    case MUT_VAR_DIRTY:
1075 1076
    case MUT_ARR_PTRS_CLEAN:
    case MUT_ARR_PTRS_DIRTY:
1077 1078 1079
    case SMALL_MUT_ARR_PTRS_CLEAN:
    case SMALL_MUT_ARR_PTRS_DIRTY:
    case BLOCKING_QUEUE:
1080

1081
        // thunks are retainers.
1082 1083 1084 1085 1086 1087 1088
    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:
1089 1090
    case AP:
    case AP_STACK:
1091

1092
        // Static thunks, or CAFS, are obviously retainers.
1093 1094
    case THUNK_STATIC:

1095 1096
        // WEAK objects are roots; there is separate code in which traversing
        // begins from WEAK objects.
1097
    case WEAK:
Ben Gamari's avatar
Ben Gamari committed
1098
        return true;
1099

1100 1101 1102
        //
        // False case
        //
1103

1104
        // constructors
1105
    case CONSTR:
Simon Marlow's avatar
Simon Marlow committed
1106
    case CONSTR_NOCAF:
1107 1108 1109 1110 1111
    case CONSTR_1_0:
    case CONSTR_0_1:
    case CONSTR_2_0:
    case CONSTR_1_1:
    case CONSTR_0_2:
1112
        // functions
1113 1114 1115 1116 1117 1118
    case FUN:
    case FUN_1_0:
    case FUN_0_1:
    case FUN_2_0:
    case FUN_1_1:
    case FUN_0_2:
1119
        // partial applications
1120
    case PAP:
1121
        // indirection
Ian Lynagh's avatar
Ian Lynagh committed
1122 1123 1124 1125
    // 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:
1126
    case BLACKHOLE:
1127
    case WHITEHOLE:
1128
        // static objects
1129
    case FUN_STATIC:
1130
        // misc
1131
    case PRIM:
1132 1133
    case BCO:
    case ARR_WORDS:
1134
    case COMPACT_NFDATA:
1135
        // STM
1136
    case TREC_CHUNK:
1137
        // immutable arrays
1138 1139 1140 1141
    case MUT_ARR_PTRS_FROZEN_CLEAN:
    case MUT_ARR_PTRS_FROZEN_DIRTY:
    case SMALL_MUT_ARR_PTRS_FROZEN_CLEAN:
    case SMALL_MUT_ARR_PTRS_FROZEN_DIRTY:
Ben Gamari's avatar
Ben Gamari committed
1142
        return false;
1143

1144 1145 1146 1147 1148
        //
        // Error case
        //
        // Stack objects are invalid because they are never treated as
        // legal objects during retainer profiling.