GC refactoring, remove "steps"
[ghc-hetmet.git] / rts / sm / Evac.c
1 /* -----------------------------------------------------------------------------
2  *
3  * (c) The GHC Team 1998-2008
4  *
5  * Generational garbage collector: evacuation functions
6  *
7  * Documentation on the architecture of the Garbage Collector can be
8  * found in the online commentary:
9  * 
10  *   http://hackage.haskell.org/trac/ghc/wiki/Commentary/Rts/Storage/GC
11  *
12  * ---------------------------------------------------------------------------*/
13
14 #include "PosixSource.h"
15 #include "Rts.h"
16
17 #include "Evac.h"
18 #include "Storage.h"
19 #include "GC.h"
20 #include "GCThread.h"
21 #include "GCUtils.h"
22 #include "Compact.h"
23 #include "MarkStack.h"
24 #include "Prelude.h"
25 #include "Trace.h"
26 #include "LdvProfile.h"
27
28 #if defined(PROF_SPIN) && defined(THREADED_RTS) && defined(PARALLEL_GC)
29 StgWord64 whitehole_spin = 0;
30 #endif
31
32 #if defined(THREADED_RTS) && !defined(PARALLEL_GC)
33 #define evacuate(p) evacuate1(p)
34 #define HEAP_ALLOCED_GC(p) HEAP_ALLOCED(p)
35 #endif
36
37 #if !defined(PARALLEL_GC)
38 #define copy_tag_nolock(p, info, src, size, stp, tag) \
39         copy_tag(p, info, src, size, stp, tag)
40 #endif
41
42 /* Used to avoid long recursion due to selector thunks
43  */
44 #define MAX_THUNK_SELECTOR_DEPTH 16
45
46 static void eval_thunk_selector (StgClosure **q, StgSelector * p, rtsBool);
47 STATIC_INLINE void evacuate_large(StgPtr p);
48
49 /* -----------------------------------------------------------------------------
50    Allocate some space in which to copy an object.
51    -------------------------------------------------------------------------- */
52
53 STATIC_INLINE StgPtr
54 alloc_for_copy (nat size, generation *gen)
55 {
56     StgPtr to;
57     gen_workspace *ws;
58
59     /* Find out where we're going, using the handy "to" pointer in 
60      * the gen of the source object.  If it turns out we need to
61      * evacuate to an older generation, adjust it here (see comment
62      * by evacuate()).
63      */
64     if (gen < gct->evac_gen) {
65         if (gct->eager_promotion) {
66             gen = gct->evac_gen;
67         } else {
68             gct->failed_to_evac = rtsTrue;
69         }
70     }
71     
72     ws = &gct->gens[gen->no];
73     // this compiles to a single mem access to gen->abs_no only
74     
75     /* chain a new block onto the to-space for the destination gen if
76      * necessary.
77      */
78     to = ws->todo_free;
79     ws->todo_free += size;
80     if (ws->todo_free > ws->todo_lim) {
81         to = todo_block_full(size, ws);
82     }
83     ASSERT(ws->todo_free >= ws->todo_bd->free && ws->todo_free <= ws->todo_lim);
84
85     return to;
86 }
87
88 /* -----------------------------------------------------------------------------
89    The evacuate() code
90    -------------------------------------------------------------------------- */
91
92 STATIC_INLINE GNUC_ATTR_HOT void
93 copy_tag(StgClosure **p, const StgInfoTable *info, 
94          StgClosure *src, nat size, generation *gen, StgWord tag)
95 {
96     StgPtr to, from;
97     nat i;
98
99     to = alloc_for_copy(size,gen);
100     
101     from = (StgPtr)src;
102     to[0] = (W_)info;
103     for (i = 1; i < size; i++) { // unroll for small i
104         to[i] = from[i];
105     }
106
107 //  if (to+size+2 < bd->start + BLOCK_SIZE_W) {
108 //      __builtin_prefetch(to + size + 2, 1);
109 //  }
110
111 #if defined(PARALLEL_GC)
112     {
113         const StgInfoTable *new_info;
114         new_info = (const StgInfoTable *)cas((StgPtr)&src->header.info, (W_)info, MK_FORWARDING_PTR(to));
115         if (new_info != info) {
116             return evacuate(p); // does the failed_to_evac stuff
117         } else {
118             *p = TAG_CLOSURE(tag,(StgClosure*)to);
119         }
120     }
121 #else
122     src->header.info = (const StgInfoTable *)MK_FORWARDING_PTR(to);
123     *p = TAG_CLOSURE(tag,(StgClosure*)to);
124 #endif
125
126 #ifdef PROFILING
127     // We store the size of the just evacuated object in the LDV word so that
128     // the profiler can guess the position of the next object later.
129     SET_EVACUAEE_FOR_LDV(from, size);
130 #endif
131 }
132
133 #if defined(PARALLEL_GC)
134 STATIC_INLINE void
135 copy_tag_nolock(StgClosure **p, const StgInfoTable *info, 
136          StgClosure *src, nat size, generation *gen, StgWord tag)
137 {
138     StgPtr to, from;
139     nat i;
140
141     to = alloc_for_copy(size,gen);
142     *p = TAG_CLOSURE(tag,(StgClosure*)to);
143     src->header.info = (const StgInfoTable *)MK_FORWARDING_PTR(to);
144     
145     from = (StgPtr)src;
146     to[0] = (W_)info;
147     for (i = 1; i < size; i++) { // unroll for small i
148         to[i] = from[i];
149     }
150
151 //  if (to+size+2 < bd->start + BLOCK_SIZE_W) {
152 //      __builtin_prefetch(to + size + 2, 1);
153 //  }
154
155 #ifdef PROFILING
156     // We store the size of the just evacuated object in the LDV word so that
157     // the profiler can guess the position of the next object later.
158     SET_EVACUAEE_FOR_LDV(from, size);
159 #endif
160 }
161 #endif
162
163 /* Special version of copy() for when we only want to copy the info
164  * pointer of an object, but reserve some padding after it.  This is
165  * used to optimise evacuation of BLACKHOLEs.
166  */
167 static rtsBool
168 copyPart(StgClosure **p, StgClosure *src, nat size_to_reserve, 
169          nat size_to_copy, generation *gen)
170 {
171     StgPtr to, from;
172     nat i;
173     StgWord info;
174     
175 #if defined(PARALLEL_GC)
176 spin:
177         info = xchg((StgPtr)&src->header.info, (W_)&stg_WHITEHOLE_info);
178         if (info == (W_)&stg_WHITEHOLE_info) {
179 #ifdef PROF_SPIN
180             whitehole_spin++;
181 #endif
182             goto spin;
183         }
184     if (IS_FORWARDING_PTR(info)) {
185         src->header.info = (const StgInfoTable *)info;
186         evacuate(p); // does the failed_to_evac stuff
187         return rtsFalse;
188     }
189 #else
190     info = (W_)src->header.info;
191 #endif
192
193     to = alloc_for_copy(size_to_reserve, gen);
194     *p = (StgClosure *)to;
195
196     from = (StgPtr)src;
197     to[0] = info;
198     for (i = 1; i < size_to_copy; i++) { // unroll for small i
199         to[i] = from[i];
200     }
201     
202 #if defined(PARALLEL_GC)
203     write_barrier();
204 #endif
205     src->header.info = (const StgInfoTable*)MK_FORWARDING_PTR(to);
206     
207 #ifdef PROFILING
208     // We store the size of the just evacuated object in the LDV word so that
209     // the profiler can guess the position of the next object later.
210     SET_EVACUAEE_FOR_LDV(from, size_to_reserve);
211     // fill the slop
212     if (size_to_reserve - size_to_copy > 0)
213         LDV_FILL_SLOP(to + size_to_copy, (int)(size_to_reserve - size_to_copy));
214 #endif
215
216     return rtsTrue;
217 }
218
219
220 /* Copy wrappers that don't tag the closure after copying */
221 STATIC_INLINE GNUC_ATTR_HOT void
222 copy(StgClosure **p, const StgInfoTable *info, 
223      StgClosure *src, nat size, generation *gen)
224 {
225     copy_tag(p,info,src,size,gen,0);
226 }
227
228 /* -----------------------------------------------------------------------------
229    Evacuate a large object
230
231    This just consists of removing the object from the (doubly-linked)
232    gen->large_objects list, and linking it on to the (singly-linked)
233    gen->new_large_objects list, from where it will be scavenged later.
234
235    Convention: bd->flags has BF_EVACUATED set for a large object
236    that has been evacuated, or unset otherwise.
237    -------------------------------------------------------------------------- */
238
239 STATIC_INLINE void
240 evacuate_large(StgPtr p)
241 {
242   bdescr *bd = Bdescr(p);
243   generation *gen, *new_gen;
244   gen_workspace *ws;
245     
246   gen = bd->gen;
247   ACQUIRE_SPIN_LOCK(&gen->sync_large_objects);
248
249   // already evacuated? 
250   if (bd->flags & BF_EVACUATED) { 
251     /* Don't forget to set the gct->failed_to_evac flag if we didn't get
252      * the desired destination (see comments in evacuate()).
253      */
254     if (gen < gct->evac_gen) {
255         gct->failed_to_evac = rtsTrue;
256         TICK_GC_FAILED_PROMOTION();
257     }
258     RELEASE_SPIN_LOCK(&gen->sync_large_objects);
259     return;
260   }
261
262   // remove from large_object list 
263   if (bd->u.back) {
264     bd->u.back->link = bd->link;
265   } else { // first object in the list 
266     gen->large_objects = bd->link;
267   }
268   if (bd->link) {
269     bd->link->u.back = bd->u.back;
270   }
271   
272   /* link it on to the evacuated large object list of the destination gen
273    */
274   new_gen = gen->to;
275   if (new_gen < gct->evac_gen) {
276       if (gct->eager_promotion) {
277           new_gen = gct->evac_gen;
278       } else {
279           gct->failed_to_evac = rtsTrue;
280       }
281   }
282
283   ws = &gct->gens[new_gen->no];
284
285   bd->flags |= BF_EVACUATED;
286   initBdescr(bd, new_gen, new_gen->to);
287
288   // If this is a block of pinned objects, we don't have to scan
289   // these objects, because they aren't allowed to contain any
290   // pointers.  For these blocks, we skip the scavenge stage and put
291   // them straight on the scavenged_large_objects list.
292   if (bd->flags & BF_PINNED) {
293       ASSERT(get_itbl((StgClosure *)p)->type == ARR_WORDS);
294       if (new_gen != gen) { ACQUIRE_SPIN_LOCK(&new_gen->sync_large_objects); }
295       dbl_link_onto(bd, &new_gen->scavenged_large_objects);
296       new_gen->n_scavenged_large_blocks += bd->blocks;
297       if (new_gen != gen) { RELEASE_SPIN_LOCK(&new_gen->sync_large_objects); }
298   } else {
299       bd->link = ws->todo_large_objects;
300       ws->todo_large_objects = bd;
301   }
302
303   RELEASE_SPIN_LOCK(&gen->sync_large_objects);
304 }
305
306 /* ----------------------------------------------------------------------------
307    Evacuate
308
309    This is called (eventually) for every live object in the system.
310
311    The caller to evacuate specifies a desired generation in the
312    gct->evac_gen thread-local variable.  The following conditions apply to
313    evacuating an object which resides in generation M when we're
314    collecting up to generation N
315
316    if  M >= gct->evac_gen 
317            if  M > N     do nothing
318            else          evac to gen->to
319
320    if  M < gct->evac_gen      evac to gct->evac_gen, step 0
321
322    if the object is already evacuated, then we check which generation
323    it now resides in.
324
325    if  M >= gct->evac_gen     do nothing
326    if  M <  gct->evac_gen     set gct->failed_to_evac flag to indicate that we
327                          didn't manage to evacuate this object into gct->evac_gen.
328
329
330    OPTIMISATION NOTES:
331
332    evacuate() is the single most important function performance-wise
333    in the GC.  Various things have been tried to speed it up, but as
334    far as I can tell the code generated by gcc 3.2 with -O2 is about
335    as good as it's going to get.  We pass the argument to evacuate()
336    in a register using the 'regparm' attribute (see the prototype for
337    evacuate() near the top of this file).
338
339    Changing evacuate() to take an (StgClosure **) rather than
340    returning the new pointer seems attractive, because we can avoid
341    writing back the pointer when it hasn't changed (eg. for a static
342    object, or an object in a generation > N).  However, I tried it and
343    it doesn't help.  One reason is that the (StgClosure **) pointer
344    gets spilled to the stack inside evacuate(), resulting in far more
345    extra reads/writes than we save.
346    ------------------------------------------------------------------------- */
347
348 REGPARM1 GNUC_ATTR_HOT void 
349 evacuate(StgClosure **p)
350 {
351   bdescr *bd = NULL;
352   generation *gen;
353   StgClosure *q;
354   const StgInfoTable *info;
355   StgWord tag;
356
357   q = *p;
358
359 loop:
360   /* The tag and the pointer are split, to be merged after evacing */
361   tag = GET_CLOSURE_TAG(q);
362   q = UNTAG_CLOSURE(q);
363
364   ASSERT(LOOKS_LIKE_CLOSURE_PTR(q));
365
366   if (!HEAP_ALLOCED_GC(q)) {
367
368       if (!major_gc) return;
369
370       info = get_itbl(q);
371       switch (info->type) {
372
373       case THUNK_STATIC:
374           if (info->srt_bitmap != 0) {
375               if (*THUNK_STATIC_LINK((StgClosure *)q) == NULL) {
376 #ifndef THREADED_RTS
377                   *THUNK_STATIC_LINK((StgClosure *)q) = gct->static_objects;
378                   gct->static_objects = (StgClosure *)q;
379 #else
380                   StgPtr link;
381                   link = (StgPtr)cas((StgPtr)THUNK_STATIC_LINK((StgClosure *)q),
382                                      (StgWord)NULL,
383                                      (StgWord)gct->static_objects);
384                   if (link == NULL) {
385                       gct->static_objects = (StgClosure *)q;
386                   }
387 #endif
388               }
389           }
390           return;
391
392       case FUN_STATIC:
393           if (info->srt_bitmap != 0 &&
394               *FUN_STATIC_LINK((StgClosure *)q) == NULL) {
395 #ifndef THREADED_RTS
396               *FUN_STATIC_LINK((StgClosure *)q) = gct->static_objects;
397               gct->static_objects = (StgClosure *)q;
398 #else
399               StgPtr link;
400               link = (StgPtr)cas((StgPtr)FUN_STATIC_LINK((StgClosure *)q),
401                                  (StgWord)NULL,
402                                  (StgWord)gct->static_objects);
403               if (link == NULL) {
404                   gct->static_objects = (StgClosure *)q;
405               }
406 #endif
407           }
408           return;
409           
410       case IND_STATIC:
411           /* If q->saved_info != NULL, then it's a revertible CAF - it'll be
412            * on the CAF list, so don't do anything with it here (we'll
413            * scavenge it later).
414            */
415           if (((StgIndStatic *)q)->saved_info == NULL) {
416               if (*IND_STATIC_LINK((StgClosure *)q) == NULL) {
417 #ifndef THREADED_RTS
418                   *IND_STATIC_LINK((StgClosure *)q) = gct->static_objects;
419                   gct->static_objects = (StgClosure *)q;
420 #else
421                   StgPtr link;
422                   link = (StgPtr)cas((StgPtr)IND_STATIC_LINK((StgClosure *)q),
423                                      (StgWord)NULL,
424                                      (StgWord)gct->static_objects);
425                   if (link == NULL) {
426                       gct->static_objects = (StgClosure *)q;
427                   }
428 #endif
429               }
430           }
431           return;
432           
433       case CONSTR_STATIC:
434           if (*STATIC_LINK(info,(StgClosure *)q) == NULL) {
435 #ifndef THREADED_RTS
436               *STATIC_LINK(info,(StgClosure *)q) = gct->static_objects;
437               gct->static_objects = (StgClosure *)q;
438 #else
439               StgPtr link;
440               link = (StgPtr)cas((StgPtr)STATIC_LINK(info,(StgClosure *)q),
441                                  (StgWord)NULL,
442                                  (StgWord)gct->static_objects);
443               if (link == NULL) {
444                   gct->static_objects = (StgClosure *)q;
445               }
446 #endif
447           }
448           /* I am assuming that static_objects pointers are not
449            * written to other objects, and thus, no need to retag. */
450           return;
451           
452       case CONSTR_NOCAF_STATIC:
453           /* no need to put these on the static linked list, they don't need
454            * to be scavenged.
455            */
456           return;
457           
458       default:
459           barf("evacuate(static): strange closure type %d", (int)(info->type));
460       }
461   }
462
463   bd = Bdescr((P_)q);
464
465   if ((bd->flags & (BF_LARGE | BF_MARKED | BF_EVACUATED)) != 0) {
466
467       // pointer into to-space: just return it.  It might be a pointer
468       // into a generation that we aren't collecting (> N), or it
469       // might just be a pointer into to-space.  The latter doesn't
470       // happen often, but allowing it makes certain things a bit
471       // easier; e.g. scavenging an object is idempotent, so it's OK to
472       // have an object on the mutable list multiple times.
473       if (bd->flags & BF_EVACUATED) {
474           // We aren't copying this object, so we have to check
475           // whether it is already in the target generation.  (this is
476           // the write barrier).
477           if (bd->gen < gct->evac_gen) {
478               gct->failed_to_evac = rtsTrue;
479               TICK_GC_FAILED_PROMOTION();
480           }
481           return;
482       }
483
484       /* evacuate large objects by re-linking them onto a different list.
485        */
486       if (bd->flags & BF_LARGE) {
487           info = get_itbl(q);
488           if (info->type == TSO && 
489               ((StgTSO *)q)->what_next == ThreadRelocated) {
490               q = (StgClosure *)((StgTSO *)q)->_link;
491               *p = q;
492               goto loop;
493           }
494           evacuate_large((P_)q);
495           return;
496       }
497       
498       /* If the object is in a gen that we're compacting, then we
499        * need to use an alternative evacuate procedure.
500        */
501       if (!is_marked((P_)q,bd)) {
502           mark((P_)q,bd);
503           push_mark_stack((P_)q);
504       }
505       return;
506   }
507       
508   gen = bd->dest;
509
510   info = q->header.info;
511   if (IS_FORWARDING_PTR(info))
512   {
513     /* Already evacuated, just return the forwarding address.
514      * HOWEVER: if the requested destination generation (gct->evac_gen) is
515      * older than the actual generation (because the object was
516      * already evacuated to a younger generation) then we have to
517      * set the gct->failed_to_evac flag to indicate that we couldn't 
518      * manage to promote the object to the desired generation.
519      */
520     /* 
521      * Optimisation: the check is fairly expensive, but we can often
522      * shortcut it if either the required generation is 0, or the
523      * current object (the EVACUATED) is in a high enough generation.
524      * We know that an EVACUATED always points to an object in the
525      * same or an older generation.  gen is the lowest generation that the
526      * current object would be evacuated to, so we only do the full
527      * check if gen is too low.
528      */
529       StgClosure *e = (StgClosure*)UN_FORWARDING_PTR(info);
530       *p = TAG_CLOSURE(tag,e);
531       if (gen < gct->evac_gen) {  // optimisation 
532           if (Bdescr((P_)e)->gen < gct->evac_gen) {
533               gct->failed_to_evac = rtsTrue;
534               TICK_GC_FAILED_PROMOTION();
535           }
536       }
537       return;
538   }
539
540   switch (INFO_PTR_TO_STRUCT(info)->type) {
541
542   case WHITEHOLE:
543       goto loop;
544
545   case MUT_VAR_CLEAN:
546   case MUT_VAR_DIRTY:
547   case MVAR_CLEAN:
548   case MVAR_DIRTY:
549       copy(p,info,q,sizeW_fromITBL(INFO_PTR_TO_STRUCT(info)),gen);
550       return;
551
552   // For ints and chars of low value, save space by replacing references to
553   //    these with closures with references to common, shared ones in the RTS.
554   //
555   // * Except when compiling into Windows DLLs which don't support cross-package
556   //    data references very well.
557   //
558   case CONSTR_0_1:
559   {   
560 #if defined(__PIC__) && defined(mingw32_HOST_OS) 
561       copy_tag_nolock(p,info,q,sizeofW(StgHeader)+1,gen,tag);
562 #else
563       StgWord w = (StgWord)q->payload[0];
564       if (info == Czh_con_info &&
565           // unsigned, so always true:  (StgChar)w >= MIN_CHARLIKE &&  
566           (StgChar)w <= MAX_CHARLIKE) {
567           *p =  TAG_CLOSURE(tag,
568                             (StgClosure *)CHARLIKE_CLOSURE((StgChar)w)
569                            );
570       }
571       else if (info == Izh_con_info &&
572           (StgInt)w >= MIN_INTLIKE && (StgInt)w <= MAX_INTLIKE) {
573           *p = TAG_CLOSURE(tag,
574                              (StgClosure *)INTLIKE_CLOSURE((StgInt)w)
575                              );
576       }
577       else {
578           copy_tag_nolock(p,info,q,sizeofW(StgHeader)+1,gen,tag);
579       }
580 #endif
581       return;
582   }
583
584   case FUN_0_1:
585   case FUN_1_0:
586   case CONSTR_1_0:
587       copy_tag_nolock(p,info,q,sizeofW(StgHeader)+1,gen,tag);
588       return;
589
590   case THUNK_1_0:
591   case THUNK_0_1:
592       copy(p,info,q,sizeofW(StgThunk)+1,gen);
593       return;
594
595   case THUNK_1_1:
596   case THUNK_2_0:
597   case THUNK_0_2:
598 #ifdef NO_PROMOTE_THUNKS
599 #error bitrotted
600 #endif
601     copy(p,info,q,sizeofW(StgThunk)+2,gen);
602     return;
603
604   case FUN_1_1:
605   case FUN_2_0:
606   case FUN_0_2:
607   case CONSTR_1_1:
608   case CONSTR_2_0:
609       copy_tag_nolock(p,info,q,sizeofW(StgHeader)+2,gen,tag);
610       return;
611
612   case CONSTR_0_2:
613       copy_tag_nolock(p,info,q,sizeofW(StgHeader)+2,gen,tag);
614       return;
615
616   case THUNK:
617       copy(p,info,q,thunk_sizeW_fromITBL(INFO_PTR_TO_STRUCT(info)),gen);
618       return;
619
620   case FUN:
621   case IND_PERM:
622   case IND_OLDGEN_PERM:
623   case CONSTR:
624       copy_tag_nolock(p,info,q,sizeW_fromITBL(INFO_PTR_TO_STRUCT(info)),gen,tag);
625       return;
626
627   case WEAK:
628   case STABLE_NAME:
629       copy_tag(p,info,q,sizeW_fromITBL(INFO_PTR_TO_STRUCT(info)),gen,tag);
630       return;
631
632   case BCO:
633       copy(p,info,q,bco_sizeW((StgBCO *)q),gen);
634       return;
635
636   case CAF_BLACKHOLE:
637   case BLACKHOLE:
638       copyPart(p,q,BLACKHOLE_sizeW(),sizeofW(StgHeader),gen);
639       return;
640
641   case THUNK_SELECTOR:
642       eval_thunk_selector(p, (StgSelector *)q, rtsTrue);
643       return;
644
645   case IND:
646   case IND_OLDGEN:
647     // follow chains of indirections, don't evacuate them 
648     q = ((StgInd*)q)->indirectee;
649     *p = q;
650     goto loop;
651
652   case RET_BCO:
653   case RET_SMALL:
654   case RET_BIG:
655   case RET_DYN:
656   case UPDATE_FRAME:
657   case STOP_FRAME:
658   case CATCH_FRAME:
659   case CATCH_STM_FRAME:
660   case CATCH_RETRY_FRAME:
661   case ATOMICALLY_FRAME:
662     // shouldn't see these 
663     barf("evacuate: stack frame at %p\n", q);
664
665   case PAP:
666       copy(p,info,q,pap_sizeW((StgPAP*)q),gen);
667       return;
668
669   case AP:
670       copy(p,info,q,ap_sizeW((StgAP*)q),gen);
671       return;
672
673   case AP_STACK:
674       copy(p,info,q,ap_stack_sizeW((StgAP_STACK*)q),gen);
675       return;
676
677   case ARR_WORDS:
678       // just copy the block 
679       copy(p,info,q,arr_words_sizeW((StgArrWords *)q),gen);
680       return;
681
682   case MUT_ARR_PTRS_CLEAN:
683   case MUT_ARR_PTRS_DIRTY:
684   case MUT_ARR_PTRS_FROZEN:
685   case MUT_ARR_PTRS_FROZEN0:
686       // just copy the block 
687       copy(p,info,q,mut_arr_ptrs_sizeW((StgMutArrPtrs *)q),gen);
688       return;
689
690   case TSO:
691     {
692       StgTSO *tso = (StgTSO *)q;
693
694       /* Deal with redirected TSOs (a TSO that's had its stack enlarged).
695        */
696       if (tso->what_next == ThreadRelocated) {
697         q = (StgClosure *)tso->_link;
698         *p = q;
699         goto loop;
700       }
701
702       /* To evacuate a small TSO, we need to adjust the stack pointer
703        */
704       {
705           StgTSO *new_tso;
706           StgPtr r, s;
707           rtsBool mine;
708
709           mine = copyPart(p,(StgClosure *)tso, tso_sizeW(tso), 
710                           sizeofW(StgTSO), gen);
711           if (mine) {
712               new_tso = (StgTSO *)*p;
713               move_TSO(tso, new_tso);
714               for (r = tso->sp, s = new_tso->sp;
715                    r < tso->stack+tso->stack_size;) {
716                   *s++ = *r++;
717               }
718           }
719           return;
720       }
721     }
722
723   case TREC_HEADER: 
724       copy(p,info,q,sizeofW(StgTRecHeader),gen);
725       return;
726
727   case TVAR_WATCH_QUEUE:
728       copy(p,info,q,sizeofW(StgTVarWatchQueue),gen);
729       return;
730
731   case TVAR:
732       copy(p,info,q,sizeofW(StgTVar),gen);
733       return;
734     
735   case TREC_CHUNK:
736       copy(p,info,q,sizeofW(StgTRecChunk),gen);
737       return;
738
739   case ATOMIC_INVARIANT:
740       copy(p,info,q,sizeofW(StgAtomicInvariant),gen);
741       return;
742
743   case INVARIANT_CHECK_QUEUE:
744       copy(p,info,q,sizeofW(StgInvariantCheckQueue),gen);
745       return;
746
747   default:
748     barf("evacuate: strange closure type %d", (int)(INFO_PTR_TO_STRUCT(info)->type));
749   }
750
751   barf("evacuate");
752 }
753
754 /* -----------------------------------------------------------------------------
755    Evaluate a THUNK_SELECTOR if possible.
756
757    p points to a THUNK_SELECTOR that we want to evaluate.  The
758    result of "evaluating" it will be evacuated and a pointer to the
759    to-space closure will be returned.
760
761    If the THUNK_SELECTOR could not be evaluated (its selectee is still
762    a THUNK, for example), then the THUNK_SELECTOR itself will be
763    evacuated.
764    -------------------------------------------------------------------------- */
765 static void
766 unchain_thunk_selectors(StgSelector *p, StgClosure *val)
767 {
768     StgSelector *prev;
769
770     prev = NULL;
771     while (p)
772     {
773 #ifdef THREADED_RTS
774         ASSERT(p->header.info == &stg_WHITEHOLE_info);
775 #else
776         ASSERT(p->header.info == &stg_BLACKHOLE_info);
777 #endif
778         // val must be in to-space.  Not always: when we recursively
779         // invoke eval_thunk_selector(), the recursive calls will not 
780         // evacuate the value (because we want to select on the value,
781         // not evacuate it), so in this case val is in from-space.
782         // ASSERT(!HEAP_ALLOCED_GC(val) || Bdescr((P_)val)->gen_no > N || (Bdescr((P_)val)->flags & BF_EVACUATED));
783
784         prev = (StgSelector*)((StgClosure *)p)->payload[0];
785
786         // Update the THUNK_SELECTOR with an indirection to the
787         // value.  The value is still in from-space at this stage.
788         //
789         // (old note: Why not do upd_evacuee(q,p)?  Because we have an
790         // invariant that an EVACUATED closure always points to an
791         // object in the same or an older generation (required by
792         // the short-cut test in the EVACUATED case, below).
793         if ((StgClosure *)p == val) {
794             // must be a loop; just leave a BLACKHOLE in place.  This
795             // can happen when we have a chain of selectors that
796             // eventually loops back on itself.  We can't leave an
797             // indirection pointing to itself, and we want the program
798             // to deadlock if it ever enters this closure, so
799             // BLACKHOLE is correct.
800             SET_INFO(p, &stg_BLACKHOLE_info);
801         } else {
802             ((StgInd *)p)->indirectee = val;
803             write_barrier();
804             SET_INFO(p, &stg_IND_info);
805         }
806
807         // For the purposes of LDV profiling, we have created an
808         // indirection.
809         LDV_RECORD_CREATE(p);
810
811         p = prev;
812     }
813 }
814
815 static void
816 eval_thunk_selector (StgClosure **q, StgSelector * p, rtsBool evac)
817                  // NB. for legacy reasons, p & q are swapped around :(
818 {
819     nat field;
820     StgInfoTable *info;
821     StgWord info_ptr;
822     StgClosure *selectee;
823     StgSelector *prev_thunk_selector;
824     bdescr *bd;
825     StgClosure *val;
826     
827     prev_thunk_selector = NULL;
828     // this is a chain of THUNK_SELECTORs that we are going to update
829     // to point to the value of the current THUNK_SELECTOR.  Each
830     // closure on the chain is a BLACKHOLE, and points to the next in the
831     // chain with payload[0].
832
833 selector_chain:
834
835     bd = Bdescr((StgPtr)p);
836     if (HEAP_ALLOCED_GC(p)) {
837         // If the THUNK_SELECTOR is in to-space or in a generation that we
838         // are not collecting, then bale out early.  We won't be able to
839         // save any space in any case, and updating with an indirection is
840         // trickier in a non-collected gen: we would have to update the
841         // mutable list.
842         if (bd->flags & BF_EVACUATED) {
843             unchain_thunk_selectors(prev_thunk_selector, (StgClosure *)p);
844             *q = (StgClosure *)p;
845             // shortcut, behave as for:  if (evac) evacuate(q);
846             if (evac && bd->gen < gct->evac_gen) {
847                 gct->failed_to_evac = rtsTrue;
848                 TICK_GC_FAILED_PROMOTION();
849             }
850             return;
851         }
852         // we don't update THUNK_SELECTORS in the compacted
853         // generation, because compaction does not remove the INDs
854         // that result, this causes confusion later
855         // (scavenge_mark_stack doesn't deal with IND).  BEWARE!  This
856         // bit is very tricky to get right.  If you make changes
857         // around here, test by compiling stage 3 with +RTS -c -RTS.
858         if (bd->flags & BF_MARKED) {
859             // must call evacuate() to mark this closure if evac==rtsTrue
860             *q = (StgClosure *)p;
861             if (evac) evacuate(q);
862             unchain_thunk_selectors(prev_thunk_selector, (StgClosure *)p);
863             return;
864         }
865     }
866
867
868     // BLACKHOLE the selector thunk, since it is now under evaluation.
869     // This is important to stop us going into an infinite loop if
870     // this selector thunk eventually refers to itself.
871 #if defined(THREADED_RTS)
872     // In threaded mode, we'll use WHITEHOLE to lock the selector
873     // thunk while we evaluate it.
874     {
875         do {
876             info_ptr = xchg((StgPtr)&p->header.info, (W_)&stg_WHITEHOLE_info);
877         } while (info_ptr == (W_)&stg_WHITEHOLE_info);
878
879         // make sure someone else didn't get here first...
880         if (IS_FORWARDING_PTR(p) || 
881             INFO_PTR_TO_STRUCT(info_ptr)->type != THUNK_SELECTOR) {
882             // v. tricky now.  The THUNK_SELECTOR has been evacuated
883             // by another thread, and is now either a forwarding ptr or IND.
884             // We need to extract ourselves from the current situation
885             // as cleanly as possible.
886             //   - unlock the closure
887             //   - update *q, we may have done *some* evaluation
888             //   - if evac, we need to call evacuate(), because we
889             //     need the write-barrier stuff.
890             //   - undo the chain we've built to point to p.
891             SET_INFO(p, (const StgInfoTable *)info_ptr);
892             *q = (StgClosure *)p;
893             if (evac) evacuate(q);
894             unchain_thunk_selectors(prev_thunk_selector, (StgClosure *)p);
895             return;
896         }
897     }
898 #else
899     // Save the real info pointer (NOTE: not the same as get_itbl()).
900     info_ptr = (StgWord)p->header.info;
901     SET_INFO(p,&stg_BLACKHOLE_info);
902 #endif
903
904     field = INFO_PTR_TO_STRUCT(info_ptr)->layout.selector_offset;
905
906     // The selectee might be a constructor closure,
907     // so we untag the pointer.
908     selectee = UNTAG_CLOSURE(p->selectee);
909
910 selector_loop:
911     // selectee now points to the closure that we're trying to select
912     // a field from.  It may or may not be in to-space: we try not to
913     // end up in to-space, but it's impractical to avoid it in
914     // general.  The compacting GC scatters to-space pointers in
915     // from-space during marking, for example.  We rely on the property
916     // that evacuate() doesn't mind if it gets passed a to-space pointer.
917
918     info = (StgInfoTable*)selectee->header.info;
919
920     if (IS_FORWARDING_PTR(info)) {
921         // We don't follow pointers into to-space; the constructor
922         // has already been evacuated, so we won't save any space
923         // leaks by evaluating this selector thunk anyhow.
924         goto bale_out;
925     }
926
927     info = INFO_PTR_TO_STRUCT(info);
928     switch (info->type) {
929       case WHITEHOLE:
930           goto bale_out; // about to be evacuated by another thread (or a loop).
931         
932       case CONSTR:
933       case CONSTR_1_0:
934       case CONSTR_0_1:
935       case CONSTR_2_0:
936       case CONSTR_1_1:
937       case CONSTR_0_2:
938       case CONSTR_STATIC:
939       case CONSTR_NOCAF_STATIC:
940           {
941               // check that the size is in range 
942               ASSERT(field <  (StgWord32)(info->layout.payload.ptrs + 
943                                           info->layout.payload.nptrs));
944           
945               // Select the right field from the constructor
946               val = selectee->payload[field];
947               
948 #ifdef PROFILING
949               // For the purposes of LDV profiling, we have destroyed
950               // the original selector thunk, p.
951               SET_INFO(p, (StgInfoTable *)info_ptr);
952               LDV_RECORD_DEAD_FILL_SLOP_DYNAMIC((StgClosure *)p);
953 #if defined(THREADED_RTS)
954               SET_INFO(p, &stg_WHITEHOLE_info);
955 #else
956               SET_INFO(p, &stg_BLACKHOLE_info);
957 #endif
958 #endif
959
960               // the closure in val is now the "value" of the
961               // THUNK_SELECTOR in p.  However, val may itself be a
962               // THUNK_SELECTOR, in which case we want to continue
963               // evaluating until we find the real value, and then
964               // update the whole chain to point to the value.
965           val_loop:
966               info_ptr = (StgWord)UNTAG_CLOSURE(val)->header.info;
967               if (!IS_FORWARDING_PTR(info_ptr))
968               {
969                   info = INFO_PTR_TO_STRUCT(info_ptr);
970                   switch (info->type) {
971                   case IND:
972                   case IND_PERM:
973                   case IND_OLDGEN:
974                   case IND_OLDGEN_PERM:
975                   case IND_STATIC:
976                       val = ((StgInd *)val)->indirectee;
977                       goto val_loop;
978                   case THUNK_SELECTOR:
979                       ((StgClosure*)p)->payload[0] = (StgClosure *)prev_thunk_selector;
980                       prev_thunk_selector = p;
981                       p = (StgSelector*)val;
982                       goto selector_chain;
983                   default:
984                       break;
985                   }
986               }
987               ((StgClosure*)p)->payload[0] = (StgClosure *)prev_thunk_selector;
988               prev_thunk_selector = p;
989
990               *q = val;
991
992               // update the other selectors in the chain *before*
993               // evacuating the value.  This is necessary in the case
994               // where the value turns out to be one of the selectors
995               // in the chain (i.e. we have a loop), and evacuating it
996               // would corrupt the chain.
997               unchain_thunk_selectors(prev_thunk_selector, val);
998
999               // evacuate() cannot recurse through
1000               // eval_thunk_selector(), because we know val is not
1001               // a THUNK_SELECTOR.
1002               if (evac) evacuate(q);
1003               return;
1004           }
1005
1006       case IND:
1007       case IND_PERM:
1008       case IND_OLDGEN:
1009       case IND_OLDGEN_PERM:
1010       case IND_STATIC:
1011           // Again, we might need to untag a constructor.
1012           selectee = UNTAG_CLOSURE( ((StgInd *)selectee)->indirectee );
1013           goto selector_loop;
1014
1015       case THUNK_SELECTOR:
1016       {
1017           StgClosure *val;
1018
1019           // recursively evaluate this selector.  We don't want to
1020           // recurse indefinitely, so we impose a depth bound.
1021           if (gct->thunk_selector_depth >= MAX_THUNK_SELECTOR_DEPTH) {
1022               goto bale_out;
1023           }
1024
1025           gct->thunk_selector_depth++;
1026           // rtsFalse says "don't evacuate the result".  It will,
1027           // however, update any THUNK_SELECTORs that are evaluated
1028           // along the way.
1029           eval_thunk_selector(&val, (StgSelector*)selectee, rtsFalse);
1030           gct->thunk_selector_depth--;
1031
1032           // did we actually manage to evaluate it?
1033           if (val == selectee) goto bale_out;
1034
1035           // Of course this pointer might be tagged...
1036           selectee = UNTAG_CLOSURE(val);
1037           goto selector_loop;
1038       }
1039
1040       case AP:
1041       case AP_STACK:
1042       case THUNK:
1043       case THUNK_1_0:
1044       case THUNK_0_1:
1045       case THUNK_2_0:
1046       case THUNK_1_1:
1047       case THUNK_0_2:
1048       case THUNK_STATIC:
1049       case CAF_BLACKHOLE:
1050       case BLACKHOLE:
1051           // not evaluated yet 
1052           goto bale_out;
1053     
1054       default:
1055         barf("eval_thunk_selector: strange selectee %d",
1056              (int)(info->type));
1057     }
1058
1059 bale_out:
1060     // We didn't manage to evaluate this thunk; restore the old info
1061     // pointer.  But don't forget: we still need to evacuate the thunk itself.
1062     SET_INFO(p, (const StgInfoTable *)info_ptr);
1063     // THREADED_RTS: we just unlocked the thunk, so another thread
1064     // might get in and update it.  copy() will lock it again and
1065     // check whether it was updated in the meantime.
1066     *q = (StgClosure *)p;
1067     if (evac) {
1068         copy(q,(const StgInfoTable *)info_ptr,(StgClosure *)p,THUNK_SELECTOR_sizeW(),bd->dest);
1069     }
1070     unchain_thunk_selectors(prev_thunk_selector, *q);
1071     return;
1072 }