RetainerProfile.c 68.8 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"
33
#include "Stable.h" /* markStableTables */
Simon Marlow's avatar
Simon Marlow committed
34
#include "sm/Storage.h" // for END_OF_STATIC_LIST
35

36 37 38 39 40 41 42 43 44 45 46 47
/* Note [What is a retainer?]
   ~~~~~~~~~~~~~~~~~~~~~~~~~~
The definition of what sorts of things are counted as retainers is a bit hard to
pin down. Intuitively, we want to identify closures which will help the user
identify memory leaks due to thunks. In practice we also end up lumping mutable
objects in this group for reasons that have been lost to time.

The definition of retainer is implemented in isRetainer(), defined later in this
file.
*/


48 49 50 51 52 53 54 55 56 57 58 59 60
/*
  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.
 */

/* -----------------------------------------------------------------------------
 * Declarations...
 * -------------------------------------------------------------------------- */

61
static uint32_t retainerGeneration;  // generation
62

63 64 65
static uint32_t numObjectVisited;    // total number of objects visited
static uint32_t timesAnyObjectVisited;  // number of times any objects are
                                        // visited
66 67 68 69 70 71 72 73 74

/*
  The rs field in the profile header of any object points to its retainer
  set in an indirect way: if flip is 0, it points to the retainer set;
  if flip is 1, it points to the next byte after the retainer set (even
  for NULL pointers). Therefore, with flip 1, (rs ^ 1) is the actual
  pointer. See retainerSetOf().
 */

75
StgWord flip = 0;     // flip bit
76 77 78 79 80
                      // must be 0 if DEBUG_RETAINER is on (for static closures)

#define setRetainerSetToNull(c)   \
  (c)->header.prof.hp.rs = (RetainerSet *)((StgWord)NULL | flip)

81
static void retainStack(StgClosure *, retainer, StgPtr, StgPtr);
82
static void retainClosure(StgClosure *, StgClosure *, retainer);
Ben Gamari's avatar
Ben Gamari committed
83
#if defined(DEBUG_RETAINER)
84 85 86
static void belongToHeap(StgPtr p);
#endif

Ben Gamari's avatar
Ben Gamari committed
87
#if defined(DEBUG_RETAINER)
88 89 90 91 92 93 94
/*
  cStackSize records how many times retainStack() has been invoked recursively,
  that is, the number of activation records for retainStack() on the C stack.
  maxCStackSize records its max value.
  Invariants:
    cStackSize <= maxCStackSize
 */
95
static uint32_t cStackSize, maxCStackSize;
96

97
static uint32_t sumOfNewCost;        // sum of the cost of each object, computed
98
                                // when the object is first visited
99
static uint32_t sumOfNewCostExtra;   // for those objects not visited during
100
                                // retainer profiling, e.g., MUT_VAR
101
static uint32_t costArray[N_CLOSURE_TYPES];
102

103
uint32_t sumOfCostLinear;            // sum of the costs of all object, computed
104 105
                                // when linearly traversing the heap after
                                // retainer profiling
106
uint32_t costArrayLinear[N_CLOSURE_TYPES];
107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130
#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 {
    posTypeStep,
    posTypePtrs,
    posTypeSRT,
} nextPosType;

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

    // layout.payload
    struct {
131 132 133
        // See StgClosureInfo in InfoTables.h
        StgHalfWord pos;
        StgHalfWord ptrs;
134
        StgPtr payload;
135 136 137 138
    } ptrs;

    // SRT
    struct {
139
        StgClosure *srt;
140 141 142 143 144 145 146 147 148 149
    } srt;
} nextPos;

typedef struct {
    nextPosType type;
    nextPos next;
} stackPos;

typedef struct {
    StgClosure *c;
150
    retainer c_child_r;
151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170
    stackPos info;
} stackElement;

/*
  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.
 */
sof's avatar
sof committed
171
static bdescr *firstStack = NULL;
172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194
static bdescr *currentStack;
static stackElement *stackBottom, *stackTop, *stackLimit;

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

/*
  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
    retainer profiling, maxStackSize + maxCStackSize is some value no greater
    than the actual depth of the graph.
 */
Ben Gamari's avatar
Ben Gamari committed
195
#if defined(DEBUG_RETAINER)
196 197 198 199 200 201 202 203 204 205 206
static int stackSize, maxStackSize;
#endif

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

/* -----------------------------------------------------------------------------
 * Add a new block group to the stack.
 * Invariants:
 *  currentStack->link == s.
 * -------------------------------------------------------------------------- */
207
static INLINE void
208 209 210 211 212 213 214 215 216 217 218 219 220 221
newStackBlock( bdescr *bd )
{
    currentStack = bd;
    stackTop     = (stackElement *)(bd->start + BLOCK_SIZE_W * bd->blocks);
    stackBottom  = (stackElement *)bd->start;
    stackLimit   = (stackElement *)stackTop;
    bd->free     = (StgPtr)stackLimit;
}

/* -----------------------------------------------------------------------------
 * Return to the previous block group.
 * Invariants:
 *   s->link == currentStack.
 * -------------------------------------------------------------------------- */
222
static INLINE void
223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238
returnToOldStack( bdescr *bd )
{
    currentStack = bd;
    stackTop = (stackElement *)bd->free;
    stackBottom = (stackElement *)bd->start;
    stackLimit = (stackElement *)(bd->start + BLOCK_SIZE_W * bd->blocks);
    bd->free = (StgPtr)stackLimit;
}

/* -----------------------------------------------------------------------------
 *  Initializes the traverse stack.
 * -------------------------------------------------------------------------- */
static void
initializeTraverseStack( void )
{
    if (firstStack != NULL) {
239
        freeChain(firstStack);
240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261
    }

    firstStack = allocGroup(BLOCKS_IN_STACK);
    firstStack->link = NULL;
    firstStack->u.back = NULL;

    newStackBlock(firstStack);
}

/* -----------------------------------------------------------------------------
 * Frees all the block groups in the traverse stack.
 * Invariants:
 *   firstStack != NULL
 * -------------------------------------------------------------------------- */
static void
closeTraverseStack( void )
{
    freeChain(firstStack);
    firstStack = NULL;
}

/* -----------------------------------------------------------------------------
Ben Gamari's avatar
Ben Gamari committed
262
 * Returns true if the whole stack is empty.
263
 * -------------------------------------------------------------------------- */
Ben Gamari's avatar
Ben Gamari committed
264
static INLINE bool
265 266 267 268 269
isEmptyRetainerStack( void )
{
    return (firstStack == currentStack) && stackTop == stackLimit;
}

sof's avatar
sof committed
270 271 272
/* -----------------------------------------------------------------------------
 * Returns size of stack
 * -------------------------------------------------------------------------- */
273
W_
274
retainerStackBlocks( void )
sof's avatar
sof committed
275 276
{
    bdescr* bd;
277
    W_ res = 0;
sof's avatar
sof committed
278

279
    for (bd = firstStack; bd != NULL; bd = bd->link)
sof's avatar
sof committed
280 281 282 283 284
      res += bd->blocks;

    return res;
}

285
/* -----------------------------------------------------------------------------
Ben Gamari's avatar
Ben Gamari committed
286
 * Returns true if stackTop is at the stack boundary of the current stack,
287 288
 * i.e., if the current stack chunk is empty.
 * -------------------------------------------------------------------------- */
Ben Gamari's avatar
Ben Gamari committed
289
static INLINE bool
290 291 292 293 294 295 296 297 298 299
isOnBoundary( void )
{
    return stackTop == currentStackBoundary;
}

/* -----------------------------------------------------------------------------
 * Initializes *info from ptrs and payload.
 * Invariants:
 *   payload[] begins with ptrs pointers followed by non-pointers.
 * -------------------------------------------------------------------------- */
300
static INLINE void
301
init_ptrs( stackPos *info, uint32_t ptrs, StgPtr payload )
302 303 304 305 306 307 308 309 310 311
{
    info->type              = posTypePtrs;
    info->next.ptrs.pos     = 0;
    info->next.ptrs.ptrs    = ptrs;
    info->next.ptrs.payload = payload;
}

/* -----------------------------------------------------------------------------
 * Find the next object from *info.
 * -------------------------------------------------------------------------- */
312
static INLINE StgClosure *
313 314 315
find_ptrs( stackPos *info )
{
    if (info->next.ptrs.pos < info->next.ptrs.ptrs) {
316
        return (StgClosure *)info->next.ptrs.payload[info->next.ptrs.pos++];
317
    } else {
318
        return NULL;
319 320 321 322 323 324
    }
}

/* -----------------------------------------------------------------------------
 *  Initializes *info from SRT information stored in *infoTable.
 * -------------------------------------------------------------------------- */
325
static INLINE void
326
init_srt_fun( stackPos *info, const StgFunInfoTable *infoTable )
327
{
328 329 330
    info->type = posTypeSRT;
    if (infoTable->i.srt) {
        info->next.srt.srt = (StgClosure*)GET_FUN_SRT(infoTable);
331
    } else {
332
        info->next.srt.srt = NULL;
333
    }
334 335
}

336
static INLINE void
337
init_srt_thunk( stackPos *info, const StgThunkInfoTable *infoTable )
338
{
339 340
    if (infoTable->i.srt) {
        info->next.srt.srt = (StgClosure*)GET_SRT(infoTable);
341
    } else {
342
        info->next.srt.srt = NULL;
343
    }
344 345 346 347 348
}

/* -----------------------------------------------------------------------------
 * Find the next object from *info.
 * -------------------------------------------------------------------------- */
349
static INLINE StgClosure *
350 351 352
find_srt( stackPos *info )
{
    StgClosure *c;
353
    if (info->type == posTypeSRT) {
354 355 356
        c = info->next.srt.srt;
        info->next.srt.srt = NULL;
        return c;
357 358 359 360 361 362 363
    }
}

/* -----------------------------------------------------------------------------
 *  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
364
 *  child, *c_child is set to that child and nothing is pushed onto
365 366 367 368 369 370
 *  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.
371
 *     *c is not any of TSO, AP, PAP, AP_STACK, which means that
372 373 374
 *        there cannot be any stack objects.
 *  Note: SRTs are considered to  be children as well.
 * -------------------------------------------------------------------------- */
375
static INLINE void
376
push( StgClosure *c, retainer c_child_r, StgClosure **first_child )
377 378 379 380
{
    stackElement se;
    bdescr *nbd;      // Next Block Descriptor

Ben Gamari's avatar
Ben Gamari committed
381
#if defined(DEBUG_RETAINER)
382
    // debugBelch("push(): stackTop = 0x%x, currentStackBoundary = 0x%x\n", stackTop, currentStackBoundary);
383 384 385
#endif

    ASSERT(get_itbl(c)->type != TSO);
386
    ASSERT(get_itbl(c)->type != AP_STACK);
387 388 389 390 391 392 393 394 395 396

    //
    // fill in se
    //

    se.c = c;
    se.c_child_r = c_child_r;

    // fill in se.info
    switch (get_itbl(c)->type) {
397
        // no child, no SRT
398 399 400
    case CONSTR_0_1:
    case CONSTR_0_2:
    case ARR_WORDS:
gcampax's avatar
gcampax committed
401
    case COMPACT_NFDATA:
402 403
        *first_child = NULL;
        return;
404

405
        // one child (fixed), no SRT
406 407
    case MUT_VAR_CLEAN:
    case MUT_VAR_DIRTY:
408 409
        *first_child = ((StgMutVar *)c)->var;
        return;
410
    case THUNK_SELECTOR:
411 412
        *first_child = ((StgSelector *)c)->selectee;
        return;
413
    case BLACKHOLE:
414 415
        *first_child = ((StgInd *)c)->indirectee;
        return;
416 417
    case CONSTR_1_0:
    case CONSTR_1_1:
418 419
        *first_child = c->payload[0];
        return;
420

421 422 423
        // 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;
424

425 426
        // two children (fixed), no SRT
        // need to push a stackElement, but nothing to store in se.info
427
    case CONSTR_2_0:
428 429 430 431
        *first_child = c->payload[0];         // return the first pointer
        // se.info.type = posTypeStep;
        // se.info.next.step = 2;            // 2 = second
        break;
432

433 434
        // three children (fixed), no SRT
        // need to push a stackElement
435 436
    case MVAR_CLEAN:
    case MVAR_DIRTY:
437 438 439 440 441 442 443 444
        // 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;
        // se.info.type = posTypeStep;
        se.info.next.step = 2;            // 2 = second
        break;

        // three children (fixed), no SRT
445
    case WEAK:
446 447 448 449
        *first_child = ((StgWeak *)c)->key;
        // se.info.type = posTypeStep;
        se.info.next.step = 2;
        break;
450

451
        // layout.payload.ptrs, no SRT
452
    case TVAR:
453
    case CONSTR:
Simon Marlow's avatar
Simon Marlow committed
454
    case CONSTR_NOCAF:
455
    case PRIM:
456
    case MUT_PRIM:
457
    case BCO:
458 459 460 461 462 463 464 465
        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
466 467
    case MUT_ARR_PTRS_CLEAN:
    case MUT_ARR_PTRS_DIRTY:
468
    case MUT_ARR_PTRS_FROZEN:
469
    case MUT_ARR_PTRS_FROZEN0:
470 471 472 473 474 475 476 477
        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
478 479 480 481
    case SMALL_MUT_ARR_PTRS_CLEAN:
    case SMALL_MUT_ARR_PTRS_DIRTY:
    case SMALL_MUT_ARR_PTRS_FROZEN:
    case SMALL_MUT_ARR_PTRS_FROZEN0:
482 483 484 485 486 487
        init_ptrs(&se.info, ((StgSmallMutArrPtrs *)c)->ptrs,
                  (StgPtr)(((StgSmallMutArrPtrs *)c)->payload));
        *first_child = find_ptrs(&se.info);
        if (*first_child == NULL)
            return;
        break;
488

489
    // layout.payload.ptrs, SRT
490 491 492
    case FUN_STATIC:
        ASSERT(get_itbl(c)->srt != 0);
        /* fallthrough */
493 494
    case FUN:           // *c is a heap object.
    case FUN_2_0:
495 496 497 498 499 500
        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;
501

502 503
    case THUNK:
    case THUNK_2_0:
504 505 506 507 508 509 510 511 512
        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
513 514
    case FUN_1_0:
    case FUN_1_1:
515 516 517 518
        *first_child = c->payload[0];
        ASSERT(*first_child != NULL);
        init_srt_fun(&se.info, get_fun_itbl(c));
        break;
519

520 521
    case THUNK_1_0:
    case THUNK_1_1:
522 523 524 525
        *first_child = ((StgThunk *)c)->payload[0];
        ASSERT(*first_child != NULL);
        init_srt_thunk(&se.info, get_thunk_itbl(c));
        break;
526

527
    case FUN_0_1:      // *c is a heap object.
528
    case FUN_0_2:
529 530
    fun_srt_only:
        init_srt_fun(&se.info, get_fun_itbl(c));
531 532 533 534
        *first_child = find_srt(&se.info);
        if (*first_child == NULL)
            return;     // no child
        break;
535 536 537

    // SRT only
    case THUNK_STATIC:
538
        ASSERT(get_itbl(c)->srt_bitmap != 0);
539 540
    case THUNK_0_1:
    case THUNK_0_2:
541 542
    thunk_srt_only:
        init_srt_thunk(&se.info, get_thunk_itbl(c));
543 544 545 546 547
        *first_child = find_srt(&se.info);
        if (*first_child == NULL)
            return;     // no child
        break;

548
    case TREC_CHUNK:
549 550 551
        *first_child = (StgClosure *)((StgTRecChunk *)c)->prev_chunk;
        se.info.next.step = 0;  // entry no.
        break;
552

553
        // cannot appear
554
    case PAP:
555 556
    case AP:
    case AP_STACK:
557
    case TSO:
558
    case STACK:
559
    case IND_STATIC:
560
        // stack objects
561 562
    case UPDATE_FRAME:
    case CATCH_FRAME:
563
    case UNDERFLOW_FRAME:
564 565 566 567
    case STOP_FRAME:
    case RET_BCO:
    case RET_SMALL:
    case RET_BIG:
568
        // invalid objects
569 570 571
    case IND:
    case INVALID_OBJECT:
    default:
572
        barf("Invalid object *c in push(): %d", get_itbl(c)->type);
573
        return;
574 575 576
    }

    if (stackTop - 1 < stackBottom) {
Ben Gamari's avatar
Ben Gamari committed
577
#if defined(DEBUG_RETAINER)
578
        // debugBelch("push() to the next stack.\n");
579
#endif
580 581 582 583 584 585 586 587 588 589 590 591 592
        // currentStack->free is updated when the active stack is switched
        // to the next stack.
        currentStack->free = (StgPtr)stackTop;

        if (currentStack->link == NULL) {
            nbd = allocGroup(BLOCKS_IN_STACK);
            nbd->link = NULL;
            nbd->u.back = currentStack;
            currentStack->link = nbd;
        } else
            nbd = currentStack->link;

        newStackBlock(nbd);
593 594 595 596 597 598 599 600
    }

    // adjust stackTop (acutal push)
    stackTop--;
    // 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.
601 602 603 604 605 606

    // ToDo: The line below leads to the warning:
    //    warning: 'se.info.type' may be used uninitialized in this function
    // This is caused by the fact that there are execution paths through the
    // large switch statement above where some cases do not initialize this
    // field. Is this really harmless? Can we avoid the warning?
607 608
    *stackTop = se;

Ben Gamari's avatar
Ben Gamari committed
609
#if defined(DEBUG_RETAINER)
610 611 612
    stackSize++;
    if (stackSize > maxStackSize) maxStackSize = stackSize;
    // ASSERT(stackSize >= 0);
613
    // debugBelch("stackSize = %d\n", stackSize);
614 615 616 617 618 619 620 621 622 623 624 625 626
#endif
}

/* -----------------------------------------------------------------------------
 *  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
627
 *    INLINE function (for the sake of execution speed).  popOffReal()
628 629 630 631 632 633 634
 *    is called only within popOff() and nowhere else.
 * -------------------------------------------------------------------------- */
static void
popOffReal(void)
{
    bdescr *pbd;    // Previous Block Descriptor

Ben Gamari's avatar
Ben Gamari committed
635
#if defined(DEBUG_RETAINER)
636
    // debugBelch("pop() to the previous stack.\n");
637 638 639 640 641 642
#endif

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

    if (firstStack == currentStack) {
643 644 645
        // The stack is completely empty.
        stackTop++;
        ASSERT(stackTop == stackLimit);
Ben Gamari's avatar
Ben Gamari committed
646
#if defined(DEBUG_RETAINER)
647 648 649 650 651 652
        stackSize--;
        if (stackSize > maxStackSize) maxStackSize = stackSize;
        /*
          ASSERT(stackSize >= 0);
          debugBelch("stackSize = %d\n", stackSize);
        */
653
#endif
654
        return;
655 656 657 658 659 660 661 662 663 664 665 666
    }

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

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

    returnToOldStack(pbd);

Ben Gamari's avatar
Ben Gamari committed
667
#if defined(DEBUG_RETAINER)
668 669 670 671
    stackSize--;
    if (stackSize > maxStackSize) maxStackSize = stackSize;
    /*
      ASSERT(stackSize >= 0);
672
      debugBelch("stackSize = %d\n", stackSize);
673 674 675 676
    */
#endif
}

677
static INLINE void
678
popOff(void) {
Ben Gamari's avatar
Ben Gamari committed
679
#if defined(DEBUG_RETAINER)
680
    // debugBelch("\tpopOff(): stackTop = 0x%x, currentStackBoundary = 0x%x\n", stackTop, currentStackBoundary);
681 682 683 684 685 686 687
#endif

    ASSERT(stackTop != stackLimit);
    ASSERT(!isEmptyRetainerStack());

    // <= (instead of <) is wrong!
    if (stackTop + 1 < stackLimit) {
688
        stackTop++;
Ben Gamari's avatar
Ben Gamari committed
689
#if defined(DEBUG_RETAINER)
690 691 692 693 694 695
        stackSize--;
        if (stackSize > maxStackSize) maxStackSize = stackSize;
        /*
          ASSERT(stackSize >= 0);
          debugBelch("stackSize = %d\n", stackSize);
        */
696
#endif
697
        return;
698 699 700 701 702 703 704 705 706 707 708 709 710 711 712
    }

    popOffReal();
}

/* -----------------------------------------------------------------------------
 *  Finds the next object to be considered for retainer profiling and store
 *  its pointer to *c.
 *  Test if the topmost stack element indicates that more objects are left,
 *  and if so, retrieve the first object and store its pointer to *c. Also,
 *  set *cp and *r 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.
 *  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
713
 *  the current stack chunk becomes empty, indicated by true returned by
714 715 716 717 718
 *  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.
 * -------------------------------------------------------------------------- */
719
static INLINE void
720
pop( StgClosure **c, StgClosure **cp, retainer *r )
721 722 723
{
    stackElement *se;

Ben Gamari's avatar
Ben Gamari committed
724
#if defined(DEBUG_RETAINER)
725
    // debugBelch("pop(): stackTop = 0x%x, currentStackBoundary = 0x%x\n", stackTop, currentStackBoundary);
726 727 728
#endif

    do {
729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747
        if (isOnBoundary()) {     // if the current stack chunk is depleted
            *c = NULL;
            return;
        }

        se = stackTop;

        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;
            *r = se->c_child_r;
            popOff();
            return;

            // three children (fixed), no SRT
            // need to push a stackElement
748 749
        case MVAR_CLEAN:
        case MVAR_DIRTY:
750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782
            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;
                popOff();
            }
            *cp = se->c;
            *r = se->c_child_r;
            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;
                popOff();
            }
            *cp = se->c;
            *r = se->c_child_r;
            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;
783 784
            uint32_t entry_no = se->info.next.step >> 2;
            uint32_t field_no = se->info.next.step & 3;
785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802
            if (entry_no == ((StgTRecChunk *)se->c)->next_entry_idx) {
                *c = NULL;
                popOff();
                return;
            }
            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;
            *r = se->c_child_r;
            se->info.next.step++;
            return;
        }
803

804 805
        case TVAR:
        case CONSTR:
806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824
        case PRIM:
        case MUT_PRIM:
        case BCO:
            // StgMutArrPtr.ptrs, no SRT
        case MUT_ARR_PTRS_CLEAN:
        case MUT_ARR_PTRS_DIRTY:
        case MUT_ARR_PTRS_FROZEN:
        case MUT_ARR_PTRS_FROZEN0:
            *c = find_ptrs(&se->info);
            if (*c == NULL) {
                popOff();
                break;
            }
            *cp = se->c;
            *r = se->c_child_r;
            return;

            // layout.payload.ptrs, SRT
        case FUN:         // always a heap object
825
        case FUN_STATIC:
826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884
        case FUN_2_0:
            if (se->info.type == posTypePtrs) {
                *c = find_ptrs(&se->info);
                if (*c != NULL) {
                    *cp = se->c;
                    *r = se->c_child_r;
                    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;
                    *r = se->c_child_r;
                    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;
                *r = se->c_child_r;
                return;
            }
            popOff();
            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:
885 886
        case STACK:
        case IND_STATIC:
Simon Marlow's avatar
Simon Marlow committed
887
        case CONSTR_NOCAF:
888
            // stack objects
889
        case UPDATE_FRAME:
890
        case CATCH_FRAME:
891 892
        case UNDERFLOW_FRAME:
        case STOP_FRAME:
893 894 895 896 897 898 899 900 901 902
        case RET_BCO:
        case RET_SMALL:
        case RET_BIG:
            // invalid objects
        case IND:
        case INVALID_OBJECT:
        default:
            barf("Invalid object *c in pop()");
            return;
        }
Ben Gamari's avatar
Ben Gamari committed
903
    } while (true);
904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922
}

/* -----------------------------------------------------------------------------
 * 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
923
#if defined(SECOND_APPROACH)
924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941
    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.
 * -------------------------------------------------------------------------- */
942
static INLINE void
943 944 945
maybeInitRetainerSet( StgClosure *c )
{
    if (!isRetainerSetFieldValid(c)) {
946
        setRetainerSetToNull(c);
947 948 949 950
    }
}

/* -----------------------------------------------------------------------------
Ben Gamari's avatar
Ben Gamari committed
951
 * Returns true if *c is a retainer.
952
 * -------------------------------------------------------------------------- */
Ben Gamari's avatar
Ben Gamari committed
953
static INLINE bool
954 955 956
isRetainer( StgClosure *c )
{
    switch (get_itbl(c)->type) {
957 958 959 960
        //
        //  True case
        //
        // TSOs MUST be retainers: they constitute the set of roots.
961
    case TSO:
962
    case STACK:
963

964
        // mutable objects
965
    case MUT_PRIM:
966 967
    case MVAR_CLEAN:
    case MVAR_DIRTY:
968
    case TVAR:
969 970
    case MUT_VAR_CLEAN:
    case MUT_VAR_DIRTY:
971 972
    case MUT_ARR_PTRS_CLEAN:
    case MUT_ARR_PTRS_DIRTY:
973 974 975
    case SMALL_MUT_ARR_PTRS_CLEAN:
    case SMALL_MUT_ARR_PTRS_DIRTY:
    case BLOCKING_QUEUE:
976

977
        // thunks are retainers.
978 979 980 981 982 983 984
    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:
985 986
    case AP:
    case AP_STACK:
987

988
        // Static thunks, or CAFS, are obviously retainers.
989 990
    case THUNK_STATIC:

991 992
        // WEAK objects are roots; there is separate code in which traversing
        // begins from WEAK objects.
993
    case WEAK:
Ben Gamari's avatar
Ben Gamari committed
994
        return true;
995

996 997 998
        //
        // False case
        //
999

1000
        // constructors
1001
    case CONSTR:
Simon Marlow's avatar
Simon Marlow committed
1002
    case CONSTR_NOCAF:
1003 1004 1005 1006 1007
    case CONSTR_1_0:
    case CONSTR_0_1:
    case CONSTR_2_0:
    case CONSTR_1_1:
    case CONSTR_0_2:
1008
        // functions
1009 1010 1011 1012 1013 1014
    case FUN:
    case FUN_1_0:
    case FUN_0_1:
    case FUN_2_0:
    case FUN_1_1:
    case FUN_0_2:
1015
        // partial applications
1016
    case PAP:
1017
        // indirection
Ian Lynagh's avatar
Ian Lynagh committed
1018 1019 1020 1021
    // 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:
1022
    case BLACKHOLE:
1023
    case WHITEHOLE:
1024
        // static objects
1025
    case FUN_STATIC:
1026
        // misc
1027
    case PRIM:
1028 1029
    case BCO:
    case ARR_WORDS:
1030
    case COMPACT_NFDATA:
1031
        // STM
1032
    case TREC_CHUNK:
1033 1034 1035
        // immutable arrays
    case MUT_ARR_PTRS_FROZEN:
    case MUT_ARR_PTRS_FROZEN0:
1036 1037
    case SMALL_MUT_ARR_PTRS_FROZEN:
    case SMALL_MUT_ARR_PTRS_FROZEN0:
Ben Gamari's avatar
Ben Gamari committed
1038
        return false;
1039

1040 1041 1042 1043 1044
        //
        // Error case
        //
        // Stack objects are invalid because they are never treated as
        // legal objects during retainer profiling.
1045 1046
    case UPDATE_FRAME:
    case CATCH_FRAME:
1047 1048
    case CATCH_RETRY_FRAME:
    case CATCH_STM_FRAME:
1049
    case UNDERFLOW_FRAME:
1050
    case ATOMICALLY_FRAME:
1051 1052 1053 1054
    case STOP_FRAME:
    case RET_BCO:
    case RET_SMALL:
    case RET_BIG:
1055
    case RET_FUN:
1056
        // other cases
1057 1058 1059
    case IND:
    case INVALID_OBJECT:
    default:
1060
        barf("Invalid object in isRetainer(): %d", get_itbl(c)->type);
Ben Gamari's avatar
Ben Gamari committed
1061
        return false;
1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073
    }
}

/* -----------------------------------------------------------------------------
 *  Returns the retainer function value for the closure *c, i.e., R(*c).
 *  This function does NOT return the retainer(s) of *c.
 *  Invariants:
 *    *c must be a retainer.
 *  Note:
 *    Depending on the definition of this function, the maintenance of retainer
 *    sets can be made easier. If most retainer sets are likely to be created
 *    again across garbage collections, refreshAllRetainerSet() in
1074
 *    RetainerSet.c can simply do nothing.
1075 1076 1077 1078
 *    If this is not the case, we can free all the retainer sets and
 *    re-initialize the hash table.
 *    See refreshAllRetainerSet() in RetainerSet.c.
 * -------------------------------------------------------------------------- */
1079
static INLINE retainer
1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093
getRetainerFrom( StgClosure *c )
{
    ASSERT(isRetainer(c));

    return c->header.prof.ccs;
}

/* -----------------------------------------------------------------------------
 *  Associates the retainer set *s with the closure *c, that is, *s becomes
 *  the retainer set of *c.
 *  Invariants:
 *    c != NULL
 *    s != NULL
 * -------------------------------------------------------------------------- */
1094
static INLINE void
1095
associate( StgClosure *c, RetainerSet *s )
1096 1097 1098 1099 1100 1101
{
    // StgWord has the same size as pointers, so the following type
    // casting is okay.
    RSET(c) = (RetainerSet *)((StgWord)s | flip);
}

1102 1103 1104 1105 1106
/* -----------------------------------------------------------------------------
   Call retainClosure for each of the closures covered by a large bitmap.
   -------------------------------------------------------------------------- */

static void
1107
retain_large_bitmap (StgPtr p, StgLargeBitmap *large_bitmap, uint32_t size,
1108
                     StgClosure *c, retainer c_child_r)
1109
{
1110
    uint32_t i, b;
1111
    StgWord bitmap;
1112

1113 1114 1115
    b = 0;
    bitmap = large_bitmap->bitmap[b];
    for (i = 0; i < size; ) {
1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126
        if ((bitmap & 1) == 0) {
            retainClosure((StgClosure *)*p, c, c_child_r);
        }
        i++;
        p++;
        if (i % BITS_IN(W_) == 0) {
            b++;
            bitmap = large_bitmap->bitmap[b];
        } else {
            bitmap = bitmap >> 1;
        }
1127 1128 1129
    }
}

1130
static INLINE StgPtr
1131
retain_small_bitmap (StgPtr p, uint32_t size, StgWord bitmap,
1132
                     StgClosure *c, retainer c_child_r)
1133 1134
{
    while (size > 0) {
1135 1136 1137 1138 1139 1140
        if ((bitmap & 1) == 0) {
            retainClosure((StgClosure *)*p, c, c_child_r);
        }
        p++;
        bitmap = bitmap >> 1;
        size--;
1141 1142 1143 1144
    }
    return p;
}

1145 1146 1147 1148 1149 1150
/* -----------------------------------------------------------------------------
 *  Process all the objects in the stack chunk from stackStart to stackEnd
 *  with *c and *c_child_r being their parent and their most recent retainer,
 *  respectively. Treat stackOptionalFun as another child of *c if it is
 *  not NULL.
 *  Invariants:
1151
 *    *c is one of the following: TSO, AP_STACK.
1152 1153 1154 1155 1156
 *    If *c is TSO, c == c_child_r.
 *    stackStart < stackEnd.
 *    RSET(c) and RSET(c_child_r) are valid, i.e., their
 *    interpretation conforms to the current value of flip (even when they
 *    are interpreted to be NULL).
1157
 *    If *c is TSO, its state is not ThreadComplete,or ThreadKilled,
1158
 *    which means that its stack is ready to process.
1159 1160 1161 1162 1163
 *  Note:
 *    This code was almost plagiarzied from GC.c! For each pointer,
 *    retainClosure() is invoked instead of evacuate().
 * -------------------------------------------------------------------------- */
static void
1164
retainStack( StgClosure *c, retainer c_child_r,
1165
             StgPtr stackStart, StgPtr stackEnd )
1166 1167
{
    stackElement *oldStackBoundary;
1168
    StgPtr p;
1169
    const StgRetInfoTable *info;
1170
    StgWord bitmap;
1171
    uint32_t size;
1172

Ben Gamari's avatar
Ben Gamari committed
1173
#if defined(DEBUG_RETAINER)
1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186
    cStackSize++;
    if (cStackSize > maxCStackSize) maxCStackSize = cStackSize;
#endif

    /*
      Each invocation of retainStack() creates a new virtual
      stack. Since all such stacks share a single common stack, we
      record the current currentStackBoundary, which will be restored
      at the exit.
    */
    oldStackBoundary = currentStackBoundary;
    currentStackBoundary = stackTop;

Ben Gamari's avatar
Ben Gamari committed
1187
#if defined(DEBUG_RETAINER)
1188
    // debugBelch("retainStack() called: oldStackBoundary = 0x%x, currentStackBoundary = 0x%x\n", oldStackBoundary, currentStackBoundary);
1189 1190
#endif

1191 1192
    ASSERT(get_itbl(c)->type == STACK);

1193 1194
    p = stackStart;
    while (p < stackEnd) {
1195
        info = get_ret_itbl((StgClosure *)p);
1196

1197
        switch(info->i.type) {
1198

1199 1200 1201 1202
        case UPDATE_FRAME:
            retainClosure(((StgUpdateFrame *)p)->updatee, c, c_child_r);
            p += sizeofW(StgUpdateFrame);
            continue;
1203

1204 1205
        case UNDERFLOW_FRAME:
        case STOP_FRAME:
1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216
        case CATCH_FRAME:
        case CATCH_STM_FRAME:
        case CATCH_RETRY_FRAME:
        case ATOMICALLY_FRAME:
        case RET_SMALL:
            bitmap = BITMAP_BITS(info->i.layout.bitmap);
            size   = BITMAP_SIZE(info->i.layout.bitmap);
            p++;
            p = retain_small_bitmap(p, size, bitmap, c, c_child_r);

        follow_srt:
1217 1218 1219
            if (info->i.srt) {
                retainClosure(GET_SRT(info),c,c_child_r);
            }
1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243
            continue;

        case RET_BCO: {
            StgBCO *bco;

            p++;
            retainClosure((StgClosure *)*p, c, c_child_r);
            bco = (StgBCO *)*p;
            p++;
            size = BCO_BITMAP_SIZE(bco);
            retain_large_bitmap(p, BCO_BITMAP(bco), size, c, c_child_r);
            p += size;
            continue;
        }

            // large bitmap (> 32 entries, or > 64 on a 64-bit machine)
        case RET_BIG:
            size = GET_LARGE_BITMAP(&info->i)->size;
            p++;
            retain_large_bitmap(p, GET_LARGE_BITMAP(&info->i),
                                size, c, c_child_r);
            p += size;
            // and don't forget to follow the SRT
            goto follow_srt;
1244

1245
        case RET_FUN: {
1246
            StgRetFun *ret_fun = (StgRetFun *)p;
1247
            const StgFunInfoTable *fun_info;
1248 1249

            retainClosure(ret_fun->fun, c, c_child_r);
1250
            fun_info = get_fun_itbl(UNTAG_CONST_CLOSURE(ret_fun->fun));
1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277

            p = (P_)&ret_fun->payload;
            switch (fun_info->f.fun_type) {
            case ARG_GEN:
                bitmap = BITMAP_BITS(fun_info->f.b.bitmap);
                size = BITMAP_SIZE(fun_info->f.b.bitmap);
                p = retain_small_bitmap(p, size, bitmap, c, c_child_r);
                break;
            case ARG_GEN_BIG:
                size = GET_FUN_LARGE_BITMAP(fun_info)->size;
                retain_large_bitmap(p, GET_FUN_LARGE_BITMAP(fun_info),
                                    size, c, c_child_r);
                p += size;
                break;
            default:
                bitmap = BITMAP_BITS(stg_arg_bitmaps[fun_info->f.fun_type]);
                size = BITMAP_SIZE(stg_arg_bitmaps[fun_info->f.fun_type]);
                p = retain_small_bitmap(p, size, bitmap, c, c_child_r);
                break;
            }
            goto follow_srt;
        }

        default:
            barf("Invalid object found in retainStack(): %d",
                 (int)(info->i.type));
        }
1278 1279 1280 1281
    }

    // restore currentStackBoundary
    currentStackBoundary = oldStackBoundary;
Ben Gamari's avatar
Ben Gamari committed
1282
#if defined(DEBUG_RETAINER)
1283
    // debugBelch("retainStack() finished: currentStackBoundary = 0x%x\n", currentStackBoundary);
1284 1285
#endif

Ben Gamari's avatar
Ben Gamari committed
1286
#if defined(DEBUG_RETAINER)
1287 1288 1289 1290
    cStackSize--;
#endif
}

1291 1292 1293 1294
/* ----------------------------------------------------------------------------
 * Call retainClosure for each of the children of a PAP/AP
 * ------------------------------------------------------------------------- */

1295
static INLINE StgPtr
Simon Marlow's avatar
Simon Marlow committed
1296
retain_PAP_payload (StgClosure *pap,    /* NOT tagged */
1297
                    retainer c_child_r, /* NOT tagged */
Simon Marlow's avatar
Simon Marlow committed
1298
                    StgClosure *fun,    /* tagged */
1299
                    StgClosure** payload, StgWord n_args)
1300 1301
{
    StgPtr p;
1302
    StgWord bitmap;
1303
    const StgFunInfoTable *fun_info;
1304

1305
    retainClosure(fun, pap, c_child_r);
Simon Marlow's avatar
Simon Marlow committed
1306
    fun = UNTAG_CLOSURE(fun);
1307
    fun_info = get_fun_itbl(fun);
1308 1309
    ASSERT(fun_info->i.type != PAP);

1310
    p = (StgPtr)payload;
1311

1312
    switch (fun_info->f.fun_type) {
1313
    case ARG_GEN:
1314 1315 1316 1317
        bitmap = BITMAP_BITS(fun_info->f.b.bitmap);
        p = retain_small_bitmap(p, n_args, bitmap,
                                pap, c_child_r);
        break;
1318
    case ARG_GEN_BIG:
1319 1320 1321 1322
        retain_large_bitmap(p, GET_FUN_LARGE_BITMAP(fun_info),
                            n_args, pap, c_child_r);
        p += n_args;
        break;
1323
    case ARG_BCO:
1324 1325 1326 1327
        retain_large_bitmap((StgPtr)payload, BCO_BITMAP(fun),
                            n_args, pap, c_child_r);
        p += n_args;
        break;
1328
    default:
1329 1330 1331
        bitmap = BITMAP_BITS(stg_arg_bitmaps[fun_info->f.fun_type]);
        p = retain_small_bitmap(p, n_args, bitmap, pap, c_child_r);
        break;
1332 1333 1334 1335
    }
    return p;
}

1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349
/* -----------------------------------------------------------------------------
 *  Compute the retainer set of *c0 and all its desecents by traversing.
 *  *cp0 is the parent of *c0, and *r0 is the most recent retainer of *c0.
 *  Invariants:
 *    c0 = cp0 = r0 holds only for root objects.
 *    RSET(cp0) and RSET(r0) are valid, i.e., their
 *    interpretation conforms to the current value of flip (even when they
 *    are interpreted to be NULL).
 *    However, RSET(c0) may be corrupt, i.e., it may not conform to
 *    the current value of flip. If it does not, during the execution
 *    of this function, RSET(c0) must be initialized as well as all
 *    its descendants.
 *  Note:
 *    stackTop must be the same at the beginning and the exit of this function.
1350
 *    *c0 can be TSO (as well as AP_STACK).
1351 1352
 * -------------------------------------------------------------------------- */
static void
1353
retainClosure( StgClosure *c0, StgClosure *cp0, retainer r0 )
1354
{
Simon Marlow's avatar
Simon Marlow committed
1355