1 /* -----------------------------------------------------------------------------
3 * (c) The GHC Team 1998-2003
5 * Generational garbage collector
7 * ---------------------------------------------------------------------------*/
9 #include "PosixSource.h"
14 #include "OSThreads.h"
16 #include "LdvProfile.h"
21 #include "BlockAlloc.h"
27 #include "ParTicky.h" // ToDo: move into Rts.h
28 #include "GCCompact.h"
31 #if defined(GRAN) || defined(PAR)
32 # include "GranSimRts.h"
33 # include "ParallelRts.h"
37 # include "ParallelDebug.h"
42 #if defined(RTS_GTK_FRONTPANEL)
43 #include "FrontPanel.h"
46 #include "RetainerProfile.h"
50 // Turn off inlining when debugging - it obfuscates things
53 # define STATIC_INLINE static
56 /* STATIC OBJECT LIST.
59 * We maintain a linked list of static objects that are still live.
60 * The requirements for this list are:
62 * - we need to scan the list while adding to it, in order to
63 * scavenge all the static objects (in the same way that
64 * breadth-first scavenging works for dynamic objects).
66 * - we need to be able to tell whether an object is already on
67 * the list, to break loops.
69 * Each static object has a "static link field", which we use for
70 * linking objects on to the list. We use a stack-type list, consing
71 * objects on the front as they are added (this means that the
72 * scavenge phase is depth-first, not breadth-first, but that
75 * A separate list is kept for objects that have been scavenged
76 * already - this is so that we can zero all the marks afterwards.
78 * An object is on the list if its static link field is non-zero; this
79 * means that we have to mark the end of the list with '1', not NULL.
81 * Extra notes for generational GC:
83 * Each generation has a static object list associated with it. When
84 * collecting generations up to N, we treat the static object lists
85 * from generations > N as roots.
87 * We build up a static object list while collecting generations 0..N,
88 * which is then appended to the static object list of generation N+1.
90 static StgClosure* static_objects; // live static objects
91 StgClosure* scavenged_static_objects; // static objects scavenged so far
93 /* N is the oldest generation being collected, where the generations
94 * are numbered starting at 0. A major GC (indicated by the major_gc
95 * flag) is when we're collecting all generations. We only attempt to
96 * deal with static objects and GC CAFs when doing a major GC.
99 static rtsBool major_gc;
101 /* Youngest generation that objects should be evacuated to in
102 * evacuate(). (Logically an argument to evacuate, but it's static
103 * a lot of the time so we optimise it into a global variable).
109 StgWeak *old_weak_ptr_list; // also pending finaliser list
111 /* Which stage of processing various kinds of weak pointer are we at?
112 * (see traverse_weak_ptr_list() below for discussion).
114 typedef enum { WeakPtrs, WeakThreads, WeakDone } WeakStage;
115 static WeakStage weak_stage;
117 /* List of all threads during GC
119 static StgTSO *old_all_threads;
120 StgTSO *resurrected_threads;
122 /* Flag indicating failure to evacuate an object to the desired
125 static rtsBool failed_to_evac;
127 /* Old to-space (used for two-space collector only)
129 static bdescr *old_to_blocks;
131 /* Data used for allocation area sizing.
133 static lnat new_blocks; // blocks allocated during this GC
134 static lnat g0s0_pcnt_kept = 30; // percentage of g0s0 live at last minor GC
136 /* Used to avoid long recursion due to selector thunks
138 static lnat thunk_selector_depth = 0;
139 #define MAX_THUNK_SELECTOR_DEPTH 8
141 /* -----------------------------------------------------------------------------
142 Static function declarations
143 -------------------------------------------------------------------------- */
145 static bdescr * gc_alloc_block ( step *stp );
146 static void mark_root ( StgClosure **root );
148 // Use a register argument for evacuate, if available.
150 #define REGPARM1 __attribute__((regparm(1)))
155 REGPARM1 static StgClosure * evacuate (StgClosure *q);
157 static void zero_static_object_list ( StgClosure* first_static );
159 static rtsBool traverse_weak_ptr_list ( void );
160 static void mark_weak_ptr_list ( StgWeak **list );
162 static StgClosure * eval_thunk_selector ( nat field, StgSelector * p );
165 static void scavenge ( step * );
166 static void scavenge_mark_stack ( void );
167 static void scavenge_stack ( StgPtr p, StgPtr stack_end );
168 static rtsBool scavenge_one ( StgPtr p );
169 static void scavenge_large ( step * );
170 static void scavenge_static ( void );
171 static void scavenge_mutable_list ( generation *g );
173 static void scavenge_large_bitmap ( StgPtr p,
174 StgLargeBitmap *large_bitmap,
177 #if 0 && defined(DEBUG)
178 static void gcCAFs ( void );
181 /* -----------------------------------------------------------------------------
182 inline functions etc. for dealing with the mark bitmap & stack.
183 -------------------------------------------------------------------------- */
185 #define MARK_STACK_BLOCKS 4
187 static bdescr *mark_stack_bdescr;
188 static StgPtr *mark_stack;
189 static StgPtr *mark_sp;
190 static StgPtr *mark_splim;
192 // Flag and pointers used for falling back to a linear scan when the
193 // mark stack overflows.
194 static rtsBool mark_stack_overflowed;
195 static bdescr *oldgen_scan_bd;
196 static StgPtr oldgen_scan;
198 STATIC_INLINE rtsBool
199 mark_stack_empty(void)
201 return mark_sp == mark_stack;
204 STATIC_INLINE rtsBool
205 mark_stack_full(void)
207 return mark_sp >= mark_splim;
211 reset_mark_stack(void)
213 mark_sp = mark_stack;
217 push_mark_stack(StgPtr p)
228 /* -----------------------------------------------------------------------------
229 Allocate a new to-space block in the given step.
230 -------------------------------------------------------------------------- */
233 gc_alloc_block(step *stp)
235 bdescr *bd = allocBlock();
236 bd->gen_no = stp->gen_no;
240 // blocks in to-space in generations up to and including N
241 // get the BF_EVACUATED flag.
242 if (stp->gen_no <= N) {
243 bd->flags = BF_EVACUATED;
248 // Start a new to-space block, chain it on after the previous one.
249 if (stp->hp_bd == NULL) {
252 stp->hp_bd->free = stp->hp;
253 stp->hp_bd->link = bd;
258 stp->hpLim = stp->hp + BLOCK_SIZE_W;
266 /* -----------------------------------------------------------------------------
269 Rough outline of the algorithm: for garbage collecting generation N
270 (and all younger generations):
272 - follow all pointers in the root set. the root set includes all
273 mutable objects in all generations (mutable_list).
275 - for each pointer, evacuate the object it points to into either
277 + to-space of the step given by step->to, which is the next
278 highest step in this generation or the first step in the next
279 generation if this is the last step.
281 + to-space of generations[evac_gen]->steps[0], if evac_gen != 0.
282 When we evacuate an object we attempt to evacuate
283 everything it points to into the same generation - this is
284 achieved by setting evac_gen to the desired generation. If
285 we can't do this, then an entry in the mut list has to
286 be made for the cross-generation pointer.
288 + if the object is already in a generation > N, then leave
291 - repeatedly scavenge to-space from each step in each generation
292 being collected until no more objects can be evacuated.
294 - free from-space in each step, and set from-space = to-space.
296 Locks held: sched_mutex
298 -------------------------------------------------------------------------- */
301 GarbageCollect ( void (*get_roots)(evac_fn), rtsBool force_major_gc )
305 lnat live, allocated, collected = 0, copied = 0;
306 lnat oldgen_saved_blocks = 0;
310 CostCentreStack *prev_CCS;
313 #if defined(DEBUG) && defined(GRAN)
314 IF_DEBUG(gc, debugBelch("@@ Starting garbage collection at %ld (%lx)\n",
318 #if defined(RTS_USER_SIGNALS)
323 // tell the STM to discard any cached closures its hoping to re-use
326 // tell the stats department that we've started a GC
329 // Init stats and print par specific (timing) info
330 PAR_TICKY_PAR_START();
332 // attribute any costs to CCS_GC
338 /* Approximate how much we allocated.
339 * Todo: only when generating stats?
341 allocated = calcAllocated();
343 /* Figure out which generation to collect
345 if (force_major_gc) {
346 N = RtsFlags.GcFlags.generations - 1;
350 for (g = 0; g < RtsFlags.GcFlags.generations; g++) {
351 if (generations[g].steps[0].n_blocks +
352 generations[g].steps[0].n_large_blocks
353 >= generations[g].max_blocks) {
357 major_gc = (N == RtsFlags.GcFlags.generations-1);
360 #ifdef RTS_GTK_FRONTPANEL
361 if (RtsFlags.GcFlags.frontpanel) {
362 updateFrontPanelBeforeGC(N);
366 // check stack sanity *before* GC (ToDo: check all threads)
368 // ToDo!: check sanity IF_DEBUG(sanity, checkTSOsSanity());
370 IF_DEBUG(sanity, checkFreeListSanity());
372 /* Initialise the static object lists
374 static_objects = END_OF_STATIC_LIST;
375 scavenged_static_objects = END_OF_STATIC_LIST;
377 /* Save the old to-space if we're doing a two-space collection
379 if (RtsFlags.GcFlags.generations == 1) {
380 old_to_blocks = g0s0->to_blocks;
381 g0s0->to_blocks = NULL;
382 g0s0->n_to_blocks = 0;
385 /* Keep a count of how many new blocks we allocated during this GC
386 * (used for resizing the allocation area, later).
390 // Initialise to-space in all the generations/steps that we're
393 for (g = 0; g <= N; g++) {
395 // throw away the mutable list. Invariant: the mutable list
396 // always has at least one block; this means we can avoid a check for
397 // NULL in recordMutable().
399 freeChain(generations[g].mut_list);
400 generations[g].mut_list = allocBlock();
403 for (s = 0; s < generations[g].n_steps; s++) {
405 // generation 0, step 0 doesn't need to-space
406 if (g == 0 && s == 0 && RtsFlags.GcFlags.generations > 1) {
410 stp = &generations[g].steps[s];
411 ASSERT(stp->gen_no == g);
413 // start a new to-space for this step.
416 stp->to_blocks = NULL;
418 // allocate the first to-space block; extra blocks will be
419 // chained on as necessary.
420 bd = gc_alloc_block(stp);
422 stp->scan = bd->start;
425 // initialise the large object queues.
426 stp->new_large_objects = NULL;
427 stp->scavenged_large_objects = NULL;
428 stp->n_scavenged_large_blocks = 0;
430 // mark the large objects as not evacuated yet
431 for (bd = stp->large_objects; bd; bd = bd->link) {
432 bd->flags &= ~BF_EVACUATED;
435 // for a compacted step, we need to allocate the bitmap
436 if (stp->is_compacted) {
437 nat bitmap_size; // in bytes
438 bdescr *bitmap_bdescr;
441 bitmap_size = stp->n_blocks * BLOCK_SIZE / (sizeof(W_)*BITS_PER_BYTE);
443 if (bitmap_size > 0) {
444 bitmap_bdescr = allocGroup((lnat)BLOCK_ROUND_UP(bitmap_size)
446 stp->bitmap = bitmap_bdescr;
447 bitmap = bitmap_bdescr->start;
449 IF_DEBUG(gc, debugBelch("bitmap_size: %d, bitmap: %p",
450 bitmap_size, bitmap););
452 // don't forget to fill it with zeros!
453 memset(bitmap, 0, bitmap_size);
455 // For each block in this step, point to its bitmap from the
457 for (bd=stp->blocks; bd != NULL; bd = bd->link) {
458 bd->u.bitmap = bitmap;
459 bitmap += BLOCK_SIZE_W / (sizeof(W_)*BITS_PER_BYTE);
461 // Also at this point we set the BF_COMPACTED flag
462 // for this block. The invariant is that
463 // BF_COMPACTED is always unset, except during GC
464 // when it is set on those blocks which will be
466 bd->flags |= BF_COMPACTED;
473 /* make sure the older generations have at least one block to
474 * allocate into (this makes things easier for copy(), see below).
476 for (g = N+1; g < RtsFlags.GcFlags.generations; g++) {
477 for (s = 0; s < generations[g].n_steps; s++) {
478 stp = &generations[g].steps[s];
479 if (stp->hp_bd == NULL) {
480 ASSERT(stp->blocks == NULL);
481 bd = gc_alloc_block(stp);
485 /* Set the scan pointer for older generations: remember we
486 * still have to scavenge objects that have been promoted. */
488 stp->scan_bd = stp->hp_bd;
489 stp->to_blocks = NULL;
490 stp->n_to_blocks = 0;
491 stp->new_large_objects = NULL;
492 stp->scavenged_large_objects = NULL;
493 stp->n_scavenged_large_blocks = 0;
497 /* Allocate a mark stack if we're doing a major collection.
500 mark_stack_bdescr = allocGroup(MARK_STACK_BLOCKS);
501 mark_stack = (StgPtr *)mark_stack_bdescr->start;
502 mark_sp = mark_stack;
503 mark_splim = mark_stack + (MARK_STACK_BLOCKS * BLOCK_SIZE_W);
505 mark_stack_bdescr = NULL;
508 /* -----------------------------------------------------------------------
509 * follow all the roots that we know about:
510 * - mutable lists from each generation > N
511 * we want to *scavenge* these roots, not evacuate them: they're not
512 * going to move in this GC.
513 * Also: do them in reverse generation order. This is because we
514 * often want to promote objects that are pointed to by older
515 * generations early, so we don't have to repeatedly copy them.
516 * Doing the generations in reverse order ensures that we don't end
517 * up in the situation where we want to evac an object to gen 3 and
518 * it has already been evaced to gen 2.
522 for (g = RtsFlags.GcFlags.generations-1; g > N; g--) {
523 generations[g].saved_mut_list = generations[g].mut_list;
524 generations[g].mut_list = allocBlock();
525 // mut_list always has at least one block.
528 for (g = RtsFlags.GcFlags.generations-1; g > N; g--) {
529 IF_PAR_DEBUG(verbose, printMutableList(&generations[g]));
530 scavenge_mutable_list(&generations[g]);
532 for (st = generations[g].n_steps-1; st >= 0; st--) {
533 scavenge(&generations[g].steps[st]);
538 /* follow roots from the CAF list (used by GHCi)
543 /* follow all the roots that the application knows about.
546 get_roots(mark_root);
549 /* And don't forget to mark the TSO if we got here direct from
551 /* Not needed in a seq version?
553 CurrentTSO = (StgTSO *)MarkRoot((StgClosure *)CurrentTSO);
557 // Mark the entries in the GALA table of the parallel system
558 markLocalGAs(major_gc);
559 // Mark all entries on the list of pending fetches
560 markPendingFetches(major_gc);
563 /* Mark the weak pointer list, and prepare to detect dead weak
566 mark_weak_ptr_list(&weak_ptr_list);
567 old_weak_ptr_list = weak_ptr_list;
568 weak_ptr_list = NULL;
569 weak_stage = WeakPtrs;
571 /* The all_threads list is like the weak_ptr_list.
572 * See traverse_weak_ptr_list() for the details.
574 old_all_threads = all_threads;
575 all_threads = END_TSO_QUEUE;
576 resurrected_threads = END_TSO_QUEUE;
578 /* Mark the stable pointer table.
580 markStablePtrTable(mark_root);
582 /* -------------------------------------------------------------------------
583 * Repeatedly scavenge all the areas we know about until there's no
584 * more scavenging to be done.
591 // scavenge static objects
592 if (major_gc && static_objects != END_OF_STATIC_LIST) {
593 IF_DEBUG(sanity, checkStaticObjects(static_objects));
597 /* When scavenging the older generations: Objects may have been
598 * evacuated from generations <= N into older generations, and we
599 * need to scavenge these objects. We're going to try to ensure that
600 * any evacuations that occur move the objects into at least the
601 * same generation as the object being scavenged, otherwise we
602 * have to create new entries on the mutable list for the older
606 // scavenge each step in generations 0..maxgen
612 // scavenge objects in compacted generation
613 if (mark_stack_overflowed || oldgen_scan_bd != NULL ||
614 (mark_stack_bdescr != NULL && !mark_stack_empty())) {
615 scavenge_mark_stack();
619 for (gen = RtsFlags.GcFlags.generations; --gen >= 0; ) {
620 for (st = generations[gen].n_steps; --st >= 0; ) {
621 if (gen == 0 && st == 0 && RtsFlags.GcFlags.generations > 1) {
624 stp = &generations[gen].steps[st];
626 if (stp->hp_bd != stp->scan_bd || stp->scan < stp->hp) {
631 if (stp->new_large_objects != NULL) {
640 if (flag) { goto loop; }
642 // must be last... invariant is that everything is fully
643 // scavenged at this point.
644 if (traverse_weak_ptr_list()) { // returns rtsTrue if evaced something
649 /* Update the pointers from the "main thread" list - these are
650 * treated as weak pointers because we want to allow a main thread
651 * to get a BlockedOnDeadMVar exception in the same way as any other
652 * thread. Note that the threads should all have been retained by
653 * GC by virtue of being on the all_threads list, we're just
654 * updating pointers here.
659 for (m = main_threads; m != NULL; m = m->link) {
660 tso = (StgTSO *) isAlive((StgClosure *)m->tso);
662 barf("main thread has been GC'd");
669 // Reconstruct the Global Address tables used in GUM
670 rebuildGAtables(major_gc);
671 IF_DEBUG(sanity, checkLAGAtable(rtsTrue/*check closures, too*/));
674 // Now see which stable names are still alive.
677 // Tidy the end of the to-space chains
678 for (g = 0; g < RtsFlags.GcFlags.generations; g++) {
679 for (s = 0; s < generations[g].n_steps; s++) {
680 stp = &generations[g].steps[s];
681 if (!(g == 0 && s == 0 && RtsFlags.GcFlags.generations > 1)) {
682 ASSERT(Bdescr(stp->hp) == stp->hp_bd);
683 stp->hp_bd->free = stp->hp;
689 // We call processHeapClosureForDead() on every closure destroyed during
690 // the current garbage collection, so we invoke LdvCensusForDead().
691 if (RtsFlags.ProfFlags.doHeapProfile == HEAP_BY_LDV
692 || RtsFlags.ProfFlags.bioSelector != NULL)
696 // NO MORE EVACUATION AFTER THIS POINT!
697 // Finally: compaction of the oldest generation.
698 if (major_gc && oldest_gen->steps[0].is_compacted) {
699 // save number of blocks for stats
700 oldgen_saved_blocks = oldest_gen->steps[0].n_blocks;
704 IF_DEBUG(sanity, checkGlobalTSOList(rtsFalse));
706 /* run through all the generations/steps and tidy up
708 copied = new_blocks * BLOCK_SIZE_W;
709 for (g = 0; g < RtsFlags.GcFlags.generations; g++) {
712 generations[g].collections++; // for stats
715 // Count the mutable list as bytes "copied" for the purposes of
716 // stats. Every mutable list is copied during every GC.
718 for (bd = generations[g].mut_list; bd != NULL; bd = bd->link) {
719 copied += (bd->free - bd->start) * sizeof(StgWord);
723 for (s = 0; s < generations[g].n_steps; s++) {
725 stp = &generations[g].steps[s];
727 if (!(g == 0 && s == 0 && RtsFlags.GcFlags.generations > 1)) {
728 // stats information: how much we copied
730 copied -= stp->hp_bd->start + BLOCK_SIZE_W -
735 // for generations we collected...
738 // rough calculation of garbage collected, for stats output
739 if (stp->is_compacted) {
740 collected += (oldgen_saved_blocks - stp->n_blocks) * BLOCK_SIZE_W;
742 collected += stp->n_blocks * BLOCK_SIZE_W;
745 /* free old memory and shift to-space into from-space for all
746 * the collected steps (except the allocation area). These
747 * freed blocks will probaby be quickly recycled.
749 if (!(g == 0 && s == 0)) {
750 if (stp->is_compacted) {
751 // for a compacted step, just shift the new to-space
752 // onto the front of the now-compacted existing blocks.
753 for (bd = stp->to_blocks; bd != NULL; bd = bd->link) {
754 bd->flags &= ~BF_EVACUATED; // now from-space
756 // tack the new blocks on the end of the existing blocks
757 if (stp->blocks == NULL) {
758 stp->blocks = stp->to_blocks;
760 for (bd = stp->blocks; bd != NULL; bd = next) {
763 bd->link = stp->to_blocks;
765 // NB. this step might not be compacted next
766 // time, so reset the BF_COMPACTED flags.
767 // They are set before GC if we're going to
768 // compact. (search for BF_COMPACTED above).
769 bd->flags &= ~BF_COMPACTED;
772 // add the new blocks to the block tally
773 stp->n_blocks += stp->n_to_blocks;
775 freeChain(stp->blocks);
776 stp->blocks = stp->to_blocks;
777 stp->n_blocks = stp->n_to_blocks;
778 for (bd = stp->blocks; bd != NULL; bd = bd->link) {
779 bd->flags &= ~BF_EVACUATED; // now from-space
782 stp->to_blocks = NULL;
783 stp->n_to_blocks = 0;
786 /* LARGE OBJECTS. The current live large objects are chained on
787 * scavenged_large, having been moved during garbage
788 * collection from large_objects. Any objects left on
789 * large_objects list are therefore dead, so we free them here.
791 for (bd = stp->large_objects; bd != NULL; bd = next) {
797 // update the count of blocks used by large objects
798 for (bd = stp->scavenged_large_objects; bd != NULL; bd = bd->link) {
799 bd->flags &= ~BF_EVACUATED;
801 stp->large_objects = stp->scavenged_large_objects;
802 stp->n_large_blocks = stp->n_scavenged_large_blocks;
805 // for older generations...
807 /* For older generations, we need to append the
808 * scavenged_large_object list (i.e. large objects that have been
809 * promoted during this GC) to the large_object list for that step.
811 for (bd = stp->scavenged_large_objects; bd; bd = next) {
813 bd->flags &= ~BF_EVACUATED;
814 dbl_link_onto(bd, &stp->large_objects);
817 // add the new blocks we promoted during this GC
818 stp->n_blocks += stp->n_to_blocks;
819 stp->n_to_blocks = 0;
820 stp->n_large_blocks += stp->n_scavenged_large_blocks;
825 /* Reset the sizes of the older generations when we do a major
828 * CURRENT STRATEGY: make all generations except zero the same size.
829 * We have to stay within the maximum heap size, and leave a certain
830 * percentage of the maximum heap size available to allocate into.
832 if (major_gc && RtsFlags.GcFlags.generations > 1) {
833 nat live, size, min_alloc;
834 nat max = RtsFlags.GcFlags.maxHeapSize;
835 nat gens = RtsFlags.GcFlags.generations;
837 // live in the oldest generations
838 live = oldest_gen->steps[0].n_blocks +
839 oldest_gen->steps[0].n_large_blocks;
841 // default max size for all generations except zero
842 size = stg_max(live * RtsFlags.GcFlags.oldGenFactor,
843 RtsFlags.GcFlags.minOldGenSize);
845 // minimum size for generation zero
846 min_alloc = stg_max((RtsFlags.GcFlags.pcFreeHeap * max) / 200,
847 RtsFlags.GcFlags.minAllocAreaSize);
849 // Auto-enable compaction when the residency reaches a
850 // certain percentage of the maximum heap size (default: 30%).
851 if (RtsFlags.GcFlags.generations > 1 &&
852 (RtsFlags.GcFlags.compact ||
854 oldest_gen->steps[0].n_blocks >
855 (RtsFlags.GcFlags.compactThreshold * max) / 100))) {
856 oldest_gen->steps[0].is_compacted = 1;
857 // debugBelch("compaction: on\n", live);
859 oldest_gen->steps[0].is_compacted = 0;
860 // debugBelch("compaction: off\n", live);
863 // if we're going to go over the maximum heap size, reduce the
864 // size of the generations accordingly. The calculation is
865 // different if compaction is turned on, because we don't need
866 // to double the space required to collect the old generation.
869 // this test is necessary to ensure that the calculations
870 // below don't have any negative results - we're working
871 // with unsigned values here.
872 if (max < min_alloc) {
876 if (oldest_gen->steps[0].is_compacted) {
877 if ( (size + (size - 1) * (gens - 2) * 2) + min_alloc > max ) {
878 size = (max - min_alloc) / ((gens - 1) * 2 - 1);
881 if ( (size * (gens - 1) * 2) + min_alloc > max ) {
882 size = (max - min_alloc) / ((gens - 1) * 2);
892 debugBelch("live: %d, min_alloc: %d, size : %d, max = %d\n", live,
893 min_alloc, size, max);
896 for (g = 0; g < gens; g++) {
897 generations[g].max_blocks = size;
901 // Guess the amount of live data for stats.
904 /* Free the small objects allocated via allocate(), since this will
905 * all have been copied into G0S1 now.
907 if (small_alloc_list != NULL) {
908 freeChain(small_alloc_list);
910 small_alloc_list = NULL;
914 alloc_blocks_lim = RtsFlags.GcFlags.minAllocAreaSize;
916 // Start a new pinned_object_block
917 pinned_object_block = NULL;
919 /* Free the mark stack.
921 if (mark_stack_bdescr != NULL) {
922 freeGroup(mark_stack_bdescr);
927 for (g = 0; g <= N; g++) {
928 for (s = 0; s < generations[g].n_steps; s++) {
929 stp = &generations[g].steps[s];
930 if (stp->is_compacted && stp->bitmap != NULL) {
931 freeGroup(stp->bitmap);
936 /* Two-space collector:
937 * Free the old to-space, and estimate the amount of live data.
939 if (RtsFlags.GcFlags.generations == 1) {
942 if (old_to_blocks != NULL) {
943 freeChain(old_to_blocks);
945 for (bd = g0s0->to_blocks; bd != NULL; bd = bd->link) {
946 bd->flags = 0; // now from-space
949 /* For a two-space collector, we need to resize the nursery. */
951 /* set up a new nursery. Allocate a nursery size based on a
952 * function of the amount of live data (by default a factor of 2)
953 * Use the blocks from the old nursery if possible, freeing up any
956 * If we get near the maximum heap size, then adjust our nursery
957 * size accordingly. If the nursery is the same size as the live
958 * data (L), then we need 3L bytes. We can reduce the size of the
959 * nursery to bring the required memory down near 2L bytes.
961 * A normal 2-space collector would need 4L bytes to give the same
962 * performance we get from 3L bytes, reducing to the same
963 * performance at 2L bytes.
965 blocks = g0s0->n_to_blocks;
967 if ( RtsFlags.GcFlags.maxHeapSize != 0 &&
968 blocks * RtsFlags.GcFlags.oldGenFactor * 2 >
969 RtsFlags.GcFlags.maxHeapSize ) {
970 long adjusted_blocks; // signed on purpose
973 adjusted_blocks = (RtsFlags.GcFlags.maxHeapSize - 2 * blocks);
974 IF_DEBUG(gc, debugBelch("@@ Near maximum heap size of 0x%x blocks, blocks = %d, adjusted to %ld", RtsFlags.GcFlags.maxHeapSize, blocks, adjusted_blocks));
975 pc_free = adjusted_blocks * 100 / RtsFlags.GcFlags.maxHeapSize;
976 if (pc_free < RtsFlags.GcFlags.pcFreeHeap) /* might even be < 0 */ {
979 blocks = adjusted_blocks;
982 blocks *= RtsFlags.GcFlags.oldGenFactor;
983 if (blocks < RtsFlags.GcFlags.minAllocAreaSize) {
984 blocks = RtsFlags.GcFlags.minAllocAreaSize;
987 resizeNurseries(blocks);
990 /* Generational collector:
991 * If the user has given us a suggested heap size, adjust our
992 * allocation area to make best use of the memory available.
995 if (RtsFlags.GcFlags.heapSizeSuggestion) {
997 nat needed = calcNeeded(); // approx blocks needed at next GC
999 /* Guess how much will be live in generation 0 step 0 next time.
1000 * A good approximation is obtained by finding the
1001 * percentage of g0s0 that was live at the last minor GC.
1004 g0s0_pcnt_kept = (new_blocks * 100) / countNurseryBlocks();
1007 /* Estimate a size for the allocation area based on the
1008 * information available. We might end up going slightly under
1009 * or over the suggested heap size, but we should be pretty
1012 * Formula: suggested - needed
1013 * ----------------------------
1014 * 1 + g0s0_pcnt_kept/100
1016 * where 'needed' is the amount of memory needed at the next
1017 * collection for collecting all steps except g0s0.
1020 (((long)RtsFlags.GcFlags.heapSizeSuggestion - (long)needed) * 100) /
1021 (100 + (long)g0s0_pcnt_kept);
1023 if (blocks < (long)RtsFlags.GcFlags.minAllocAreaSize) {
1024 blocks = RtsFlags.GcFlags.minAllocAreaSize;
1027 resizeNurseries((nat)blocks);
1030 // we might have added extra large blocks to the nursery, so
1031 // resize back to minAllocAreaSize again.
1032 resizeNurseries(RtsFlags.GcFlags.minAllocAreaSize);
1036 // mark the garbage collected CAFs as dead
1037 #if 0 && defined(DEBUG) // doesn't work at the moment
1038 if (major_gc) { gcCAFs(); }
1042 // resetStaticObjectForRetainerProfiling() must be called before
1044 resetStaticObjectForRetainerProfiling();
1047 // zero the scavenged static object list
1049 zero_static_object_list(scavenged_static_objects);
1052 // Reset the nursery
1055 RELEASE_LOCK(&sched_mutex);
1057 // start any pending finalizers
1058 scheduleFinalizers(old_weak_ptr_list);
1060 // send exceptions to any threads which were about to die
1061 resurrectThreads(resurrected_threads);
1063 ACQUIRE_LOCK(&sched_mutex);
1065 // Update the stable pointer hash table.
1066 updateStablePtrTable(major_gc);
1068 // check sanity after GC
1069 IF_DEBUG(sanity, checkSanity());
1071 // extra GC trace info
1072 IF_DEBUG(gc, statDescribeGens());
1075 // symbol-table based profiling
1076 /* heapCensus(to_blocks); */ /* ToDo */
1079 // restore enclosing cost centre
1084 // check for memory leaks if sanity checking is on
1085 IF_DEBUG(sanity, memInventory());
1087 #ifdef RTS_GTK_FRONTPANEL
1088 if (RtsFlags.GcFlags.frontpanel) {
1089 updateFrontPanelAfterGC( N, live );
1093 // ok, GC over: tell the stats department what happened.
1094 stat_endGC(allocated, collected, live, copied, N);
1096 #if defined(RTS_USER_SIGNALS)
1097 // unblock signals again
1098 unblockUserSignals();
1105 /* -----------------------------------------------------------------------------
1108 traverse_weak_ptr_list is called possibly many times during garbage
1109 collection. It returns a flag indicating whether it did any work
1110 (i.e. called evacuate on any live pointers).
1112 Invariant: traverse_weak_ptr_list is called when the heap is in an
1113 idempotent state. That means that there are no pending
1114 evacuate/scavenge operations. This invariant helps the weak
1115 pointer code decide which weak pointers are dead - if there are no
1116 new live weak pointers, then all the currently unreachable ones are
1119 For generational GC: we just don't try to finalize weak pointers in
1120 older generations than the one we're collecting. This could
1121 probably be optimised by keeping per-generation lists of weak
1122 pointers, but for a few weak pointers this scheme will work.
1124 There are three distinct stages to processing weak pointers:
1126 - weak_stage == WeakPtrs
1128 We process all the weak pointers whos keys are alive (evacuate
1129 their values and finalizers), and repeat until we can find no new
1130 live keys. If no live keys are found in this pass, then we
1131 evacuate the finalizers of all the dead weak pointers in order to
1134 - weak_stage == WeakThreads
1136 Now, we discover which *threads* are still alive. Pointers to
1137 threads from the all_threads and main thread lists are the
1138 weakest of all: a pointers from the finalizer of a dead weak
1139 pointer can keep a thread alive. Any threads found to be unreachable
1140 are evacuated and placed on the resurrected_threads list so we
1141 can send them a signal later.
1143 - weak_stage == WeakDone
1145 No more evacuation is done.
1147 -------------------------------------------------------------------------- */
1150 traverse_weak_ptr_list(void)
1152 StgWeak *w, **last_w, *next_w;
1154 rtsBool flag = rtsFalse;
1156 switch (weak_stage) {
1162 /* doesn't matter where we evacuate values/finalizers to, since
1163 * these pointers are treated as roots (iff the keys are alive).
1167 last_w = &old_weak_ptr_list;
1168 for (w = old_weak_ptr_list; w != NULL; w = next_w) {
1170 /* There might be a DEAD_WEAK on the list if finalizeWeak# was
1171 * called on a live weak pointer object. Just remove it.
1173 if (w->header.info == &stg_DEAD_WEAK_info) {
1174 next_w = ((StgDeadWeak *)w)->link;
1179 switch (get_itbl(w)->type) {
1182 next_w = (StgWeak *)((StgEvacuated *)w)->evacuee;
1187 /* Now, check whether the key is reachable.
1189 new = isAlive(w->key);
1192 // evacuate the value and finalizer
1193 w->value = evacuate(w->value);
1194 w->finalizer = evacuate(w->finalizer);
1195 // remove this weak ptr from the old_weak_ptr list
1197 // and put it on the new weak ptr list
1199 w->link = weak_ptr_list;
1202 IF_DEBUG(weak, debugBelch("Weak pointer still alive at %p -> %p",
1207 last_w = &(w->link);
1213 barf("traverse_weak_ptr_list: not WEAK");
1217 /* If we didn't make any changes, then we can go round and kill all
1218 * the dead weak pointers. The old_weak_ptr list is used as a list
1219 * of pending finalizers later on.
1221 if (flag == rtsFalse) {
1222 for (w = old_weak_ptr_list; w; w = w->link) {
1223 w->finalizer = evacuate(w->finalizer);
1226 // Next, move to the WeakThreads stage after fully
1227 // scavenging the finalizers we've just evacuated.
1228 weak_stage = WeakThreads;
1234 /* Now deal with the all_threads list, which behaves somewhat like
1235 * the weak ptr list. If we discover any threads that are about to
1236 * become garbage, we wake them up and administer an exception.
1239 StgTSO *t, *tmp, *next, **prev;
1241 prev = &old_all_threads;
1242 for (t = old_all_threads; t != END_TSO_QUEUE; t = next) {
1244 tmp = (StgTSO *)isAlive((StgClosure *)t);
1250 ASSERT(get_itbl(t)->type == TSO);
1251 switch (t->what_next) {
1252 case ThreadRelocated:
1257 case ThreadComplete:
1258 // finshed or died. The thread might still be alive, but we
1259 // don't keep it on the all_threads list. Don't forget to
1260 // stub out its global_link field.
1261 next = t->global_link;
1262 t->global_link = END_TSO_QUEUE;
1270 // not alive (yet): leave this thread on the
1271 // old_all_threads list.
1272 prev = &(t->global_link);
1273 next = t->global_link;
1276 // alive: move this thread onto the all_threads list.
1277 next = t->global_link;
1278 t->global_link = all_threads;
1285 /* And resurrect any threads which were about to become garbage.
1288 StgTSO *t, *tmp, *next;
1289 for (t = old_all_threads; t != END_TSO_QUEUE; t = next) {
1290 next = t->global_link;
1291 tmp = (StgTSO *)evacuate((StgClosure *)t);
1292 tmp->global_link = resurrected_threads;
1293 resurrected_threads = tmp;
1297 weak_stage = WeakDone; // *now* we're done,
1298 return rtsTrue; // but one more round of scavenging, please
1301 barf("traverse_weak_ptr_list");
1307 /* -----------------------------------------------------------------------------
1308 After GC, the live weak pointer list may have forwarding pointers
1309 on it, because a weak pointer object was evacuated after being
1310 moved to the live weak pointer list. We remove those forwarding
1313 Also, we don't consider weak pointer objects to be reachable, but
1314 we must nevertheless consider them to be "live" and retain them.
1315 Therefore any weak pointer objects which haven't as yet been
1316 evacuated need to be evacuated now.
1317 -------------------------------------------------------------------------- */
1321 mark_weak_ptr_list ( StgWeak **list )
1323 StgWeak *w, **last_w;
1326 for (w = *list; w; w = w->link) {
1327 // w might be WEAK, EVACUATED, or DEAD_WEAK (actually CON_STATIC) here
1328 ASSERT(w->header.info == &stg_DEAD_WEAK_info
1329 || get_itbl(w)->type == WEAK || get_itbl(w)->type == EVACUATED);
1330 w = (StgWeak *)evacuate((StgClosure *)w);
1332 last_w = &(w->link);
1336 /* -----------------------------------------------------------------------------
1337 isAlive determines whether the given closure is still alive (after
1338 a garbage collection) or not. It returns the new address of the
1339 closure if it is alive, or NULL otherwise.
1341 NOTE: Use it before compaction only!
1342 -------------------------------------------------------------------------- */
1346 isAlive(StgClosure *p)
1348 const StgInfoTable *info;
1353 ASSERT(LOOKS_LIKE_CLOSURE_PTR(p));
1356 // ignore static closures
1358 // ToDo: for static closures, check the static link field.
1359 // Problem here is that we sometimes don't set the link field, eg.
1360 // for static closures with an empty SRT or CONSTR_STATIC_NOCAFs.
1362 if (!HEAP_ALLOCED(p)) {
1366 // ignore closures in generations that we're not collecting.
1368 if (bd->gen_no > N) {
1372 // if it's a pointer into to-space, then we're done
1373 if (bd->flags & BF_EVACUATED) {
1377 // large objects use the evacuated flag
1378 if (bd->flags & BF_LARGE) {
1382 // check the mark bit for compacted steps
1383 if ((bd->flags & BF_COMPACTED) && is_marked((P_)p,bd)) {
1387 switch (info->type) {
1392 case IND_OLDGEN: // rely on compatible layout with StgInd
1393 case IND_OLDGEN_PERM:
1394 // follow indirections
1395 p = ((StgInd *)p)->indirectee;
1400 return ((StgEvacuated *)p)->evacuee;
1403 if (((StgTSO *)p)->what_next == ThreadRelocated) {
1404 p = (StgClosure *)((StgTSO *)p)->link;
1417 mark_root(StgClosure **root)
1419 *root = evacuate(*root);
1423 upd_evacuee(StgClosure *p, StgClosure *dest)
1425 // not true: (ToDo: perhaps it should be)
1426 // ASSERT(Bdescr((P_)dest)->flags & BF_EVACUATED);
1427 SET_INFO(p, &stg_EVACUATED_info);
1428 ((StgEvacuated *)p)->evacuee = dest;
1432 STATIC_INLINE StgClosure *
1433 copy(StgClosure *src, nat size, step *stp)
1438 nat size_org = size;
1441 TICK_GC_WORDS_COPIED(size);
1442 /* Find out where we're going, using the handy "to" pointer in
1443 * the step of the source object. If it turns out we need to
1444 * evacuate to an older generation, adjust it here (see comment
1447 if (stp->gen_no < evac_gen) {
1448 #ifdef NO_EAGER_PROMOTION
1449 failed_to_evac = rtsTrue;
1451 stp = &generations[evac_gen].steps[0];
1455 /* chain a new block onto the to-space for the destination step if
1458 if (stp->hp + size >= stp->hpLim) {
1459 gc_alloc_block(stp);
1462 for(to = stp->hp, from = (P_)src; size>0; --size) {
1468 upd_evacuee(src,(StgClosure *)dest);
1470 // We store the size of the just evacuated object in the LDV word so that
1471 // the profiler can guess the position of the next object later.
1472 SET_EVACUAEE_FOR_LDV(src, size_org);
1474 return (StgClosure *)dest;
1477 /* Special version of copy() for when we only want to copy the info
1478 * pointer of an object, but reserve some padding after it. This is
1479 * used to optimise evacuation of BLACKHOLEs.
1484 copyPart(StgClosure *src, nat size_to_reserve, nat size_to_copy, step *stp)
1489 nat size_to_copy_org = size_to_copy;
1492 TICK_GC_WORDS_COPIED(size_to_copy);
1493 if (stp->gen_no < evac_gen) {
1494 #ifdef NO_EAGER_PROMOTION
1495 failed_to_evac = rtsTrue;
1497 stp = &generations[evac_gen].steps[0];
1501 if (stp->hp + size_to_reserve >= stp->hpLim) {
1502 gc_alloc_block(stp);
1505 for(to = stp->hp, from = (P_)src; size_to_copy>0; --size_to_copy) {
1510 stp->hp += size_to_reserve;
1511 upd_evacuee(src,(StgClosure *)dest);
1513 // We store the size of the just evacuated object in the LDV word so that
1514 // the profiler can guess the position of the next object later.
1515 // size_to_copy_org is wrong because the closure already occupies size_to_reserve
1517 SET_EVACUAEE_FOR_LDV(src, size_to_reserve);
1519 if (size_to_reserve - size_to_copy_org > 0)
1520 FILL_SLOP(stp->hp - 1, (int)(size_to_reserve - size_to_copy_org));
1522 return (StgClosure *)dest;
1526 /* -----------------------------------------------------------------------------
1527 Evacuate a large object
1529 This just consists of removing the object from the (doubly-linked)
1530 step->large_objects list, and linking it on to the (singly-linked)
1531 step->new_large_objects list, from where it will be scavenged later.
1533 Convention: bd->flags has BF_EVACUATED set for a large object
1534 that has been evacuated, or unset otherwise.
1535 -------------------------------------------------------------------------- */
1539 evacuate_large(StgPtr p)
1541 bdescr *bd = Bdescr(p);
1544 // object must be at the beginning of the block (or be a ByteArray)
1545 ASSERT(get_itbl((StgClosure *)p)->type == ARR_WORDS ||
1546 (((W_)p & BLOCK_MASK) == 0));
1548 // already evacuated?
1549 if (bd->flags & BF_EVACUATED) {
1550 /* Don't forget to set the failed_to_evac flag if we didn't get
1551 * the desired destination (see comments in evacuate()).
1553 if (bd->gen_no < evac_gen) {
1554 failed_to_evac = rtsTrue;
1555 TICK_GC_FAILED_PROMOTION();
1561 // remove from large_object list
1563 bd->u.back->link = bd->link;
1564 } else { // first object in the list
1565 stp->large_objects = bd->link;
1568 bd->link->u.back = bd->u.back;
1571 /* link it on to the evacuated large object list of the destination step
1574 if (stp->gen_no < evac_gen) {
1575 #ifdef NO_EAGER_PROMOTION
1576 failed_to_evac = rtsTrue;
1578 stp = &generations[evac_gen].steps[0];
1583 bd->gen_no = stp->gen_no;
1584 bd->link = stp->new_large_objects;
1585 stp->new_large_objects = bd;
1586 bd->flags |= BF_EVACUATED;
1589 /* -----------------------------------------------------------------------------
1592 This is called (eventually) for every live object in the system.
1594 The caller to evacuate specifies a desired generation in the
1595 evac_gen global variable. The following conditions apply to
1596 evacuating an object which resides in generation M when we're
1597 collecting up to generation N
1601 else evac to step->to
1603 if M < evac_gen evac to evac_gen, step 0
1605 if the object is already evacuated, then we check which generation
1608 if M >= evac_gen do nothing
1609 if M < evac_gen set failed_to_evac flag to indicate that we
1610 didn't manage to evacuate this object into evac_gen.
1615 evacuate() is the single most important function performance-wise
1616 in the GC. Various things have been tried to speed it up, but as
1617 far as I can tell the code generated by gcc 3.2 with -O2 is about
1618 as good as it's going to get. We pass the argument to evacuate()
1619 in a register using the 'regparm' attribute (see the prototype for
1620 evacuate() near the top of this file).
1622 Changing evacuate() to take an (StgClosure **) rather than
1623 returning the new pointer seems attractive, because we can avoid
1624 writing back the pointer when it hasn't changed (eg. for a static
1625 object, or an object in a generation > N). However, I tried it and
1626 it doesn't help. One reason is that the (StgClosure **) pointer
1627 gets spilled to the stack inside evacuate(), resulting in far more
1628 extra reads/writes than we save.
1629 -------------------------------------------------------------------------- */
1631 REGPARM1 static StgClosure *
1632 evacuate(StgClosure *q)
1639 const StgInfoTable *info;
1642 if (HEAP_ALLOCED(q)) {
1645 if (bd->gen_no > N) {
1646 /* Can't evacuate this object, because it's in a generation
1647 * older than the ones we're collecting. Let's hope that it's
1648 * in evac_gen or older, or we will have to arrange to track
1649 * this pointer using the mutable list.
1651 if (bd->gen_no < evac_gen) {
1653 failed_to_evac = rtsTrue;
1654 TICK_GC_FAILED_PROMOTION();
1659 /* evacuate large objects by re-linking them onto a different list.
1661 if (bd->flags & BF_LARGE) {
1663 if (info->type == TSO &&
1664 ((StgTSO *)q)->what_next == ThreadRelocated) {
1665 q = (StgClosure *)((StgTSO *)q)->link;
1668 evacuate_large((P_)q);
1672 /* If the object is in a step that we're compacting, then we
1673 * need to use an alternative evacuate procedure.
1675 if (bd->flags & BF_COMPACTED) {
1676 if (!is_marked((P_)q,bd)) {
1678 if (mark_stack_full()) {
1679 mark_stack_overflowed = rtsTrue;
1682 push_mark_stack((P_)q);
1687 /* Object is not already evacuated. */
1688 ASSERT((bd->flags & BF_EVACUATED) == 0);
1693 else stp = NULL; // make sure copy() will crash if HEAP_ALLOCED is wrong
1696 // make sure the info pointer is into text space
1697 ASSERT(LOOKS_LIKE_CLOSURE_PTR(q));
1700 switch (info -> type) {
1704 return copy(q,sizeW_fromITBL(info),stp);
1708 StgWord w = (StgWord)q->payload[0];
1709 if (q->header.info == Czh_con_info &&
1710 // unsigned, so always true: (StgChar)w >= MIN_CHARLIKE &&
1711 (StgChar)w <= MAX_CHARLIKE) {
1712 return (StgClosure *)CHARLIKE_CLOSURE((StgChar)w);
1714 if (q->header.info == Izh_con_info &&
1715 (StgInt)w >= MIN_INTLIKE && (StgInt)w <= MAX_INTLIKE) {
1716 return (StgClosure *)INTLIKE_CLOSURE((StgInt)w);
1718 // else, fall through ...
1726 return copy(q,sizeofW(StgHeader)+1,stp);
1731 #ifdef NO_PROMOTE_THUNKS
1732 if (bd->gen_no == 0 &&
1733 bd->step->no != 0 &&
1734 bd->step->no == generations[bd->gen_no].n_steps-1) {
1738 return copy(q,sizeofW(StgHeader)+2,stp);
1746 return copy(q,sizeofW(StgHeader)+2,stp);
1752 case IND_OLDGEN_PERM:
1756 return copy(q,sizeW_fromITBL(info),stp);
1759 return copy(q,bco_sizeW((StgBCO *)q),stp);
1762 case SE_CAF_BLACKHOLE:
1765 return copyPart(q,BLACKHOLE_sizeW(),sizeofW(StgHeader),stp);
1767 case THUNK_SELECTOR:
1771 if (thunk_selector_depth > MAX_THUNK_SELECTOR_DEPTH) {
1772 return copy(q,THUNK_SELECTOR_sizeW(),stp);
1775 p = eval_thunk_selector(info->layout.selector_offset,
1779 return copy(q,THUNK_SELECTOR_sizeW(),stp);
1781 // q is still BLACKHOLE'd.
1782 thunk_selector_depth++;
1784 thunk_selector_depth--;
1787 // We store the size of the just evacuated object in the
1788 // LDV word so that the profiler can guess the position of
1789 // the next object later.
1790 SET_EVACUAEE_FOR_LDV(q, THUNK_SELECTOR_sizeW());
1798 // follow chains of indirections, don't evacuate them
1799 q = ((StgInd*)q)->indirectee;
1803 if (info->srt_bitmap != 0 && major_gc &&
1804 THUNK_STATIC_LINK((StgClosure *)q) == NULL) {
1805 THUNK_STATIC_LINK((StgClosure *)q) = static_objects;
1806 static_objects = (StgClosure *)q;
1811 if (info->srt_bitmap != 0 && major_gc &&
1812 FUN_STATIC_LINK((StgClosure *)q) == NULL) {
1813 FUN_STATIC_LINK((StgClosure *)q) = static_objects;
1814 static_objects = (StgClosure *)q;
1819 /* If q->saved_info != NULL, then it's a revertible CAF - it'll be
1820 * on the CAF list, so don't do anything with it here (we'll
1821 * scavenge it later).
1824 && ((StgIndStatic *)q)->saved_info == NULL
1825 && IND_STATIC_LINK((StgClosure *)q) == NULL) {
1826 IND_STATIC_LINK((StgClosure *)q) = static_objects;
1827 static_objects = (StgClosure *)q;
1832 if (major_gc && STATIC_LINK(info,(StgClosure *)q) == NULL) {
1833 STATIC_LINK(info,(StgClosure *)q) = static_objects;
1834 static_objects = (StgClosure *)q;
1838 case CONSTR_INTLIKE:
1839 case CONSTR_CHARLIKE:
1840 case CONSTR_NOCAF_STATIC:
1841 /* no need to put these on the static linked list, they don't need
1855 case CATCH_STM_FRAME:
1856 case CATCH_RETRY_FRAME:
1857 case ATOMICALLY_FRAME:
1858 // shouldn't see these
1859 barf("evacuate: stack frame at %p\n", q);
1863 return copy(q,pap_sizeW((StgPAP*)q),stp);
1866 return copy(q,ap_stack_sizeW((StgAP_STACK*)q),stp);
1869 /* Already evacuated, just return the forwarding address.
1870 * HOWEVER: if the requested destination generation (evac_gen) is
1871 * older than the actual generation (because the object was
1872 * already evacuated to a younger generation) then we have to
1873 * set the failed_to_evac flag to indicate that we couldn't
1874 * manage to promote the object to the desired generation.
1876 if (evac_gen > 0) { // optimisation
1877 StgClosure *p = ((StgEvacuated*)q)->evacuee;
1878 if (HEAP_ALLOCED(p) && Bdescr((P_)p)->gen_no < evac_gen) {
1879 failed_to_evac = rtsTrue;
1880 TICK_GC_FAILED_PROMOTION();
1883 return ((StgEvacuated*)q)->evacuee;
1886 // just copy the block
1887 return copy(q,arr_words_sizeW((StgArrWords *)q),stp);
1890 case MUT_ARR_PTRS_FROZEN:
1891 case MUT_ARR_PTRS_FROZEN0:
1892 // just copy the block
1893 return copy(q,mut_arr_ptrs_sizeW((StgMutArrPtrs *)q),stp);
1897 StgTSO *tso = (StgTSO *)q;
1899 /* Deal with redirected TSOs (a TSO that's had its stack enlarged).
1901 if (tso->what_next == ThreadRelocated) {
1902 q = (StgClosure *)tso->link;
1906 /* To evacuate a small TSO, we need to relocate the update frame
1913 new_tso = (StgTSO *)copyPart((StgClosure *)tso,
1915 sizeofW(StgTSO), stp);
1916 move_TSO(tso, new_tso);
1917 for (p = tso->sp, q = new_tso->sp;
1918 p < tso->stack+tso->stack_size;) {
1922 return (StgClosure *)new_tso;
1929 //StgInfoTable *rip = get_closure_info(q, &size, &ptrs, &nonptrs, &vhs, str);
1930 to = copy(q,BLACKHOLE_sizeW(),stp);
1931 //ToDo: derive size etc from reverted IP
1932 //to = copy(q,size,stp);
1934 debugBelch("@@ evacuate: RBH %p (%s) to %p (%s)",
1935 q, info_type(q), to, info_type(to)));
1940 ASSERT(sizeofW(StgBlockedFetch) >= MIN_NONUPD_SIZE);
1941 to = copy(q,sizeofW(StgBlockedFetch),stp);
1943 debugBelch("@@ evacuate: %p (%s) to %p (%s)",
1944 q, info_type(q), to, info_type(to)));
1951 ASSERT(sizeofW(StgBlockedFetch) >= MIN_UPD_SIZE);
1952 to = copy(q,sizeofW(StgFetchMe),stp);
1954 debugBelch("@@ evacuate: %p (%s) to %p (%s)",
1955 q, info_type(q), to, info_type(to)));
1959 ASSERT(sizeofW(StgBlockedFetch) >= MIN_UPD_SIZE);
1960 to = copy(q,sizeofW(StgFetchMeBlockingQueue),stp);
1962 debugBelch("@@ evacuate: %p (%s) to %p (%s)",
1963 q, info_type(q), to, info_type(to)));
1968 return copy(q,sizeofW(StgTRecHeader),stp);
1970 case TVAR_WAIT_QUEUE:
1971 return copy(q,sizeofW(StgTVarWaitQueue),stp);
1974 return copy(q,sizeofW(StgTVar),stp);
1977 return copy(q,sizeofW(StgTRecChunk),stp);
1980 barf("evacuate: strange closure type %d", (int)(info->type));
1986 /* -----------------------------------------------------------------------------
1987 Evaluate a THUNK_SELECTOR if possible.
1989 returns: NULL if we couldn't evaluate this THUNK_SELECTOR, or
1990 a closure pointer if we evaluated it and this is the result. Note
1991 that "evaluating" the THUNK_SELECTOR doesn't necessarily mean
1992 reducing it to HNF, just that we have eliminated the selection.
1993 The result might be another thunk, or even another THUNK_SELECTOR.
1995 If the return value is non-NULL, the original selector thunk has
1996 been BLACKHOLE'd, and should be updated with an indirection or a
1997 forwarding pointer. If the return value is NULL, then the selector
2001 ToDo: the treatment of THUNK_SELECTORS could be improved in the
2002 following way (from a suggestion by Ian Lynagh):
2004 We can have a chain like this:
2008 |-----> sel_0 --> (a,b)
2010 |-----> sel_0 --> ...
2012 and the depth limit means we don't go all the way to the end of the
2013 chain, which results in a space leak. This affects the recursive
2014 call to evacuate() in the THUNK_SELECTOR case in evacuate(): *not*
2015 the recursive call to eval_thunk_selector() in
2016 eval_thunk_selector().
2018 We could eliminate the depth bound in this case, in the following
2021 - traverse the chain once to discover the *value* of the
2022 THUNK_SELECTOR. Mark all THUNK_SELECTORS that we
2023 visit on the way as having been visited already (somehow).
2025 - in a second pass, traverse the chain again updating all
2026 THUNK_SEELCTORS that we find on the way with indirections to
2029 - if we encounter a "marked" THUNK_SELECTOR in a normal
2030 evacuate(), we konw it can't be updated so just evac it.
2032 Program that illustrates the problem:
2035 foo (x:xs) = let (ys, zs) = foo xs
2036 in if x >= 0 then (x:ys, zs) else (ys, x:zs)
2038 main = bar [1..(100000000::Int)]
2039 bar xs = (\(ys, zs) -> print ys >> print zs) (foo xs)
2041 -------------------------------------------------------------------------- */
2043 static inline rtsBool
2044 is_to_space ( StgClosure *p )
2048 bd = Bdescr((StgPtr)p);
2049 if (HEAP_ALLOCED(p) &&
2050 ((bd->flags & BF_EVACUATED)
2051 || ((bd->flags & BF_COMPACTED) &&
2052 is_marked((P_)p,bd)))) {
2060 eval_thunk_selector( nat field, StgSelector * p )
2063 const StgInfoTable *info_ptr;
2064 StgClosure *selectee;
2066 selectee = p->selectee;
2068 // Save the real info pointer (NOTE: not the same as get_itbl()).
2069 info_ptr = p->header.info;
2071 // If the THUNK_SELECTOR is in a generation that we are not
2072 // collecting, then bail out early. We won't be able to save any
2073 // space in any case, and updating with an indirection is trickier
2075 if (Bdescr((StgPtr)p)->gen_no > N) {
2079 // BLACKHOLE the selector thunk, since it is now under evaluation.
2080 // This is important to stop us going into an infinite loop if
2081 // this selector thunk eventually refers to itself.
2082 SET_INFO(p,&stg_BLACKHOLE_info);
2086 // We don't want to end up in to-space, because this causes
2087 // problems when the GC later tries to evacuate the result of
2088 // eval_thunk_selector(). There are various ways this could
2091 // 1. following an IND_STATIC
2093 // 2. when the old generation is compacted, the mark phase updates
2094 // from-space pointers to be to-space pointers, and we can't
2095 // reliably tell which we're following (eg. from an IND_STATIC).
2097 // 3. compacting GC again: if we're looking at a constructor in
2098 // the compacted generation, it might point directly to objects
2099 // in to-space. We must bale out here, otherwise doing the selection
2100 // will result in a to-space pointer being returned.
2102 // (1) is dealt with using a BF_EVACUATED test on the
2103 // selectee. (2) and (3): we can tell if we're looking at an
2104 // object in the compacted generation that might point to
2105 // to-space objects by testing that (a) it is BF_COMPACTED, (b)
2106 // the compacted generation is being collected, and (c) the
2107 // object is marked. Only a marked object may have pointers that
2108 // point to to-space objects, because that happens when
2111 // The to-space test is now embodied in the in_to_space() inline
2112 // function, as it is re-used below.
2114 if (is_to_space(selectee)) {
2118 info = get_itbl(selectee);
2119 switch (info->type) {
2127 case CONSTR_NOCAF_STATIC:
2128 // check that the size is in range
2129 ASSERT(field < (StgWord32)(info->layout.payload.ptrs +
2130 info->layout.payload.nptrs));
2132 // Select the right field from the constructor, and check
2133 // that the result isn't in to-space. It might be in
2134 // to-space if, for example, this constructor contains
2135 // pointers to younger-gen objects (and is on the mut-once
2140 q = selectee->payload[field];
2141 if (is_to_space(q)) {
2151 case IND_OLDGEN_PERM:
2153 selectee = ((StgInd *)selectee)->indirectee;
2157 // We don't follow pointers into to-space; the constructor
2158 // has already been evacuated, so we won't save any space
2159 // leaks by evaluating this selector thunk anyhow.
2162 case THUNK_SELECTOR:
2166 // check that we don't recurse too much, re-using the
2167 // depth bound also used in evacuate().
2168 if (thunk_selector_depth >= MAX_THUNK_SELECTOR_DEPTH) {
2171 thunk_selector_depth++;
2173 val = eval_thunk_selector(info->layout.selector_offset,
2174 (StgSelector *)selectee);
2176 thunk_selector_depth--;
2181 // We evaluated this selector thunk, so update it with
2182 // an indirection. NOTE: we don't use UPD_IND here,
2183 // because we are guaranteed that p is in a generation
2184 // that we are collecting, and we never want to put the
2185 // indirection on a mutable list.
2187 // For the purposes of LDV profiling, we have destroyed
2188 // the original selector thunk.
2189 SET_INFO(p, info_ptr);
2190 LDV_RECORD_DEAD_FILL_SLOP_DYNAMIC(selectee);
2192 ((StgInd *)selectee)->indirectee = val;
2193 SET_INFO(selectee,&stg_IND_info);
2195 // For the purposes of LDV profiling, we have created an
2197 LDV_RECORD_CREATE(selectee);
2214 case SE_CAF_BLACKHOLE:
2226 // not evaluated yet
2230 barf("eval_thunk_selector: strange selectee %d",
2235 // We didn't manage to evaluate this thunk; restore the old info pointer
2236 SET_INFO(p, info_ptr);
2240 /* -----------------------------------------------------------------------------
2241 move_TSO is called to update the TSO structure after it has been
2242 moved from one place to another.
2243 -------------------------------------------------------------------------- */
2246 move_TSO (StgTSO *src, StgTSO *dest)
2250 // relocate the stack pointer...
2251 diff = (StgPtr)dest - (StgPtr)src; // In *words*
2252 dest->sp = (StgPtr)dest->sp + diff;
2255 /* Similar to scavenge_large_bitmap(), but we don't write back the
2256 * pointers we get back from evacuate().
2259 scavenge_large_srt_bitmap( StgLargeSRT *large_srt )
2266 bitmap = large_srt->l.bitmap[b];
2267 size = (nat)large_srt->l.size;
2268 p = (StgClosure **)large_srt->srt;
2269 for (i = 0; i < size; ) {
2270 if ((bitmap & 1) != 0) {
2275 if (i % BITS_IN(W_) == 0) {
2277 bitmap = large_srt->l.bitmap[b];
2279 bitmap = bitmap >> 1;
2284 /* evacuate the SRT. If srt_bitmap is zero, then there isn't an
2285 * srt field in the info table. That's ok, because we'll
2286 * never dereference it.
2289 scavenge_srt (StgClosure **srt, nat srt_bitmap)
2294 bitmap = srt_bitmap;
2297 if (bitmap == (StgHalfWord)(-1)) {
2298 scavenge_large_srt_bitmap( (StgLargeSRT *)srt );
2302 while (bitmap != 0) {
2303 if ((bitmap & 1) != 0) {
2304 #ifdef ENABLE_WIN32_DLL_SUPPORT
2305 // Special-case to handle references to closures hiding out in DLLs, since
2306 // double indirections required to get at those. The code generator knows
2307 // which is which when generating the SRT, so it stores the (indirect)
2308 // reference to the DLL closure in the table by first adding one to it.
2309 // We check for this here, and undo the addition before evacuating it.
2311 // If the SRT entry hasn't got bit 0 set, the SRT entry points to a
2312 // closure that's fixed at link-time, and no extra magic is required.
2313 if ( (unsigned long)(*srt) & 0x1 ) {
2314 evacuate(*stgCast(StgClosure**,(stgCast(unsigned long, *srt) & ~0x1)));
2323 bitmap = bitmap >> 1;
2329 scavenge_thunk_srt(const StgInfoTable *info)
2331 StgThunkInfoTable *thunk_info;
2333 thunk_info = itbl_to_thunk_itbl(info);
2334 scavenge_srt((StgClosure **)GET_SRT(thunk_info), thunk_info->i.srt_bitmap);
2338 scavenge_fun_srt(const StgInfoTable *info)
2340 StgFunInfoTable *fun_info;
2342 fun_info = itbl_to_fun_itbl(info);
2343 scavenge_srt((StgClosure **)GET_FUN_SRT(fun_info), fun_info->i.srt_bitmap);
2347 scavenge_ret_srt(const StgInfoTable *info)
2349 StgRetInfoTable *ret_info;
2351 ret_info = itbl_to_ret_itbl(info);
2352 scavenge_srt((StgClosure **)GET_SRT(ret_info), ret_info->i.srt_bitmap);
2355 /* -----------------------------------------------------------------------------
2357 -------------------------------------------------------------------------- */
2360 scavengeTSO (StgTSO *tso)
2362 // chase the link field for any TSOs on the same queue
2363 tso->link = (StgTSO *)evacuate((StgClosure *)tso->link);
2364 if ( tso->why_blocked == BlockedOnMVar
2365 || tso->why_blocked == BlockedOnBlackHole
2366 || tso->why_blocked == BlockedOnException
2368 || tso->why_blocked == BlockedOnGA
2369 || tso->why_blocked == BlockedOnGA_NoSend
2372 tso->block_info.closure = evacuate(tso->block_info.closure);
2374 if ( tso->blocked_exceptions != NULL ) {
2375 tso->blocked_exceptions =
2376 (StgTSO *)evacuate((StgClosure *)tso->blocked_exceptions);
2379 // scavange current transaction record
2380 tso->trec = (StgTRecHeader *)evacuate((StgClosure *)tso->trec);
2382 // scavenge this thread's stack
2383 scavenge_stack(tso->sp, &(tso->stack[tso->stack_size]));
2386 /* -----------------------------------------------------------------------------
2387 Blocks of function args occur on the stack (at the top) and
2389 -------------------------------------------------------------------------- */
2391 STATIC_INLINE StgPtr
2392 scavenge_arg_block (StgFunInfoTable *fun_info, StgClosure **args)
2399 switch (fun_info->f.fun_type) {
2401 bitmap = BITMAP_BITS(fun_info->f.b.bitmap);
2402 size = BITMAP_SIZE(fun_info->f.b.bitmap);
2405 size = GET_FUN_LARGE_BITMAP(fun_info)->size;
2406 scavenge_large_bitmap(p, GET_FUN_LARGE_BITMAP(fun_info), size);
2410 bitmap = BITMAP_BITS(stg_arg_bitmaps[fun_info->f.fun_type]);
2411 size = BITMAP_SIZE(stg_arg_bitmaps[fun_info->f.fun_type]);
2414 if ((bitmap & 1) == 0) {
2415 *p = (StgWord)(StgPtr)evacuate((StgClosure *)*p);
2418 bitmap = bitmap >> 1;
2426 STATIC_INLINE StgPtr
2427 scavenge_PAP (StgPAP *pap)
2430 StgWord bitmap, size;
2431 StgFunInfoTable *fun_info;
2433 pap->fun = evacuate(pap->fun);
2434 fun_info = get_fun_itbl(pap->fun);
2435 ASSERT(fun_info->i.type != PAP);
2437 p = (StgPtr)pap->payload;
2440 switch (fun_info->f.fun_type) {
2442 bitmap = BITMAP_BITS(fun_info->f.b.bitmap);
2445 scavenge_large_bitmap(p, GET_FUN_LARGE_BITMAP(fun_info), size);
2449 scavenge_large_bitmap((StgPtr)pap->payload, BCO_BITMAP(pap->fun), size);
2453 bitmap = BITMAP_BITS(stg_arg_bitmaps[fun_info->f.fun_type]);
2457 if ((bitmap & 1) == 0) {
2458 *p = (StgWord)(StgPtr)evacuate((StgClosure *)*p);
2461 bitmap = bitmap >> 1;
2469 /* -----------------------------------------------------------------------------
2470 Scavenge a given step until there are no more objects in this step
2473 evac_gen is set by the caller to be either zero (for a step in a
2474 generation < N) or G where G is the generation of the step being
2477 We sometimes temporarily change evac_gen back to zero if we're
2478 scavenging a mutable object where early promotion isn't such a good
2480 -------------------------------------------------------------------------- */
2488 nat saved_evac_gen = evac_gen;
2493 failed_to_evac = rtsFalse;
2495 /* scavenge phase - standard breadth-first scavenging of the
2499 while (bd != stp->hp_bd || p < stp->hp) {
2501 // If we're at the end of this block, move on to the next block
2502 if (bd != stp->hp_bd && p == bd->free) {
2508 ASSERT(LOOKS_LIKE_CLOSURE_PTR(p));
2509 info = get_itbl((StgClosure *)p);
2511 ASSERT(thunk_selector_depth == 0);
2514 switch (info->type) {
2518 StgMVar *mvar = ((StgMVar *)p);
2520 mvar->head = (StgTSO *)evacuate((StgClosure *)mvar->head);
2521 mvar->tail = (StgTSO *)evacuate((StgClosure *)mvar->tail);
2522 mvar->value = evacuate((StgClosure *)mvar->value);
2523 evac_gen = saved_evac_gen;
2524 failed_to_evac = rtsTrue; // mutable.
2525 p += sizeofW(StgMVar);
2530 scavenge_fun_srt(info);
2531 ((StgClosure *)p)->payload[1] = evacuate(((StgClosure *)p)->payload[1]);
2532 ((StgClosure *)p)->payload[0] = evacuate(((StgClosure *)p)->payload[0]);
2533 p += sizeofW(StgHeader) + 2;
2537 scavenge_thunk_srt(info);
2539 ((StgClosure *)p)->payload[1] = evacuate(((StgClosure *)p)->payload[1]);
2540 ((StgClosure *)p)->payload[0] = evacuate(((StgClosure *)p)->payload[0]);
2541 p += sizeofW(StgHeader) + 2;
2545 scavenge_thunk_srt(info);
2546 ((StgClosure *)p)->payload[0] = evacuate(((StgClosure *)p)->payload[0]);
2547 p += sizeofW(StgHeader) + 1;
2551 scavenge_fun_srt(info);
2553 ((StgClosure *)p)->payload[0] = evacuate(((StgClosure *)p)->payload[0]);
2554 p += sizeofW(StgHeader) + 1;
2558 scavenge_thunk_srt(info);
2559 p += sizeofW(StgHeader) + 1;
2563 scavenge_fun_srt(info);
2565 p += sizeofW(StgHeader) + 1;
2569 scavenge_thunk_srt(info);
2570 p += sizeofW(StgHeader) + 2;
2574 scavenge_fun_srt(info);
2576 p += sizeofW(StgHeader) + 2;
2580 scavenge_thunk_srt(info);
2581 ((StgClosure *)p)->payload[0] = evacuate(((StgClosure *)p)->payload[0]);
2582 p += sizeofW(StgHeader) + 2;
2586 scavenge_fun_srt(info);
2588 ((StgClosure *)p)->payload[0] = evacuate(((StgClosure *)p)->payload[0]);
2589 p += sizeofW(StgHeader) + 2;
2593 scavenge_fun_srt(info);
2597 scavenge_thunk_srt(info);
2608 end = (P_)((StgClosure *)p)->payload + info->layout.payload.ptrs;
2609 for (p = (P_)((StgClosure *)p)->payload; p < end; p++) {
2610 *p = (StgWord)(StgPtr)evacuate((StgClosure *)*p);
2612 p += info->layout.payload.nptrs;
2617 StgBCO *bco = (StgBCO *)p;
2618 bco->instrs = (StgArrWords *)evacuate((StgClosure *)bco->instrs);
2619 bco->literals = (StgArrWords *)evacuate((StgClosure *)bco->literals);
2620 bco->ptrs = (StgMutArrPtrs *)evacuate((StgClosure *)bco->ptrs);
2621 bco->itbls = (StgArrWords *)evacuate((StgClosure *)bco->itbls);
2622 p += bco_sizeW(bco);
2627 if (stp->gen->no != 0) {
2630 // No need to call LDV_recordDead_FILL_SLOP_DYNAMIC() because an
2631 // IND_OLDGEN_PERM closure is larger than an IND_PERM closure.
2632 LDV_recordDead((StgClosure *)p, sizeofW(StgInd));
2635 // Todo: maybe use SET_HDR() and remove LDV_RECORD_CREATE()?
2637 SET_INFO(((StgClosure *)p), &stg_IND_OLDGEN_PERM_info);
2639 // We pretend that p has just been created.
2640 LDV_RECORD_CREATE((StgClosure *)p);
2643 case IND_OLDGEN_PERM:
2644 ((StgInd *)p)->indirectee = evacuate(((StgInd *)p)->indirectee);
2645 p += sizeofW(StgInd);
2650 ((StgMutVar *)p)->var = evacuate(((StgMutVar *)p)->var);
2651 evac_gen = saved_evac_gen;
2652 failed_to_evac = rtsTrue; // mutable anyhow
2653 p += sizeofW(StgMutVar);
2657 case SE_CAF_BLACKHOLE:
2660 p += BLACKHOLE_sizeW();
2663 case THUNK_SELECTOR:
2665 StgSelector *s = (StgSelector *)p;
2666 s->selectee = evacuate(s->selectee);
2667 p += THUNK_SELECTOR_sizeW();
2671 // A chunk of stack saved in a heap object
2674 StgAP_STACK *ap = (StgAP_STACK *)p;
2676 ap->fun = evacuate(ap->fun);
2677 scavenge_stack((StgPtr)ap->payload, (StgPtr)ap->payload + ap->size);
2678 p = (StgPtr)ap->payload + ap->size;
2684 p = scavenge_PAP((StgPAP *)p);
2688 // nothing to follow
2689 p += arr_words_sizeW((StgArrWords *)p);
2693 // follow everything
2697 evac_gen = 0; // repeatedly mutable
2698 next = p + mut_arr_ptrs_sizeW((StgMutArrPtrs*)p);
2699 for (p = (P_)((StgMutArrPtrs *)p)->payload; p < next; p++) {
2700 *p = (StgWord)(StgPtr)evacuate((StgClosure *)*p);
2702 evac_gen = saved_evac_gen;
2703 failed_to_evac = rtsTrue; // mutable anyhow.
2707 case MUT_ARR_PTRS_FROZEN:
2708 case MUT_ARR_PTRS_FROZEN0:
2709 // follow everything
2713 next = p + mut_arr_ptrs_sizeW((StgMutArrPtrs*)p);
2714 for (p = (P_)((StgMutArrPtrs *)p)->payload; p < next; p++) {
2715 *p = (StgWord)(StgPtr)evacuate((StgClosure *)*p);
2717 // it's tempting to recordMutable() if failed_to_evac is
2718 // false, but that breaks some assumptions (eg. every
2719 // closure on the mutable list is supposed to have the MUT
2720 // flag set, and MUT_ARR_PTRS_FROZEN doesn't).
2726 StgTSO *tso = (StgTSO *)p;
2729 evac_gen = saved_evac_gen;
2730 failed_to_evac = rtsTrue; // mutable anyhow.
2731 p += tso_sizeW(tso);
2739 nat size, ptrs, nonptrs, vhs;
2741 StgInfoTable *rip = get_closure_info(p, &size, &ptrs, &nonptrs, &vhs, str);
2743 StgRBH *rbh = (StgRBH *)p;
2744 (StgClosure *)rbh->blocking_queue =
2745 evacuate((StgClosure *)rbh->blocking_queue);
2746 failed_to_evac = rtsTrue; // mutable anyhow.
2748 debugBelch("@@ scavenge: RBH %p (%s) (new blocking_queue link=%p)",
2749 p, info_type(p), (StgClosure *)rbh->blocking_queue));
2750 // ToDo: use size of reverted closure here!
2751 p += BLACKHOLE_sizeW();
2757 StgBlockedFetch *bf = (StgBlockedFetch *)p;
2758 // follow the pointer to the node which is being demanded
2759 (StgClosure *)bf->node =
2760 evacuate((StgClosure *)bf->node);
2761 // follow the link to the rest of the blocking queue
2762 (StgClosure *)bf->link =
2763 evacuate((StgClosure *)bf->link);
2765 debugBelch("@@ scavenge: %p (%s); node is now %p; exciting, isn't it",
2766 bf, info_type((StgClosure *)bf),
2767 bf->node, info_type(bf->node)));
2768 p += sizeofW(StgBlockedFetch);
2776 p += sizeofW(StgFetchMe);
2777 break; // nothing to do in this case
2781 StgFetchMeBlockingQueue *fmbq = (StgFetchMeBlockingQueue *)p;
2782 (StgClosure *)fmbq->blocking_queue =
2783 evacuate((StgClosure *)fmbq->blocking_queue);
2785 debugBelch("@@ scavenge: %p (%s) exciting, isn't it",
2786 p, info_type((StgClosure *)p)));
2787 p += sizeofW(StgFetchMeBlockingQueue);
2792 case TVAR_WAIT_QUEUE:
2794 StgTVarWaitQueue *wq = ((StgTVarWaitQueue *) p);
2796 wq->waiting_tso = (StgTSO *)evacuate((StgClosure*)wq->waiting_tso);
2797 wq->next_queue_entry = (StgTVarWaitQueue *)evacuate((StgClosure*)wq->next_queue_entry);
2798 wq->prev_queue_entry = (StgTVarWaitQueue *)evacuate((StgClosure*)wq->prev_queue_entry);
2799 evac_gen = saved_evac_gen;
2800 failed_to_evac = rtsTrue; // mutable
2801 p += sizeofW(StgTVarWaitQueue);
2807 StgTVar *tvar = ((StgTVar *) p);
2809 tvar->current_value = evacuate((StgClosure*)tvar->current_value);
2810 tvar->first_wait_queue_entry = (StgTVarWaitQueue *)evacuate((StgClosure*)tvar->first_wait_queue_entry);
2811 evac_gen = saved_evac_gen;
2812 failed_to_evac = rtsTrue; // mutable
2813 p += sizeofW(StgTVar);
2819 StgTRecHeader *trec = ((StgTRecHeader *) p);
2821 trec->enclosing_trec = (StgTRecHeader *)evacuate((StgClosure*)trec->enclosing_trec);
2822 trec->current_chunk = (StgTRecChunk *)evacuate((StgClosure*)trec->current_chunk);
2823 evac_gen = saved_evac_gen;
2824 failed_to_evac = rtsTrue; // mutable
2825 p += sizeofW(StgTRecHeader);
2832 StgTRecChunk *tc = ((StgTRecChunk *) p);
2833 TRecEntry *e = &(tc -> entries[0]);
2835 tc->prev_chunk = (StgTRecChunk *)evacuate((StgClosure*)tc->prev_chunk);
2836 for (i = 0; i < tc -> next_entry_idx; i ++, e++ ) {
2837 e->tvar = (StgTVar *)evacuate((StgClosure*)e->tvar);
2838 e->expected_value = evacuate((StgClosure*)e->expected_value);
2839 e->new_value = evacuate((StgClosure*)e->new_value);
2841 evac_gen = saved_evac_gen;
2842 failed_to_evac = rtsTrue; // mutable
2843 p += sizeofW(StgTRecChunk);
2848 barf("scavenge: unimplemented/strange closure type %d @ %p",
2853 * We need to record the current object on the mutable list if
2854 * (a) It is actually mutable, or
2855 * (b) It contains pointers to a younger generation.
2856 * Case (b) arises if we didn't manage to promote everything that
2857 * the current object points to into the current generation.
2859 if (failed_to_evac) {
2860 failed_to_evac = rtsFalse;
2861 recordMutableGen((StgClosure *)q, stp->gen);
2869 /* -----------------------------------------------------------------------------
2870 Scavenge everything on the mark stack.
2872 This is slightly different from scavenge():
2873 - we don't walk linearly through the objects, so the scavenger
2874 doesn't need to advance the pointer on to the next object.
2875 -------------------------------------------------------------------------- */
2878 scavenge_mark_stack(void)
2884 evac_gen = oldest_gen->no;
2885 saved_evac_gen = evac_gen;
2888 while (!mark_stack_empty()) {
2889 p = pop_mark_stack();
2891 ASSERT(LOOKS_LIKE_CLOSURE_PTR(p));
2892 info = get_itbl((StgClosure *)p);
2895 switch (info->type) {
2899 StgMVar *mvar = ((StgMVar *)p);
2901 mvar->head = (StgTSO *)evacuate((StgClosure *)mvar->head);
2902 mvar->tail = (StgTSO *)evacuate((StgClosure *)mvar->tail);
2903 mvar->value = evacuate((StgClosure *)mvar->value);
2904 evac_gen = saved_evac_gen;
2905 failed_to_evac = rtsTrue; // mutable.
2910 scavenge_fun_srt(info);
2911 ((StgClosure *)p)->payload[1] = evacuate(((StgClosure *)p)->payload[1]);
2912 ((StgClosure *)p)->payload[0] = evacuate(((StgClosure *)p)->payload[0]);
2916 scavenge_thunk_srt(info);
2918 ((StgClosure *)p)->payload[1] = evacuate(((StgClosure *)p)->payload[1]);
2919 ((StgClosure *)p)->payload[0] = evacuate(((StgClosure *)p)->payload[0]);
2924 scavenge_fun_srt(info);
2925 ((StgClosure *)p)->payload[0] = evacuate(((StgClosure *)p)->payload[0]);
2930 scavenge_thunk_srt(info);
2933 ((StgClosure *)p)->payload[0] = evacuate(((StgClosure *)p)->payload[0]);
2938 scavenge_fun_srt(info);
2943 scavenge_thunk_srt(info);
2951 scavenge_fun_srt(info);
2955 scavenge_thunk_srt(info);
2966 end = (P_)((StgClosure *)p)->payload + info->layout.payload.ptrs;
2967 for (p = (P_)((StgClosure *)p)->payload; p < end; p++) {
2968 *p = (StgWord)(StgPtr)evacuate((StgClosure *)*p);
2974 StgBCO *bco = (StgBCO *)p;
2975 bco->instrs = (StgArrWords *)evacuate((StgClosure *)bco->instrs);
2976 bco->literals = (StgArrWords *)evacuate((StgClosure *)bco->literals);
2977 bco->ptrs = (StgMutArrPtrs *)evacuate((StgClosure *)bco->ptrs);
2978 bco->itbls = (StgArrWords *)evacuate((StgClosure *)bco->itbls);
2983 // don't need to do anything here: the only possible case
2984 // is that we're in a 1-space compacting collector, with
2985 // no "old" generation.
2989 case IND_OLDGEN_PERM:
2990 ((StgInd *)p)->indirectee =
2991 evacuate(((StgInd *)p)->indirectee);
2996 ((StgMutVar *)p)->var = evacuate(((StgMutVar *)p)->var);
2997 evac_gen = saved_evac_gen;
2998 failed_to_evac = rtsTrue;
3002 case SE_CAF_BLACKHOLE:
3008 case THUNK_SELECTOR:
3010 StgSelector *s = (StgSelector *)p;
3011 s->selectee = evacuate(s->selectee);
3015 // A chunk of stack saved in a heap object
3018 StgAP_STACK *ap = (StgAP_STACK *)p;
3020 ap->fun = evacuate(ap->fun);
3021 scavenge_stack((StgPtr)ap->payload, (StgPtr)ap->payload + ap->size);
3027 scavenge_PAP((StgPAP *)p);
3031 // follow everything
3035 evac_gen = 0; // repeatedly mutable
3036 next = p + mut_arr_ptrs_sizeW((StgMutArrPtrs*)p);
3037 for (p = (P_)((StgMutArrPtrs *)p)->payload; p < next; p++) {
3038 *p = (StgWord)(StgPtr)evacuate((StgClosure *)*p);
3040 evac_gen = saved_evac_gen;
3041 failed_to_evac = rtsTrue; // mutable anyhow.
3045 case MUT_ARR_PTRS_FROZEN:
3046 case MUT_ARR_PTRS_FROZEN0:
3047 // follow everything
3051 next = p + mut_arr_ptrs_sizeW((StgMutArrPtrs*)p);
3052 for (p = (P_)((StgMutArrPtrs *)p)->payload; p < next; p++) {
3053 *p = (StgWord)(StgPtr)evacuate((StgClosure *)*p);
3060 StgTSO *tso = (StgTSO *)p;
3063 evac_gen = saved_evac_gen;
3064 failed_to_evac = rtsTrue;
3072 nat size, ptrs, nonptrs, vhs;
3074 StgInfoTable *rip = get_closure_info(p, &size, &ptrs, &nonptrs, &vhs, str);
3076 StgRBH *rbh = (StgRBH *)p;
3077 bh->blocking_queue =
3078 (StgTSO *)evacuate((StgClosure *)bh->blocking_queue);
3079 failed_to_evac = rtsTrue; // mutable anyhow.
3081 debugBelch("@@ scavenge: RBH %p (%s) (new blocking_queue link=%p)",
3082 p, info_type(p), (StgClosure *)rbh->blocking_queue));
3088 StgBlockedFetch *bf = (StgBlockedFetch *)p;
3089 // follow the pointer to the node which is being demanded
3090 (StgClosure *)bf->node =
3091 evacuate((StgClosure *)bf->node);
3092 // follow the link to the rest of the blocking queue
3093 (StgClosure *)bf->link =
3094 evacuate((StgClosure *)bf->link);
3096 debugBelch("@@ scavenge: %p (%s); node is now %p; exciting, isn't it",
3097 bf, info_type((StgClosure *)bf),
3098 bf->node, info_type(bf->node)));
3106 break; // nothing to do in this case
3110 StgFetchMeBlockingQueue *fmbq = (StgFetchMeBlockingQueue *)p;
3111 (StgClosure *)fmbq->blocking_queue =
3112 evacuate((StgClosure *)fmbq->blocking_queue);
3114 debugBelch("@@ scavenge: %p (%s) exciting, isn't it",
3115 p, info_type((StgClosure *)p)));
3120 case TVAR_WAIT_QUEUE:
3122 StgTVarWaitQueue *wq = ((StgTVarWaitQueue *) p);
3124 wq->waiting_tso = (StgTSO *)evacuate((StgClosure*)wq->waiting_tso);
3125 wq->next_queue_entry = (StgTVarWaitQueue *)evacuate((StgClosure*)wq->next_queue_entry);
3126 wq->prev_queue_entry = (StgTVarWaitQueue *)evacuate((StgClosure*)wq->prev_queue_entry);
3127 evac_gen = saved_evac_gen;
3128 failed_to_evac = rtsTrue; // mutable
3134 StgTVar *tvar = ((StgTVar *) p);
3136 tvar->current_value = evacuate((StgClosure*)tvar->current_value);
3137 tvar->first_wait_queue_entry = (StgTVarWaitQueue *)evacuate((StgClosure*)tvar->first_wait_queue_entry);
3138 evac_gen = saved_evac_gen;
3139 failed_to_evac = rtsTrue; // mutable
3146 StgTRecChunk *tc = ((StgTRecChunk *) p);
3147 TRecEntry *e = &(tc -> entries[0]);
3149 tc->prev_chunk = (StgTRecChunk *)evacuate((StgClosure*)tc->prev_chunk);
3150 for (i = 0; i < tc -> next_entry_idx; i ++, e++ ) {
3151 e->tvar = (StgTVar *)evacuate((StgClosure*)e->tvar);
3152 e->expected_value = evacuate((StgClosure*)e->expected_value);
3153 e->new_value = evacuate((StgClosure*)e->new_value);
3155 evac_gen = saved_evac_gen;
3156 failed_to_evac = rtsTrue; // mutable
3162 StgTRecHeader *trec = ((StgTRecHeader *) p);
3164 trec->enclosing_trec = (StgTRecHeader *)evacuate((StgClosure*)trec->enclosing_trec);
3165 trec->current_chunk = (StgTRecChunk *)evacuate((StgClosure*)trec->current_chunk);
3166 evac_gen = saved_evac_gen;
3167 failed_to_evac = rtsTrue; // mutable
3172 barf("scavenge_mark_stack: unimplemented/strange closure type %d @ %p",
3176 if (failed_to_evac) {
3177 failed_to_evac = rtsFalse;
3178 recordMutableGen((StgClosure *)q, &generations[evac_gen]);
3181 // mark the next bit to indicate "scavenged"
3182 mark(q+1, Bdescr(q));
3184 } // while (!mark_stack_empty())
3186 // start a new linear scan if the mark stack overflowed at some point
3187 if (mark_stack_overflowed && oldgen_scan_bd == NULL) {
3188 IF_DEBUG(gc, debugBelch("scavenge_mark_stack: starting linear scan"));
3189 mark_stack_overflowed = rtsFalse;
3190 oldgen_scan_bd = oldest_gen->steps[0].blocks;
3191 oldgen_scan = oldgen_scan_bd->start;
3194 if (oldgen_scan_bd) {
3195 // push a new thing on the mark stack
3197 // find a closure that is marked but not scavenged, and start
3199 while (oldgen_scan < oldgen_scan_bd->free
3200 && !is_marked(oldgen_scan,oldgen_scan_bd)) {
3204 if (oldgen_scan < oldgen_scan_bd->free) {
3206 // already scavenged?
3207 if (is_marked(oldgen_scan+1,oldgen_scan_bd)) {
3208 oldgen_scan += sizeofW(StgHeader) + MIN_NONUPD_SIZE;
3211 push_mark_stack(oldgen_scan);
3212 // ToDo: bump the linear scan by the actual size of the object
3213 oldgen_scan += sizeofW(StgHeader) + MIN_NONUPD_SIZE;
3217 oldgen_scan_bd = oldgen_scan_bd->link;
3218 if (oldgen_scan_bd != NULL) {
3219 oldgen_scan = oldgen_scan_bd->start;
3225 /* -----------------------------------------------------------------------------
3226 Scavenge one object.
3228 This is used for objects that are temporarily marked as mutable
3229 because they contain old-to-new generation pointers. Only certain
3230 objects can have this property.
3231 -------------------------------------------------------------------------- */
3234 scavenge_one(StgPtr p)
3236 const StgInfoTable *info;
3237 nat saved_evac_gen = evac_gen;
3240 ASSERT(LOOKS_LIKE_CLOSURE_PTR(p));
3241 info = get_itbl((StgClosure *)p);
3243 switch (info->type) {
3247 StgMVar *mvar = ((StgMVar *)p);
3249 mvar->head = (StgTSO *)evacuate((StgClosure *)mvar->head);
3250 mvar->tail = (StgTSO *)evacuate((StgClosure *)mvar->tail);
3251 mvar->value = evacuate((StgClosure *)mvar->value);
3252 evac_gen = saved_evac_gen;
3253 failed_to_evac = rtsTrue; // mutable.
3258 case FUN_1_0: // hardly worth specialising these guys
3281 end = (StgPtr)((StgClosure *)p)->payload + info->layout.payload.ptrs;
3282 for (q = (StgPtr)((StgClosure *)p)->payload; q < end; q++) {
3283 *q = (StgWord)(StgPtr)evacuate((StgClosure *)*q);
3290 ((StgMutVar *)p)->var = evacuate(((StgMutVar *)p)->var);
3291 evac_gen = saved_evac_gen;
3292 failed_to_evac = rtsTrue; // mutable anyhow
3296 case SE_CAF_BLACKHOLE:
3301 case THUNK_SELECTOR:
3303 StgSelector *s = (StgSelector *)p;
3304 s->selectee = evacuate(s->selectee);
3310 StgAP_STACK *ap = (StgAP_STACK *)p;
3312 ap->fun = evacuate(ap->fun);
3313 scavenge_stack((StgPtr)ap->payload, (StgPtr)ap->payload + ap->size);
3314 p = (StgPtr)ap->payload + ap->size;
3320 p = scavenge_PAP((StgPAP *)p);
3324 // nothing to follow
3329 // follow everything
3332 evac_gen = 0; // repeatedly mutable
3333 next = p + mut_arr_ptrs_sizeW((StgMutArrPtrs*)p);
3334 for (p = (P_)((StgMutArrPtrs *)p)->payload; p < next; p++) {
3335 *p = (StgWord)(StgPtr)evacuate((StgClosure *)*p);
3337 evac_gen = saved_evac_gen;
3338 failed_to_evac = rtsTrue;
3342 case MUT_ARR_PTRS_FROZEN:
3343 case MUT_ARR_PTRS_FROZEN0:
3345 // follow everything
3348 next = p + mut_arr_ptrs_sizeW((StgMutArrPtrs*)p);
3349 for (p = (P_)((StgMutArrPtrs *)p)->payload; p < next; p++) {
3350 *p = (StgWord)(StgPtr)evacuate((StgClosure *)*p);
3357 StgTSO *tso = (StgTSO *)p;
3359 evac_gen = 0; // repeatedly mutable
3361 evac_gen = saved_evac_gen;
3362 failed_to_evac = rtsTrue;
3370 nat size, ptrs, nonptrs, vhs;
3372 StgInfoTable *rip = get_closure_info(p, &size, &ptrs, &nonptrs, &vhs, str);
3374 StgRBH *rbh = (StgRBH *)p;
3375 (StgClosure *)rbh->blocking_queue =
3376 evacuate((StgClosure *)rbh->blocking_queue);
3377 failed_to_evac = rtsTrue; // mutable anyhow.
3379 debugBelch("@@ scavenge: RBH %p (%s) (new blocking_queue link=%p)",
3380 p, info_type(p), (StgClosure *)rbh->blocking_queue));
3381 // ToDo: use size of reverted closure here!
3387 StgBlockedFetch *bf = (StgBlockedFetch *)p;
3388 // follow the pointer to the node which is being demanded
3389 (StgClosure *)bf->node =
3390 evacuate((StgClosure *)bf->node);
3391 // follow the link to the rest of the blocking queue
3392 (StgClosure *)bf->link =
3393 evacuate((StgClosure *)bf->link);
3395 debugBelch("@@ scavenge: %p (%s); node is now %p; exciting, isn't it",
3396 bf, info_type((StgClosure *)bf),
3397 bf->node, info_type(bf->node)));
3405 break; // nothing to do in this case
3409 StgFetchMeBlockingQueue *fmbq = (StgFetchMeBlockingQueue *)p;
3410 (StgClosure *)fmbq->blocking_queue =
3411 evacuate((StgClosure *)fmbq->blocking_queue);
3413 debugBelch("@@ scavenge: %p (%s) exciting, isn't it",
3414 p, info_type((StgClosure *)p)));
3419 case TVAR_WAIT_QUEUE:
3421 StgTVarWaitQueue *wq = ((StgTVarWaitQueue *) p);
3423 wq->waiting_tso = (StgTSO *)evacuate((StgClosure*)wq->waiting_tso);
3424 wq->next_queue_entry = (StgTVarWaitQueue *)evacuate((StgClosure*)wq->next_queue_entry);
3425 wq->prev_queue_entry = (StgTVarWaitQueue *)evacuate((StgClosure*)wq->prev_queue_entry);
3426 evac_gen = saved_evac_gen;
3427 failed_to_evac = rtsTrue; // mutable
3433 StgTVar *tvar = ((StgTVar *) p);
3435 tvar->current_value = evacuate((StgClosure*)tvar->current_value);
3436 tvar->first_wait_queue_entry = (StgTVarWaitQueue *)evacuate((StgClosure*)tvar->first_wait_queue_entry);
3437 evac_gen = saved_evac_gen;
3438 failed_to_evac = rtsTrue; // mutable
3444 StgTRecHeader *trec = ((StgTRecHeader *) p);
3446 trec->enclosing_trec = (StgTRecHeader *)evacuate((StgClosure*)trec->enclosing_trec);
3447 trec->current_chunk = (StgTRecChunk *)evacuate((StgClosure*)trec->current_chunk);
3448 evac_gen = saved_evac_gen;
3449 failed_to_evac = rtsTrue; // mutable
3456 StgTRecChunk *tc = ((StgTRecChunk *) p);
3457 TRecEntry *e = &(tc -> entries[0]);
3459 tc->prev_chunk = (StgTRecChunk *)evacuate((StgClosure*)tc->prev_chunk);
3460 for (i = 0; i < tc -> next_entry_idx; i ++, e++ ) {
3461 e->tvar = (StgTVar *)evacuate((StgClosure*)e->tvar);
3462 e->expected_value = evacuate((StgClosure*)e->expected_value);
3463 e->new_value = evacuate((StgClosure*)e->new_value);
3465 evac_gen = saved_evac_gen;
3466 failed_to_evac = rtsTrue; // mutable
3471 case IND_OLDGEN_PERM:
3474 /* Careful here: a THUNK can be on the mutable list because
3475 * it contains pointers to young gen objects. If such a thunk
3476 * is updated, the IND_OLDGEN will be added to the mutable
3477 * list again, and we'll scavenge it twice. evacuate()
3478 * doesn't check whether the object has already been
3479 * evacuated, so we perform that check here.
3481 StgClosure *q = ((StgInd *)p)->indirectee;
3482 if (HEAP_ALLOCED(q) && Bdescr((StgPtr)q)->flags & BF_EVACUATED) {
3485 ((StgInd *)p)->indirectee = evacuate(q);
3488 #if 0 && defined(DEBUG)
3489 if (RtsFlags.DebugFlags.gc)
3490 /* Debugging code to print out the size of the thing we just
3494 StgPtr start = gen->steps[0].scan;
3495 bdescr *start_bd = gen->steps[0].scan_bd;
3497 scavenge(&gen->steps[0]);
3498 if (start_bd != gen->steps[0].scan_bd) {
3499 size += (P_)BLOCK_ROUND_UP(start) - start;
3500 start_bd = start_bd->link;
3501 while (start_bd != gen->steps[0].scan_bd) {
3502 size += BLOCK_SIZE_W;
3503 start_bd = start_bd->link;
3505 size += gen->steps[0].scan -
3506 (P_)BLOCK_ROUND_DOWN(gen->steps[0].scan);
3508 size = gen->steps[0].scan - start;
3510 debugBelch("evac IND_OLDGEN: %ld bytes", size * sizeof(W_));
3516 barf("scavenge_one: strange object %d", (int)(info->type));
3519 no_luck = failed_to_evac;
3520 failed_to_evac = rtsFalse;
3524 /* -----------------------------------------------------------------------------
3525 Scavenging mutable lists.
3527 We treat the mutable list of each generation > N (i.e. all the
3528 generations older than the one being collected) as roots. We also
3529 remove non-mutable objects from the mutable list at this point.
3530 -------------------------------------------------------------------------- */
3533 scavenge_mutable_list(generation *gen)
3538 bd = gen->saved_mut_list;
3541 for (; bd != NULL; bd = bd->link) {
3542 for (q = bd->start; q < bd->free; q++) {
3544 ASSERT(LOOKS_LIKE_CLOSURE_PTR(p));
3545 if (scavenge_one(p)) {
3546 /* didn't manage to promote everything, so put the
3547 * object back on the list.
3549 recordMutableGen((StgClosure *)p,gen);
3554 // free the old mut_list
3555 freeChain(gen->saved_mut_list);
3556 gen->saved_mut_list = NULL;
3561 scavenge_static(void)
3563 StgClosure* p = static_objects;
3564 const StgInfoTable *info;
3566 /* Always evacuate straight to the oldest generation for static
3568 evac_gen = oldest_gen->no;
3570 /* keep going until we've scavenged all the objects on the linked
3572 while (p != END_OF_STATIC_LIST) {
3574 ASSERT(LOOKS_LIKE_CLOSURE_PTR(p));
3577 if (info->type==RBH)
3578 info = REVERT_INFOPTR(info); // if it's an RBH, look at the orig closure
3580 // make sure the info pointer is into text space
3582 /* Take this object *off* the static_objects list,
3583 * and put it on the scavenged_static_objects list.
3585 static_objects = STATIC_LINK(info,p);
3586 STATIC_LINK(info,p) = scavenged_static_objects;
3587 scavenged_static_objects = p;
3589 switch (info -> type) {
3593 StgInd *ind = (StgInd *)p;
3594 ind->indirectee = evacuate(ind->indirectee);
3596 /* might fail to evacuate it, in which case we have to pop it
3597 * back on the mutable list of the oldest generation. We
3598 * leave it *on* the scavenged_static_objects list, though,
3599 * in case we visit this object again.
3601 if (failed_to_evac) {
3602 failed_to_evac = rtsFalse;
3603 recordMutableGen((StgClosure *)p,oldest_gen);
3609 scavenge_thunk_srt(info);
3613 scavenge_fun_srt(info);
3620 next = (P_)p->payload + info->layout.payload.ptrs;
3621 // evacuate the pointers
3622 for (q = (P_)p->payload; q < next; q++) {
3623 *q = (StgWord)(StgPtr)evacuate((StgClosure *)*q);
3629 barf("scavenge_static: strange closure %d", (int)(info->type));
3632 ASSERT(failed_to_evac == rtsFalse);
3634 /* get the next static object from the list. Remember, there might
3635 * be more stuff on this list now that we've done some evacuating!
3636 * (static_objects is a global)
3642 /* -----------------------------------------------------------------------------
3643 scavenge a chunk of memory described by a bitmap
3644 -------------------------------------------------------------------------- */
3647 scavenge_large_bitmap( StgPtr p, StgLargeBitmap *large_bitmap, nat size )
3653 bitmap = large_bitmap->bitmap[b];
3654 for (i = 0; i < size; ) {
3655 if ((bitmap & 1) == 0) {
3656 *p = (StgWord)(StgPtr)evacuate((StgClosure *)*p);
3660 if (i % BITS_IN(W_) == 0) {
3662 bitmap = large_bitmap->bitmap[b];
3664 bitmap = bitmap >> 1;
3669 STATIC_INLINE StgPtr
3670 scavenge_small_bitmap (StgPtr p, nat size, StgWord bitmap)
3673 if ((bitmap & 1) == 0) {
3674 *p = (StgWord)(StgPtr)evacuate((StgClosure *)*p);
3677 bitmap = bitmap >> 1;
3683 /* -----------------------------------------------------------------------------
3684 scavenge_stack walks over a section of stack and evacuates all the
3685 objects pointed to by it. We can use the same code for walking
3686 AP_STACK_UPDs, since these are just sections of copied stack.
3687 -------------------------------------------------------------------------- */
3691 scavenge_stack(StgPtr p, StgPtr stack_end)
3693 const StgRetInfoTable* info;
3697 //IF_DEBUG(sanity, debugBelch(" scavenging stack between %p and %p", p, stack_end));
3700 * Each time around this loop, we are looking at a chunk of stack
3701 * that starts with an activation record.
3704 while (p < stack_end) {
3705 info = get_ret_itbl((StgClosure *)p);
3707 switch (info->i.type) {
3710 ((StgUpdateFrame *)p)->updatee
3711 = evacuate(((StgUpdateFrame *)p)->updatee);
3712 p += sizeofW(StgUpdateFrame);
3715 // small bitmap (< 32 entries, or 64 on a 64-bit machine)
3716 case CATCH_STM_FRAME:
3717 case CATCH_RETRY_FRAME:
3718 case ATOMICALLY_FRAME:
3723 bitmap = BITMAP_BITS(info->i.layout.bitmap);
3724 size = BITMAP_SIZE(info->i.layout.bitmap);
3725 // NOTE: the payload starts immediately after the info-ptr, we
3726 // don't have an StgHeader in the same sense as a heap closure.
3728 p = scavenge_small_bitmap(p, size, bitmap);
3731 scavenge_srt((StgClosure **)GET_SRT(info), info->i.srt_bitmap);
3739 *p = (StgWord)(StgPtr)evacuate((StgClosure *)*p);
3742 size = BCO_BITMAP_SIZE(bco);
3743 scavenge_large_bitmap(p, BCO_BITMAP(bco), size);
3748 // large bitmap (> 32 entries, or > 64 on a 64-bit machine)
3754 size = GET_LARGE_BITMAP(&info->i)->size;
3756 scavenge_large_bitmap(p, GET_LARGE_BITMAP(&info->i), size);
3758 // and don't forget to follow the SRT
3762 // Dynamic bitmap: the mask is stored on the stack, and
3763 // there are a number of non-pointers followed by a number
3764 // of pointers above the bitmapped area. (see StgMacros.h,
3769 dyn = ((StgRetDyn *)p)->liveness;
3771 // traverse the bitmap first
3772 bitmap = RET_DYN_LIVENESS(dyn);
3773 p = (P_)&((StgRetDyn *)p)->payload[0];
3774 size = RET_DYN_BITMAP_SIZE;
3775 p = scavenge_small_bitmap(p, size, bitmap);
3777 // skip over the non-ptr words
3778 p += RET_DYN_NONPTRS(dyn) + RET_DYN_NONPTR_REGS_SIZE;
3780 // follow the ptr words
3781 for (size = RET_DYN_PTRS(dyn); size > 0; size--) {
3782 *p = (StgWord)(StgPtr)evacuate((StgClosure *)*p);
3790 StgRetFun *ret_fun = (StgRetFun *)p;
3791 StgFunInfoTable *fun_info;
3793 ret_fun->fun = evacuate(ret_fun->fun);
3794 fun_info = get_fun_itbl(ret_fun->fun);
3795 p = scavenge_arg_block(fun_info, ret_fun->payload);
3800 barf("scavenge_stack: weird activation record found on stack: %d", (int)(info->i.type));
3805 /*-----------------------------------------------------------------------------
3806 scavenge the large object list.
3808 evac_gen set by caller; similar games played with evac_gen as with
3809 scavenge() - see comment at the top of scavenge(). Most large
3810 objects are (repeatedly) mutable, so most of the time evac_gen will
3812 --------------------------------------------------------------------------- */
3815 scavenge_large(step *stp)
3820 bd = stp->new_large_objects;
3822 for (; bd != NULL; bd = stp->new_large_objects) {
3824 /* take this object *off* the large objects list and put it on
3825 * the scavenged large objects list. This is so that we can
3826 * treat new_large_objects as a stack and push new objects on
3827 * the front when evacuating.
3829 stp->new_large_objects = bd->link;
3830 dbl_link_onto(bd, &stp->scavenged_large_objects);
3832 // update the block count in this step.
3833 stp->n_scavenged_large_blocks += bd->blocks;
3836 if (scavenge_one(p)) {
3837 recordMutableGen((StgClosure *)p, stp->gen);
3842 /* -----------------------------------------------------------------------------
3843 Initialising the static object & mutable lists
3844 -------------------------------------------------------------------------- */
3847 zero_static_object_list(StgClosure* first_static)
3851 const StgInfoTable *info;
3853 for (p = first_static; p != END_OF_STATIC_LIST; p = link) {
3855 link = STATIC_LINK(info, p);
3856 STATIC_LINK(info,p) = NULL;
3860 /* -----------------------------------------------------------------------------
3862 -------------------------------------------------------------------------- */
3869 for (c = (StgIndStatic *)revertible_caf_list; c != NULL;
3870 c = (StgIndStatic *)c->static_link)
3872 SET_INFO(c, c->saved_info);
3873 c->saved_info = NULL;
3874 // could, but not necessary: c->static_link = NULL;
3876 revertible_caf_list = NULL;
3880 markCAFs( evac_fn evac )
3884 for (c = (StgIndStatic *)caf_list; c != NULL;
3885 c = (StgIndStatic *)c->static_link)
3887 evac(&c->indirectee);
3889 for (c = (StgIndStatic *)revertible_caf_list; c != NULL;
3890 c = (StgIndStatic *)c->static_link)
3892 evac(&c->indirectee);
3896 /* -----------------------------------------------------------------------------
3897 Sanity code for CAF garbage collection.
3899 With DEBUG turned on, we manage a CAF list in addition to the SRT
3900 mechanism. After GC, we run down the CAF list and blackhole any
3901 CAFs which have been garbage collected. This means we get an error
3902 whenever the program tries to enter a garbage collected CAF.
3904 Any garbage collected CAFs are taken off the CAF list at the same
3906 -------------------------------------------------------------------------- */
3908 #if 0 && defined(DEBUG)
3915 const StgInfoTable *info;
3926 ASSERT(info->type == IND_STATIC);
3928 if (STATIC_LINK(info,p) == NULL) {
3929 IF_DEBUG(gccafs, debugBelch("CAF gc'd at 0x%04lx", (long)p));
3931 SET_INFO(p,&stg_BLACKHOLE_info);
3932 p = STATIC_LINK2(info,p);
3936 pp = &STATIC_LINK2(info,p);
3943 // debugBelch("%d CAFs live", i);
3948 /* -----------------------------------------------------------------------------
3951 Whenever a thread returns to the scheduler after possibly doing
3952 some work, we have to run down the stack and black-hole all the
3953 closures referred to by update frames.
3954 -------------------------------------------------------------------------- */
3957 threadLazyBlackHole(StgTSO *tso)
3960 StgRetInfoTable *info;
3964 stack_end = &tso->stack[tso->stack_size];
3966 frame = (StgClosure *)tso->sp;
3969 info = get_ret_itbl(frame);
3971 switch (info->i.type) {
3974 bh = ((StgUpdateFrame *)frame)->updatee;
3976 /* if the thunk is already blackholed, it means we've also
3977 * already blackholed the rest of the thunks on this stack,
3978 * so we can stop early.
3980 * The blackhole made for a CAF is a CAF_BLACKHOLE, so they
3981 * don't interfere with this optimisation.
3983 if (bh->header.info == &stg_BLACKHOLE_info) {
3987 if (bh->header.info != &stg_CAF_BLACKHOLE_info) {
3988 #if (!defined(LAZY_BLACKHOLING)) && defined(DEBUG)
3989 debugBelch("Unexpected lazy BHing required at 0x%04x\n",(int)bh);
3993 // We pretend that bh is now dead.
3994 LDV_recordDead_FILL_SLOP_DYNAMIC((StgClosure *)bh);
3996 SET_INFO(bh,&stg_BLACKHOLE_info);
3998 // We pretend that bh has just been created.
3999 LDV_RECORD_CREATE(bh);
4002 frame = (StgClosure *) ((StgUpdateFrame *)frame + 1);
4008 // normal stack frames; do nothing except advance the pointer
4010 frame = (StgClosure *)((StgPtr)frame + stack_frame_sizeW(frame));
4016 /* -----------------------------------------------------------------------------
4019 * Code largely pinched from old RTS, then hacked to bits. We also do
4020 * lazy black holing here.
4022 * -------------------------------------------------------------------------- */
4024 struct stack_gap { StgWord gap_size; struct stack_gap *next_gap; };
4027 threadSqueezeStack(StgTSO *tso)
4030 rtsBool prev_was_update_frame;
4031 StgClosure *updatee = NULL;
4033 StgRetInfoTable *info;
4034 StgWord current_gap_size;
4035 struct stack_gap *gap;
4038 // Traverse the stack upwards, replacing adjacent update frames
4039 // with a single update frame and a "stack gap". A stack gap
4040 // contains two values: the size of the gap, and the distance
4041 // to the next gap (or the stack top).
4043 bottom = &(tso->stack[tso->stack_size]);
4047 ASSERT(frame < bottom);
4049 prev_was_update_frame = rtsFalse;
4050 current_gap_size = 0;
4051 gap = (struct stack_gap *) (tso->sp - sizeofW(StgUpdateFrame));
4053 while (frame < bottom) {
4055 info = get_ret_itbl((StgClosure *)frame);
4056 switch (info->i.type) {
4060 StgUpdateFrame *upd = (StgUpdateFrame *)frame;
4062 if (upd->updatee->header.info == &stg_BLACKHOLE_info) {
4064 // found a BLACKHOLE'd update frame; we've been here
4065 // before, in a previous GC, so just break out.
4067 // Mark the end of the gap, if we're in one.
4068 if (current_gap_size != 0) {
4069 gap = (struct stack_gap *)(frame-sizeofW(StgUpdateFrame));
4072 frame += sizeofW(StgUpdateFrame);
4073 goto done_traversing;
4076 if (prev_was_update_frame) {
4078 TICK_UPD_SQUEEZED();
4079 /* wasn't there something about update squeezing and ticky to be
4080 * sorted out? oh yes: we aren't counting each enter properly
4081 * in this case. See the log somewhere. KSW 1999-04-21
4083 * Check two things: that the two update frames don't point to
4084 * the same object, and that the updatee_bypass isn't already an
4085 * indirection. Both of these cases only happen when we're in a
4086 * block hole-style loop (and there are multiple update frames
4087 * on the stack pointing to the same closure), but they can both
4088 * screw us up if we don't check.
4090 if (upd->updatee != updatee && !closure_IND(upd->updatee)) {
4091 UPD_IND_NOLOCK(upd->updatee, updatee);
4094 // now mark this update frame as a stack gap. The gap
4095 // marker resides in the bottom-most update frame of
4096 // the series of adjacent frames, and covers all the
4097 // frames in this series.
4098 current_gap_size += sizeofW(StgUpdateFrame);
4099 ((struct stack_gap *)frame)->gap_size = current_gap_size;
4100 ((struct stack_gap *)frame)->next_gap = gap;
4102 frame += sizeofW(StgUpdateFrame);
4106 // single update frame, or the topmost update frame in a series
4108 StgClosure *bh = upd->updatee;
4110 // Do lazy black-holing
4111 if (bh->header.info != &stg_BLACKHOLE_info &&
4112 bh->header.info != &stg_CAF_BLACKHOLE_info) {
4113 #if (!defined(LAZY_BLACKHOLING)) && defined(DEBUG)
4114 debugBelch("Unexpected lazy BHing required at 0x%04x",(int)bh);
4117 /* zero out the slop so that the sanity checker can tell
4118 * where the next closure is.
4121 StgInfoTable *bh_info = get_itbl(bh);
4122 nat np = bh_info->layout.payload.ptrs,
4123 nw = bh_info->layout.payload.nptrs, i;
4124 /* don't zero out slop for a THUNK_SELECTOR,
4125 * because its layout info is used for a
4126 * different purpose, and it's exactly the
4127 * same size as a BLACKHOLE in any case.
4129 if (bh_info->type != THUNK_SELECTOR) {
4130 for (i = 0; i < np + nw; i++) {
4131 ((StgClosure *)bh)->payload[i] = INVALID_OBJECT;
4137 // We pretend that bh is now dead.
4138 LDV_recordDead_FILL_SLOP_DYNAMIC((StgClosure *)bh);
4140 // Todo: maybe use SET_HDR() and remove LDV_RECORD_CREATE()?
4141 SET_INFO(bh,&stg_BLACKHOLE_info);
4143 // We pretend that bh has just been created.
4144 LDV_RECORD_CREATE(bh);
4147 prev_was_update_frame = rtsTrue;
4148 updatee = upd->updatee;
4149 frame += sizeofW(StgUpdateFrame);
4155 prev_was_update_frame = rtsFalse;
4157 // we're not in a gap... check whether this is the end of a gap
4158 // (an update frame can't be the end of a gap).
4159 if (current_gap_size != 0) {
4160 gap = (struct stack_gap *) (frame - sizeofW(StgUpdateFrame));
4162 current_gap_size = 0;
4164 frame += stack_frame_sizeW((StgClosure *)frame);
4171 // Now we have a stack with gaps in it, and we have to walk down
4172 // shoving the stack up to fill in the gaps. A diagram might
4176 // | ********* | <- sp
4180 // | stack_gap | <- gap | chunk_size
4182 // | ......... | <- gap_end v
4188 // 'sp' points the the current top-of-stack
4189 // 'gap' points to the stack_gap structure inside the gap
4190 // ***** indicates real stack data
4191 // ..... indicates gap
4192 // <empty> indicates unused
4196 void *gap_start, *next_gap_start, *gap_end;
4199 next_gap_start = (void *)((unsigned char*)gap + sizeof(StgUpdateFrame));
4200 sp = next_gap_start;
4202 while ((StgPtr)gap > tso->sp) {
4204 // we're working in *bytes* now...
4205 gap_start = next_gap_start;
4206 gap_end = (void*) ((unsigned char*)gap_start - gap->gap_size * sizeof(W_));
4208 gap = gap->next_gap;
4209 next_gap_start = (void *)((unsigned char*)gap + sizeof(StgUpdateFrame));
4211 chunk_size = (unsigned char*)gap_end - (unsigned char*)next_gap_start;
4213 memmove(sp, next_gap_start, chunk_size);
4216 tso->sp = (StgPtr)sp;
4220 /* -----------------------------------------------------------------------------
4223 * We have to prepare for GC - this means doing lazy black holing
4224 * here. We also take the opportunity to do stack squeezing if it's
4226 * -------------------------------------------------------------------------- */
4228 threadPaused(StgTSO *tso)
4230 if ( RtsFlags.GcFlags.squeezeUpdFrames == rtsTrue )
4231 threadSqueezeStack(tso); // does black holing too
4233 threadLazyBlackHole(tso);
4236 /* -----------------------------------------------------------------------------
4238 * -------------------------------------------------------------------------- */
4242 printMutableList(generation *gen)
4247 debugBelch("@@ Mutable list %p: ", gen->mut_list);
4249 for (bd = gen->mut_list; bd != NULL; bd = bd->link) {
4250 for (p = bd->start; p < bd->free; p++) {
4251 debugBelch("%p (%s), ", (void *)*p, info_type((StgClosure *)*p));
4257 STATIC_INLINE rtsBool
4258 maybeLarge(StgClosure *closure)
4260 StgInfoTable *info = get_itbl(closure);
4262 /* closure types that may be found on the new_large_objects list;
4263 see scavenge_large */
4264 return (info->type == MUT_ARR_PTRS ||
4265 info->type == MUT_ARR_PTRS_FROZEN ||
4266 info->type == MUT_ARR_PTRS_FROZEN0 ||
4267 info->type == TSO ||
4268 info->type == ARR_WORDS);