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

#ifdef PROFILING

12 13 14 15 16 17 18
// Turn off inlining when debugging - it obfuscates things
#ifdef DEBUG
#define INLINE
#else
#define INLINE inline
#endif

19 20 21 22 23 24 25 26 27 28 29 30
#include "Rts.h"
#include "RtsUtils.h"
#include "RetainerProfile.h"
#include "RetainerSet.h"
#include "Schedule.h"
#include "Printer.h"
#include "RtsFlags.h"
#include "Weak.h"
#include "Sanity.h"
#include "Profiling.h"
#include "Stats.h"
#include "ProfHeap.h"
31
#include "Apply.h"
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58

/*
  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...
 * -------------------------------------------------------------------------- */

static nat retainerGeneration;	// generation

static nat numObjectVisited;	// total number of objects visited
static nat timesAnyObjectVisited; // number of times any objects are visited

/*
  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().
 */

59
StgWord flip = 0;     // flip bit
60 61 62 63 64
                      // must be 0 if DEBUG_RETAINER is on (for static closures)

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

65
static void retainStack(StgClosure *, retainer, StgPtr, StgPtr);
66
static void retainClosure(StgClosure *, StgClosure *, retainer);
67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106
#ifdef DEBUG_RETAINER
static void belongToHeap(StgPtr p);
#endif

#ifdef DEBUG_RETAINER
/*
  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
 */
static nat cStackSize, maxCStackSize;

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

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

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

    // layout.payload
    struct {
    // See StgClosureInfo in InfoTables.h
#if SIZEOF_VOID_P == 8
	StgWord32 pos;
	StgWord32 ptrs;
#else
	StgWord16 pos;
	StgWord16 ptrs;
#endif
	StgPtr payload;
    } ptrs;

    // SRT
    struct {
	StgClosure **srt;
130
	StgWord    srt_bitmap;
131
    } srt;
132 133 134 135 136 137 138

    // Large SRT
    struct {
	StgLargeSRT *srt;
	StgWord offset;
    } large_srt;
	
139 140 141 142 143 144 145 146 147
} nextPos;

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

typedef struct {
    StgClosure *c;
148
    retainer c_child_r;
149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168
    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
169
static bdescr *firstStack = NULL;
170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204
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.
 */
#ifdef DEBUG_RETAINER
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.
 * -------------------------------------------------------------------------- */
205
static INLINE void
206 207 208 209 210 211 212 213 214 215 216 217 218 219
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.
 * -------------------------------------------------------------------------- */
220
static INLINE void
221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261
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) {
	freeChain(firstStack);
    }

    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;
}

/* -----------------------------------------------------------------------------
 * Returns rtsTrue if the whole stack is empty.
 * -------------------------------------------------------------------------- */
262
static INLINE rtsBool
263 264 265 266 267
isEmptyRetainerStack( void )
{
    return (firstStack == currentStack) && stackTop == stackLimit;
}

sof's avatar
sof committed
268 269 270
/* -----------------------------------------------------------------------------
 * Returns size of stack
 * -------------------------------------------------------------------------- */
271
#ifdef DEBUG
sof's avatar
sof committed
272
lnat
273
retainerStackBlocks( void )
sof's avatar
sof committed
274 275 276 277 278 279 280 281 282
{
    bdescr* bd;
    lnat res = 0;

    for (bd = firstStack; bd != NULL; bd = bd->link) 
      res += bd->blocks;

    return res;
}
283
#endif
sof's avatar
sof committed
284

285 286 287 288
/* -----------------------------------------------------------------------------
 * Returns rtsTrue if stackTop is at the stack boundary of the current stack,
 * i.e., if the current stack chunk is empty.
 * -------------------------------------------------------------------------- */
289
static INLINE rtsBool
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 302 303 304 305 306 307 308 309 310 311
init_ptrs( stackPos *info, nat ptrs, StgPtr payload )
{
    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 316 317 318 319 320 321 322 323 324
find_ptrs( stackPos *info )
{
    if (info->next.ptrs.pos < info->next.ptrs.ptrs) {
	return (StgClosure *)info->next.ptrs.payload[info->next.ptrs.pos++];
    } else {
	return NULL;
    }
}

/* -----------------------------------------------------------------------------
 *  Initializes *info from SRT information stored in *infoTable.
 * -------------------------------------------------------------------------- */
325
static INLINE void
326
init_srt_fun( stackPos *info, StgFunInfoTable *infoTable )
327
{
328 329
    if (infoTable->i.srt_bitmap == (StgHalfWord)(-1)) {
	info->type = posTypeLargeSRT;
330
	info->next.large_srt.srt = (StgLargeSRT *)GET_FUN_SRT(infoTable);
331 332 333
	info->next.large_srt.offset = 0;
    } else {
	info->type = posTypeSRT;
334
	info->next.srt.srt = (StgClosure **)GET_FUN_SRT(infoTable);
335 336
	info->next.srt.srt_bitmap = infoTable->i.srt_bitmap;
    }
337 338
}

339
static INLINE void
340 341
init_srt_thunk( stackPos *info, StgThunkInfoTable *infoTable )
{
342 343
    if (infoTable->i.srt_bitmap == (StgHalfWord)(-1)) {
	info->type = posTypeLargeSRT;
344
	info->next.large_srt.srt = (StgLargeSRT *)GET_SRT(infoTable);
345 346 347
	info->next.large_srt.offset = 0;
    } else {
	info->type = posTypeSRT;
348
	info->next.srt.srt = (StgClosure **)GET_SRT(infoTable);
349 350
	info->next.srt.srt_bitmap = infoTable->i.srt_bitmap;
    }
351 352 353 354 355
}

/* -----------------------------------------------------------------------------
 * Find the next object from *info.
 * -------------------------------------------------------------------------- */
356
static INLINE StgClosure *
357 358 359
find_srt( stackPos *info )
{
    StgClosure *c;
360
    StgWord bitmap;
361

362 363 364 365 366
    if (info->type == posTypeSRT) {
	// Small SRT bitmap
	bitmap = info->next.srt.srt_bitmap;
	while (bitmap != 0) {
	    if ((bitmap & 1) != 0) {
367
#if defined(__PIC__) && defined(mingw32_TARGET_OS)
368 369 370 371
		if ((unsigned long)(*(info->next.srt.srt)) & 0x1)
		    c = (* (StgClosure **)((unsigned long)*(info->next.srt.srt)) & ~0x1);
		else
		    c = *(info->next.srt.srt);
372
#else
373
		c = *(info->next.srt.srt);
374
#endif
375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409
		bitmap = bitmap >> 1;
		info->next.srt.srt++;
		info->next.srt.srt_bitmap = bitmap;
		return c;
	    }
	    bitmap = bitmap >> 1;
	    info->next.srt.srt++;
	}
	// bitmap is now zero...
	return NULL;
    }
    else {
	// Large SRT bitmap
	nat i = info->next.large_srt.offset;
	StgWord bitmap;

	// Follow the pattern from GC.c:scavenge_large_srt_bitmap().
	bitmap = info->next.large_srt.srt->l.bitmap[i / BITS_IN(W_)];
	bitmap = bitmap >> (i % BITS_IN(StgWord));
	while (i < info->next.large_srt.srt->l.size) {
	    if ((bitmap & 1) != 0) {
		c = ((StgClosure **)info->next.large_srt.srt->srt)[i];
		i++;
		info->next.large_srt.offset = i;
		return c;
	    }
	    i++;
	    if (i % BITS_IN(W_) == 0) {
		bitmap = info->next.large_srt.srt->l.bitmap[i / BITS_IN(W_)];
	    } else {
		bitmap = bitmap >> 1;
	    }
	}
	// reached the end of this bitmap.
	info->next.large_srt.offset = i;
410 411 412 413 414 415 416 417 418 419 420 421 422 423 424
	return NULL;
    }
}

/* -----------------------------------------------------------------------------
 *  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
 *  child, *c_chlid is set to that child and nothing is pushed onto
 *  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.
425
 *     *c is not any of TSO, AP, PAP, AP_STACK, which means that
426 427 428
 *        there cannot be any stack objects.
 *  Note: SRTs are considered to  be children as well.
 * -------------------------------------------------------------------------- */
429
static INLINE void
430
push( StgClosure *c, retainer c_child_r, StgClosure **first_child )
431 432 433 434 435
{
    stackElement se;
    bdescr *nbd;      // Next Block Descriptor

#ifdef DEBUG_RETAINER
436
    // debugBelch("push(): stackTop = 0x%x, currentStackBoundary = 0x%x\n", stackTop, currentStackBoundary);
437 438 439
#endif

    ASSERT(get_itbl(c)->type != TSO);
440
    ASSERT(get_itbl(c)->type != AP_STACK);
441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460

    //
    // fill in se
    //

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

    // fill in se.info
    switch (get_itbl(c)->type) {
	// no child, no SRT
    case CONSTR_0_1:
    case CONSTR_0_2:
    case CAF_BLACKHOLE:
    case BLACKHOLE:
    case ARR_WORDS:
	*first_child = NULL;
	return;

	// one child (fixed), no SRT
461 462
    case MUT_VAR_CLEAN:
    case MUT_VAR_DIRTY:
463 464 465 466 467 468 469 470
	*first_child = ((StgMutVar *)c)->var;
	return;
    case THUNK_SELECTOR:
	*first_child = ((StgSelector *)c)->selectee;
	return;
    case IND_PERM:
    case IND_OLDGEN_PERM:
    case IND_OLDGEN:
471
	*first_child = ((StgInd *)c)->indirectee;
472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491
	return;
    case CONSTR_1_0:
    case CONSTR_1_1:
	*first_child = c->payload[0];
	return;

	// 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;

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

	// three children (fixed), no SRT
	// need to push a stackElement
492 493
    case MVAR_CLEAN:
    case MVAR_DIRTY:
494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520
	// 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
    case WEAK:
	*first_child = ((StgWeak *)c)->key;
	// se.info.type = posTypeStep;
	se.info.next.step = 2;
	break;

	// layout.payload.ptrs, no SRT
    case CONSTR:
    case STABLE_NAME:
    case BCO:
    case CONSTR_STATIC:
	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
521 522
    case MUT_ARR_PTRS_CLEAN:
    case MUT_ARR_PTRS_DIRTY:
523
    case MUT_ARR_PTRS_FROZEN:
524
    case MUT_ARR_PTRS_FROZEN0:
525 526 527 528 529 530 531 532 533 534
	init_ptrs(&se.info, ((StgMutArrPtrs *)c)->ptrs,
		  (StgPtr)(((StgMutArrPtrs *)c)->payload));
	*first_child = find_ptrs(&se.info);
	if (*first_child == NULL)
	    return;
	break;

    // layout.payload.ptrs, SRT
    case FUN:           // *c is a heap object.
    case FUN_2_0:
535 536 537 538 539 540 541
	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;

542 543
    case THUNK:
    case THUNK_2_0:
544 545
	init_ptrs(&se.info, get_itbl(c)->layout.payload.ptrs, 
		  (StgPtr)((StgThunk *)c)->payload);
546 547 548
	*first_child = find_ptrs(&se.info);
	if (*first_child == NULL)
	    // no child from ptrs, so check SRT
549
	    goto thunk_srt_only;
550 551 552 553 554
	break;

	// 1 fixed child, SRT
    case FUN_1_0:
    case FUN_1_1:
555 556 557 558 559
	*first_child = c->payload[0];
	ASSERT(*first_child != NULL);
	init_srt_fun(&se.info, get_fun_itbl(c));
	break;

560 561
    case THUNK_1_0:
    case THUNK_1_1:
562
	*first_child = ((StgThunk *)c)->payload[0];
563
	ASSERT(*first_child != NULL);
564
	init_srt_thunk(&se.info, get_thunk_itbl(c));
565 566 567
	break;

    case FUN_STATIC:      // *c is a heap object.
568
	ASSERT(get_itbl(c)->srt_bitmap != 0);
569 570
    case FUN_0_1:
    case FUN_0_2:
571 572 573 574 575 576 577 578 579
    fun_srt_only:
        init_srt_fun(&se.info, get_fun_itbl(c));
	*first_child = find_srt(&se.info);
	if (*first_child == NULL)
	    return;     // no child
	break;

    // SRT only
    case THUNK_STATIC:
580
	ASSERT(get_itbl(c)->srt_bitmap != 0);
581 582
    case THUNK_0_1:
    case THUNK_0_2:
583 584
    thunk_srt_only:
        init_srt_thunk(&se.info, get_thunk_itbl(c));
585 586 587 588
	*first_child = find_srt(&se.info);
	if (*first_child == NULL)
	    return;     // no child
	break;
589
	
tharris@microsoft.com's avatar
tharris@microsoft.com committed
590 591
    case TVAR_WATCH_QUEUE:
	*first_child = (StgClosure *)((StgTVarWatchQueue *)c)->closure;
592 593 594 595 596 597 598 599 600 601 602 603
	se.info.next.step = 2;            // 2 = second
	break;
    case TVAR:
	*first_child = (StgClosure *)((StgTVar *)c)->current_value;
	break;
    case TREC_HEADER:
	*first_child = (StgClosure *)((StgTRecHeader *)c)->enclosing_trec;
	break;
    case TREC_CHUNK:
	*first_child = (StgClosure *)((StgTRecChunk *)c)->prev_chunk;
	se.info.next.step = 0;  // entry no.
	break;
604 605 606

	// cannot appear
    case PAP:
607 608
    case AP:
    case AP_STACK:
609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634
    case TSO:
    case IND_STATIC:
    case CONSTR_NOCAF_STATIC:
	// stack objects
    case UPDATE_FRAME:
    case CATCH_FRAME:
    case STOP_FRAME:
    case RET_DYN:
    case RET_BCO:
    case RET_SMALL:
    case RET_BIG:
	// invalid objects
    case IND:
    case BLOCKED_FETCH:
    case FETCH_ME:
    case FETCH_ME_BQ:
    case RBH:
    case REMOTE_REF:
    case INVALID_OBJECT:
    default:
	barf("Invalid object *c in push()");
	return;
    }

    if (stackTop - 1 < stackBottom) {
#ifdef DEBUG_RETAINER
635
	// debugBelch("push() to the next stack.\n");
636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657
#endif
	// 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);
    }

    // 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.
658 659 660 661 662 663

    // 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?
664 665 666 667 668 669
    *stackTop = se;

#ifdef DEBUG_RETAINER
    stackSize++;
    if (stackSize > maxStackSize) maxStackSize = stackSize;
    // ASSERT(stackSize >= 0);
670
    // debugBelch("stackSize = %d\n", stackSize);
671 672 673 674 675 676 677 678 679 680 681 682 683
#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
684
 *    INLINE function (for the sake of execution speed).  popOffReal()
685 686 687 688 689 690 691 692
 *    is called only within popOff() and nowhere else.
 * -------------------------------------------------------------------------- */
static void
popOffReal(void)
{
    bdescr *pbd;    // Previous Block Descriptor

#ifdef DEBUG_RETAINER
693
    // debugBelch("pop() to the previous stack.\n");
694 695 696 697 698 699 700 701 702 703 704 705 706 707
#endif

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

    if (firstStack == currentStack) {
	// The stack is completely empty.
	stackTop++;
	ASSERT(stackTop == stackLimit);
#ifdef DEBUG_RETAINER
	stackSize--;
	if (stackSize > maxStackSize) maxStackSize = stackSize;
	/*
	  ASSERT(stackSize >= 0);
708
	  debugBelch("stackSize = %d\n", stackSize);
709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728
	*/
#endif
	return;
    }

    // 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);

#ifdef DEBUG_RETAINER
    stackSize--;
    if (stackSize > maxStackSize) maxStackSize = stackSize;
    /*
      ASSERT(stackSize >= 0);
729
      debugBelch("stackSize = %d\n", stackSize);
730 731 732 733
    */
#endif
}

734
static INLINE void
735 736
popOff(void) {
#ifdef DEBUG_RETAINER
737
    // debugBelch("\tpopOff(): stackTop = 0x%x, currentStackBoundary = 0x%x\n", stackTop, currentStackBoundary);
738 739 740 741 742 743 744 745 746 747 748 749 750
#endif

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

    // <= (instead of <) is wrong!
    if (stackTop + 1 < stackLimit) {
	stackTop++;
#ifdef DEBUG_RETAINER
	stackSize--;
	if (stackSize > maxStackSize) maxStackSize = stackSize;
	/*
	  ASSERT(stackSize >= 0);
751
	  debugBelch("stackSize = %d\n", stackSize);
752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775
	*/
#endif
	return;
    }

    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
 *  the current stack chunk becomes empty, indicated by rtsTrue returned by
 *  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.
 * -------------------------------------------------------------------------- */
776
static INLINE void
777
pop( StgClosure **c, StgClosure **cp, retainer *r )
778 779 780 781
{
    stackElement *se;

#ifdef DEBUG_RETAINER
782
    // debugBelch("pop(): stackTop = 0x%x, currentStackBoundary = 0x%x\n", stackTop, currentStackBoundary);
783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804
#endif

    do {
	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
805 806
        case MVAR_CLEAN:
        case MVAR_DIRTY:
807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832
	    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;

tharris@microsoft.com's avatar
tharris@microsoft.com committed
833
	case TVAR_WATCH_QUEUE:
834
	    if (se->info.next.step == 2) {
tharris@microsoft.com's avatar
tharris@microsoft.com committed
835
		*c = (StgClosure *)((StgTVarWatchQueue *)se->c)->next_queue_entry;
836 837 838
		se->info.next.step++;             // move to the next step
		// no popOff
	    } else {
tharris@microsoft.com's avatar
tharris@microsoft.com committed
839
		*c = (StgClosure *)((StgTVarWatchQueue *)se->c)->prev_queue_entry;
840 841 842 843 844 845 846
		popOff();
	    }
	    *cp = se->c;
	    *r = se->c_child_r;
	    return;

	case TVAR:
tharris@microsoft.com's avatar
tharris@microsoft.com committed
847
	    *c = (StgClosure *)((StgTVar *)se->c)->first_watch_queue_entry;
848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865
	    *cp = se->c;
	    *r = se->c_child_r;
	    popOff();
	    return;

	case TREC_HEADER:
	    *c = (StgClosure *)((StgTRecHeader *)se->c)->current_chunk;
	    *cp = se->c;
	    *r = se->c_child_r;
	    popOff();
	    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).
866
	    TRecEntry *entry;
867 868 869 870 871 872 873
	    nat entry_no = se->info.next.step >> 2;
	    nat field_no = se->info.next.step & 3;
	    if (entry_no == ((StgTRecChunk *)se->c)->next_entry_idx) {
		*c = NULL;
		popOff();
		return;
	    }
874
	    entry = &((StgTRecChunk *)se->c)->entries[entry_no];
875 876 877 878 879 880 881 882 883 884 885 886 887
	    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;
	}

888 889 890 891 892
	case CONSTR:
	case STABLE_NAME:
	case BCO:
	case CONSTR_STATIC:
	    // StgMutArrPtr.ptrs, no SRT
893 894
	case MUT_ARR_PTRS_CLEAN:
	case MUT_ARR_PTRS_DIRTY:
895
	case MUT_ARR_PTRS_FROZEN:
896
	case MUT_ARR_PTRS_FROZEN0:
897 898 899 900 901 902 903 904 905 906 907 908
	    *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
	case FUN_2_0:
909 910 911 912 913 914 915 916 917 918 919
	    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;

920 921 922 923 924 925 926 927 928
	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;
		}
929
		init_srt_thunk(&se->info, get_thunk_itbl(se->c));
930
	    }
931
	    goto do_srt;
932 933

	    // SRT
934
	do_srt:
935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960
	case THUNK_STATIC:
	case FUN_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 CAF_BLACKHOLE:
	case BLACKHOLE:
	case ARR_WORDS:
	    // one child (fixed), no SRT
961 962
	case MUT_VAR_CLEAN:
	case MUT_VAR_DIRTY:
963 964 965 966 967 968 969
	case THUNK_SELECTOR:
	case IND_PERM:
	case IND_OLDGEN_PERM:
	case IND_OLDGEN:
	case CONSTR_1_1:
	    // cannot appear
	case PAP:
970 971
	case AP:
	case AP_STACK:
972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033
	case TSO:
	case IND_STATIC:
	case CONSTR_NOCAF_STATIC:
	    // stack objects
	case RET_DYN:
	case UPDATE_FRAME:
	case CATCH_FRAME:
	case STOP_FRAME:
	case RET_BCO:
	case RET_SMALL:
	case RET_BIG:
	    // invalid objects
	case IND:
	case BLOCKED_FETCH:
	case FETCH_ME:
	case FETCH_ME_BQ:
	case RBH:
	case REMOTE_REF:
	case INVALID_OBJECT:
	default:
	    barf("Invalid object *c in pop()");
	    return;
	}
    } while (rtsTrue);
}

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

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

/* -----------------------------------------------------------------------------
 *  This function must be called before f-closing prof_file.
 * -------------------------------------------------------------------------- */
void
endRetainerProfiling( void )
{
#ifdef SECOND_APPROACH
    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.
 * -------------------------------------------------------------------------- */
1034
static INLINE void
1035 1036 1037 1038 1039 1040 1041 1042 1043 1044
maybeInitRetainerSet( StgClosure *c )
{
    if (!isRetainerSetFieldValid(c)) {
	setRetainerSetToNull(c);
    }
}

/* -----------------------------------------------------------------------------
 * Returns rtsTrue if *c is a retainer.
 * -------------------------------------------------------------------------- */
1045
static INLINE rtsBool
1046 1047 1048 1049 1050 1051 1052 1053 1054 1055
isRetainer( StgClosure *c )
{
    switch (get_itbl(c)->type) {
	//
	//  True case
	//
	// TSOs MUST be retainers: they constitute the set of roots.
    case TSO:

	// mutable objects
1056 1057
    case MVAR_CLEAN:
    case MVAR_DIRTY:
1058 1059
    case MUT_VAR_CLEAN:
    case MUT_VAR_DIRTY:
1060 1061
    case MUT_ARR_PTRS_CLEAN:
    case MUT_ARR_PTRS_DIRTY:
1062
    case MUT_ARR_PTRS_FROZEN:
1063
    case MUT_ARR_PTRS_FROZEN0:
1064 1065 1066 1067 1068 1069 1070 1071 1072

	// thunks are retainers.
    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:
1073 1074
    case AP:
    case AP_STACK:
1075 1076 1077 1078 1079 1080 1081

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

	// WEAK objects are roots; there is separate code in which traversing
	// begins from WEAK objects.
    case WEAK:
1082 1083 1084 1085

	// Since the other mutvar-type things are retainers, seems
	// like the right thing to do:
    case TVAR:
1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121
	return rtsTrue;

	//
	// False case
	//

	// constructors
    case CONSTR:
    case CONSTR_1_0:
    case CONSTR_0_1:
    case CONSTR_2_0:
    case CONSTR_1_1:
    case CONSTR_0_2:
	// functions
    case FUN:
    case FUN_1_0:
    case FUN_0_1:
    case FUN_2_0:
    case FUN_1_1:
    case FUN_0_2:
	// partial applications
    case PAP:
	// blackholes
    case CAF_BLACKHOLE:
    case BLACKHOLE:
	// indirection
    case IND_PERM:
    case IND_OLDGEN_PERM:
    case IND_OLDGEN:
	// static objects
    case CONSTR_STATIC:
    case FUN_STATIC:
	// misc
    case STABLE_NAME:
    case BCO:
    case ARR_WORDS:
1122
	// STM
tharris@microsoft.com's avatar
tharris@microsoft.com committed
1123
    case TVAR_WATCH_QUEUE:
1124 1125
    case TREC_HEADER:
    case TREC_CHUNK:
1126 1127 1128 1129 1130 1131 1132
	return rtsFalse;

	//
	// Error case
	//
	// IND_STATIC cannot be *c, *cp, *r in the retainer profiling loop.
    case IND_STATIC:
1133
	// CONSTR_NOCAF_STATIC
1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167
	// cannot be *c, *cp, *r in the retainer profiling loop.
    case CONSTR_NOCAF_STATIC:
	// Stack objects are invalid because they are never treated as
	// legal objects during retainer profiling.
    case UPDATE_FRAME:
    case CATCH_FRAME:
    case STOP_FRAME:
    case RET_DYN:
    case RET_BCO:
    case RET_SMALL:
    case RET_BIG:
	// other cases
    case IND:
    case BLOCKED_FETCH:
    case FETCH_ME:
    case FETCH_ME_BQ:
    case RBH:
    case REMOTE_REF:
    case INVALID_OBJECT:
    default:
	barf("Invalid object in isRetainer(): %d", get_itbl(c)->type);
	return rtsFalse;
    }
}

/* -----------------------------------------------------------------------------
 *  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
1168
 *    RetainerSet.c can simply do nothing.
1169 1170 1171 1172
 *    If this is not the case, we can free all the retainer sets and
 *    re-initialize the hash table.
 *    See refreshAllRetainerSet() in RetainerSet.c.
 * -------------------------------------------------------------------------- */
1173
static INLINE retainer
1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196
getRetainerFrom( StgClosure *c )
{
    ASSERT(isRetainer(c));

#if defined(RETAINER_SCHEME_INFO)
    // Retainer scheme 1: retainer = info table
    return get_itbl(c);
#elif defined(RETAINER_SCHEME_CCS)
    // Retainer scheme 2: retainer = cost centre stack
    return c->header.prof.ccs;
#elif defined(RETAINER_SCHEME_CC)
    // Retainer scheme 3: retainer = cost centre
    return c->header.prof.ccs->cc;
#endif
}

/* -----------------------------------------------------------------------------
 *  Associates the retainer set *s with the closure *c, that is, *s becomes
 *  the retainer set of *c.
 *  Invariants:
 *    c != NULL
 *    s != NULL
 * -------------------------------------------------------------------------- */
1197
static INLINE void
1198
associate( StgClosure *c, RetainerSet *s )
1199 1200 1201 1202 1203 1204
{
    // StgWord has the same size as pointers, so the following type
    // casting is okay.
    RSET(c) = (RetainerSet *)((StgWord)s | flip);
}

1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232
/* -----------------------------------------------------------------------------
   Call retainClosure for each of the closures covered by a large bitmap.
   -------------------------------------------------------------------------- */

static void
retain_large_bitmap (StgPtr p, StgLargeBitmap *large_bitmap, nat size,
		     StgClosure *c, retainer c_child_r)
{
    nat i, b;
    StgWord bitmap;
    
    b = 0;
    bitmap = large_bitmap->bitmap[b];
    for (i = 0; i < size; ) {
	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;
	}
    }
}

1233
static INLINE StgPtr
1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247
retain_small_bitmap (StgPtr p, nat size, StgWord bitmap,
		     StgClosure *c, retainer c_child_r)
{
    while (size > 0) {
	if ((bitmap & 1) == 0) {
	    retainClosure((StgClosure *)*p, c, c_child_r);
	}
	p++;
	bitmap = bitmap >> 1;
	size--;
    }
    return p;
}

1248 1249 1250 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 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309
/* -----------------------------------------------------------------------------
 * Call retainClosure for each of the closures in an SRT.
 * ------------------------------------------------------------------------- */

static void
retain_large_srt_bitmap (StgLargeSRT *srt, StgClosure *c, retainer c_child_r)
{
    nat i, b, size;
    StgWord bitmap;
    StgClosure **p;
    
    b = 0;
    p = (StgClosure **)srt->srt;
    size   = srt->l.size;
    bitmap = srt->l.bitmap[b];
    for (i = 0; i < size; ) {
	if ((bitmap & 1) != 0) {
	    retainClosure((StgClosure *)*p, c, c_child_r);
	}
	i++;
	p++;
	if (i % BITS_IN(W_) == 0) {
	    b++;
	    bitmap = srt->l.bitmap[b];
	} else {
	    bitmap = bitmap >> 1;
	}
    }
}

static INLINE void
retainSRT (StgClosure **srt, nat srt_bitmap, StgClosure *c, retainer c_child_r)
{
  nat bitmap;
  StgClosure **p;

  bitmap = srt_bitmap;
  p = srt;

  if (bitmap == (StgHalfWord)(-1)) {  
      retain_large_srt_bitmap( (StgLargeSRT *)srt, c, c_child_r );
      return;
  }

  while (bitmap != 0) {
      if ((bitmap & 1) != 0) {
#ifdef ENABLE_WIN32_DLL_SUPPORT
	  if ( (unsigned long)(*srt) & 0x1 ) {
	      retainClosure(*stgCast(StgClosure**,(stgCast(unsigned long, *srt) & ~0x1)), 
			    c, c_child_r);
	  } else {
	      retainClosure(*srt,c,c_child_r);
	  }
#else
	  retainClosure(*srt,c,c_child_r);
#endif
      }
      p++;
      bitmap = bitmap >> 1;
  }
}

1310 1311 1312 1313 1314 1315
/* -----------------------------------------------------------------------------
 *  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:
1316
 *    *c is one of the following: TSO, AP_STACK.
1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328
 *    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).
 *    If *c is TSO, its state is not any of ThreadRelocated, ThreadComplete,
 *    or ThreadKilled, which means that its stack is ready to process.
 *  Note:
 *    This code was almost plagiarzied from GC.c! For each pointer,
 *    retainClosure() is invoked instead of evacuate().
 * -------------------------------------------------------------------------- */
static void
1329
retainStack( StgClosure *c, retainer c_child_r,
1330
	     StgPtr stackStart, StgPtr stackEnd )
1331 1332
{
    stackElement *oldStackBoundary;
1333 1334
    StgPtr p;
    StgRetInfoTable *info;
1335
    StgWord32 bitmap;
1336
    nat size;
1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352

#ifdef DEBUG_RETAINER
    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;

#ifdef DEBUG_RETAINER
1353
    // debugBelch("retainStack() called: oldStackBoundary = 0x%x, currentStackBoundary = 0x%x\n", oldStackBoundary, currentStackBoundary);
1354 1355
#endif

1356 1357 1358 1359 1360
    ASSERT(get_itbl(c)->type != TSO || 
	   (((StgTSO *)c)->what_next != ThreadRelocated &&
	    ((StgTSO *)c)->what_next != ThreadComplete &&
	    ((StgTSO *)c)->what_next != ThreadKilled));
    
1361 1362
    p = stackStart;
    while (p < stackEnd) {
1363
	info = get_ret_itbl((StgClosure *)p);
1364

1365
	switch(info->i.type) {
1366 1367 1368 1369 1370 1371 1372 1373

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

	case STOP_FRAME:
	case CATCH_FRAME:
1374 1375 1376
	case CATCH_STM_FRAME:
	case CATCH_RETRY_FRAME:
	case ATOMICALLY_FRAME:
1377
	case RET_SMALL:
1378 1379
	    bitmap = BITMAP_BITS(info->i.layout.bitmap);
	    size   = BITMAP_SIZE(info->i.layout.bitmap);
1380
	    p++;
1381 1382
	    p = retain_small_bitmap(p, size, bitmap, c, c_child_r);

1383
	follow_srt:
1384
	    retainSRT((StgClosure **)GET_SRT(info), info->i.srt_bitmap, c, c_child_r);
1385
	    continue;
1386

1387 1388 1389 1390 1391 1392 1393 1394 1395 1396
	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;
1397
	    continue;
1398
	}
1399

1400
	    // large bitmap (> 32 entries, or > 64 on a 64-bit machine) 
1401
	case RET_BIG:
1402
	    size = GET_LARGE_BITMAP(&info->i)->size;
1403
	    p++;
1404
	    retain_large_bitmap(p, GET_LARGE_BITMAP(&info->i),
1405 1406 1407 1408
				size, c, c_child_r);
	    p += size;
	    // and don't forget to follow the SRT 
	    goto follow_srt;
1409

1410 1411 1412 1413 1414 1415
	    // Dynamic bitmap: the mask is stored on the stack 
	case RET_DYN: {
	    StgWord dyn;
	    dyn = ((StgRetDyn *)p)->liveness;

	    // traverse the bitmap first
1416
	    bitmap = RET_DYN_LIVENESS(dyn);
1417
	    p      = (P_)&((StgRetDyn *)p)->payload[0];
1418
	    size   = RET_DYN_BITMAP_SIZE;
1419 1420 1421
	    p = retain_small_bitmap(p, size, bitmap, c, c_child_r);
	    
	    // skip over the non-ptr words
1422
	    p += RET_DYN_NONPTRS(dyn) + RET_DYN_NONPTR_REGS_SIZE;
1423 1424
	    
	    // follow the ptr words
1425
	    for (size = RET_DYN_PTRS(dyn); size > 0; size--) {
1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436
		retainClosure((StgClosure *)*p, c, c_child_r);
		p++;
	    }
	    continue;
	}

	case RET_FUN: {
	    StgRetFun *ret_fun = (StgRetFun *)p;
	    StgFunInfoTable *fun_info;
	    
	    retainClosure(ret_fun->fun, c, c_child_r);
Ian Lynagh's avatar
Ian Lynagh committed
1437
	    fun_info = get_fun_itbl(UNTAG_CLOSURE(ret_fun->fun));
1438 1439
	    
	    p = (P_)&ret_fun->payload;
1440
	    switch (fun_info->f.fun_type) {
1441
	    case ARG_GEN:
1442 1443
		bitmap = BITMAP_BITS(fun_info->f.b.bitmap);
		size = BITMAP_SIZE(fun_info->f.b.bitmap);
1444 1445 1446
		p = retain_small_bitmap(p, size, bitmap, c, c_child_r);
		break;
	    case ARG_GEN_BIG:
1447 1448
		size = GET_FUN_LARGE_BITMAP(fun_info)->size;
		retain_large_bitmap(p, GET_FUN_LARGE_BITMAP(fun_info), 
1449 1450 1451 1452
				    size, c, c_child_r);
		p += size;
		break;
	    default:
1453 1454
		bitmap = BITMAP_BITS(stg_arg_bitmaps[fun_info->f.fun_type]);
		size = BITMAP_SIZE(stg_arg_bitmaps[fun_info->f.fun_type]);
1455 1456
		p = retain_small_bitmap(p, size, bitmap, c, c_child_r);
		break;
1457
	    }
1458
	    goto follow_srt;
1459
	}
1460

1461 1462
	default:
	    barf("Invalid object found in retainStack(): %d",
1463
		 (int)(info->i.type));
1464 1465 1466 1467 1468 1469
	}
    }

    // restore currentStackBoundary
    currentStackBoundary = oldStackBoundary;
#ifdef DEBUG_RETAINER
1470
    // debugBelch("retainStack() finished: currentStackBoundary = 0x%x\n", currentStackBoundary);
1471 1472 1473 1474 1475 1476 1477
#endif

#ifdef DEBUG_RETAINER
    cStackSize--;
#endif
}

1478 1479 1480 1481
/* ----------------------------------------------------------------------------
 * Call retainClosure for each of the children of a PAP/AP
 * ------------------------------------------------------------------------- */

1482
static INLINE StgPtr
Simon Marlow's avatar
Simon Marlow committed
1483 1484 1485
retain_PAP_payload (StgClosure *pap,    /* NOT tagged */
                    retainer c_child_r, /* NOT tagged */ 
                    StgClosure *fun,    /* tagged */
1486
		    StgClosure** payload, StgWord n_args)
1487 1488
{
    StgPtr p;
1489
    StgWord bitmap;
1490 1491
    StgFunInfoTable *fun_info;

1492
    retainClosure(fun, pap, c_child_r);
Simon Marlow's avatar
Simon Marlow committed
1493
    fun = UNTAG_CLOSURE(fun);
1494
    fun_info = get_fun_itbl(fun);
1495 1496
    ASSERT(fun_info->i.type != PAP);

1497
    p = (StgPtr)payload;
1498

1499
    switch (fun_info->f.fun_type) {
1500
    case ARG_GEN:
1501
	bitmap = BITMAP_BITS(fun_info->f.b.bitmap);
1502 1503
	p = retain_small_bitmap(p, n_args, bitmap, 
				pap, c_child_r);
1504 1505
	break;
    case ARG_GEN_BIG:
1506
	retain_large_bitmap(p, GET_FUN_LARGE_BITMAP(fun_info),
1507 1508
			    n_args, pap, c_child_r);
	p += n_args;
1509 1510
	break;
    case ARG_BCO:
1511 1512 1513
	retain_large_bitmap((StgPtr)payload, BCO_BITMAP(fun),
			    n_args, pap, c_child_r);
	p += n_args;
1514 1515
	break;
    default:
1516
	bitmap = BITMAP_BITS(stg_arg_bitmaps[fun_info->f.fun_type]);
1517
	p = retain_small_bitmap(p, n_args, bitmap, pap, c_child_r);
1518 1519 1520 1521 1522
	break;
    }
    return p;
}

1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536
/* -----------------------------------------------------------------------------
 *  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.
1537
 *    *c0 can be TSO (as well as AP_STACK).
1538 1539
 * -------------------------------------------------------------------------- */
static void
1540
retainClosure( StgClosure *c0, StgClosure *cp0, retainer r0 )
1541
{
Simon Marlow's avatar
Simon Marlow committed
1542 1543 1544
    // c = Current closure                          (possibly tagged)
    // cp = Current closure's Parent                (NOT tagged)
    // r = current closures' most recent Retainer   (NOT tagged)
1545 1546
    // c_child_r = current closure's children's most recent retainer
    // first_child = first child of c
1547
    StgClosure *c, *cp, *first_child;
1548
    RetainerSet *s, *retainerSetOfc;
1549
    retainer r, c_child_r;
1550 1551 1552 1553 1554 1555 1556 1557
    StgWord typeOfc;

#ifdef DEBUG_RETAINER
    // StgPtr oldStackTop;
#endif

#ifdef DEBUG_RETAINER
    // oldStackTop = stackTop;
1558
    // debugBelch("retainClosure() called: c0 = 0x%x, cp0 = 0x%x, r0 = 0x%x\n", c0, cp0, r0);
1559 1560 1561 1562 1563 1564 1565 1566 1567
#endif

    // (c, cp, r) = (c0, cp0, r0)
    c = c0;
    cp = cp0;
    r = r0;
    goto inner_loop;

loop:
1568
    //debugBelch("loop");
1569 1570 1571 1572 1573
    // pop to (c, cp, r);
    pop(&c, &cp, &r);

    if (c == NULL) {
#ifdef DEBUG_RETAINER
1574
	// debugBelch("retainClosure() ends: oldStackTop = 0x%x, stackTop = 0x%x\n", oldStackTop, stackTop);
1575 1576 1577 1578
#endif
	return;
    }

1579
    //debugBelch("inner_loop");
1580 1581

inner_loop:
Simon Marlow's avatar
Simon Marlow committed
1582 1583
    c = UNTAG_CLOSURE(c);

1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620
    // c  = current closure under consideration,
    // cp = current closure's parent,
    // r  = current closure's most recent retainer
    //
    // Loop invariants (on the meaning of c, cp, r, and their retainer sets):
    //   RSET(cp) and RSET(r) are valid.
    //   RSET(c) is valid only if c has been visited before.
    //
    // Loop invariants (on the relation between c, cp, and r)
    //   if cp is not a retainer, r belongs to RSET(cp).
    //   if cp is a retainer, r == cp.

    typeOfc = get_itbl(c)->type;

#ifdef DEBUG_RETAINER
    switch (typeOfc) {
    case IND_STATIC:
    case CONSTR_NOCAF_STATIC:
    case CONSTR_STATIC:
    case THUNK_STATIC:
    case FUN_STATIC:
	break;
    default:
	if (retainerSetOf(c) == NULL) {   // first visit?
	    costArray[typeOfc] += cost(c);
	    sumOfNewCost += cost(c);
	}
	break;
    }
#endif

    // special cases
    switch (typeOfc) {
    case TSO:
	if (((StgTSO *)c)->what_next == ThreadComplete ||
	    ((StgTSO *)c)->what_next == ThreadKilled) {
#ifdef DEBUG_RETAINER
1621
	    debugBelch("ThreadComplete or ThreadKilled encountered in retainClosure()\n");
1622 1623 1624 1625 1626
#endif
	    goto loop;
	}
	if (((StgTSO *)c)->what_next == ThreadRelocated) {
#ifdef DEBUG_RETAINER
1627
	    debugBelch("ThreadRelocated encountered in retainClosure()\n");
1628
#endif
1629
	    c = (StgClosure *)((StgTSO *)c)->_link;
1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646
	    goto inner_loop;
	}
	break;

    case IND_STATIC:
	// We just skip IND_STATIC, so its retainer set is never computed.
	c = ((StgIndStatic *)c)->indirectee;
	goto inner_loop;
	// static objects with no pointers out, so goto loop.
    case CONSTR_NOCAF_STATIC:
	// It is not just enough not to compute the retainer set for *c; it is
	// mandatory because CONSTR_NOCAF_STATIC are not reachable from
	// scavenged_static_objects, the list from which is assumed to traverse
	// all static objects after major garbage collections.
	goto loop;
    case THUNK_STATIC:
    case FUN_STATIC:
1647
	if (get_itbl(c)->srt_bitmap == 0) {
1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701
	    // No need to compute the retainer set; no dynamic objects
	    // are reachable from *c.
	    //
	    // Static objects: if we traverse all the live closures,
	    // including static closures, during each heap census then
	    // we will observe that some static closures appear and
	    // disappear.  eg. a closure may contain a pointer to a
	    // static function 'f' which is not otherwise reachable
	    // (it doesn't indirectly point to any CAFs, so it doesn't
	    // appear in any SRTs), so we would find 'f' during
	    // traversal.  However on the next sweep there may be no
	    // closures pointing to 'f'.
	    //
	    // We must therefore ignore static closures whose SRT is
	    // empty, because these are exactly the closures that may
	    // "appear".  A closure with a non-empty SRT, and which is
	    // still required, will always be reachable.
	    //
	    // But what about CONSTR_STATIC?  Surely these may be able
	    // to appear, and they don't have SRTs, so we can't
	    // check.  So for now, we're calling
	    // resetStaticObjectForRetainerProfiling() from the
	    // garbage collector to reset the retainer sets in all the
	    // reachable static objects.
	    goto loop;
	}
    default:
	break;
    }

    // The above objects are ignored in computing the average number of times
    // an object is visited.
    timesAnyObjectVisited++;

    // If this is the first visit to c, initialize its retainer set.
    maybeInitRetainerSet(c);
    retainerSetOfc = retainerSetOf(c);

    // Now compute s:
    //    isRetainer(cp) == rtsTrue => s == NULL
    //    isRetainer(cp) == rtsFalse => s == cp.retainer
    if (isRetainer(cp))
	s = NULL;
    else
	s = retainerSetOf(cp);

    // (c, cp, r, s) is available.

    // (c, cp, r, s, R_r) is available, so compute the retainer set for *c.
    if (retainerSetOfc == NULL) {
	// This is the first visit to *c.
	numObjectVisited++;

	if (s == NULL)
1702
	    associate(c, singleton(r));
1703 1704
	else
	    // s is actually the retainer set of *c!
1705
	    associate(c, s);
1706 1707

	// compute c_child_r
1708
	c_child_r = isRetainer(c) ? getRetainerFrom(c) : r;
1709 1710
    } else {
	// This is not the first visit to *c.
1711
	if (isMember(r, retainerSetOfc))
1712 1713 1714
	    goto loop;          // no need to process child

	if (s == NULL)
1715
	    associate(c, addElement(r, retainerSetOfc));
1716 1717 1718 1719 1720 1721
	else {
	    // s is not NULL and cp is not a retainer. This means that
	    // each time *cp is visited, so is *c. Thus, if s has
	    // exactly one more element in its retainer set than c, s
	    // is also the new retainer set for *c.
	    if (s->num == retainerSetOfc->num + 1) {
1722
		associate(c, s);
1723 1724 1725
	    }
	    // Otherwise, just add R_r to the current retainer set of *c.
	    else {
1726
		associate(c, addElement(r, retainerSetOfc));
1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741
	    }
	}

	if (isRetainer(c))
	    goto loop;          // no need to process child

	// compute c_child_r
	c_child_r = r;
    }

    // now, RSET() of all of *c, *cp, and *r is valid.
    // (c, c_child_r) are available.

    // process child

1742 1743 1744 1745 1746
    // Special case closures: we process these all in one go rather
    // than attempting to save the current position, because doing so
    // would be hard.
    switch (typeOfc) {
    case TSO:
1747 1748 1749 1750
	retainStack(c, c_child_r,
		    ((StgTSO *)c)->sp,
		    ((StgTSO *)c)->stack + ((StgTSO *)c)->stack_size);
	goto loop;
1751 1752

    case PAP:
1753 1754 1755 1756 1757 1758
    {
	StgPAP *pap = (StgPAP *)c;
	retain_PAP_payload(c, c_child_r, pap->fun, pap->payload, pap->n_args);
	goto loop;
    }

1759
    case AP:
1760 1761 1762
    {
	StgAP *ap = (StgAP *)c;
	retain_PAP_payload(c, c_child_r, ap->fun, ap->payload, ap->n_args);
1763
	goto loop;
1764
    }
1765 1766 1767

    case AP_STACK:
	retainClosure(((StgAP_STACK *)c)->fun, c, c_child_r);