remove EVACUATED: store the forwarding pointer in the info pointer
[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
25 #if defined(PROF_SPIN) && defined(THREADED_RTS)
26 StgWord64 whitehole_spin = 0;
27 #endif
28
29 /* Used to avoid long recursion due to selector thunks
30  */
31 #define MAX_THUNK_SELECTOR_DEPTH 16
32
33 static void eval_thunk_selector (StgClosure **q, StgSelector * p, rtsBool);
34 STATIC_INLINE void evacuate_large(StgPtr p);
35
36 /* -----------------------------------------------------------------------------
37    Allocate some space in which to copy an object.
38    -------------------------------------------------------------------------- */
39
40 STATIC_INLINE StgPtr
41 alloc_for_copy (nat size, step *stp)
42 {
43     StgPtr to;
44     step_workspace *ws;
45
46     /* Find out where we're going, using the handy "to" pointer in 
47      * the step of the source object.  If it turns out we need to
48      * evacuate to an older generation, adjust it here (see comment
49      * by evacuate()).
50      */
51     if (stp < gct->evac_step) {
52         if (gct->eager_promotion) {
53             stp = gct->evac_step;
54         } else {
55             gct->failed_to_evac = rtsTrue;
56         }
57     }
58     
59     ws = &gct->steps[stp->abs_no];
60     // this compiles to a single mem access to stp->abs_no only
61     
62     /* chain a new block onto the to-space for the destination step if
63      * necessary.
64      */
65     to = ws->todo_free;
66     if (to + size > ws->todo_lim) {
67         to = todo_block_full(size, ws);
68     }
69     ws->todo_free = to + size;
70     ASSERT(ws->todo_free >= ws->todo_bd->free && ws->todo_free <= ws->todo_lim);
71
72     return to;
73 }
74
75 /* -----------------------------------------------------------------------------
76    The evacuate() code
77    -------------------------------------------------------------------------- */
78
79 #undef PARALLEL_GC
80 #include "Evac.c-inc"
81
82 #ifdef THREADED_RTS
83 #define PARALLEL_GC
84 #include "Evac.c-inc"
85 #endif
86
87 /* -----------------------------------------------------------------------------
88    Evacuate a large object
89
90    This just consists of removing the object from the (doubly-linked)
91    step->large_objects list, and linking it on to the (singly-linked)
92    step->new_large_objects list, from where it will be scavenged later.
93
94    Convention: bd->flags has BF_EVACUATED set for a large object
95    that has been evacuated, or unset otherwise.
96    -------------------------------------------------------------------------- */
97
98 STATIC_INLINE void
99 evacuate_large(StgPtr p)
100 {
101   bdescr *bd = Bdescr(p);
102   step *stp, *new_stp;
103   step_workspace *ws;
104     
105   stp = bd->step;
106   ACQUIRE_SPIN_LOCK(&stp->sync_large_objects);
107
108   // object must be at the beginning of the block (or be a ByteArray)
109   ASSERT(get_itbl((StgClosure *)p)->type == ARR_WORDS ||
110          (((W_)p & BLOCK_MASK) == 0));
111
112   // already evacuated? 
113   if (bd->flags & BF_EVACUATED) { 
114     /* Don't forget to set the gct->failed_to_evac flag if we didn't get
115      * the desired destination (see comments in evacuate()).
116      */
117     if (stp < gct->evac_step) {
118         gct->failed_to_evac = rtsTrue;
119         TICK_GC_FAILED_PROMOTION();
120     }
121     RELEASE_SPIN_LOCK(&stp->sync_large_objects);
122     return;
123   }
124
125   // remove from large_object list 
126   if (bd->u.back) {
127     bd->u.back->link = bd->link;
128   } else { // first object in the list 
129     stp->large_objects = bd->link;
130   }
131   if (bd->link) {
132     bd->link->u.back = bd->u.back;
133   }
134   
135   /* link it on to the evacuated large object list of the destination step
136    */
137   new_stp = stp->to;
138   if (new_stp < gct->evac_step) {
139       if (gct->eager_promotion) {
140           new_stp = gct->evac_step;
141       } else {
142           gct->failed_to_evac = rtsTrue;
143       }
144   }
145
146   ws = &gct->steps[new_stp->abs_no];
147   bd->flags |= BF_EVACUATED;
148   bd->step = new_stp;
149   bd->gen_no = new_stp->gen_no;
150   bd->link = ws->todo_large_objects;
151   ws->todo_large_objects = bd;
152
153   RELEASE_SPIN_LOCK(&stp->sync_large_objects);
154 }
155
156 /* -----------------------------------------------------------------------------
157    Evaluate a THUNK_SELECTOR if possible.
158
159    p points to a THUNK_SELECTOR that we want to evaluate.  The
160    result of "evaluating" it will be evacuated and a pointer to the
161    to-space closure will be returned.
162
163    If the THUNK_SELECTOR could not be evaluated (its selectee is still
164    a THUNK, for example), then the THUNK_SELECTOR itself will be
165    evacuated.
166    -------------------------------------------------------------------------- */
167 static void
168 unchain_thunk_selectors(StgSelector *p, StgClosure *val)
169 {
170     StgSelector *prev;
171
172     prev = NULL;
173     while (p)
174     {
175 #ifdef THREADED_RTS
176         ASSERT(p->header.info == &stg_WHITEHOLE_info);
177 #else
178         ASSERT(p->header.info == &stg_BLACKHOLE_info);
179 #endif
180         // val must be in to-space.  Not always: when we recursively
181         // invoke eval_thunk_selector(), the recursive calls will not 
182         // evacuate the value (because we want to select on the value,
183         // not evacuate it), so in this case val is in from-space.
184         // ASSERT(!HEAP_ALLOCED(val) || Bdescr((P_)val)->gen_no > N || (Bdescr((P_)val)->flags & BF_EVACUATED));
185
186         prev = (StgSelector*)((StgClosure *)p)->payload[0];
187
188         // Update the THUNK_SELECTOR with an indirection to the
189         // EVACUATED closure now at p.  Why do this rather than
190         // upd_evacuee(q,p)?  Because we have an invariant that an
191         // EVACUATED closure always points to an object in the
192         // same or an older generation (required by the short-cut
193         // test in the EVACUATED case, below).
194         ((StgInd *)p)->indirectee = val;
195         write_barrier();
196         SET_INFO(p, &stg_IND_info);
197
198         // For the purposes of LDV profiling, we have created an
199         // indirection.
200         LDV_RECORD_CREATE(p);
201
202         p = prev;
203     }
204 }
205
206 static void
207 eval_thunk_selector (StgClosure **q, StgSelector * p, rtsBool evac)
208                  // NB. for legacy reasons, p & q are swapped around :(
209 {
210     nat field;
211     StgInfoTable *info;
212     StgWord info_ptr;
213     StgClosure *selectee;
214     StgSelector *prev_thunk_selector;
215     bdescr *bd;
216     StgClosure *val;
217     
218     prev_thunk_selector = NULL;
219     // this is a chain of THUNK_SELECTORs that we are going to update
220     // to point to the value of the current THUNK_SELECTOR.  Each
221     // closure on the chain is a BLACKHOLE, and points to the next in the
222     // chain with payload[0].
223
224 selector_chain:
225
226     bd = Bdescr((StgPtr)p);
227     if (HEAP_ALLOCED(p)) {
228         // If the THUNK_SELECTOR is in to-space or in a generation that we
229         // are not collecting, then bale out early.  We won't be able to
230         // save any space in any case, and updating with an indirection is
231         // trickier in a non-collected gen: we would have to update the
232         // mutable list.
233         if (bd->flags & BF_EVACUATED) {
234             unchain_thunk_selectors(prev_thunk_selector, (StgClosure *)p);
235             *q = (StgClosure *)p;
236             return;
237         }
238         // we don't update THUNK_SELECTORS in the compacted
239         // generation, because compaction does not remove the INDs
240         // that result, this causes confusion later
241         // (scavenge_mark_stack doesn't deal with IND).  BEWARE!  This
242         // bit is very tricky to get right.  If you make changes
243         // around here, test by compiling stage 3 with +RTS -c -RTS.
244         if (bd->flags & BF_COMPACTED) {
245             // must call evacuate() to mark this closure if evac==rtsTrue
246             *q = (StgClosure *)p;
247             if (evac) evacuate(q);
248             unchain_thunk_selectors(prev_thunk_selector, (StgClosure *)p);
249             return;
250         }
251     }
252
253
254     // BLACKHOLE the selector thunk, since it is now under evaluation.
255     // This is important to stop us going into an infinite loop if
256     // this selector thunk eventually refers to itself.
257 #if defined(THREADED_RTS)
258     // In threaded mode, we'll use WHITEHOLE to lock the selector
259     // thunk while we evaluate it.
260     {
261         do {
262             info_ptr = xchg((StgPtr)&p->header.info, (W_)&stg_WHITEHOLE_info);
263         } while (info_ptr == (W_)&stg_WHITEHOLE_info);
264
265         // make sure someone else didn't get here first...
266         if (IS_FORWARDING_PTR(p) || 
267             INFO_PTR_TO_STRUCT(info_ptr)->type != THUNK_SELECTOR) {
268             // v. tricky now.  The THUNK_SELECTOR has been evacuated
269             // by another thread, and is now either a forwarding ptr or IND.
270             // We need to extract ourselves from the current situation
271             // as cleanly as possible.
272             //   - unlock the closure
273             //   - update *q, we may have done *some* evaluation
274             //   - if evac, we need to call evacuate(), because we
275             //     need the write-barrier stuff.
276             //   - undo the chain we've built to point to p.
277             SET_INFO(p, (const StgInfoTable *)info_ptr);
278             *q = (StgClosure *)p;
279             if (evac) evacuate(q);
280             unchain_thunk_selectors(prev_thunk_selector, (StgClosure *)p);
281             return;
282         }
283     }
284 #else
285     // Save the real info pointer (NOTE: not the same as get_itbl()).
286     info_ptr = (StgWord)p->header.info;
287     SET_INFO(p,&stg_BLACKHOLE_info);
288 #endif
289
290     field = INFO_PTR_TO_STRUCT(info_ptr)->layout.selector_offset;
291
292     // The selectee might be a constructor closure,
293     // so we untag the pointer.
294     selectee = UNTAG_CLOSURE(p->selectee);
295
296 selector_loop:
297     // selectee now points to the closure that we're trying to select
298     // a field from.  It may or may not be in to-space: we try not to
299     // end up in to-space, but it's impractical to avoid it in
300     // general.  The compacting GC scatters to-space pointers in
301     // from-space during marking, for example.  We rely on the property
302     // that evacuate() doesn't mind if it gets passed a to-space pointer.
303
304     info = (StgInfoTable*)selectee->header.info;
305
306     if (IS_FORWARDING_PTR(info)) {
307         // We don't follow pointers into to-space; the constructor
308         // has already been evacuated, so we won't save any space
309         // leaks by evaluating this selector thunk anyhow.
310         goto bale_out;
311     }
312
313     info = INFO_PTR_TO_STRUCT(info);
314     switch (info->type) {
315       case WHITEHOLE:
316           goto bale_out; // about to be evacuated by another thread (or a loop).
317         
318       case CONSTR:
319       case CONSTR_1_0:
320       case CONSTR_0_1:
321       case CONSTR_2_0:
322       case CONSTR_1_1:
323       case CONSTR_0_2:
324       case CONSTR_STATIC:
325       case CONSTR_NOCAF_STATIC:
326           {
327               // check that the size is in range 
328               ASSERT(field <  (StgWord32)(info->layout.payload.ptrs + 
329                                           info->layout.payload.nptrs));
330           
331               // Select the right field from the constructor
332               val = selectee->payload[field];
333               
334 #ifdef PROFILING
335               // For the purposes of LDV profiling, we have destroyed
336               // the original selector thunk, p.
337               SET_INFO(p, (StgInfoTable *)info_ptr);
338               LDV_RECORD_DEAD_FILL_SLOP_DYNAMIC((StgClosure *)p);
339               SET_INFO(p, &stg_BLACKHOLE_info);
340 #endif
341
342               // the closure in val is now the "value" of the
343               // THUNK_SELECTOR in p.  However, val may itself be a
344               // THUNK_SELECTOR, in which case we want to continue
345               // evaluating until we find the real value, and then
346               // update the whole chain to point to the value.
347           val_loop:
348               info_ptr = (StgWord)UNTAG_CLOSURE(val)->header.info;
349               if (!IS_FORWARDING_PTR(info_ptr))
350               {
351                   info = INFO_PTR_TO_STRUCT(info_ptr);
352                   switch (info->type) {
353                   case IND:
354                   case IND_PERM:
355                   case IND_OLDGEN:
356                   case IND_OLDGEN_PERM:
357                   case IND_STATIC:
358                       val = ((StgInd *)val)->indirectee;
359                       goto val_loop;
360                   case THUNK_SELECTOR:
361                       ((StgClosure*)p)->payload[0] = (StgClosure *)prev_thunk_selector;
362                       prev_thunk_selector = p;
363                       p = (StgSelector*)val;
364                       goto selector_chain;
365                   default:
366                       break;
367                   }
368               }
369               ((StgClosure*)p)->payload[0] = (StgClosure *)prev_thunk_selector;
370               prev_thunk_selector = p;
371
372               *q = val;
373               if (evac) evacuate(q);
374               val = *q;
375               // evacuate() cannot recurse through
376               // eval_thunk_selector(), because we know val is not
377               // a THUNK_SELECTOR.
378               unchain_thunk_selectors(prev_thunk_selector, val);
379               return;
380           }
381
382       case IND:
383       case IND_PERM:
384       case IND_OLDGEN:
385       case IND_OLDGEN_PERM:
386       case IND_STATIC:
387           // Again, we might need to untag a constructor.
388           selectee = UNTAG_CLOSURE( ((StgInd *)selectee)->indirectee );
389           goto selector_loop;
390
391       case THUNK_SELECTOR:
392       {
393           StgClosure *val;
394
395           // recursively evaluate this selector.  We don't want to
396           // recurse indefinitely, so we impose a depth bound.
397           if (gct->thunk_selector_depth >= MAX_THUNK_SELECTOR_DEPTH) {
398               goto bale_out;
399           }
400
401           gct->thunk_selector_depth++;
402           // rtsFalse says "don't evacuate the result".  It will,
403           // however, update any THUNK_SELECTORs that are evaluated
404           // along the way.
405           eval_thunk_selector(&val, (StgSelector*)selectee, rtsFalse);
406           gct->thunk_selector_depth--;
407
408           // did we actually manage to evaluate it?
409           if (val == selectee) goto bale_out;
410
411           // Of course this pointer might be tagged...
412           selectee = UNTAG_CLOSURE(val);
413           goto selector_loop;
414       }
415
416       case AP:
417       case AP_STACK:
418       case THUNK:
419       case THUNK_1_0:
420       case THUNK_0_1:
421       case THUNK_2_0:
422       case THUNK_1_1:
423       case THUNK_0_2:
424       case THUNK_STATIC:
425       case CAF_BLACKHOLE:
426       case SE_CAF_BLACKHOLE:
427       case SE_BLACKHOLE:
428       case BLACKHOLE:
429           // not evaluated yet 
430           goto bale_out;
431     
432       default:
433         barf("eval_thunk_selector: strange selectee %d",
434              (int)(info->type));
435     }
436
437 bale_out:
438     // We didn't manage to evaluate this thunk; restore the old info
439     // pointer.  But don't forget: we still need to evacuate the thunk itself.
440     SET_INFO(p, (const StgInfoTable *)info_ptr);
441     // THREADED_RTS: we just unlocked the thunk, so another thread
442     // might get in and update it.  copy() will lock it again and
443     // check whether it was updated in the meantime.
444     *q = (StgClosure *)p;
445     if (evac) {
446         copy(q,(const StgInfoTable *)info_ptr,(StgClosure *)p,THUNK_SELECTOR_sizeW(),bd->step->to);
447     }
448     unchain_thunk_selectors(prev_thunk_selector, *q);
449     return;
450 }
451
452 /* -----------------------------------------------------------------------------
453    move_TSO is called to update the TSO structure after it has been
454    moved from one place to another.
455    -------------------------------------------------------------------------- */
456
457 void
458 move_TSO (StgTSO *src, StgTSO *dest)
459 {
460     ptrdiff_t diff;
461
462     // relocate the stack pointer... 
463     diff = (StgPtr)dest - (StgPtr)src; // In *words* 
464     dest->sp = (StgPtr)dest->sp + diff;
465 }
466