1 /* -----------------------------------------------------------------------------
3 * (c) The GHC Team, 2001
8 * ---------------------------------------------------------------------------*/
12 // Turn off inlining when debugging - it obfuscates things
21 #include "RetainerProfile.h"
22 #include "RetainerSet.h"
29 #include "Profiling.h"
31 #include "BlockAlloc.h"
36 Note: what to change in order to plug-in a new retainer profiling scheme?
37 (1) type retainer in ../includes/StgRetainerProf.h
38 (2) retainer function R(), i.e., getRetainerFrom()
39 (3) the two hashing functions, hashKeySingleton() and hashKeyAddElement(),
40 in RetainerSet.h, if needed.
41 (4) printRetainer() and printRetainerSetShort() in RetainerSet.c.
44 /* -----------------------------------------------------------------------------
46 * -------------------------------------------------------------------------- */
48 static nat retainerGeneration; // generation
50 static nat numObjectVisited; // total number of objects visited
51 static nat timesAnyObjectVisited; // number of times any objects are visited
54 The rs field in the profile header of any object points to its retainer
55 set in an indirect way: if flip is 0, it points to the retainer set;
56 if flip is 1, it points to the next byte after the retainer set (even
57 for NULL pointers). Therefore, with flip 1, (rs ^ 1) is the actual
58 pointer. See retainerSetOf().
61 StgWord flip = 0; // flip bit
62 // must be 0 if DEBUG_RETAINER is on (for static closures)
64 #define setRetainerSetToNull(c) \
65 (c)->header.prof.hp.rs = (RetainerSet *)((StgWord)NULL | flip)
67 static void retainStack(StgClosure *, retainer, StgPtr, StgPtr);
68 static void retainClosure(StgClosure *, StgClosure *, retainer);
70 static void belongToHeap(StgPtr p);
75 cStackSize records how many times retainStack() has been invoked recursively,
76 that is, the number of activation records for retainStack() on the C stack.
77 maxCStackSize records its max value.
79 cStackSize <= maxCStackSize
81 static nat cStackSize, maxCStackSize;
83 static nat sumOfNewCost; // sum of the cost of each object, computed
84 // when the object is first visited
85 static nat sumOfNewCostExtra; // for those objects not visited during
86 // retainer profiling, e.g., MUT_VAR
87 static nat costArray[N_CLOSURE_TYPES];
89 nat sumOfCostLinear; // sum of the costs of all object, computed
90 // when linearly traversing the heap after
92 nat costArrayLinear[N_CLOSURE_TYPES];
95 /* -----------------------------------------------------------------------------
96 * Retainer stack - header
98 * Although the retainer stack implementation could be separated *
99 * from the retainer profiling engine, there does not seem to be
100 * any advantage in doing that; retainer stack is an integral part
101 * of retainer profiling engine and cannot be use elsewhere at
103 * -------------------------------------------------------------------------- */
113 // fixed layout or layout specified by a field in the closure
118 // See StgClosureInfo in InfoTables.h
119 #if SIZEOF_VOID_P == 8
156 firstStack points to the first block group.
157 currentStack points to the block group currently being used.
158 currentStack->free == stackLimit.
159 stackTop points to the topmost byte in the stack of currentStack.
160 Unless the whole stack is empty, stackTop must point to the topmost
161 object (or byte) in the whole stack. Thus, it is only when the whole stack
162 is empty that stackTop == stackLimit (not during the execution of push()
164 stackBottom == currentStack->start.
165 stackLimit == currentStack->start + BLOCK_SIZE_W * currentStack->blocks.
167 When a current stack becomes empty, stackTop is set to point to
168 the topmost element on the previous block group so as to satisfy
169 the invariants described above.
171 static bdescr *firstStack = NULL;
172 static bdescr *currentStack;
173 static stackElement *stackBottom, *stackTop, *stackLimit;
176 currentStackBoundary is used to mark the current stack chunk.
177 If stackTop == currentStackBoundary, it means that the current stack chunk
178 is empty. It is the responsibility of the user to keep currentStackBoundary
179 valid all the time if it is to be employed.
181 static stackElement *currentStackBoundary;
184 stackSize records the current size of the stack.
185 maxStackSize records its high water mark.
187 stackSize <= maxStackSize
189 stackSize is just an estimate measure of the depth of the graph. The reason
190 is that some heap objects have only a single child and may not result
191 in a new element being pushed onto the stack. Therefore, at the end of
192 retainer profiling, maxStackSize + maxCStackSize is some value no greater
193 than the actual depth of the graph.
195 #ifdef DEBUG_RETAINER
196 static int stackSize, maxStackSize;
199 // number of blocks allocated for one stack
200 #define BLOCKS_IN_STACK 1
202 /* -----------------------------------------------------------------------------
203 * Add a new block group to the stack.
205 * currentStack->link == s.
206 * -------------------------------------------------------------------------- */
208 newStackBlock( bdescr *bd )
211 stackTop = (stackElement *)(bd->start + BLOCK_SIZE_W * bd->blocks);
212 stackBottom = (stackElement *)bd->start;
213 stackLimit = (stackElement *)stackTop;
214 bd->free = (StgPtr)stackLimit;
217 /* -----------------------------------------------------------------------------
218 * Return to the previous block group.
220 * s->link == currentStack.
221 * -------------------------------------------------------------------------- */
223 returnToOldStack( bdescr *bd )
226 stackTop = (stackElement *)bd->free;
227 stackBottom = (stackElement *)bd->start;
228 stackLimit = (stackElement *)(bd->start + BLOCK_SIZE_W * bd->blocks);
229 bd->free = (StgPtr)stackLimit;
232 /* -----------------------------------------------------------------------------
233 * Initializes the traverse stack.
234 * -------------------------------------------------------------------------- */
236 initializeTraverseStack( void )
238 if (firstStack != NULL) {
239 freeChain(firstStack);
242 firstStack = allocGroup(BLOCKS_IN_STACK);
243 firstStack->link = NULL;
244 firstStack->u.back = NULL;
246 newStackBlock(firstStack);
249 /* -----------------------------------------------------------------------------
250 * Frees all the block groups in the traverse stack.
253 * -------------------------------------------------------------------------- */
255 closeTraverseStack( void )
257 freeChain(firstStack);
261 /* -----------------------------------------------------------------------------
262 * Returns rtsTrue if the whole stack is empty.
263 * -------------------------------------------------------------------------- */
264 static INLINE rtsBool
265 isEmptyRetainerStack( void )
267 return (firstStack == currentStack) && stackTop == stackLimit;
270 /* -----------------------------------------------------------------------------
271 * Returns size of stack
272 * -------------------------------------------------------------------------- */
275 retainerStackBlocks( void )
280 for (bd = firstStack; bd != NULL; bd = bd->link)
287 /* -----------------------------------------------------------------------------
288 * Returns rtsTrue if stackTop is at the stack boundary of the current stack,
289 * i.e., if the current stack chunk is empty.
290 * -------------------------------------------------------------------------- */
291 static INLINE rtsBool
294 return stackTop == currentStackBoundary;
297 /* -----------------------------------------------------------------------------
298 * Initializes *info from ptrs and payload.
300 * payload[] begins with ptrs pointers followed by non-pointers.
301 * -------------------------------------------------------------------------- */
303 init_ptrs( stackPos *info, nat ptrs, StgPtr payload )
305 info->type = posTypePtrs;
306 info->next.ptrs.pos = 0;
307 info->next.ptrs.ptrs = ptrs;
308 info->next.ptrs.payload = payload;
311 /* -----------------------------------------------------------------------------
312 * Find the next object from *info.
313 * -------------------------------------------------------------------------- */
314 static INLINE StgClosure *
315 find_ptrs( stackPos *info )
317 if (info->next.ptrs.pos < info->next.ptrs.ptrs) {
318 return (StgClosure *)info->next.ptrs.payload[info->next.ptrs.pos++];
324 /* -----------------------------------------------------------------------------
325 * Initializes *info from SRT information stored in *infoTable.
326 * -------------------------------------------------------------------------- */
328 init_srt_fun( stackPos *info, StgFunInfoTable *infoTable )
330 if (infoTable->i.srt_bitmap == (StgHalfWord)(-1)) {
331 info->type = posTypeLargeSRT;
332 info->next.large_srt.srt = (StgLargeSRT *)GET_FUN_SRT(infoTable);
333 info->next.large_srt.offset = 0;
335 info->type = posTypeSRT;
336 info->next.srt.srt = (StgClosure **)GET_FUN_SRT(infoTable);
337 info->next.srt.srt_bitmap = infoTable->i.srt_bitmap;
342 init_srt_thunk( stackPos *info, StgThunkInfoTable *infoTable )
344 if (infoTable->i.srt_bitmap == (StgHalfWord)(-1)) {
345 info->type = posTypeLargeSRT;
346 info->next.large_srt.srt = (StgLargeSRT *)GET_SRT(infoTable);
347 info->next.large_srt.offset = 0;
349 info->type = posTypeSRT;
350 info->next.srt.srt = (StgClosure **)GET_SRT(infoTable);
351 info->next.srt.srt_bitmap = infoTable->i.srt_bitmap;
355 /* -----------------------------------------------------------------------------
356 * Find the next object from *info.
357 * -------------------------------------------------------------------------- */
358 static INLINE StgClosure *
359 find_srt( stackPos *info )
364 if (info->type == posTypeSRT) {
366 bitmap = info->next.srt.srt_bitmap;
367 while (bitmap != 0) {
368 if ((bitmap & 1) != 0) {
369 #ifdef ENABLE_WIN32_DLL_SUPPORT
371 if ((unsigned long)(*(info->next.srt.srt)) & 0x1)
372 c = (* (StgClosure **)((unsigned long)*(info->next.srt.srt)) & ~0x1);
374 c = *(info->next.srt.srt);
376 c = *(info->next.srt.srt);
378 bitmap = bitmap >> 1;
379 info->next.srt.srt++;
380 info->next.srt.srt_bitmap = bitmap;
383 bitmap = bitmap >> 1;
384 info->next.srt.srt++;
386 // bitmap is now zero...
391 nat i = info->next.large_srt.offset;
394 // Follow the pattern from GC.c:scavenge_large_srt_bitmap().
395 bitmap = info->next.large_srt.srt->l.bitmap[i / BITS_IN(W_)];
396 bitmap = bitmap >> (i % BITS_IN(StgWord));
397 while (i < info->next.large_srt.srt->l.size) {
398 if ((bitmap & 1) != 0) {
399 c = ((StgClosure **)info->next.large_srt.srt->srt)[i];
401 info->next.large_srt.offset = i;
405 if (i % BITS_IN(W_) == 0) {
406 bitmap = info->next.large_srt.srt->l.bitmap[i / BITS_IN(W_)];
408 bitmap = bitmap >> 1;
411 // reached the end of this bitmap.
412 info->next.large_srt.offset = i;
417 /* -----------------------------------------------------------------------------
418 * push() pushes a stackElement representing the next child of *c
419 * onto the traverse stack. If *c has no child, *first_child is set
420 * to NULL and nothing is pushed onto the stack. If *c has only one
421 * child, *c_chlid is set to that child and nothing is pushed onto
422 * the stack. If *c has more than two children, *first_child is set
423 * to the first child and a stackElement representing the second
424 * child is pushed onto the stack.
427 * *c_child_r is the most recent retainer of *c's children.
428 * *c is not any of TSO, AP, PAP, AP_STACK, which means that
429 * there cannot be any stack objects.
430 * Note: SRTs are considered to be children as well.
431 * -------------------------------------------------------------------------- */
433 push( StgClosure *c, retainer c_child_r, StgClosure **first_child )
436 bdescr *nbd; // Next Block Descriptor
438 #ifdef DEBUG_RETAINER
439 // debugBelch("push(): stackTop = 0x%x, currentStackBoundary = 0x%x\n", stackTop, currentStackBoundary);
442 ASSERT(get_itbl(c)->type != TSO);
443 ASSERT(get_itbl(c)->type != AP_STACK);
450 se.c_child_r = c_child_r;
453 switch (get_itbl(c)->type) {
460 case SE_CAF_BLACKHOLE:
465 // one child (fixed), no SRT
468 *first_child = ((StgMutVar *)c)->var;
471 *first_child = ((StgSelector *)c)->selectee;
474 case IND_OLDGEN_PERM:
476 *first_child = ((StgInd *)c)->indirectee;
480 *first_child = c->payload[0];
483 // For CONSTR_2_0 and MVAR, we use se.info.step to record the position
484 // of the next child. We do not write a separate initialization code.
485 // Also we do not have to initialize info.type;
487 // two children (fixed), no SRT
488 // need to push a stackElement, but nothing to store in se.info
490 *first_child = c->payload[0]; // return the first pointer
491 // se.info.type = posTypeStep;
492 // se.info.next.step = 2; // 2 = second
495 // three children (fixed), no SRT
496 // need to push a stackElement
498 // head must be TSO and the head of a linked list of TSOs.
499 // Shoule it be a child? Seems to be yes.
500 *first_child = (StgClosure *)((StgMVar *)c)->head;
501 // se.info.type = posTypeStep;
502 se.info.next.step = 2; // 2 = second
505 // three children (fixed), no SRT
507 *first_child = ((StgWeak *)c)->key;
508 // se.info.type = posTypeStep;
509 se.info.next.step = 2;
512 // layout.payload.ptrs, no SRT
517 init_ptrs(&se.info, get_itbl(c)->layout.payload.ptrs,
519 *first_child = find_ptrs(&se.info);
520 if (*first_child == NULL)
524 // StgMutArrPtr.ptrs, no SRT
525 case MUT_ARR_PTRS_CLEAN:
526 case MUT_ARR_PTRS_DIRTY:
527 case MUT_ARR_PTRS_FROZEN:
528 case MUT_ARR_PTRS_FROZEN0:
529 init_ptrs(&se.info, ((StgMutArrPtrs *)c)->ptrs,
530 (StgPtr)(((StgMutArrPtrs *)c)->payload));
531 *first_child = find_ptrs(&se.info);
532 if (*first_child == NULL)
536 // layout.payload.ptrs, SRT
537 case FUN: // *c is a heap object.
539 init_ptrs(&se.info, get_itbl(c)->layout.payload.ptrs, (StgPtr)c->payload);
540 *first_child = find_ptrs(&se.info);
541 if (*first_child == NULL)
542 // no child from ptrs, so check SRT
548 init_ptrs(&se.info, get_itbl(c)->layout.payload.ptrs,
549 (StgPtr)((StgThunk *)c)->payload);
550 *first_child = find_ptrs(&se.info);
551 if (*first_child == NULL)
552 // no child from ptrs, so check SRT
556 // 1 fixed child, SRT
559 *first_child = c->payload[0];
560 ASSERT(*first_child != NULL);
561 init_srt_fun(&se.info, get_fun_itbl(c));
566 *first_child = ((StgThunk *)c)->payload[0];
567 ASSERT(*first_child != NULL);
568 init_srt_thunk(&se.info, get_thunk_itbl(c));
571 case FUN_STATIC: // *c is a heap object.
572 ASSERT(get_itbl(c)->srt_bitmap != 0);
576 init_srt_fun(&se.info, get_fun_itbl(c));
577 *first_child = find_srt(&se.info);
578 if (*first_child == NULL)
584 ASSERT(get_itbl(c)->srt_bitmap != 0);
588 init_srt_thunk(&se.info, get_thunk_itbl(c));
589 *first_child = find_srt(&se.info);
590 if (*first_child == NULL)
594 case TVAR_WAIT_QUEUE:
595 *first_child = (StgClosure *)((StgTVarWaitQueue *)c)->waiting_tso;
596 se.info.next.step = 2; // 2 = second
599 *first_child = (StgClosure *)((StgTVar *)c)->current_value;
602 *first_child = (StgClosure *)((StgTRecHeader *)c)->enclosing_trec;
605 *first_child = (StgClosure *)((StgTRecChunk *)c)->prev_chunk;
606 se.info.next.step = 0; // entry no.
615 case CONSTR_NOCAF_STATIC:
636 barf("Invalid object *c in push()");
640 if (stackTop - 1 < stackBottom) {
641 #ifdef DEBUG_RETAINER
642 // debugBelch("push() to the next stack.\n");
644 // currentStack->free is updated when the active stack is switched
645 // to the next stack.
646 currentStack->free = (StgPtr)stackTop;
648 if (currentStack->link == NULL) {
649 nbd = allocGroup(BLOCKS_IN_STACK);
651 nbd->u.back = currentStack;
652 currentStack->link = nbd;
654 nbd = currentStack->link;
659 // adjust stackTop (acutal push)
661 // If the size of stackElement was huge, we would better replace the
662 // following statement by either a memcpy() call or a switch statement
663 // on the type of the element. Currently, the size of stackElement is
664 // small enough (5 words) that this direct assignment seems to be enough.
667 #ifdef DEBUG_RETAINER
669 if (stackSize > maxStackSize) maxStackSize = stackSize;
670 // ASSERT(stackSize >= 0);
671 // debugBelch("stackSize = %d\n", stackSize);
675 /* -----------------------------------------------------------------------------
676 * popOff() and popOffReal(): Pop a stackElement off the traverse stack.
678 * stackTop cannot be equal to stackLimit unless the whole stack is
679 * empty, in which case popOff() is not allowed.
681 * You can think of popOffReal() as a part of popOff() which is
682 * executed at the end of popOff() in necessary. Since popOff() is
683 * likely to be executed quite often while popOffReal() is not, we
684 * separate popOffReal() from popOff(), which is declared as an
685 * INLINE function (for the sake of execution speed). popOffReal()
686 * is called only within popOff() and nowhere else.
687 * -------------------------------------------------------------------------- */
691 bdescr *pbd; // Previous Block Descriptor
693 #ifdef DEBUG_RETAINER
694 // debugBelch("pop() to the previous stack.\n");
697 ASSERT(stackTop + 1 == stackLimit);
698 ASSERT(stackBottom == (stackElement *)currentStack->start);
700 if (firstStack == currentStack) {
701 // The stack is completely empty.
703 ASSERT(stackTop == stackLimit);
704 #ifdef DEBUG_RETAINER
706 if (stackSize > maxStackSize) maxStackSize = stackSize;
708 ASSERT(stackSize >= 0);
709 debugBelch("stackSize = %d\n", stackSize);
715 // currentStack->free is updated when the active stack is switched back
716 // to the previous stack.
717 currentStack->free = (StgPtr)stackLimit;
719 // find the previous block descriptor
720 pbd = currentStack->u.back;
723 returnToOldStack(pbd);
725 #ifdef DEBUG_RETAINER
727 if (stackSize > maxStackSize) maxStackSize = stackSize;
729 ASSERT(stackSize >= 0);
730 debugBelch("stackSize = %d\n", stackSize);
737 #ifdef DEBUG_RETAINER
738 // debugBelch("\tpopOff(): stackTop = 0x%x, currentStackBoundary = 0x%x\n", stackTop, currentStackBoundary);
741 ASSERT(stackTop != stackLimit);
742 ASSERT(!isEmptyRetainerStack());
744 // <= (instead of <) is wrong!
745 if (stackTop + 1 < stackLimit) {
747 #ifdef DEBUG_RETAINER
749 if (stackSize > maxStackSize) maxStackSize = stackSize;
751 ASSERT(stackSize >= 0);
752 debugBelch("stackSize = %d\n", stackSize);
761 /* -----------------------------------------------------------------------------
762 * Finds the next object to be considered for retainer profiling and store
764 * Test if the topmost stack element indicates that more objects are left,
765 * and if so, retrieve the first object and store its pointer to *c. Also,
766 * set *cp and *r appropriately, both of which are stored in the stack element.
767 * The topmost stack element then is overwritten so as for it to now denote
769 * If the topmost stack element indicates no more objects are left, pop
770 * off the stack element until either an object can be retrieved or
771 * the current stack chunk becomes empty, indicated by rtsTrue returned by
772 * isOnBoundary(), in which case *c is set to NULL.
774 * It is okay to call this function even when the current stack chunk
776 * -------------------------------------------------------------------------- */
778 pop( StgClosure **c, StgClosure **cp, retainer *r )
782 #ifdef DEBUG_RETAINER
783 // debugBelch("pop(): stackTop = 0x%x, currentStackBoundary = 0x%x\n", stackTop, currentStackBoundary);
787 if (isOnBoundary()) { // if the current stack chunk is depleted
794 switch (get_itbl(se->c)->type) {
795 // two children (fixed), no SRT
796 // nothing in se.info
798 *c = se->c->payload[1];
804 // three children (fixed), no SRT
805 // need to push a stackElement
807 if (se->info.next.step == 2) {
808 *c = (StgClosure *)((StgMVar *)se->c)->tail;
809 se->info.next.step++; // move to the next step
812 *c = ((StgMVar *)se->c)->value;
819 // three children (fixed), no SRT
821 if (se->info.next.step == 2) {
822 *c = ((StgWeak *)se->c)->value;
823 se->info.next.step++;
826 *c = ((StgWeak *)se->c)->finalizer;
833 case TVAR_WAIT_QUEUE:
834 if (se->info.next.step == 2) {
835 *c = (StgClosure *)((StgTVarWaitQueue *)se->c)->next_queue_entry;
836 se->info.next.step++; // move to the next step
839 *c = (StgClosure *)((StgTVarWaitQueue *)se->c)->prev_queue_entry;
847 *c = (StgClosure *)((StgTVar *)se->c)->first_wait_queue_entry;
854 *c = (StgClosure *)((StgTRecHeader *)se->c)->current_chunk;
861 // These are pretty complicated: we have N entries, each
862 // of which contains 3 fields that we want to follow. So
863 // we divide the step counter: the 2 low bits indicate
864 // which field, and the rest of the bits indicate the
865 // entry number (starting from zero).
866 nat entry_no = se->info.next.step >> 2;
867 nat field_no = se->info.next.step & 3;
868 if (entry_no == ((StgTRecChunk *)se->c)->next_entry_idx) {
873 TRecEntry *entry = &((StgTRecChunk *)se->c)->entries[entry_no];
875 *c = (StgClosure *)entry->tvar;
876 } else if (field_no == 1) {
877 *c = entry->expected_value;
879 *c = entry->new_value;
883 se->info.next.step++;
891 // StgMutArrPtr.ptrs, no SRT
892 case MUT_ARR_PTRS_CLEAN:
893 case MUT_ARR_PTRS_DIRTY:
894 case MUT_ARR_PTRS_FROZEN:
895 case MUT_ARR_PTRS_FROZEN0:
896 *c = find_ptrs(&se->info);
905 // layout.payload.ptrs, SRT
906 case FUN: // always a heap object
908 if (se->info.type == posTypePtrs) {
909 *c = find_ptrs(&se->info);
915 init_srt_fun(&se->info, get_fun_itbl(se->c));
921 if (se->info.type == posTypePtrs) {
922 *c = find_ptrs(&se->info);
928 init_srt_thunk(&se->info, get_thunk_itbl(se->c));
944 *c = find_srt(&se->info);
953 // no child (fixed), no SRT
959 case SE_CAF_BLACKHOLE:
961 // one child (fixed), no SRT
966 case IND_OLDGEN_PERM:
975 case CONSTR_NOCAF_STATIC:
996 barf("Invalid object *c in pop()");
1002 /* -----------------------------------------------------------------------------
1003 * RETAINER PROFILING ENGINE
1004 * -------------------------------------------------------------------------- */
1007 initRetainerProfiling( void )
1009 initializeAllRetainerSet();
1010 retainerGeneration = 0;
1013 /* -----------------------------------------------------------------------------
1014 * This function must be called before f-closing prof_file.
1015 * -------------------------------------------------------------------------- */
1017 endRetainerProfiling( void )
1019 #ifdef SECOND_APPROACH
1020 outputAllRetainerSet(prof_file);
1024 /* -----------------------------------------------------------------------------
1025 * Returns the actual pointer to the retainer set of the closure *c.
1026 * It may adjust RSET(c) subject to flip.
1028 * RSET(c) is initialized to NULL if its current value does not
1031 * Even though this function has side effects, they CAN be ignored because
1032 * subsequent calls to retainerSetOf() always result in the same return value
1033 * and retainerSetOf() is the only way to retrieve retainerSet of a given
1035 * We have to perform an XOR (^) operation each time a closure is examined.
1036 * The reason is that we do not know when a closure is visited last.
1037 * -------------------------------------------------------------------------- */
1039 maybeInitRetainerSet( StgClosure *c )
1041 if (!isRetainerSetFieldValid(c)) {
1042 setRetainerSetToNull(c);
1046 /* -----------------------------------------------------------------------------
1047 * Returns rtsTrue if *c is a retainer.
1048 * -------------------------------------------------------------------------- */
1049 static INLINE rtsBool
1050 isRetainer( StgClosure *c )
1052 switch (get_itbl(c)->type) {
1056 // TSOs MUST be retainers: they constitute the set of roots.
1063 case MUT_ARR_PTRS_CLEAN:
1064 case MUT_ARR_PTRS_DIRTY:
1065 case MUT_ARR_PTRS_FROZEN:
1066 case MUT_ARR_PTRS_FROZEN0:
1068 // thunks are retainers.
1075 case THUNK_SELECTOR:
1079 // Static thunks, or CAFS, are obviously retainers.
1082 // WEAK objects are roots; there is separate code in which traversing
1083 // begins from WEAK objects.
1086 // Since the other mutvar-type things are retainers, seems
1087 // like the right thing to do:
1109 // partial applications
1115 case SE_CAF_BLACKHOLE:
1118 case IND_OLDGEN_PERM:
1128 case TVAR_WAIT_QUEUE:
1136 // IND_STATIC cannot be *c, *cp, *r in the retainer profiling loop.
1138 // CONSTR_NOCAF_STATIC
1139 // cannot be *c, *cp, *r in the retainer profiling loop.
1140 case CONSTR_NOCAF_STATIC:
1141 // Stack objects are invalid because they are never treated as
1142 // legal objects during retainer profiling.
1160 case INVALID_OBJECT:
1162 barf("Invalid object in isRetainer(): %d", get_itbl(c)->type);
1167 /* -----------------------------------------------------------------------------
1168 * Returns the retainer function value for the closure *c, i.e., R(*c).
1169 * This function does NOT return the retainer(s) of *c.
1171 * *c must be a retainer.
1173 * Depending on the definition of this function, the maintenance of retainer
1174 * sets can be made easier. If most retainer sets are likely to be created
1175 * again across garbage collections, refreshAllRetainerSet() in
1176 * RetainerSet.c can simply do nothing.
1177 * If this is not the case, we can free all the retainer sets and
1178 * re-initialize the hash table.
1179 * See refreshAllRetainerSet() in RetainerSet.c.
1180 * -------------------------------------------------------------------------- */
1181 static INLINE retainer
1182 getRetainerFrom( StgClosure *c )
1184 ASSERT(isRetainer(c));
1186 #if defined(RETAINER_SCHEME_INFO)
1187 // Retainer scheme 1: retainer = info table
1189 #elif defined(RETAINER_SCHEME_CCS)
1190 // Retainer scheme 2: retainer = cost centre stack
1191 return c->header.prof.ccs;
1192 #elif defined(RETAINER_SCHEME_CC)
1193 // Retainer scheme 3: retainer = cost centre
1194 return c->header.prof.ccs->cc;
1198 /* -----------------------------------------------------------------------------
1199 * Associates the retainer set *s with the closure *c, that is, *s becomes
1200 * the retainer set of *c.
1204 * -------------------------------------------------------------------------- */
1206 associate( StgClosure *c, RetainerSet *s )
1208 // StgWord has the same size as pointers, so the following type
1210 RSET(c) = (RetainerSet *)((StgWord)s | flip);
1213 /* -----------------------------------------------------------------------------
1214 Call retainClosure for each of the closures covered by a large bitmap.
1215 -------------------------------------------------------------------------- */
1218 retain_large_bitmap (StgPtr p, StgLargeBitmap *large_bitmap, nat size,
1219 StgClosure *c, retainer c_child_r)
1225 bitmap = large_bitmap->bitmap[b];
1226 for (i = 0; i < size; ) {
1227 if ((bitmap & 1) == 0) {
1228 retainClosure((StgClosure *)*p, c, c_child_r);
1232 if (i % BITS_IN(W_) == 0) {
1234 bitmap = large_bitmap->bitmap[b];
1236 bitmap = bitmap >> 1;
1241 static INLINE StgPtr
1242 retain_small_bitmap (StgPtr p, nat size, StgWord bitmap,
1243 StgClosure *c, retainer c_child_r)
1246 if ((bitmap & 1) == 0) {
1247 retainClosure((StgClosure *)*p, c, c_child_r);
1250 bitmap = bitmap >> 1;
1256 /* -----------------------------------------------------------------------------
1257 * Call retainClosure for each of the closures in an SRT.
1258 * ------------------------------------------------------------------------- */
1261 retain_large_srt_bitmap (StgLargeSRT *srt, StgClosure *c, retainer c_child_r)
1268 p = (StgClosure **)srt->srt;
1270 bitmap = srt->l.bitmap[b];
1271 for (i = 0; i < size; ) {
1272 if ((bitmap & 1) != 0) {
1273 retainClosure((StgClosure *)*p, c, c_child_r);
1277 if (i % BITS_IN(W_) == 0) {
1279 bitmap = srt->l.bitmap[b];
1281 bitmap = bitmap >> 1;
1287 retainSRT (StgClosure **srt, nat srt_bitmap, StgClosure *c, retainer c_child_r)
1292 bitmap = srt_bitmap;
1295 if (bitmap == (StgHalfWord)(-1)) {
1296 retain_large_srt_bitmap( (StgLargeSRT *)srt, c, c_child_r );
1300 while (bitmap != 0) {
1301 if ((bitmap & 1) != 0) {
1302 #ifdef ENABLE_WIN32_DLL_SUPPORT
1303 if ( (unsigned long)(*srt) & 0x1 ) {
1304 retainClosure(*stgCast(StgClosure**,(stgCast(unsigned long, *srt) & ~0x1)),
1307 retainClosure(*srt,c,c_child_r);
1310 retainClosure(*srt,c,c_child_r);
1314 bitmap = bitmap >> 1;
1318 /* -----------------------------------------------------------------------------
1319 * Process all the objects in the stack chunk from stackStart to stackEnd
1320 * with *c and *c_child_r being their parent and their most recent retainer,
1321 * respectively. Treat stackOptionalFun as another child of *c if it is
1324 * *c is one of the following: TSO, AP_STACK.
1325 * If *c is TSO, c == c_child_r.
1326 * stackStart < stackEnd.
1327 * RSET(c) and RSET(c_child_r) are valid, i.e., their
1328 * interpretation conforms to the current value of flip (even when they
1329 * are interpreted to be NULL).
1330 * If *c is TSO, its state is not any of ThreadRelocated, ThreadComplete,
1331 * or ThreadKilled, which means that its stack is ready to process.
1333 * This code was almost plagiarzied from GC.c! For each pointer,
1334 * retainClosure() is invoked instead of evacuate().
1335 * -------------------------------------------------------------------------- */
1337 retainStack( StgClosure *c, retainer c_child_r,
1338 StgPtr stackStart, StgPtr stackEnd )
1340 stackElement *oldStackBoundary;
1342 StgRetInfoTable *info;
1346 #ifdef DEBUG_RETAINER
1348 if (cStackSize > maxCStackSize) maxCStackSize = cStackSize;
1352 Each invocation of retainStack() creates a new virtual
1353 stack. Since all such stacks share a single common stack, we
1354 record the current currentStackBoundary, which will be restored
1357 oldStackBoundary = currentStackBoundary;
1358 currentStackBoundary = stackTop;
1360 #ifdef DEBUG_RETAINER
1361 // debugBelch("retainStack() called: oldStackBoundary = 0x%x, currentStackBoundary = 0x%x\n", oldStackBoundary, currentStackBoundary);
1364 ASSERT(get_itbl(c)->type != TSO ||
1365 (((StgTSO *)c)->what_next != ThreadRelocated &&
1366 ((StgTSO *)c)->what_next != ThreadComplete &&
1367 ((StgTSO *)c)->what_next != ThreadKilled));
1370 while (p < stackEnd) {
1371 info = get_ret_itbl((StgClosure *)p);
1373 switch(info->i.type) {
1376 retainClosure(((StgUpdateFrame *)p)->updatee, c, c_child_r);
1377 p += sizeofW(StgUpdateFrame);
1382 case CATCH_STM_FRAME:
1383 case CATCH_RETRY_FRAME:
1384 case ATOMICALLY_FRAME:
1387 bitmap = BITMAP_BITS(info->i.layout.bitmap);
1388 size = BITMAP_SIZE(info->i.layout.bitmap);
1390 p = retain_small_bitmap(p, size, bitmap, c, c_child_r);
1393 retainSRT((StgClosure **)GET_SRT(info), info->i.srt_bitmap, c, c_child_r);
1400 retainClosure((StgClosure *)*p, c, c_child_r);
1403 size = BCO_BITMAP_SIZE(bco);
1404 retain_large_bitmap(p, BCO_BITMAP(bco), size, c, c_child_r);
1409 // large bitmap (> 32 entries, or > 64 on a 64-bit machine)
1412 size = GET_LARGE_BITMAP(&info->i)->size;
1414 retain_large_bitmap(p, GET_LARGE_BITMAP(&info->i),
1415 size, c, c_child_r);
1417 // and don't forget to follow the SRT
1420 // Dynamic bitmap: the mask is stored on the stack
1423 dyn = ((StgRetDyn *)p)->liveness;
1425 // traverse the bitmap first
1426 bitmap = RET_DYN_LIVENESS(dyn);
1427 p = (P_)&((StgRetDyn *)p)->payload[0];
1428 size = RET_DYN_BITMAP_SIZE;
1429 p = retain_small_bitmap(p, size, bitmap, c, c_child_r);
1431 // skip over the non-ptr words
1432 p += RET_DYN_NONPTRS(dyn) + RET_DYN_NONPTR_REGS_SIZE;
1434 // follow the ptr words
1435 for (size = RET_DYN_PTRS(dyn); size > 0; size--) {
1436 retainClosure((StgClosure *)*p, c, c_child_r);
1443 StgRetFun *ret_fun = (StgRetFun *)p;
1444 StgFunInfoTable *fun_info;
1446 retainClosure(ret_fun->fun, c, c_child_r);
1447 fun_info = get_fun_itbl(ret_fun->fun);
1449 p = (P_)&ret_fun->payload;
1450 switch (fun_info->f.fun_type) {
1452 bitmap = BITMAP_BITS(fun_info->f.b.bitmap);
1453 size = BITMAP_SIZE(fun_info->f.b.bitmap);
1454 p = retain_small_bitmap(p, size, bitmap, c, c_child_r);
1457 size = GET_FUN_LARGE_BITMAP(fun_info)->size;
1458 retain_large_bitmap(p, GET_FUN_LARGE_BITMAP(fun_info),
1459 size, c, c_child_r);
1463 bitmap = BITMAP_BITS(stg_arg_bitmaps[fun_info->f.fun_type]);
1464 size = BITMAP_SIZE(stg_arg_bitmaps[fun_info->f.fun_type]);
1465 p = retain_small_bitmap(p, size, bitmap, c, c_child_r);
1472 barf("Invalid object found in retainStack(): %d",
1473 (int)(info->i.type));
1477 // restore currentStackBoundary
1478 currentStackBoundary = oldStackBoundary;
1479 #ifdef DEBUG_RETAINER
1480 // debugBelch("retainStack() finished: currentStackBoundary = 0x%x\n", currentStackBoundary);
1483 #ifdef DEBUG_RETAINER
1488 /* ----------------------------------------------------------------------------
1489 * Call retainClosure for each of the children of a PAP/AP
1490 * ------------------------------------------------------------------------- */
1492 static INLINE StgPtr
1493 retain_PAP_payload (StgClosure *pap, retainer c_child_r, StgClosure *fun,
1494 StgClosure** payload, StgWord n_args)
1498 StgFunInfoTable *fun_info;
1500 retainClosure(fun, pap, c_child_r);
1501 fun_info = get_fun_itbl(fun);
1502 ASSERT(fun_info->i.type != PAP);
1504 p = (StgPtr)payload;
1506 switch (fun_info->f.fun_type) {
1508 bitmap = BITMAP_BITS(fun_info->f.b.bitmap);
1509 p = retain_small_bitmap(p, n_args, bitmap,
1513 retain_large_bitmap(p, GET_FUN_LARGE_BITMAP(fun_info),
1514 n_args, pap, c_child_r);
1518 retain_large_bitmap((StgPtr)payload, BCO_BITMAP(fun),
1519 n_args, pap, c_child_r);
1523 bitmap = BITMAP_BITS(stg_arg_bitmaps[fun_info->f.fun_type]);
1524 p = retain_small_bitmap(p, n_args, bitmap, pap, c_child_r);
1530 /* -----------------------------------------------------------------------------
1531 * Compute the retainer set of *c0 and all its desecents by traversing.
1532 * *cp0 is the parent of *c0, and *r0 is the most recent retainer of *c0.
1534 * c0 = cp0 = r0 holds only for root objects.
1535 * RSET(cp0) and RSET(r0) are valid, i.e., their
1536 * interpretation conforms to the current value of flip (even when they
1537 * are interpreted to be NULL).
1538 * However, RSET(c0) may be corrupt, i.e., it may not conform to
1539 * the current value of flip. If it does not, during the execution
1540 * of this function, RSET(c0) must be initialized as well as all
1543 * stackTop must be the same at the beginning and the exit of this function.
1544 * *c0 can be TSO (as well as AP_STACK).
1545 * -------------------------------------------------------------------------- */
1547 retainClosure( StgClosure *c0, StgClosure *cp0, retainer r0 )
1549 // c = Current closure
1550 // cp = Current closure's Parent
1551 // r = current closures' most recent Retainer
1552 // c_child_r = current closure's children's most recent retainer
1553 // first_child = first child of c
1554 StgClosure *c, *cp, *first_child;
1555 RetainerSet *s, *retainerSetOfc;
1556 retainer r, c_child_r;
1559 #ifdef DEBUG_RETAINER
1560 // StgPtr oldStackTop;
1563 #ifdef DEBUG_RETAINER
1564 // oldStackTop = stackTop;
1565 // debugBelch("retainClosure() called: c0 = 0x%x, cp0 = 0x%x, r0 = 0x%x\n", c0, cp0, r0);
1568 // (c, cp, r) = (c0, cp0, r0)
1575 //debugBelch("loop");
1576 // pop to (c, cp, r);
1580 #ifdef DEBUG_RETAINER
1581 // debugBelch("retainClosure() ends: oldStackTop = 0x%x, stackTop = 0x%x\n", oldStackTop, stackTop);
1586 //debugBelch("inner_loop");
1589 // c = current closure under consideration,
1590 // cp = current closure's parent,
1591 // r = current closure's most recent retainer
1593 // Loop invariants (on the meaning of c, cp, r, and their retainer sets):
1594 // RSET(cp) and RSET(r) are valid.
1595 // RSET(c) is valid only if c has been visited before.
1597 // Loop invariants (on the relation between c, cp, and r)
1598 // if cp is not a retainer, r belongs to RSET(cp).
1599 // if cp is a retainer, r == cp.
1601 typeOfc = get_itbl(c)->type;
1603 #ifdef DEBUG_RETAINER
1606 case CONSTR_NOCAF_STATIC:
1612 if (retainerSetOf(c) == NULL) { // first visit?
1613 costArray[typeOfc] += cost(c);
1614 sumOfNewCost += cost(c);
1623 if (((StgTSO *)c)->what_next == ThreadComplete ||
1624 ((StgTSO *)c)->what_next == ThreadKilled) {
1625 #ifdef DEBUG_RETAINER
1626 debugBelch("ThreadComplete or ThreadKilled encountered in retainClosure()\n");
1630 if (((StgTSO *)c)->what_next == ThreadRelocated) {
1631 #ifdef DEBUG_RETAINER
1632 debugBelch("ThreadRelocated encountered in retainClosure()\n");
1634 c = (StgClosure *)((StgTSO *)c)->link;
1640 // We just skip IND_STATIC, so its retainer set is never computed.
1641 c = ((StgIndStatic *)c)->indirectee;
1643 // static objects with no pointers out, so goto loop.
1644 case CONSTR_NOCAF_STATIC:
1645 // It is not just enough not to compute the retainer set for *c; it is
1646 // mandatory because CONSTR_NOCAF_STATIC are not reachable from
1647 // scavenged_static_objects, the list from which is assumed to traverse
1648 // all static objects after major garbage collections.
1652 if (get_itbl(c)->srt_bitmap == 0) {
1653 // No need to compute the retainer set; no dynamic objects
1654 // are reachable from *c.
1656 // Static objects: if we traverse all the live closures,
1657 // including static closures, during each heap census then
1658 // we will observe that some static closures appear and
1659 // disappear. eg. a closure may contain a pointer to a
1660 // static function 'f' which is not otherwise reachable
1661 // (it doesn't indirectly point to any CAFs, so it doesn't
1662 // appear in any SRTs), so we would find 'f' during
1663 // traversal. However on the next sweep there may be no
1664 // closures pointing to 'f'.
1666 // We must therefore ignore static closures whose SRT is
1667 // empty, because these are exactly the closures that may
1668 // "appear". A closure with a non-empty SRT, and which is
1669 // still required, will always be reachable.
1671 // But what about CONSTR_STATIC? Surely these may be able
1672 // to appear, and they don't have SRTs, so we can't
1673 // check. So for now, we're calling
1674 // resetStaticObjectForRetainerProfiling() from the
1675 // garbage collector to reset the retainer sets in all the
1676 // reachable static objects.
1683 // The above objects are ignored in computing the average number of times
1684 // an object is visited.
1685 timesAnyObjectVisited++;
1687 // If this is the first visit to c, initialize its retainer set.
1688 maybeInitRetainerSet(c);
1689 retainerSetOfc = retainerSetOf(c);
1692 // isRetainer(cp) == rtsTrue => s == NULL
1693 // isRetainer(cp) == rtsFalse => s == cp.retainer
1697 s = retainerSetOf(cp);
1699 // (c, cp, r, s) is available.
1701 // (c, cp, r, s, R_r) is available, so compute the retainer set for *c.
1702 if (retainerSetOfc == NULL) {
1703 // This is the first visit to *c.
1707 associate(c, singleton(r));
1709 // s is actually the retainer set of *c!
1712 // compute c_child_r
1713 c_child_r = isRetainer(c) ? getRetainerFrom(c) : r;
1715 // This is not the first visit to *c.
1716 if (isMember(r, retainerSetOfc))
1717 goto loop; // no need to process child
1720 associate(c, addElement(r, retainerSetOfc));
1722 // s is not NULL and cp is not a retainer. This means that
1723 // each time *cp is visited, so is *c. Thus, if s has
1724 // exactly one more element in its retainer set than c, s
1725 // is also the new retainer set for *c.
1726 if (s->num == retainerSetOfc->num + 1) {
1729 // Otherwise, just add R_r to the current retainer set of *c.
1731 associate(c, addElement(r, retainerSetOfc));
1736 goto loop; // no need to process child
1738 // compute c_child_r
1742 // now, RSET() of all of *c, *cp, and *r is valid.
1743 // (c, c_child_r) are available.
1747 // Special case closures: we process these all in one go rather
1748 // than attempting to save the current position, because doing so
1752 retainStack(c, c_child_r,
1754 ((StgTSO *)c)->stack + ((StgTSO *)c)->stack_size);
1759 StgPAP *pap = (StgPAP *)c;
1760 retain_PAP_payload(c, c_child_r, pap->fun, pap->payload, pap->n_args);
1766 StgAP *ap = (StgAP *)c;
1767 retain_PAP_payload(c, c_child_r, ap->fun, ap->payload, ap->n_args);
1772 retainClosure(((StgAP_STACK *)c)->fun, c, c_child_r);
1773 retainStack(c, c_child_r,
1774 (StgPtr)((StgAP_STACK *)c)->payload,
1775 (StgPtr)((StgAP_STACK *)c)->payload +
1776 ((StgAP_STACK *)c)->size);
1780 push(c, c_child_r, &first_child);
1782 // If first_child is null, c has no child.
1783 // If first_child is not null, the top stack element points to the next
1784 // object. push() may or may not push a stackElement on the stack.
1785 if (first_child == NULL)
1788 // (c, cp, r) = (first_child, c, c_child_r)
1795 /* -----------------------------------------------------------------------------
1796 * Compute the retainer set for every object reachable from *tl.
1797 * -------------------------------------------------------------------------- */
1799 retainRoot( StgClosure **tl )
1801 // We no longer assume that only TSOs and WEAKs are roots; any closure can
1804 ASSERT(isEmptyRetainerStack());
1805 currentStackBoundary = stackTop;
1807 if (*tl != &stg_END_TSO_QUEUE_closure && isRetainer(*tl)) {
1808 retainClosure(*tl, *tl, getRetainerFrom(*tl));
1810 retainClosure(*tl, *tl, CCS_SYSTEM);
1813 // NOT TRUE: ASSERT(isMember(getRetainerFrom(*tl), retainerSetOf(*tl)));
1814 // *tl might be a TSO which is ThreadComplete, in which
1815 // case we ignore it for the purposes of retainer profiling.
1818 /* -----------------------------------------------------------------------------
1819 * Compute the retainer set for each of the objects in the heap.
1820 * -------------------------------------------------------------------------- */
1822 computeRetainerSet( void )
1829 #ifdef DEBUG_RETAINER
1830 RetainerSet tmpRetainerSet;
1833 GetRoots(retainRoot); // for scheduler roots
1835 // This function is called after a major GC, when key, value, and finalizer
1836 // all are guaranteed to be valid, or reachable.
1838 // The following code assumes that WEAK objects are considered to be roots
1839 // for retainer profilng.
1840 for (weak = weak_ptr_list; weak != NULL; weak = weak->link)
1841 // retainRoot((StgClosure *)weak);
1842 retainRoot((StgClosure **)&weak);
1844 // Consider roots from the stable ptr table.
1845 markStablePtrTable(retainRoot);
1847 // The following code resets the rs field of each unvisited mutable
1848 // object (computing sumOfNewCostExtra and updating costArray[] when
1849 // debugging retainer profiler).
1850 for (g = 0; g < RtsFlags.GcFlags.generations; g++) {
1851 // NOT TRUE: even G0 has a block on its mutable list
1852 // ASSERT(g != 0 || (generations[g].mut_list == NULL));
1854 // Traversing through mut_list is necessary
1855 // because we can find MUT_VAR objects which have not been
1856 // visited during retainer profiling.
1857 for (bd = generations[g].mut_list; bd != NULL; bd = bd->link) {
1858 for (ml = bd->start; ml < bd->free; ml++) {
1860 maybeInitRetainerSet((StgClosure *)*ml);
1861 rtl = retainerSetOf((StgClosure *)*ml);
1863 #ifdef DEBUG_RETAINER
1865 // first visit to *ml
1866 // This is a violation of the interface rule!
1867 RSET(ml) = (RetainerSet *)((StgWord)(&tmpRetainerSet) | flip);
1869 switch (get_itbl((StgClosure *)ml)->type) {
1873 case CONSTR_NOCAF_STATIC:
1877 barf("Invalid object in computeRetainerSet(): %d", get_itbl((StgClosure*)ml)->type);
1881 costArray[get_itbl((StgClosure *)ml)->type] += cost((StgClosure *)ml);
1882 sumOfNewCostExtra += cost((StgClosure *)ml);
1892 /* -----------------------------------------------------------------------------
1893 * Traverse all static objects for which we compute retainer sets,
1894 * and reset their rs fields to NULL, which is accomplished by
1895 * invoking maybeInitRetainerSet(). This function must be called
1896 * before zeroing all objects reachable from scavenged_static_objects
1897 * in the case of major gabage collections. See GarbageCollect() in
1900 * The mut_once_list of the oldest generation must also be traversed?
1901 * Why? Because if the evacuation of an object pointed to by a static
1902 * indirection object fails, it is put back to the mut_once_list of
1903 * the oldest generation.
1904 * However, this is not necessary because any static indirection objects
1905 * are just traversed through to reach dynamic objects. In other words,
1906 * they are not taken into consideration in computing retainer sets.
1907 * -------------------------------------------------------------------------- */
1909 resetStaticObjectForRetainerProfiling( void )
1911 #ifdef DEBUG_RETAINER
1916 #ifdef DEBUG_RETAINER
1919 p = scavenged_static_objects;
1920 while (p != END_OF_STATIC_LIST) {
1921 #ifdef DEBUG_RETAINER
1924 switch (get_itbl(p)->type) {
1926 // Since we do not compute the retainer set of any
1927 // IND_STATIC object, we don't have to reset its retainer
1929 p = (StgClosure*)*IND_STATIC_LINK(p);
1932 maybeInitRetainerSet(p);
1933 p = (StgClosure*)*THUNK_STATIC_LINK(p);
1936 maybeInitRetainerSet(p);
1937 p = (StgClosure*)*FUN_STATIC_LINK(p);
1940 maybeInitRetainerSet(p);
1941 p = (StgClosure*)*STATIC_LINK(get_itbl(p), p);
1944 barf("resetStaticObjectForRetainerProfiling: %p (%s)",
1945 p, get_itbl(p)->type);
1949 #ifdef DEBUG_RETAINER
1950 // debugBelch("count in scavenged_static_objects = %d\n", count);
1954 /* -----------------------------------------------------------------------------
1955 * Perform retainer profiling.
1956 * N is the oldest generation being profilied, where the generations are
1957 * numbered starting at 0.
1960 * This function should be called only immediately after major garbage
1962 * ------------------------------------------------------------------------- */
1964 retainerProfile(void)
1966 #ifdef DEBUG_RETAINER
1968 nat totalHeapSize; // total raw heap size (computed by linear scanning)
1971 #ifdef DEBUG_RETAINER
1972 debugBelch(" < retainerProfile() invoked : %d>\n", retainerGeneration);
1977 // We haven't flipped the bit yet.
1978 #ifdef DEBUG_RETAINER
1979 debugBelch("Before traversing:\n");
1980 sumOfCostLinear = 0;
1981 for (i = 0;i < N_CLOSURE_TYPES; i++)
1982 costArrayLinear[i] = 0;
1983 totalHeapSize = checkHeapSanityForRetainerProfiling();
1985 debugBelch("\tsumOfCostLinear = %d, totalHeapSize = %d\n", sumOfCostLinear, totalHeapSize);
1987 debugBelch("costArrayLinear[] = ");
1988 for (i = 0;i < N_CLOSURE_TYPES; i++)
1989 debugBelch("[%u:%u] ", i, costArrayLinear[i]);
1993 ASSERT(sumOfCostLinear == totalHeapSize);
1996 #define pcostArrayLinear(index) \
1997 if (costArrayLinear[index] > 0) \
1998 debugBelch("costArrayLinear[" #index "] = %u\n", costArrayLinear[index])
1999 pcostArrayLinear(THUNK_STATIC);
2000 pcostArrayLinear(FUN_STATIC);
2001 pcostArrayLinear(CONSTR_STATIC);
2002 pcostArrayLinear(CONSTR_NOCAF_STATIC);
2006 // Now we flips flip.
2009 #ifdef DEBUG_RETAINER
2015 numObjectVisited = 0;
2016 timesAnyObjectVisited = 0;
2018 #ifdef DEBUG_RETAINER
2019 debugBelch("During traversing:\n");
2021 sumOfNewCostExtra = 0;
2022 for (i = 0;i < N_CLOSURE_TYPES; i++)
2027 We initialize the traverse stack each time the retainer profiling is
2028 performed (because the traverse stack size varies on each retainer profiling
2029 and this operation is not costly anyhow). However, we just refresh the
2032 initializeTraverseStack();
2033 #ifdef DEBUG_RETAINER
2034 initializeAllRetainerSet();
2036 refreshAllRetainerSet();
2038 computeRetainerSet();
2040 #ifdef DEBUG_RETAINER
2041 debugBelch("After traversing:\n");
2042 sumOfCostLinear = 0;
2043 for (i = 0;i < N_CLOSURE_TYPES; i++)
2044 costArrayLinear[i] = 0;
2045 totalHeapSize = checkHeapSanityForRetainerProfiling();
2047 debugBelch("\tsumOfCostLinear = %d, totalHeapSize = %d\n", sumOfCostLinear, totalHeapSize);
2048 ASSERT(sumOfCostLinear == totalHeapSize);
2050 // now, compare the two results
2053 costArray[] must be exactly the same as costArrayLinear[].
2055 1) Dead weak pointers, whose type is CONSTR. These objects are not
2056 reachable from any roots.
2058 debugBelch("Comparison:\n");
2059 debugBelch("\tcostArrayLinear[] (must be empty) = ");
2060 for (i = 0;i < N_CLOSURE_TYPES; i++)
2061 if (costArray[i] != costArrayLinear[i])
2062 // nothing should be printed except MUT_VAR after major GCs
2063 debugBelch("[%u:%u] ", i, costArrayLinear[i]);
2066 debugBelch("\tsumOfNewCost = %u\n", sumOfNewCost);
2067 debugBelch("\tsumOfNewCostExtra = %u\n", sumOfNewCostExtra);
2068 debugBelch("\tcostArray[] (must be empty) = ");
2069 for (i = 0;i < N_CLOSURE_TYPES; i++)
2070 if (costArray[i] != costArrayLinear[i])
2071 // nothing should be printed except MUT_VAR after major GCs
2072 debugBelch("[%u:%u] ", i, costArray[i]);
2075 // only for major garbage collection
2076 ASSERT(sumOfNewCost + sumOfNewCostExtra == sumOfCostLinear);
2080 closeTraverseStack();
2081 #ifdef DEBUG_RETAINER
2082 closeAllRetainerSet();
2084 // Note that there is no post-processing for the retainer sets.
2086 retainerGeneration++;
2089 retainerGeneration - 1, // retainerGeneration has just been incremented!
2090 #ifdef DEBUG_RETAINER
2091 maxCStackSize, maxStackSize,
2093 (double)timesAnyObjectVisited / numObjectVisited);
2096 /* -----------------------------------------------------------------------------
2098 * -------------------------------------------------------------------------- */
2100 #ifdef DEBUG_RETAINER
2102 #define LOOKS_LIKE_PTR(r) ((LOOKS_LIKE_STATIC_CLOSURE(r) || \
2103 ((HEAP_ALLOCED(r) && ((Bdescr((P_)r)->flags & BF_FREE) == 0)))) && \
2104 ((StgWord)(*(StgPtr)r)!=0xaaaaaaaa))
2107 sanityCheckHeapClosure( StgClosure *c )
2111 ASSERT(LOOKS_LIKE_GHC_INFO(c->header.info));
2112 ASSERT(!closure_STATIC(c));
2113 ASSERT(LOOKS_LIKE_PTR(c));
2115 if ((((StgWord)RSET(c) & 1) ^ flip) != 0) {
2116 if (get_itbl(c)->type == CONSTR &&
2117 !strcmp(get_itbl(c)->prof.closure_type, "DEAD_WEAK") &&
2118 !strcmp(get_itbl(c)->prof.closure_desc, "DEAD_WEAK")) {
2119 debugBelch("\tUnvisited dead weak pointer object found: c = %p\n", c);
2120 costArray[get_itbl(c)->type] += cost(c);
2121 sumOfNewCost += cost(c);
2124 "Unvisited object: flip = %d, c = %p(%d, %s, %s), rs = %p\n",
2125 flip, c, get_itbl(c)->type,
2126 get_itbl(c)->prof.closure_type, get_itbl(c)->prof.closure_desc,
2129 // debugBelch("sanityCheckHeapClosure) S: flip = %d, c = %p(%d), rs = %p\n", flip, c, get_itbl(c)->type, RSET(c));
2132 return closure_sizeW(c);
2136 heapCheck( bdescr *bd )
2139 static nat costSum, size;
2142 while (bd != NULL) {
2144 while (p < bd->free) {
2145 size = sanityCheckHeapClosure((StgClosure *)p);
2146 sumOfCostLinear += size;
2147 costArrayLinear[get_itbl((StgClosure *)p)->type] += size;
2149 // no need for slop check; I think slops are not used currently.
2151 ASSERT(p == bd->free);
2152 costSum += bd->free - bd->start;
2160 smallObjectPoolCheck(void)
2164 static nat costSum, size;
2166 bd = small_alloc_list;
2174 while (p < alloc_Hp) {
2175 size = sanityCheckHeapClosure((StgClosure *)p);
2176 sumOfCostLinear += size;
2177 costArrayLinear[get_itbl((StgClosure *)p)->type] += size;
2180 ASSERT(p == alloc_Hp);
2181 costSum += alloc_Hp - bd->start;
2184 while (bd != NULL) {
2186 while (p < bd->free) {
2187 size = sanityCheckHeapClosure((StgClosure *)p);
2188 sumOfCostLinear += size;
2189 costArrayLinear[get_itbl((StgClosure *)p)->type] += size;
2192 ASSERT(p == bd->free);
2193 costSum += bd->free - bd->start;
2201 chainCheck(bdescr *bd)
2206 while (bd != NULL) {
2207 // bd->free - bd->start is not an accurate measurement of the
2208 // object size. Actually it is always zero, so we compute its
2210 size = sanityCheckHeapClosure((StgClosure *)bd->start);
2211 sumOfCostLinear += size;
2212 costArrayLinear[get_itbl((StgClosure *)bd->start)->type] += size;
2221 checkHeapSanityForRetainerProfiling( void )
2226 debugBelch("START: sumOfCostLinear = %d, costSum = %d\n", sumOfCostLinear, costSum);
2227 if (RtsFlags.GcFlags.generations == 1) {
2228 costSum += heapCheck(g0s0->to_blocks);
2229 debugBelch("heapCheck: sumOfCostLinear = %d, costSum = %d\n", sumOfCostLinear, costSum);
2230 costSum += chainCheck(g0s0->large_objects);
2231 debugBelch("chainCheck: sumOfCostLinear = %d, costSum = %d\n", sumOfCostLinear, costSum);
2233 for (g = 0; g < RtsFlags.GcFlags.generations; g++)
2234 for (s = 0; s < generations[g].n_steps; s++) {
2236 After all live objects have been scavenged, the garbage
2237 collector may create some objects in
2238 scheduleFinalizers(). These objects are created throught
2239 allocate(), so the small object pool or the large object
2240 pool of the g0s0 may not be empty.
2242 if (g == 0 && s == 0) {
2243 costSum += smallObjectPoolCheck();
2244 debugBelch("smallObjectPoolCheck(): sumOfCostLinear = %d, costSum = %d\n", sumOfCostLinear, costSum);
2245 costSum += chainCheck(generations[g].steps[s].large_objects);
2246 debugBelch("chainCheck(): sumOfCostLinear = %d, costSum = %d\n", sumOfCostLinear, costSum);
2248 costSum += heapCheck(generations[g].steps[s].blocks);
2249 debugBelch("heapCheck(): sumOfCostLinear = %d, costSum = %d\n", sumOfCostLinear, costSum);
2250 costSum += chainCheck(generations[g].steps[s].large_objects);
2251 debugBelch("chainCheck(): sumOfCostLinear = %d, costSum = %d\n", sumOfCostLinear, costSum);
2260 findPointer(StgPtr p)
2266 for (g = 0; g < RtsFlags.GcFlags.generations; g++) {
2267 for (s = 0; s < generations[g].n_steps; s++) {
2268 // if (g == 0 && s == 0) continue;
2269 bd = generations[g].steps[s].blocks;
2270 for (; bd; bd = bd->link) {
2271 for (q = bd->start; q < bd->free; q++) {
2272 if (*q == (StgWord)p) {
2274 while (!LOOKS_LIKE_GHC_INFO(*r)) r--;
2275 debugBelch("Found in gen[%d], step[%d]: q = %p, r = %p\n", g, s, q, r);
2280 bd = generations[g].steps[s].large_objects;
2281 for (; bd; bd = bd->link) {
2282 e = bd->start + cost((StgClosure *)bd->start);
2283 for (q = bd->start; q < e; q++) {
2284 if (*q == (StgWord)p) {
2286 while (*r == 0 || !LOOKS_LIKE_GHC_INFO(*r)) r--;
2287 debugBelch("Found in gen[%d], large_objects: %p\n", g, r);
2297 belongToHeap(StgPtr p)
2302 for (g = 0; g < RtsFlags.GcFlags.generations; g++) {
2303 for (s = 0; s < generations[g].n_steps; s++) {
2304 // if (g == 0 && s == 0) continue;
2305 bd = generations[g].steps[s].blocks;
2306 for (; bd; bd = bd->link) {
2307 if (bd->start <= p && p < bd->free) {
2308 debugBelch("Belongs to gen[%d], step[%d]", g, s);
2312 bd = generations[g].steps[s].large_objects;
2313 for (; bd; bd = bd->link) {
2314 if (bd->start <= p && p < bd->start + getHeapClosureSize((StgClosure *)bd->start)) {
2315 debugBelch("Found in gen[%d], large_objects: %p\n", g, bd->start);
2322 #endif /* DEBUG_RETAINER */
2324 #endif /* PROFILING */