FIX #2327: a fault in the thunk-selector machinery (again)
[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 void
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 ;
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_copy - 1, (int)(size_to_reserve - size_to_copy)); 
216 #endif
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, step *stp)
224 {
225     copy_tag(p,info,src,size,stp,0);
226 }
227
228 /* -----------------------------------------------------------------------------
229    Evacuate a large object
230
231    This just consists of removing the object from the (doubly-linked)
232    step->large_objects list, and linking it on to the (singly-linked)
233    step->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   step *stp, *new_stp;
244   step_workspace *ws;
245     
246   stp = bd->step;
247   ACQUIRE_SPIN_LOCK(&stp->sync_large_objects);
248
249   // object must be at the beginning of the block (or be a ByteArray)
250   ASSERT(get_itbl((StgClosure *)p)->type == ARR_WORDS ||
251          (((W_)p & BLOCK_MASK) == 0));
252
253   // already evacuated? 
254   if (bd->flags & BF_EVACUATED) { 
255     /* Don't forget to set the gct->failed_to_evac flag if we didn't get
256      * the desired destination (see comments in evacuate()).
257      */
258     if (stp < gct->evac_step) {
259         gct->failed_to_evac = rtsTrue;
260         TICK_GC_FAILED_PROMOTION();
261     }
262     RELEASE_SPIN_LOCK(&stp->sync_large_objects);
263     return;
264   }
265
266   // remove from large_object list 
267   if (bd->u.back) {
268     bd->u.back->link = bd->link;
269   } else { // first object in the list 
270     stp->large_objects = bd->link;
271   }
272   if (bd->link) {
273     bd->link->u.back = bd->u.back;
274   }
275   
276   /* link it on to the evacuated large object list of the destination step
277    */
278   new_stp = stp->to;
279   if (new_stp < gct->evac_step) {
280       if (gct->eager_promotion) {
281           new_stp = gct->evac_step;
282       } else {
283           gct->failed_to_evac = rtsTrue;
284       }
285   }
286
287   ws = &gct->steps[new_stp->abs_no];
288   bd->flags |= BF_EVACUATED;
289   bd->step = new_stp;
290   bd->gen_no = new_stp->gen_no;
291   bd->link = ws->todo_large_objects;
292   ws->todo_large_objects = bd;
293
294   RELEASE_SPIN_LOCK(&stp->sync_large_objects);
295 }
296
297 /* ----------------------------------------------------------------------------
298    Evacuate
299
300    This is called (eventually) for every live object in the system.
301
302    The caller to evacuate specifies a desired generation in the
303    gct->evac_step thread-local variable.  The following conditions apply to
304    evacuating an object which resides in generation M when we're
305    collecting up to generation N
306
307    if  M >= gct->evac_step 
308            if  M > N     do nothing
309            else          evac to step->to
310
311    if  M < gct->evac_step      evac to gct->evac_step, step 0
312
313    if the object is already evacuated, then we check which generation
314    it now resides in.
315
316    if  M >= gct->evac_step     do nothing
317    if  M <  gct->evac_step     set gct->failed_to_evac flag to indicate that we
318                          didn't manage to evacuate this object into gct->evac_step.
319
320
321    OPTIMISATION NOTES:
322
323    evacuate() is the single most important function performance-wise
324    in the GC.  Various things have been tried to speed it up, but as
325    far as I can tell the code generated by gcc 3.2 with -O2 is about
326    as good as it's going to get.  We pass the argument to evacuate()
327    in a register using the 'regparm' attribute (see the prototype for
328    evacuate() near the top of this file).
329
330    Changing evacuate() to take an (StgClosure **) rather than
331    returning the new pointer seems attractive, because we can avoid
332    writing back the pointer when it hasn't changed (eg. for a static
333    object, or an object in a generation > N).  However, I tried it and
334    it doesn't help.  One reason is that the (StgClosure **) pointer
335    gets spilled to the stack inside evacuate(), resulting in far more
336    extra reads/writes than we save.
337    ------------------------------------------------------------------------- */
338
339 REGPARM1 GNUC_ATTR_HOT void 
340 evacuate(StgClosure **p)
341 {
342   bdescr *bd = NULL;
343   step *stp;
344   StgClosure *q;
345   const StgInfoTable *info;
346   StgWord tag;
347
348   q = *p;
349
350 loop:
351   /* The tag and the pointer are split, to be merged after evacing */
352   tag = GET_CLOSURE_TAG(q);
353   q = UNTAG_CLOSURE(q);
354
355   ASSERT(LOOKS_LIKE_CLOSURE_PTR(q));
356
357   if (!HEAP_ALLOCED(q)) {
358
359       if (!major_gc) return;
360
361       info = get_itbl(q);
362       switch (info->type) {
363
364       case THUNK_STATIC:
365           if (info->srt_bitmap != 0) {
366               if (*THUNK_STATIC_LINK((StgClosure *)q) == NULL) {
367 #ifndef THREADED_RTS
368                   *THUNK_STATIC_LINK((StgClosure *)q) = gct->static_objects;
369                   gct->static_objects = (StgClosure *)q;
370 #else
371                   StgPtr link;
372                   link = (StgPtr)cas((StgPtr)THUNK_STATIC_LINK((StgClosure *)q),
373                                      (StgWord)NULL,
374                                      (StgWord)gct->static_objects);
375                   if (link == NULL) {
376                       gct->static_objects = (StgClosure *)q;
377                   }
378 #endif
379               }
380           }
381           return;
382
383       case FUN_STATIC:
384           if (info->srt_bitmap != 0 &&
385               *FUN_STATIC_LINK((StgClosure *)q) == NULL) {
386 #ifndef THREADED_RTS
387               *FUN_STATIC_LINK((StgClosure *)q) = gct->static_objects;
388               gct->static_objects = (StgClosure *)q;
389 #else
390               StgPtr link;
391               link = (StgPtr)cas((StgPtr)FUN_STATIC_LINK((StgClosure *)q),
392                                  (StgWord)NULL,
393                                  (StgWord)gct->static_objects);
394               if (link == NULL) {
395                   gct->static_objects = (StgClosure *)q;
396               }
397 #endif
398           }
399           return;
400           
401       case IND_STATIC:
402           /* If q->saved_info != NULL, then it's a revertible CAF - it'll be
403            * on the CAF list, so don't do anything with it here (we'll
404            * scavenge it later).
405            */
406           if (((StgIndStatic *)q)->saved_info == NULL) {
407               if (*IND_STATIC_LINK((StgClosure *)q) == NULL) {
408 #ifndef THREADED_RTS
409                   *IND_STATIC_LINK((StgClosure *)q) = gct->static_objects;
410                   gct->static_objects = (StgClosure *)q;
411 #else
412                   StgPtr link;
413                   link = (StgPtr)cas((StgPtr)IND_STATIC_LINK((StgClosure *)q),
414                                      (StgWord)NULL,
415                                      (StgWord)gct->static_objects);
416                   if (link == NULL) {
417                       gct->static_objects = (StgClosure *)q;
418                   }
419 #endif
420               }
421           }
422           return;
423           
424       case CONSTR_STATIC:
425           if (*STATIC_LINK(info,(StgClosure *)q) == NULL) {
426 #ifndef THREADED_RTS
427               *STATIC_LINK(info,(StgClosure *)q) = gct->static_objects;
428               gct->static_objects = (StgClosure *)q;
429 #else
430               StgPtr link;
431               link = (StgPtr)cas((StgPtr)STATIC_LINK(info,(StgClosure *)q),
432                                  (StgWord)NULL,
433                                  (StgWord)gct->static_objects);
434               if (link == NULL) {
435                   gct->static_objects = (StgClosure *)q;
436               }
437 #endif
438           }
439           /* I am assuming that static_objects pointers are not
440            * written to other objects, and thus, no need to retag. */
441           return;
442           
443       case CONSTR_NOCAF_STATIC:
444           /* no need to put these on the static linked list, they don't need
445            * to be scavenged.
446            */
447           return;
448           
449       default:
450           barf("evacuate(static): strange closure type %d", (int)(info->type));
451       }
452   }
453
454   bd = Bdescr((P_)q);
455
456   if ((bd->flags & (BF_LARGE | BF_MARKED | BF_EVACUATED)) != 0) {
457
458       // pointer into to-space: just return it.  It might be a pointer
459       // into a generation that we aren't collecting (> N), or it
460       // might just be a pointer into to-space.  The latter doesn't
461       // happen often, but allowing it makes certain things a bit
462       // easier; e.g. scavenging an object is idempotent, so it's OK to
463       // have an object on the mutable list multiple times.
464       if (bd->flags & BF_EVACUATED) {
465           // We aren't copying this object, so we have to check
466           // whether it is already in the target generation.  (this is
467           // the write barrier).
468           if (bd->step < gct->evac_step) {
469               gct->failed_to_evac = rtsTrue;
470               TICK_GC_FAILED_PROMOTION();
471           }
472           return;
473       }
474
475       /* evacuate large objects by re-linking them onto a different list.
476        */
477       if (bd->flags & BF_LARGE) {
478           info = get_itbl(q);
479           if (info->type == TSO && 
480               ((StgTSO *)q)->what_next == ThreadRelocated) {
481               q = (StgClosure *)((StgTSO *)q)->_link;
482               *p = q;
483               goto loop;
484           }
485           evacuate_large((P_)q);
486           return;
487       }
488       
489       /* If the object is in a step that we're compacting, then we
490        * need to use an alternative evacuate procedure.
491        */
492       if (!is_marked((P_)q,bd)) {
493           mark((P_)q,bd);
494           if (mark_stack_full()) {
495               debugTrace(DEBUG_gc,"mark stack overflowed");
496               mark_stack_overflowed = rtsTrue;
497               reset_mark_stack();
498           }
499           push_mark_stack((P_)q);
500       }
501       return;
502   }
503       
504   stp = bd->step->to;
505
506   info = q->header.info;
507   if (IS_FORWARDING_PTR(info))
508   {
509     /* Already evacuated, just return the forwarding address.
510      * HOWEVER: if the requested destination generation (gct->evac_step) is
511      * older than the actual generation (because the object was
512      * already evacuated to a younger generation) then we have to
513      * set the gct->failed_to_evac flag to indicate that we couldn't 
514      * manage to promote the object to the desired generation.
515      */
516     /* 
517      * Optimisation: the check is fairly expensive, but we can often
518      * shortcut it if either the required generation is 0, or the
519      * current object (the EVACUATED) is in a high enough generation.
520      * We know that an EVACUATED always points to an object in the
521      * same or an older generation.  stp is the lowest step that the
522      * current object would be evacuated to, so we only do the full
523      * check if stp is too low.
524      */
525       StgClosure *e = (StgClosure*)UN_FORWARDING_PTR(info);
526       *p = TAG_CLOSURE(tag,e);
527       if (stp < gct->evac_step) {  // optimisation 
528           if (Bdescr((P_)e)->step < gct->evac_step) {
529               gct->failed_to_evac = rtsTrue;
530               TICK_GC_FAILED_PROMOTION();
531           }
532       }
533       return;
534   }
535
536   switch (INFO_PTR_TO_STRUCT(info)->type) {
537
538   case WHITEHOLE:
539       goto loop;
540
541   case MUT_VAR_CLEAN:
542   case MUT_VAR_DIRTY:
543   case MVAR_CLEAN:
544   case MVAR_DIRTY:
545       copy(p,info,q,sizeW_fromITBL(INFO_PTR_TO_STRUCT(info)),stp);
546       return;
547
548   case CONSTR_0_1:
549   { 
550       StgWord w = (StgWord)q->payload[0];
551       if (info == Czh_con_info &&
552           // unsigned, so always true:  (StgChar)w >= MIN_CHARLIKE &&  
553           (StgChar)w <= MAX_CHARLIKE) {
554           *p =  TAG_CLOSURE(tag,
555                             (StgClosure *)CHARLIKE_CLOSURE((StgChar)w)
556                            );
557       }
558       else if (info == Izh_con_info &&
559           (StgInt)w >= MIN_INTLIKE && (StgInt)w <= MAX_INTLIKE) {
560           *p = TAG_CLOSURE(tag,
561                              (StgClosure *)INTLIKE_CLOSURE((StgInt)w)
562                              );
563       }
564       else {
565           copy_tag_nolock(p,info,q,sizeofW(StgHeader)+1,stp,tag);
566       }
567       return;
568   }
569
570   case FUN_0_1:
571   case FUN_1_0:
572   case CONSTR_1_0:
573       copy_tag_nolock(p,info,q,sizeofW(StgHeader)+1,stp,tag);
574       return;
575
576   case THUNK_1_0:
577   case THUNK_0_1:
578       copy(p,info,q,sizeofW(StgThunk)+1,stp);
579       return;
580
581   case THUNK_1_1:
582   case THUNK_2_0:
583   case THUNK_0_2:
584 #ifdef NO_PROMOTE_THUNKS
585     if (bd->gen_no == 0 && 
586         bd->step->no != 0 &&
587         bd->step->no == generations[bd->gen_no].n_steps-1) {
588       stp = bd->step;
589     }
590 #endif
591     copy(p,info,q,sizeofW(StgThunk)+2,stp);
592     return;
593
594   case FUN_1_1:
595   case FUN_2_0:
596   case FUN_0_2:
597   case CONSTR_1_1:
598   case CONSTR_2_0:
599       copy_tag_nolock(p,info,q,sizeofW(StgHeader)+2,stp,tag);
600       return;
601
602   case CONSTR_0_2:
603       copy_tag_nolock(p,info,q,sizeofW(StgHeader)+2,stp,tag);
604       return;
605
606   case THUNK:
607       copy(p,info,q,thunk_sizeW_fromITBL(INFO_PTR_TO_STRUCT(info)),stp);
608       return;
609
610   case FUN:
611   case IND_PERM:
612   case IND_OLDGEN_PERM:
613   case CONSTR:
614       copy_tag_nolock(p,info,q,sizeW_fromITBL(INFO_PTR_TO_STRUCT(info)),stp,tag);
615       return;
616
617   case WEAK:
618   case STABLE_NAME:
619       copy_tag(p,info,q,sizeW_fromITBL(INFO_PTR_TO_STRUCT(info)),stp,tag);
620       return;
621
622   case BCO:
623       copy(p,info,q,bco_sizeW((StgBCO *)q),stp);
624       return;
625
626   case CAF_BLACKHOLE:
627   case SE_CAF_BLACKHOLE:
628   case SE_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
701           copyPart(p,(StgClosure *)tso, tso_sizeW(tso), sizeofW(StgTSO), stp);
702           new_tso = (StgTSO *)*p;
703           move_TSO(tso, new_tso);
704           for (r = tso->sp, s = new_tso->sp;
705                r < tso->stack+tso->stack_size;) {
706               *s++ = *r++;
707           }
708           return;
709       }
710     }
711
712   case TREC_HEADER: 
713       copy(p,info,q,sizeofW(StgTRecHeader),stp);
714       return;
715
716   case TVAR_WATCH_QUEUE:
717       copy(p,info,q,sizeofW(StgTVarWatchQueue),stp);
718       return;
719
720   case TVAR:
721       copy(p,info,q,sizeofW(StgTVar),stp);
722       return;
723     
724   case TREC_CHUNK:
725       copy(p,info,q,sizeofW(StgTRecChunk),stp);
726       return;
727
728   case ATOMIC_INVARIANT:
729       copy(p,info,q,sizeofW(StgAtomicInvariant),stp);
730       return;
731
732   case INVARIANT_CHECK_QUEUE:
733       copy(p,info,q,sizeofW(StgInvariantCheckQueue),stp);
734       return;
735
736   default:
737     barf("evacuate: strange closure type %d", (int)(INFO_PTR_TO_STRUCT(info)->type));
738   }
739
740   barf("evacuate");
741 }
742
743 /* -----------------------------------------------------------------------------
744    Evaluate a THUNK_SELECTOR if possible.
745
746    p points to a THUNK_SELECTOR that we want to evaluate.  The
747    result of "evaluating" it will be evacuated and a pointer to the
748    to-space closure will be returned.
749
750    If the THUNK_SELECTOR could not be evaluated (its selectee is still
751    a THUNK, for example), then the THUNK_SELECTOR itself will be
752    evacuated.
753    -------------------------------------------------------------------------- */
754 static void
755 unchain_thunk_selectors(StgSelector *p, StgClosure *val)
756 {
757     StgSelector *prev;
758
759     prev = NULL;
760     while (p)
761     {
762 #ifdef THREADED_RTS
763         ASSERT(p->header.info == &stg_WHITEHOLE_info);
764 #else
765         ASSERT(p->header.info == &stg_BLACKHOLE_info);
766 #endif
767         // val must be in to-space.  Not always: when we recursively
768         // invoke eval_thunk_selector(), the recursive calls will not 
769         // evacuate the value (because we want to select on the value,
770         // not evacuate it), so in this case val is in from-space.
771         // ASSERT(!HEAP_ALLOCED(val) || Bdescr((P_)val)->gen_no > N || (Bdescr((P_)val)->flags & BF_EVACUATED));
772
773         prev = (StgSelector*)((StgClosure *)p)->payload[0];
774
775         // Update the THUNK_SELECTOR with an indirection to the
776         // value.  The value is still in from-space at this stage.
777         //
778         // (old note: Why not do upd_evacuee(q,p)?  Because we have an
779         // invariant that an EVACUATED closure always points to an
780         // object in the same or an older generation (required by
781         // the short-cut test in the EVACUATED case, below).
782         if ((StgClosure *)p == val) {
783             // must be a loop; just leave a BLACKHOLE in place.  This
784             // can happen when we have a chain of selectors that
785             // eventually loops back on itself.  We can't leave an
786             // indirection pointing to itself, and we want the program
787             // to deadlock if it ever enters this closure, so
788             // BLACKHOLE is correct.
789             SET_INFO(p, &stg_BLACKHOLE_info);
790         } else {
791             ((StgInd *)p)->indirectee = val;
792             write_barrier();
793             SET_INFO(p, &stg_IND_info);
794         }
795
796         // For the purposes of LDV profiling, we have created an
797         // indirection.
798         LDV_RECORD_CREATE(p);
799
800         p = prev;
801     }
802 }
803
804 static void
805 eval_thunk_selector (StgClosure **q, StgSelector * p, rtsBool evac)
806                  // NB. for legacy reasons, p & q are swapped around :(
807 {
808     nat field;
809     StgInfoTable *info;
810     StgWord info_ptr;
811     StgClosure *selectee;
812     StgSelector *prev_thunk_selector;
813     bdescr *bd;
814     StgClosure *val;
815     
816     prev_thunk_selector = NULL;
817     // this is a chain of THUNK_SELECTORs that we are going to update
818     // to point to the value of the current THUNK_SELECTOR.  Each
819     // closure on the chain is a BLACKHOLE, and points to the next in the
820     // chain with payload[0].
821
822 selector_chain:
823
824     bd = Bdescr((StgPtr)p);
825     if (HEAP_ALLOCED(p)) {
826         // If the THUNK_SELECTOR is in to-space or in a generation that we
827         // are not collecting, then bale out early.  We won't be able to
828         // save any space in any case, and updating with an indirection is
829         // trickier in a non-collected gen: we would have to update the
830         // mutable list.
831         if (bd->flags & BF_EVACUATED) {
832             unchain_thunk_selectors(prev_thunk_selector, (StgClosure *)p);
833             *q = (StgClosure *)p;
834             return;
835         }
836         // we don't update THUNK_SELECTORS in the compacted
837         // generation, because compaction does not remove the INDs
838         // that result, this causes confusion later
839         // (scavenge_mark_stack doesn't deal with IND).  BEWARE!  This
840         // bit is very tricky to get right.  If you make changes
841         // around here, test by compiling stage 3 with +RTS -c -RTS.
842         if (bd->flags & BF_MARKED) {
843             // must call evacuate() to mark this closure if evac==rtsTrue
844             *q = (StgClosure *)p;
845             if (evac) evacuate(q);
846             unchain_thunk_selectors(prev_thunk_selector, (StgClosure *)p);
847             return;
848         }
849     }
850
851
852     // BLACKHOLE the selector thunk, since it is now under evaluation.
853     // This is important to stop us going into an infinite loop if
854     // this selector thunk eventually refers to itself.
855 #if defined(THREADED_RTS)
856     // In threaded mode, we'll use WHITEHOLE to lock the selector
857     // thunk while we evaluate it.
858     {
859         do {
860             info_ptr = xchg((StgPtr)&p->header.info, (W_)&stg_WHITEHOLE_info);
861         } while (info_ptr == (W_)&stg_WHITEHOLE_info);
862
863         // make sure someone else didn't get here first...
864         if (IS_FORWARDING_PTR(p) || 
865             INFO_PTR_TO_STRUCT(info_ptr)->type != THUNK_SELECTOR) {
866             // v. tricky now.  The THUNK_SELECTOR has been evacuated
867             // by another thread, and is now either a forwarding ptr or IND.
868             // We need to extract ourselves from the current situation
869             // as cleanly as possible.
870             //   - unlock the closure
871             //   - update *q, we may have done *some* evaluation
872             //   - if evac, we need to call evacuate(), because we
873             //     need the write-barrier stuff.
874             //   - undo the chain we've built to point to p.
875             SET_INFO(p, (const StgInfoTable *)info_ptr);
876             *q = (StgClosure *)p;
877             if (evac) evacuate(q);
878             unchain_thunk_selectors(prev_thunk_selector, (StgClosure *)p);
879             return;
880         }
881     }
882 #else
883     // Save the real info pointer (NOTE: not the same as get_itbl()).
884     info_ptr = (StgWord)p->header.info;
885     SET_INFO(p,&stg_BLACKHOLE_info);
886 #endif
887
888     field = INFO_PTR_TO_STRUCT(info_ptr)->layout.selector_offset;
889
890     // The selectee might be a constructor closure,
891     // so we untag the pointer.
892     selectee = UNTAG_CLOSURE(p->selectee);
893
894 selector_loop:
895     // selectee now points to the closure that we're trying to select
896     // a field from.  It may or may not be in to-space: we try not to
897     // end up in to-space, but it's impractical to avoid it in
898     // general.  The compacting GC scatters to-space pointers in
899     // from-space during marking, for example.  We rely on the property
900     // that evacuate() doesn't mind if it gets passed a to-space pointer.
901
902     info = (StgInfoTable*)selectee->header.info;
903
904     if (IS_FORWARDING_PTR(info)) {
905         // We don't follow pointers into to-space; the constructor
906         // has already been evacuated, so we won't save any space
907         // leaks by evaluating this selector thunk anyhow.
908         goto bale_out;
909     }
910
911     info = INFO_PTR_TO_STRUCT(info);
912     switch (info->type) {
913       case WHITEHOLE:
914           goto bale_out; // about to be evacuated by another thread (or a loop).
915         
916       case CONSTR:
917       case CONSTR_1_0:
918       case CONSTR_0_1:
919       case CONSTR_2_0:
920       case CONSTR_1_1:
921       case CONSTR_0_2:
922       case CONSTR_STATIC:
923       case CONSTR_NOCAF_STATIC:
924           {
925               // check that the size is in range 
926               ASSERT(field <  (StgWord32)(info->layout.payload.ptrs + 
927                                           info->layout.payload.nptrs));
928           
929               // Select the right field from the constructor
930               val = selectee->payload[field];
931               
932 #ifdef PROFILING
933               // For the purposes of LDV profiling, we have destroyed
934               // the original selector thunk, p.
935               SET_INFO(p, (StgInfoTable *)info_ptr);
936               LDV_RECORD_DEAD_FILL_SLOP_DYNAMIC((StgClosure *)p);
937               SET_INFO(p, &stg_BLACKHOLE_info);
938 #endif
939
940               // the closure in val is now the "value" of the
941               // THUNK_SELECTOR in p.  However, val may itself be a
942               // THUNK_SELECTOR, in which case we want to continue
943               // evaluating until we find the real value, and then
944               // update the whole chain to point to the value.
945           val_loop:
946               info_ptr = (StgWord)UNTAG_CLOSURE(val)->header.info;
947               if (!IS_FORWARDING_PTR(info_ptr))
948               {
949                   info = INFO_PTR_TO_STRUCT(info_ptr);
950                   switch (info->type) {
951                   case IND:
952                   case IND_PERM:
953                   case IND_OLDGEN:
954                   case IND_OLDGEN_PERM:
955                   case IND_STATIC:
956                       val = ((StgInd *)val)->indirectee;
957                       goto val_loop;
958                   case THUNK_SELECTOR:
959                       ((StgClosure*)p)->payload[0] = (StgClosure *)prev_thunk_selector;
960                       prev_thunk_selector = p;
961                       p = (StgSelector*)val;
962                       goto selector_chain;
963                   default:
964                       break;
965                   }
966               }
967               ((StgClosure*)p)->payload[0] = (StgClosure *)prev_thunk_selector;
968               prev_thunk_selector = p;
969
970               *q = val;
971
972               // update the other selectors in the chain *before*
973               // evacuating the value.  This is necessary in the case
974               // where the value turns out to be one of the selectors
975               // in the chain (i.e. we have a loop), and evacuating it
976               // would corrupt the chain.
977               unchain_thunk_selectors(prev_thunk_selector, val);
978
979               // evacuate() cannot recurse through
980               // eval_thunk_selector(), because we know val is not
981               // a THUNK_SELECTOR.
982               if (evac) evacuate(q);
983               return;
984           }
985
986       case IND:
987       case IND_PERM:
988       case IND_OLDGEN:
989       case IND_OLDGEN_PERM:
990       case IND_STATIC:
991           // Again, we might need to untag a constructor.
992           selectee = UNTAG_CLOSURE( ((StgInd *)selectee)->indirectee );
993           goto selector_loop;
994
995       case THUNK_SELECTOR:
996       {
997           StgClosure *val;
998
999           // recursively evaluate this selector.  We don't want to
1000           // recurse indefinitely, so we impose a depth bound.
1001           if (gct->thunk_selector_depth >= MAX_THUNK_SELECTOR_DEPTH) {
1002               goto bale_out;
1003           }
1004
1005           gct->thunk_selector_depth++;
1006           // rtsFalse says "don't evacuate the result".  It will,
1007           // however, update any THUNK_SELECTORs that are evaluated
1008           // along the way.
1009           eval_thunk_selector(&val, (StgSelector*)selectee, rtsFalse);
1010           gct->thunk_selector_depth--;
1011
1012           // did we actually manage to evaluate it?
1013           if (val == selectee) goto bale_out;
1014
1015           // Of course this pointer might be tagged...
1016           selectee = UNTAG_CLOSURE(val);
1017           goto selector_loop;
1018       }
1019
1020       case AP:
1021       case AP_STACK:
1022       case THUNK:
1023       case THUNK_1_0:
1024       case THUNK_0_1:
1025       case THUNK_2_0:
1026       case THUNK_1_1:
1027       case THUNK_0_2:
1028       case THUNK_STATIC:
1029       case CAF_BLACKHOLE:
1030       case SE_CAF_BLACKHOLE:
1031       case SE_BLACKHOLE:
1032       case BLACKHOLE:
1033           // not evaluated yet 
1034           goto bale_out;
1035     
1036       default:
1037         barf("eval_thunk_selector: strange selectee %d",
1038              (int)(info->type));
1039     }
1040
1041 bale_out:
1042     // We didn't manage to evaluate this thunk; restore the old info
1043     // pointer.  But don't forget: we still need to evacuate the thunk itself.
1044     SET_INFO(p, (const StgInfoTable *)info_ptr);
1045     // THREADED_RTS: we just unlocked the thunk, so another thread
1046     // might get in and update it.  copy() will lock it again and
1047     // check whether it was updated in the meantime.
1048     *q = (StgClosure *)p;
1049     if (evac) {
1050         copy(q,(const StgInfoTable *)info_ptr,(StgClosure *)p,THUNK_SELECTOR_sizeW(),bd->step->to);
1051     }
1052     unchain_thunk_selectors(prev_thunk_selector, *q);
1053     return;
1054 }