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