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