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