Evac.c 33.9 KB
Newer Older
1 2
/* -----------------------------------------------------------------------------
 *
3
 * (c) The GHC Team 1998-2008
4 5 6
 *
 * Generational garbage collector: evacuation functions
 *
7 8 9 10 11
 * Documentation on the architecture of the Garbage Collector can be
 * found in the online commentary:
 * 
 *   http://hackage.haskell.org/trac/ghc/wiki/Commentary/Rts/Storage/GC
 *
12 13
 * ---------------------------------------------------------------------------*/

Simon Marlow's avatar
Simon Marlow committed
14
#include "PosixSource.h"
15
#include "Rts.h"
Simon Marlow's avatar
Simon Marlow committed
16

17
#include "Evac.h"
Simon Marlow's avatar
Simon Marlow committed
18
#include "Storage.h"
19
#include "GC.h"
20
#include "GCThread.h"
Simon Marlow's avatar
Simon Marlow committed
21
#include "GCTDecl.h"
22 23
#include "GCUtils.h"
#include "Compact.h"
24
#include "MarkStack.h"
25
#include "Prelude.h"
26
#include "Trace.h"
Simon Marlow's avatar
Simon Marlow committed
27
#include "LdvProfile.h"
28

29
#if defined(PROF_SPIN) && defined(THREADED_RTS) && defined(PARALLEL_GC)
30
StgWord64 whitehole_spin = 0;
31 32
#endif

33 34
#if defined(THREADED_RTS) && !defined(PARALLEL_GC)
#define evacuate(p) evacuate1(p)
35
#define HEAP_ALLOCED_GC(p) HEAP_ALLOCED(p)
36 37 38 39 40 41 42
#endif

#if !defined(PARALLEL_GC)
#define copy_tag_nolock(p, info, src, size, stp, tag) \
        copy_tag(p, info, src, size, stp, tag)
#endif

43 44
/* Used to avoid long recursion due to selector thunks
 */
45
#define MAX_THUNK_SELECTOR_DEPTH 16
46

47
static void eval_thunk_selector (StgClosure **q, StgSelector * p, rtsBool);
48 49 50 51 52
STATIC_INLINE void evacuate_large(StgPtr p);

/* -----------------------------------------------------------------------------
   Allocate some space in which to copy an object.
   -------------------------------------------------------------------------- */
53

Simon Marlow's avatar
Simon Marlow committed
54
STATIC_INLINE StgPtr
Simon Marlow's avatar
Simon Marlow committed
55
alloc_for_copy (nat size, nat gen_no)
56
{
Simon Marlow's avatar
Simon Marlow committed
57
    StgPtr to;
58
    gen_workspace *ws;
Simon Marlow's avatar
Simon Marlow committed
59 60

    /* Find out where we're going, using the handy "to" pointer in 
61
     * the gen of the source object.  If it turns out we need to
Simon Marlow's avatar
Simon Marlow committed
62 63 64
     * evacuate to an older generation, adjust it here (see comment
     * by evacuate()).
     */
Simon Marlow's avatar
Simon Marlow committed
65
    if (gen_no < gct->evac_gen_no) {
Simon Marlow's avatar
Simon Marlow committed
66
	if (gct->eager_promotion) {
Simon Marlow's avatar
Simon Marlow committed
67
            gen_no = gct->evac_gen_no;
Simon Marlow's avatar
Simon Marlow committed
68 69 70 71 72
	} else {
	    gct->failed_to_evac = rtsTrue;
	}
    }
    
Simon Marlow's avatar
Simon Marlow committed
73 74
    ws = &gct->gens[gen_no];  // zero memory references here

75
    /* chain a new block onto the to-space for the destination gen if
Simon Marlow's avatar
Simon Marlow committed
76 77
     * necessary.
     */
78
    to = ws->todo_free;
Simon Marlow's avatar
Simon Marlow committed
79 80
    ws->todo_free += size;
    if (ws->todo_free > ws->todo_lim) {
81
	to = todo_block_full(size, ws);
Simon Marlow's avatar
Simon Marlow committed
82
    }
83
    ASSERT(ws->todo_free >= ws->todo_bd->free && ws->todo_free <= ws->todo_lim);
84

Simon Marlow's avatar
Simon Marlow committed
85 86
    return to;
}
87

88 89 90 91
/* -----------------------------------------------------------------------------
   The evacuate() code
   -------------------------------------------------------------------------- */

Simon Marlow's avatar
Simon Marlow committed
92
STATIC_INLINE GNUC_ATTR_HOT void
93
copy_tag(StgClosure **p, const StgInfoTable *info, 
Simon Marlow's avatar
Simon Marlow committed
94
         StgClosure *src, nat size, nat gen_no, StgWord tag)
95 96 97 98
{
    StgPtr to, from;
    nat i;

Simon Marlow's avatar
Simon Marlow committed
99
    to = alloc_for_copy(size,gen_no);
100 101 102 103 104 105 106 107 108 109 110 111 112 113
    
    from = (StgPtr)src;
    to[0] = (W_)info;
    for (i = 1; i < size; i++) { // unroll for small i
	to[i] = from[i];
    }

//  if (to+size+2 < bd->start + BLOCK_SIZE_W) {
//      __builtin_prefetch(to + size + 2, 1);
//  }

#if defined(PARALLEL_GC)
    {
        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 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135
        } else {
            *p = TAG_CLOSURE(tag,(StgClosure*)to);
        }
    }
#else
    src->header.info = (const StgInfoTable *)MK_FORWARDING_PTR(to);
    *p = TAG_CLOSURE(tag,(StgClosure*)to);
#endif

#ifdef PROFILING
    // We store the size of the just evacuated object in the LDV word so that
    // the profiler can guess the position of the next object later.
    SET_EVACUAEE_FOR_LDV(from, size);
#endif
}

#if defined(PARALLEL_GC)
STATIC_INLINE void
copy_tag_nolock(StgClosure **p, const StgInfoTable *info, 
Simon Marlow's avatar
Simon Marlow committed
136
         StgClosure *src, nat size, nat gen_no, StgWord tag)
137 138 139 140
{
    StgPtr to, from;
    nat i;

Simon Marlow's avatar
Simon Marlow committed
141
    to = alloc_for_copy(size,gen_no);
142

143 144 145 146 147 148
    from = (StgPtr)src;
    to[0] = (W_)info;
    for (i = 1; i < size; i++) { // unroll for small i
	to[i] = from[i];
    }

149 150 151
    // if somebody else reads the forwarding pointer, we better make
    // sure there's a closure at the end of it.
    write_barrier();
152
    *p = TAG_CLOSURE(tag,(StgClosure*)to);
153 154
    src->header.info = (const StgInfoTable *)MK_FORWARDING_PTR(to);

155 156 157 158 159 160 161 162 163 164
//  if (to+size+2 < bd->start + BLOCK_SIZE_W) {
//      __builtin_prefetch(to + size + 2, 1);
//  }

#ifdef PROFILING
    // We store the size of the just evacuated object in the LDV word so that
    // the profiler can guess the position of the next object later.
    SET_EVACUAEE_FOR_LDV(from, size);
#endif
}
165
#endif
166

167 168
/* Special version of copy() for when we only want to copy the info
 * pointer of an object, but reserve some padding after it.  This is
169
 * used to optimise evacuation of TSOs.
170
 */
171
static rtsBool
172
copyPart(StgClosure **p, StgClosure *src, nat size_to_reserve, 
Simon Marlow's avatar
Simon Marlow committed
173
         nat size_to_copy, nat gen_no)
174 175 176
{
    StgPtr to, from;
    nat i;
177
    StgWord info;
178
    
179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196
#if defined(PARALLEL_GC)
spin:
	info = xchg((StgPtr)&src->header.info, (W_)&stg_WHITEHOLE_info);
	if (info == (W_)&stg_WHITEHOLE_info) {
#ifdef PROF_SPIN
	    whitehole_spin++;
#endif
	    goto spin;
	}
    if (IS_FORWARDING_PTR(info)) {
	src->header.info = (const StgInfoTable *)info;
	evacuate(p); // does the failed_to_evac stuff
	return rtsFalse;
    }
#else
    info = (W_)src->header.info;
#endif

Simon Marlow's avatar
Simon Marlow committed
197
    to = alloc_for_copy(size_to_reserve, gen_no);
198 199

    from = (StgPtr)src;
200
    to[0] = info;
201 202 203 204
    for (i = 1; i < size_to_copy; i++) { // unroll for small i
	to[i] = from[i];
    }
    
205 206
    write_barrier();
    src->header.info = (const StgInfoTable*)MK_FORWARDING_PTR(to);
207
    *p = (StgClosure *)to;
208
    
209 210 211 212 213 214
#ifdef PROFILING
    // We store the size of the just evacuated object in the LDV word so that
    // the profiler can guess the position of the next object later.
    SET_EVACUAEE_FOR_LDV(from, size_to_reserve);
    // fill the slop
    if (size_to_reserve - size_to_copy > 0)
215
	LDV_FILL_SLOP(to + size_to_copy, (int)(size_to_reserve - size_to_copy));
216
#endif
217 218

    return rtsTrue;
219 220 221 222
}


/* Copy wrappers that don't tag the closure after copying */
Simon Marlow's avatar
Simon Marlow committed
223
STATIC_INLINE GNUC_ATTR_HOT void
224
copy(StgClosure **p, const StgInfoTable *info, 
Simon Marlow's avatar
Simon Marlow committed
225
     StgClosure *src, nat size, nat gen_no)
226
{
Simon Marlow's avatar
Simon Marlow committed
227
    copy_tag(p,info,src,size,gen_no,0);
228 229
}

230 231 232 233
/* -----------------------------------------------------------------------------
   Evacuate a large object

   This just consists of removing the object from the (doubly-linked)
234 235
   gen->large_objects list, and linking it on to the (singly-linked)
   gen->new_large_objects list, from where it will be scavenged later.
236 237 238 239 240 241 242 243

   Convention: bd->flags has BF_EVACUATED set for a large object
   that has been evacuated, or unset otherwise.
   -------------------------------------------------------------------------- */

STATIC_INLINE void
evacuate_large(StgPtr p)
{
244
  bdescr *bd;
245
  generation *gen, *new_gen;
Simon Marlow's avatar
Simon Marlow committed
246
  nat gen_no, new_gen_no;
247
  gen_workspace *ws;
248
    
249
  bd = Bdescr(p);
250
  gen = bd->gen;
Simon Marlow's avatar
Simon Marlow committed
251
  gen_no = bd->gen_no;
Simon Marlow's avatar
Simon Marlow committed
252
  ACQUIRE_SPIN_LOCK(&gen->sync);
253 254 255 256 257 258

  // already evacuated? 
  if (bd->flags & BF_EVACUATED) { 
    /* Don't forget to set the gct->failed_to_evac flag if we didn't get
     * the desired destination (see comments in evacuate()).
     */
Simon Marlow's avatar
Simon Marlow committed
259
    if (gen_no < gct->evac_gen_no) {
260 261 262
	gct->failed_to_evac = rtsTrue;
	TICK_GC_FAILED_PROMOTION();
    }
Simon Marlow's avatar
Simon Marlow committed
263
    RELEASE_SPIN_LOCK(&gen->sync);
264 265 266 267 268 269 270
    return;
  }

  // remove from large_object list 
  if (bd->u.back) {
    bd->u.back->link = bd->link;
  } else { // first object in the list 
271
    gen->large_objects = bd->link;
272 273 274 275 276
  }
  if (bd->link) {
    bd->link->u.back = bd->u.back;
  }
  
277
  /* link it on to the evacuated large object list of the destination gen
278
   */
Simon Marlow's avatar
Simon Marlow committed
279 280 281
  new_gen_no = bd->dest_no;

  if (new_gen_no < gct->evac_gen_no) {
282
      if (gct->eager_promotion) {
Simon Marlow's avatar
Simon Marlow committed
283
          new_gen_no = gct->evac_gen_no;
284 285 286 287 288
      } else {
	  gct->failed_to_evac = rtsTrue;
      }
  }

Simon Marlow's avatar
Simon Marlow committed
289 290
  ws = &gct->gens[new_gen_no];
  new_gen = &generations[new_gen_no];
Simon Marlow's avatar
Simon Marlow committed
291

292
  bd->flags |= BF_EVACUATED;
293
  initBdescr(bd, new_gen, new_gen->to);
Simon Marlow's avatar
Simon Marlow committed
294 295 296 297 298 299 300

  // If this is a block of pinned objects, we don't have to scan
  // these objects, because they aren't allowed to contain any
  // pointers.  For these blocks, we skip the scavenge stage and put
  // them straight on the scavenged_large_objects list.
  if (bd->flags & BF_PINNED) {
      ASSERT(get_itbl((StgClosure *)p)->type == ARR_WORDS);
Simon Marlow's avatar
Simon Marlow committed
301
      if (new_gen != gen) { ACQUIRE_SPIN_LOCK(&new_gen->sync); }
302 303
      dbl_link_onto(bd, &new_gen->scavenged_large_objects);
      new_gen->n_scavenged_large_blocks += bd->blocks;
Simon Marlow's avatar
Simon Marlow committed
304
      if (new_gen != gen) { RELEASE_SPIN_LOCK(&new_gen->sync); }
Simon Marlow's avatar
Simon Marlow committed
305 306 307 308
  } else {
      bd->link = ws->todo_large_objects;
      ws->todo_large_objects = bd;
  }
309

Simon Marlow's avatar
Simon Marlow committed
310
  RELEASE_SPIN_LOCK(&gen->sync);
311 312
}

313 314 315 316 317 318
/* ----------------------------------------------------------------------------
   Evacuate

   This is called (eventually) for every live object in the system.

   The caller to evacuate specifies a desired generation in the
319
   gct->evac_gen thread-local variable.  The following conditions apply to
320 321 322
   evacuating an object which resides in generation M when we're
   collecting up to generation N

323
   if  M >= gct->evac_gen 
324
           if  M > N     do nothing
325
	   else          evac to gen->to
326

327
   if  M < gct->evac_gen      evac to gct->evac_gen, step 0
328 329 330 331

   if the object is already evacuated, then we check which generation
   it now resides in.

332 333 334
   if  M >= gct->evac_gen     do nothing
   if  M <  gct->evac_gen     set gct->failed_to_evac flag to indicate that we
                         didn't manage to evacuate this object into gct->evac_gen.
335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354


   OPTIMISATION NOTES:

   evacuate() is the single most important function performance-wise
   in the GC.  Various things have been tried to speed it up, but as
   far as I can tell the code generated by gcc 3.2 with -O2 is about
   as good as it's going to get.  We pass the argument to evacuate()
   in a register using the 'regparm' attribute (see the prototype for
   evacuate() near the top of this file).

   Changing evacuate() to take an (StgClosure **) rather than
   returning the new pointer seems attractive, because we can avoid
   writing back the pointer when it hasn't changed (eg. for a static
   object, or an object in a generation > N).  However, I tried it and
   it doesn't help.  One reason is that the (StgClosure **) pointer
   gets spilled to the stack inside evacuate(), resulting in far more
   extra reads/writes than we save.
   ------------------------------------------------------------------------- */

Simon Marlow's avatar
Simon Marlow committed
355
REGPARM1 GNUC_ATTR_HOT void 
356 357 358
evacuate(StgClosure **p)
{
  bdescr *bd = NULL;
Simon Marlow's avatar
Simon Marlow committed
359
  nat gen_no;
360 361 362 363 364 365 366 367 368 369 370
  StgClosure *q;
  const StgInfoTable *info;
  StgWord tag;

  q = *p;

loop:
  /* The tag and the pointer are split, to be merged after evacing */
  tag = GET_CLOSURE_TAG(q);
  q = UNTAG_CLOSURE(q);

371
  ASSERTM(LOOKS_LIKE_CLOSURE_PTR(q), "invalid closure, info=%p", q->header.info);
372

373
  if (!HEAP_ALLOCED_GC(q)) {
374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421

      if (!major_gc) return;

      info = get_itbl(q);
      switch (info->type) {

      case THUNK_STATIC:
	  if (info->srt_bitmap != 0) {
	      if (*THUNK_STATIC_LINK((StgClosure *)q) == NULL) {
#ifndef THREADED_RTS
		  *THUNK_STATIC_LINK((StgClosure *)q) = gct->static_objects;
		  gct->static_objects = (StgClosure *)q;
#else
                  StgPtr link;
                  link = (StgPtr)cas((StgPtr)THUNK_STATIC_LINK((StgClosure *)q),
                                     (StgWord)NULL,
                                     (StgWord)gct->static_objects);
                  if (link == NULL) {
                      gct->static_objects = (StgClosure *)q;
                  }
#endif
	      }
	  }
	  return;

      case FUN_STATIC:
	  if (info->srt_bitmap != 0 &&
	      *FUN_STATIC_LINK((StgClosure *)q) == NULL) {
#ifndef THREADED_RTS
              *FUN_STATIC_LINK((StgClosure *)q) = gct->static_objects;
              gct->static_objects = (StgClosure *)q;
#else
              StgPtr link;
              link = (StgPtr)cas((StgPtr)FUN_STATIC_LINK((StgClosure *)q),
                                 (StgWord)NULL,
                                 (StgWord)gct->static_objects);
              if (link == NULL) {
                  gct->static_objects = (StgClosure *)q;
              }
#endif
	  }
	  return;
	  
      case IND_STATIC:
	  /* If q->saved_info != NULL, then it's a revertible CAF - it'll be
	   * on the CAF list, so don't do anything with it here (we'll
	   * scavenge it later).
	   */
Simon Marlow's avatar
Simon Marlow committed
422
          if (*IND_STATIC_LINK((StgClosure *)q) == NULL) {
423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469
#ifndef THREADED_RTS
		  *IND_STATIC_LINK((StgClosure *)q) = gct->static_objects;
		  gct->static_objects = (StgClosure *)q;
#else
                  StgPtr link;
                  link = (StgPtr)cas((StgPtr)IND_STATIC_LINK((StgClosure *)q),
                                     (StgWord)NULL,
                                     (StgWord)gct->static_objects);
                  if (link == NULL) {
                      gct->static_objects = (StgClosure *)q;
                  }
#endif
	  }
	  return;
	  
      case CONSTR_STATIC:
	  if (*STATIC_LINK(info,(StgClosure *)q) == NULL) {
#ifndef THREADED_RTS
              *STATIC_LINK(info,(StgClosure *)q) = gct->static_objects;
              gct->static_objects = (StgClosure *)q;
#else
              StgPtr link;
              link = (StgPtr)cas((StgPtr)STATIC_LINK(info,(StgClosure *)q),
                                 (StgWord)NULL,
                                 (StgWord)gct->static_objects);
              if (link == NULL) {
                  gct->static_objects = (StgClosure *)q;
              }
#endif
          }
          /* I am assuming that static_objects pointers are not
           * written to other objects, and thus, no need to retag. */
          return;
	  
      case CONSTR_NOCAF_STATIC:
	  /* no need to put these on the static linked list, they don't need
	   * to be scavenged.
	   */
	  return;
	  
      default:
	  barf("evacuate(static): strange closure type %d", (int)(info->type));
      }
  }

  bd = Bdescr((P_)q);

470
  if ((bd->flags & (BF_LARGE | BF_MARKED | BF_EVACUATED)) != 0) {
471 472 473 474 475 476 477 478 479 480 481

      // pointer into to-space: just return it.  It might be a pointer
      // into a generation that we aren't collecting (> N), or it
      // might just be a pointer into to-space.  The latter doesn't
      // happen often, but allowing it makes certain things a bit
      // easier; e.g. scavenging an object is idempotent, so it's OK to
      // have an object on the mutable list multiple times.
      if (bd->flags & BF_EVACUATED) {
          // We aren't copying this object, so we have to check
          // whether it is already in the target generation.  (this is
          // the write barrier).
Simon Marlow's avatar
Simon Marlow committed
482
          if (bd->gen_no < gct->evac_gen_no) {
483 484 485 486 487 488 489 490 491
	      gct->failed_to_evac = rtsTrue;
	      TICK_GC_FAILED_PROMOTION();
	  }
	  return;
      }

      /* evacuate large objects by re-linking them onto a different list.
       */
      if (bd->flags & BF_LARGE) {
492
          evacuate_large((P_)q);
493 494 495
	  return;
      }
      
496
      /* If the object is in a gen that we're compacting, then we
497 498
       * need to use an alternative evacuate procedure.
       */
499 500 501
      if (!is_marked((P_)q,bd)) {
          mark((P_)q,bd);
          push_mark_stack((P_)q);
502
      }
503
      return;
504 505
  }
      
Simon Marlow's avatar
Simon Marlow committed
506
  gen_no = bd->dest_no;
507 508 509 510 511

  info = q->header.info;
  if (IS_FORWARDING_PTR(info))
  {
    /* Already evacuated, just return the forwarding address.
512
     * HOWEVER: if the requested destination generation (gct->evac_gen) is
513 514 515 516 517 518 519 520 521 522
     * older than the actual generation (because the object was
     * already evacuated to a younger generation) then we have to
     * set the gct->failed_to_evac flag to indicate that we couldn't 
     * manage to promote the object to the desired generation.
     */
    /* 
     * Optimisation: the check is fairly expensive, but we can often
     * shortcut it if either the required generation is 0, or the
     * current object (the EVACUATED) is in a high enough generation.
     * We know that an EVACUATED always points to an object in the
523
     * same or an older generation.  gen is the lowest generation that the
524
     * current object would be evacuated to, so we only do the full
525
     * check if gen is too low.
526 527 528
     */
      StgClosure *e = (StgClosure*)UN_FORWARDING_PTR(info);
      *p = TAG_CLOSURE(tag,e);
Simon Marlow's avatar
Simon Marlow committed
529 530
      if (gen_no < gct->evac_gen_no) {  // optimisation
          if (Bdescr((P_)e)->gen_no < gct->evac_gen_no) {
531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546
	      gct->failed_to_evac = rtsTrue;
	      TICK_GC_FAILED_PROMOTION();
	  }
      }
      return;
  }

  switch (INFO_PTR_TO_STRUCT(info)->type) {

  case WHITEHOLE:
      goto loop;

  case MUT_VAR_CLEAN:
  case MUT_VAR_DIRTY:
  case MVAR_CLEAN:
  case MVAR_DIRTY:
Simon Marlow's avatar
Simon Marlow committed
547
      copy(p,info,q,sizeW_fromITBL(INFO_PTR_TO_STRUCT(info)),gen_no);
548 549
      return;

550 551 552 553 554 555
  // For ints and chars of low value, save space by replacing references to
  //	these with closures with references to common, shared ones in the RTS.
  //
  // * Except when compiling into Windows DLLs which don't support cross-package
  //	data references very well.
  //
556
  case CONSTR_0_1:
557 558
  {   
#if defined(__PIC__) && defined(mingw32_HOST_OS) 
Simon Marlow's avatar
Simon Marlow committed
559
      copy_tag_nolock(p,info,q,sizeofW(StgHeader)+1,gen_no,tag);
560
#else
561 562 563 564 565 566 567 568 569 570 571 572 573 574 575
      StgWord w = (StgWord)q->payload[0];
      if (info == Czh_con_info &&
	  // unsigned, so always true:  (StgChar)w >= MIN_CHARLIKE &&  
	  (StgChar)w <= MAX_CHARLIKE) {
	  *p =  TAG_CLOSURE(tag,
                            (StgClosure *)CHARLIKE_CLOSURE((StgChar)w)
			   );
      }
      else if (info == Izh_con_info &&
	  (StgInt)w >= MIN_INTLIKE && (StgInt)w <= MAX_INTLIKE) {
	  *p = TAG_CLOSURE(tag,
			     (StgClosure *)INTLIKE_CLOSURE((StgInt)w)
			     );
      }
      else {
Simon Marlow's avatar
Simon Marlow committed
576
          copy_tag_nolock(p,info,q,sizeofW(StgHeader)+1,gen_no,tag);
577
      }
578
#endif
579 580 581 582 583 584
      return;
  }

  case FUN_0_1:
  case FUN_1_0:
  case CONSTR_1_0:
Simon Marlow's avatar
Simon Marlow committed
585
      copy_tag_nolock(p,info,q,sizeofW(StgHeader)+1,gen_no,tag);
586 587 588 589
      return;

  case THUNK_1_0:
  case THUNK_0_1:
Simon Marlow's avatar
Simon Marlow committed
590
      copy(p,info,q,sizeofW(StgThunk)+1,gen_no);
591 592 593 594 595 596
      return;

  case THUNK_1_1:
  case THUNK_2_0:
  case THUNK_0_2:
#ifdef NO_PROMOTE_THUNKS
597
#error bitrotted
598
#endif
Simon Marlow's avatar
Simon Marlow committed
599
    copy(p,info,q,sizeofW(StgThunk)+2,gen_no);
600 601 602 603 604 605 606
    return;

  case FUN_1_1:
  case FUN_2_0:
  case FUN_0_2:
  case CONSTR_1_1:
  case CONSTR_2_0:
Simon Marlow's avatar
Simon Marlow committed
607
      copy_tag_nolock(p,info,q,sizeofW(StgHeader)+2,gen_no,tag);
608 609 610
      return;

  case CONSTR_0_2:
Simon Marlow's avatar
Simon Marlow committed
611
      copy_tag_nolock(p,info,q,sizeofW(StgHeader)+2,gen_no,tag);
612 613 614
      return;

  case THUNK:
Simon Marlow's avatar
Simon Marlow committed
615
      copy(p,info,q,thunk_sizeW_fromITBL(INFO_PTR_TO_STRUCT(info)),gen_no);
616 617 618 619 620
      return;

  case FUN:
  case IND_PERM:
  case CONSTR:
Simon Marlow's avatar
Simon Marlow committed
621
      copy_tag_nolock(p,info,q,sizeW_fromITBL(INFO_PTR_TO_STRUCT(info)),gen_no,tag);
622 623
      return;

624 625 626 627 628 629 630 631 632 633 634 635 636 637 638
  case BLACKHOLE:
  {
      StgClosure *r;
      const StgInfoTable *i;
      r = ((StgInd*)q)->indirectee;
      if (GET_CLOSURE_TAG(r) == 0) {
          i = r->header.info;
          if (IS_FORWARDING_PTR(i)) {
              r = (StgClosure *)UN_FORWARDING_PTR(i);
              i = r->header.info;
          }
          if (i == &stg_TSO_info
              || i == &stg_WHITEHOLE_info 
              || i == &stg_BLOCKING_QUEUE_CLEAN_info
              || i == &stg_BLOCKING_QUEUE_DIRTY_info) {
Simon Marlow's avatar
Simon Marlow committed
639
              copy(p,info,q,sizeofW(StgInd),gen_no);
640 641 642 643 644 645 646 647 648 649
              return;
          }
          ASSERT(i != &stg_IND_info);
      }
      q = r;
      *p = r;
      goto loop;
  }

  case BLOCKING_QUEUE:
650
  case WEAK:
651 652
  case PRIM:
  case MUT_PRIM:
Simon Marlow's avatar
Simon Marlow committed
653
      copy(p,info,q,sizeW_fromITBL(INFO_PTR_TO_STRUCT(info)),gen_no);
654 655 656
      return;

  case BCO:
Simon Marlow's avatar
Simon Marlow committed
657
      copy(p,info,q,bco_sizeW((StgBCO *)q),gen_no);
658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674
      return;

  case THUNK_SELECTOR:
      eval_thunk_selector(p, (StgSelector *)q, rtsTrue);
      return;

  case IND:
    // follow chains of indirections, don't evacuate them 
    q = ((StgInd*)q)->indirectee;
    *p = q;
    goto loop;

  case RET_BCO:
  case RET_SMALL:
  case RET_BIG:
  case RET_DYN:
  case UPDATE_FRAME:
675
  case UNDERFLOW_FRAME:
676 677 678 679 680 681 682 683 684
  case STOP_FRAME:
  case CATCH_FRAME:
  case CATCH_STM_FRAME:
  case CATCH_RETRY_FRAME:
  case ATOMICALLY_FRAME:
    // shouldn't see these 
    barf("evacuate: stack frame at %p\n", q);

  case PAP:
Simon Marlow's avatar
Simon Marlow committed
685
      copy(p,info,q,pap_sizeW((StgPAP*)q),gen_no);
686 687 688
      return;

  case AP:
Simon Marlow's avatar
Simon Marlow committed
689
      copy(p,info,q,ap_sizeW((StgAP*)q),gen_no);
690 691 692
      return;

  case AP_STACK:
Simon Marlow's avatar
Simon Marlow committed
693
      copy(p,info,q,ap_stack_sizeW((StgAP_STACK*)q),gen_no);
694 695 696 697
      return;

  case ARR_WORDS:
      // just copy the block 
Simon Marlow's avatar
Simon Marlow committed
698
      copy(p,info,q,arr_words_sizeW((StgArrWords *)q),gen_no);
699 700 701 702 703 704 705
      return;

  case MUT_ARR_PTRS_CLEAN:
  case MUT_ARR_PTRS_DIRTY:
  case MUT_ARR_PTRS_FROZEN:
  case MUT_ARR_PTRS_FROZEN0:
      // just copy the block 
Simon Marlow's avatar
Simon Marlow committed
706
      copy(p,info,q,mut_arr_ptrs_sizeW((StgMutArrPtrs *)q),gen_no);
707 708 709
      return;

  case TSO:
Simon Marlow's avatar
Simon Marlow committed
710
      copy(p,info,q,sizeofW(StgTSO),gen_no);
711
      return;
712

713 714 715
  case STACK:
    {
      StgStack *stack = (StgStack *)q;
716

717
      /* To evacuate a small STACK, we need to adjust the stack pointer
718 719
       */
      {
720
          StgStack *new_stack;
721
	  StgPtr r, s;
722 723
          rtsBool mine;

724
          mine = copyPart(p,(StgClosure *)stack, stack_sizeW(stack),
Simon Marlow's avatar
Simon Marlow committed
725
                          sizeofW(StgStack), gen_no);
726
          if (mine) {
727 728 729 730
              new_stack = (StgStack *)*p;
              move_STACK(stack, new_stack);
              for (r = stack->sp, s = new_stack->sp;
                   r < stack->stack + stack->stack_size;) {
731 732 733
                  *s++ = *r++;
              }
          }
734 735 736 737 738
	  return;
      }
    }

  case TREC_CHUNK:
Simon Marlow's avatar
Simon Marlow committed
739
      copy(p,info,q,sizeofW(StgTRecChunk),gen_no);
740 741 742 743 744 745 746 747 748
      return;

  default:
    barf("evacuate: strange closure type %d", (int)(INFO_PTR_TO_STRUCT(info)->type));
  }

  barf("evacuate");
}

749
/* -----------------------------------------------------------------------------
750
   Evaluate a THUNK_SELECTOR if possible.
751

752 753 754
   p points to a THUNK_SELECTOR that we want to evaluate.  The
   result of "evaluating" it will be evacuated and a pointer to the
   to-space closure will be returned.
755

756 757 758
   If the THUNK_SELECTOR could not be evaluated (its selectee is still
   a THUNK, for example), then the THUNK_SELECTOR itself will be
   evacuated.
759
   -------------------------------------------------------------------------- */
760 761 762 763
static void
unchain_thunk_selectors(StgSelector *p, StgClosure *val)
{
    StgSelector *prev;
764

765 766 767
    prev = NULL;
    while (p)
    {
simonmar@microsoft.com's avatar
simonmar@microsoft.com committed
768
        ASSERT(p->header.info == &stg_WHITEHOLE_info);
769 770 771 772
        // val must be in to-space.  Not always: when we recursively
        // invoke eval_thunk_selector(), the recursive calls will not 
        // evacuate the value (because we want to select on the value,
        // not evacuate it), so in this case val is in from-space.
773
        // ASSERT(!HEAP_ALLOCED_GC(val) || Bdescr((P_)val)->gen_no > N || (Bdescr((P_)val)->flags & BF_EVACUATED));
774

775 776 777
        prev = (StgSelector*)((StgClosure *)p)->payload[0];

        // Update the THUNK_SELECTOR with an indirection to the
778 779 780 781 782 783 784 785 786 787 788 789 790
        // value.  The value is still in from-space at this stage.
        //
        // (old note: Why not do upd_evacuee(q,p)?  Because we have an
        // invariant that an EVACUATED closure always points to an
        // object in the same or an older generation (required by
        // the short-cut test in the EVACUATED case, below).
        if ((StgClosure *)p == val) {
            // must be a loop; just leave a BLACKHOLE in place.  This
            // can happen when we have a chain of selectors that
            // eventually loops back on itself.  We can't leave an
            // indirection pointing to itself, and we want the program
            // to deadlock if it ever enters this closure, so
            // BLACKHOLE is correct.
791 792 793 794 795 796 797

            // XXX we do not have BLACKHOLEs any more; replace with
            // a THUNK_SELECTOR again.  This will go into a loop if it is
            // entered, and should result in a NonTermination exception.
            ((StgThunk *)p)->payload[0] = val;
            write_barrier();
            SET_INFO(p, &stg_sel_0_upd_info);
798 799 800 801 802
        } else {
            ((StgInd *)p)->indirectee = val;
            write_barrier();
            SET_INFO(p, &stg_IND_info);
        }
803 804 805 806 807 808 809 810

        // For the purposes of LDV profiling, we have created an
        // indirection.
        LDV_RECORD_CREATE(p);

        p = prev;
    }
}
811

812 813 814
static void
eval_thunk_selector (StgClosure **q, StgSelector * p, rtsBool evac)
                 // NB. for legacy reasons, p & q are swapped around :(
815
{
816
    nat field;
817
    StgInfoTable *info;
818
    StgWord info_ptr;
819
    StgClosure *selectee;
820 821 822
    StgSelector *prev_thunk_selector;
    bdescr *bd;
    StgClosure *val;
823
    
824 825 826
    prev_thunk_selector = NULL;
    // this is a chain of THUNK_SELECTORs that we are going to update
    // to point to the value of the current THUNK_SELECTOR.  Each
827
    // closure on the chain is a WHITEHOLE, and points to the next in the
828 829 830 831 832
    // chain with payload[0].

selector_chain:

    bd = Bdescr((StgPtr)p);
833
    if (HEAP_ALLOCED_GC(p)) {
834 835 836 837 838
        // If the THUNK_SELECTOR is in to-space or in a generation that we
        // are not collecting, then bale out early.  We won't be able to
        // save any space in any case, and updating with an indirection is
        // trickier in a non-collected gen: we would have to update the
        // mutable list.
839
        if (bd->flags & BF_EVACUATED) {
840
            unchain_thunk_selectors(prev_thunk_selector, (StgClosure *)p);
841
            *q = (StgClosure *)p;
842
            // shortcut, behave as for:  if (evac) evacuate(q);
Simon Marlow's avatar
Simon Marlow committed
843
            if (evac && bd->gen_no < gct->evac_gen_no) {
844 845 846
                gct->failed_to_evac = rtsTrue;
                TICK_GC_FAILED_PROMOTION();
            }
847
            return;
848 849 850 851 852 853 854
        }
        // we don't update THUNK_SELECTORS in the compacted
        // generation, because compaction does not remove the INDs
        // that result, this causes confusion later
        // (scavenge_mark_stack doesn't deal with IND).  BEWARE!  This
        // bit is very tricky to get right.  If you make changes
        // around here, test by compiling stage 3 with +RTS -c -RTS.
855
        if (bd->flags & BF_MARKED) {
856
            // must call evacuate() to mark this closure if evac==rtsTrue
857 858
            *q = (StgClosure *)p;
            if (evac) evacuate(q);
859
            unchain_thunk_selectors(prev_thunk_selector, (StgClosure *)p);
860
            return;
861
        }
862 863
    }

864

865
    // WHITEHOLE the selector thunk, since it is now under evaluation.
866 867
    // This is important to stop us going into an infinite loop if
    // this selector thunk eventually refers to itself.
868 869 870 871
#if defined(THREADED_RTS)
    // In threaded mode, we'll use WHITEHOLE to lock the selector
    // thunk while we evaluate it.
    {
872 873 874 875 876
        do {
            info_ptr = xchg((StgPtr)&p->header.info, (W_)&stg_WHITEHOLE_info);
        } while (info_ptr == (W_)&stg_WHITEHOLE_info);

        // make sure someone else didn't get here first...
877
        if (IS_FORWARDING_PTR(info_ptr) || 
878
            INFO_PTR_TO_STRUCT(info_ptr)->type != THUNK_SELECTOR) {
879
            // v. tricky now.  The THUNK_SELECTOR has been evacuated
880
            // by another thread, and is now either a forwarding ptr or IND.
881 882 883 884 885 886 887 888 889 890 891 892
            // We need to extract ourselves from the current situation
            // as cleanly as possible.
            //   - unlock the closure
            //   - update *q, we may have done *some* evaluation
            //   - if evac, we need to call evacuate(), because we
            //     need the write-barrier stuff.
            //   - undo the chain we've built to point to p.
            SET_INFO(p, (const StgInfoTable *)info_ptr);
            *q = (StgClosure *)p;
            if (evac) evacuate(q);
            unchain_thunk_selectors(prev_thunk_selector, (StgClosure *)p);
            return;
893 894 895 896 897
        }
    }
#else
    // Save the real info pointer (NOTE: not the same as get_itbl()).
    info_ptr = (StgWord)p->header.info;
898
    SET_INFO(p,&stg_WHITEHOLE_info);
899 900 901 902 903 904 905
#endif

    field = INFO_PTR_TO_STRUCT(info_ptr)->layout.selector_offset;

    // The selectee might be a constructor closure,
    // so we untag the pointer.
    selectee = UNTAG_CLOSURE(p->selectee);
906 907

selector_loop:
908 909 910 911 912 913
    // selectee now points to the closure that we're trying to select
    // a field from.  It may or may not be in to-space: we try not to
    // end up in to-space, but it's impractical to avoid it in
    // general.  The compacting GC scatters to-space pointers in
    // from-space during marking, for example.  We rely on the property
    // that evacuate() doesn't mind if it gets passed a to-space pointer.
914

915 916 917 918 919 920 921 922 923 924
    info = (StgInfoTable*)selectee->header.info;

    if (IS_FORWARDING_PTR(info)) {
        // We don't follow pointers into to-space; the constructor
        // has already been evacuated, so we won't save any space
        // leaks by evaluating this selector thunk anyhow.
        goto bale_out;
    }

    info = INFO_PTR_TO_STRUCT(info);
925
    switch (info->type) {
926 927 928
      case WHITEHOLE:
	  goto bale_out; // about to be evacuated by another thread (or a loop).
	
929 930 931 932 933 934 935 936
      case CONSTR:
      case CONSTR_1_0:
      case CONSTR_0_1:
      case CONSTR_2_0:
      case CONSTR_1_1:
      case CONSTR_0_2:
      case CONSTR_STATIC:
      case CONSTR_NOCAF_STATIC:
937 938 939 940
          {
              // check that the size is in range 
              ASSERT(field <  (StgWord32)(info->layout.payload.ptrs + 
                                          info->layout.payload.nptrs));
941
	  
942 943 944 945 946 947
              // Select the right field from the constructor
              val = selectee->payload[field];
              
#ifdef PROFILING
              // For the purposes of LDV profiling, we have destroyed
              // the original selector thunk, p.
simonmar@microsoft.com's avatar
simonmar@microsoft.com committed
948
              SET_INFO(p, (StgInfoTable *)info_ptr);
Simon Marlow's avatar
Simon Marlow committed
949
              OVERWRITING_CLOSURE((StgClosure*)p);
950
              SET_INFO(p, &stg_WHITEHOLE_info);
951 952 953 954 955 956 957 958
#endif

              // the closure in val is now the "value" of the
              // THUNK_SELECTOR in p.  However, val may itself be a
              // THUNK_SELECTOR, in which case we want to continue
              // evaluating until we find the real value, and then
              // update the whole chain to point to the value.
          val_loop:
959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976
              info_ptr = (StgWord)UNTAG_CLOSURE(val)->header.info;
              if (!IS_FORWARDING_PTR(info_ptr))
              {
                  info = INFO_PTR_TO_STRUCT(info_ptr);
                  switch (info->type) {
                  case IND:
                  case IND_PERM:
                  case IND_STATIC:
                      val = ((StgInd *)val)->indirectee;
                      goto val_loop;
                  case THUNK_SELECTOR:
                      ((StgClosure*)p)->payload[0] = (StgClosure *)prev_thunk_selector;
                      prev_thunk_selector = p;
                      p = (StgSelector*)val;
                      goto selector_chain;
                  default:
                      break;
                  }
977
              }
978 979 980 981
              ((StgClosure*)p)->payload[0] = (StgClosure *)prev_thunk_selector;
              prev_thunk_selector = p;

              *q = val;
982 983 984 985 986 987 988 989

              // update the other selectors in the chain *before*
              // evacuating the value.  This is necessary in the case
              // where the value turns out to be one of the selectors
              // in the chain (i.e. we have a loop), and evacuating it
              // would corrupt the chain.
              unchain_thunk_selectors(prev_thunk_selector, val);

990 991 992
              // evacuate() cannot recurse through
              // eval_thunk_selector(), because we know val is not
              // a THUNK_SELECTOR.
993
              if (evac) evacuate(q);
994
              return;
995
          }
996 997 998 999

      case IND:
      case IND_PERM:
      case IND_STATIC:
1000 1001
          // Again, we might need to untag a constructor.
          selectee = UNTAG_CLOSURE( ((StgInd *)selectee)->indirectee );
1002 1003
	  goto selector_loop;

1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030
      case BLACKHOLE:
      {
          StgClosure *r;
          const StgInfoTable *i;
          r = ((StgInd*)selectee)->indirectee;

          // establish whether this BH has been updated, and is now an
          // indirection, as in evacuate().
          if (GET_CLOSURE_TAG(r) == 0) {
              i = r->header.info;
              if (IS_FORWARDING_PTR(i)) {
                  r = (StgClosure *)UN_FORWARDING_PTR(i);
                  i = r->header.info;
              }
              if (i == &stg_TSO_info
                  || i == &stg_WHITEHOLE_info 
                  || i == &stg_BLOCKING_QUEUE_CLEAN_info
                  || i == &stg_BLOCKING_QUEUE_DIRTY_info) {
                  goto bale_out;
              }
              ASSERT(i != &stg_IND_info);
          }

          selectee = UNTAG_CLOSURE( ((StgInd *)selectee)->indirectee );
          goto selector_loop;
      }

1031 1032 1033 1034
      case THUNK_SELECTOR:
      {
	  StgClosure *val;

1035 1036
          // recursively evaluate this selector.  We don't want to
          // recurse indefinitely, so we impose a depth bound.
1037
	  if (gct->thunk_selector_depth >= MAX_THUNK_SELECTOR_DEPTH) {
1038 1039
	      goto bale_out;
	  }
1040

1041
	  gct->thunk_selector_depth++;
1042 1043 1044
          // rtsFalse says "don't evacuate the result".  It will,
          // however, update any THUNK_SELECTORs that are evaluated
          // along the way.
1045
	  eval_thunk_selector(&val, (StgSelector*)selectee, rtsFalse);
1046
	  gct->thunk_selector_depth--;
1047

1048 1049
          // did we actually manage to evaluate it?
          if (val == selectee) goto bale_out;
1050

1051 1052 1053
          // Of course this pointer might be tagged...
          selectee = UNTAG_CLOSURE(val);
          goto selector_loop;
1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065
      }

      case AP:
      case AP_STACK:
      case THUNK:
      case THUNK_1_0:
      case THUNK_0_1:
      case THUNK_2_0:
      case THUNK_1_1:
      case THUNK_0_2:
      case THUNK_STATIC:
	  // not evaluated yet 
1066
	  goto bale_out;
1067 1068 1069 1070 1071 1072 1073
    
      default:
	barf("eval_thunk_selector: strange selectee %d",
	     (int)(info->type));
    }

bale_out:
1074 1075
    // We didn't manage to evaluate this thunk; restore the old info
    // pointer.  But don't forget: we still need to evacuate the thunk itself.
1076
    SET_INFO(p, (const StgInfoTable *)info_ptr);
1077 1078 1079
    // THREADED_RTS: we just unlocked the thunk, so another thread
    // might get in and update it.  copy() will lock it again and
    // check whether it was updated in the meantime.
1080
    *q = (StgClosure *)p;
1081
    if (evac) {
Simon Marlow's avatar
Simon Marlow committed
1082
        copy(q,(const StgInfoTable *)info_ptr,(StgClosure *)p,THUNK_SELECTOR_sizeW(),bd->dest_no);
1083
    }
1084
    unchain_thunk_selectors(prev_thunk_selector, *q);
1085
    return;
1086
}