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