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