Pack.c 112 KB
Newer Older
1
/* 
2
   Time-stamp: <Thu Mar 30 2000 22:53:32 Stardate: [-30]4584.56 hwloidl>
3
   $Id: Pack.c,v 1.5 2000/08/07 23:37:24 qrczak Exp $
4 5 6 7 8 9 10 11 12 13 14 15 16 17

   Graph packing and unpacking code for sending it to another processor
   and retrieving the original graph structure from the packet.
   In the old RTS the code was split into Pack.c and Unpack.c (now deceased)
   Used in GUM and GrAnSim.

   The GrAnSim version of the code defines routines for *simulating* the
   packing of closures in the same way it is done in the parallel runtime
   system. Basically GrAnSim only puts the addresses of the closures to be
   transferred into a buffer. This buffer will then be associated with the
   event of transferring the graph. When this event is scheduled, the
   @UnpackGraph@ routine is called and the buffer can be discarded
   afterwards.

18 19
   Note that in GranSim we need many buffers, not just one per PE.
*/
20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81

//@node Graph packing, , ,
//@section Graph packing

#if defined(PAR) || defined(GRAN)   /* whole file */

//@menu
//* Includes::			
//* Prototypes::		
//* Global variables::		
//* ADT of Closure Queues::	
//* Initialisation for packing::  
//* Packing Functions::		
//* Low level packing routines::  
//* Unpacking routines::	
//* Aux fcts for packing::	
//* Printing Packet Contents::	
//* End of file::		
//@end menu
//*/

//@node Includes, Prototypes, Graph packing, Graph packing
//@subsection Includes

#include "Rts.h"
#include "RtsFlags.h"
#include "RtsUtils.h"
#include "ClosureTypes.h"
#include "Storage.h"
#include "Hash.h"
#include "Parallel.h"
#include "GranSimRts.h"
#include "ParallelRts.h"
# if defined(DEBUG)
# include "ParallelDebug.h"
# endif
#include "FetchMe.h"

/* Which RTS flag should be used to get the size of the pack buffer ? */
# if defined(PAR)
#  define RTS_PACK_BUFFER_SIZE   RtsFlags.ParFlags.packBufferSize
# else   /* GRAN */
#  define RTS_PACK_BUFFER_SIZE   RtsFlags.GranFlags.packBufferSize
# endif

//@node Prototypes, Global variables, Includes, Graph packing
//@subsection Prototypes
/* 
   Code declarations. 
*/

//@node ADT of closure queues, Init for packing, Prototypes, Prototypes
//@subsubsection ADT of closure queues

static inline void    	  InitClosureQueue(void);
static inline rtsBool 	  QueueEmpty(void);
static inline void    	  QueueClosure(StgClosure *closure);
static inline StgClosure *DeQueueClosure(void);

//@node Init for packing, Packing routines, ADT of closure queues, Prototypes
//@subsubsection Init for packing

82
static void     InitPacking(rtsBool unpack);
83
# if defined(PAR)
84
rtsBool         InitPackBuffer(void);
85 86 87 88 89 90 91 92 93 94 95 96 97 98
# elif defined(GRAN)
rtsPackBuffer  *InstantiatePackBuffer (void);
static void     reallocPackBuffer (void);
# endif

//@node Packing routines, Low level packing fcts, Init for packing, Prototypes
//@subsubsection Packing routines

static void    PackClosure (StgClosure *closure);

//@node Low level packing fcts, Unpacking routines, Packing routines, Prototypes
//@subsubsection Low level packing fcts

# if defined(GRAN)
99
static  void    Pack (StgClosure *data);
100
# else
101
static  void    Pack (StgWord data);
102

103 104
static void    PackGeneric(StgClosure *closure);
static void    PackArray(StgClosure *closure);
105 106
static void    PackPLC (StgPtr addr);
static void    PackOffset (int offset);
107 108 109 110 111
static void    PackPAP(StgPAP *pap);
static rtsPackBuffer *PackTSO(StgTSO *tso, nat *packBufferSize);
static rtsPackBuffer *PackStkO(StgPtr stko, nat *packBufferSize);
static void           PackFetchMe(StgClosure *closure);

112 113 114 115 116 117 118 119 120
static void    GlobaliseAndPackGA (StgClosure *closure);
# endif

//@node Unpacking routines, Aux fcts for packing, Low level packing fcts, Prototypes
//@subsubsection Unpacking routines

# if defined(PAR)
void        InitPendingGABuffer(nat size); 
void        CommonUp(StgClosure *src, StgClosure *dst);
121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136
static StgClosure *SetGAandCommonUp(globalAddr *gaP, StgClosure *closure, 
				  rtsBool hasGA);
static nat         FillInClosure(StgWord ***bufptrP, StgClosure *graph);
static void        LocateNextParent(StgClosure **parentP,
				    nat *pptrP, nat *pptrsP, nat *sizeP);
StgClosure        *UnpackGraph(rtsPackBuffer *packBuffer,
			       globalAddr **gamap,
			       nat *nGAs);
static  StgClosure *UnpackClosure (StgWord ***bufptrP, StgClosure **graphP, 
				   globalAddr *ga);
static  StgWord   **UnpackGA(StgWord **bufptr, globalAddr *ga);
static  StgClosure *UnpackOffset(globalAddr *ga);
static  StgClosure *UnpackPLC(globalAddr *ga);
static  void        UnpackArray(StgWord ***bufptrP, StgClosure *graph);
static  nat         UnpackPAP(StgWord ***bufptrP, StgClosure *graph);

137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152
# elif defined(GRAN)
void        CommonUp(StgClosure *src, StgClosure *dst);
StgClosure *UnpackGraph(rtsPackBuffer* buffer);
#endif

//@node Aux fcts for packing,  , Unpacking routines, Prototypes
//@subsubsection Aux fcts for packing

# if defined(PAR)
static void 	DonePacking(void);
static void 	AmPacking(StgClosure *closure);
static int  	OffsetFor(StgClosure *closure);
static rtsBool  NotYetPacking(int offset);
static rtsBool  RoomToPack (nat size, nat ptrs);
       rtsBool  isOffset(globalAddr *ga);
       rtsBool  isFixed(globalAddr *ga);
153
       rtsBool  isConstr(globalAddr *ga);
154 155 156 157 158 159 160 161 162 163 164 165 166 167 168
# elif defined(GRAN)
static void     DonePacking(void);
static rtsBool  NotYetPacking(StgClosure *closure);
# endif

//@node Global variables, ADT of Closure Queues, Prototypes, Graph packing
//@subsection Global variables
/*
  Static data declarations
*/

static nat     pack_locn,           /* ptr to first free loc in pack buffer */
               clq_size, clq_pos,
               buf_id = 1;          /* identifier for buffer */
static nat     unpacked_size;
169
static rtsBool roomInBuffer;
170 171 172 173 174 175

/* 
   The pack buffer
   To be pedantic: in GrAnSim we're packing *addresses* of closures,
   not the closures themselves.
*/
176 177 178
static rtsPackBuffer *globalPackBuffer = NULL,    /* for packing a graph */
                     *globalUnpackBuffer = NULL;  /* for unpacking a graph */

179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196

/*
  Bit of a hack for testing if a closure is the root of the graph. This is
  set in @PackNearbyGraph@ and tested in @PackClosure@.  
*/

static nat          packed_thunks = 0;
static StgClosure  *graph_root;

# if defined(PAR)
/*
  The offset hash table is used during packing to record the location in
  the pack buffer of each closure which is packed.
*/
//@cindex offsetTable
static HashTable *offsetTable;

//@cindex PendingGABuffer
197 198
static globalAddr *PendingGABuffer, *gaga;

199 200
# endif /* PAR */

201

202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225
//@node ADT of Closure Queues, Initialisation for packing, Global variables, Graph packing
//@subsection ADT of Closure Queues

//@menu
//* Closure Queues::		
//* Init routines::		
//* Basic routines::		
//@end menu

//@node Closure Queues, Init routines, ADT of Closure Queues, ADT of Closure Queues
//@subsubsection Closure Queues
/*
  Closure Queues

  These routines manage the closure queue.
*/

static nat clq_pos, clq_size;

static StgClosure **ClosureQueue = NULL;   /* HWL: init in main */

//@node Init routines, Basic routines, Closure Queues, ADT of Closure Queues
//@subsubsection Init routines

226
/* @InitClosureQueue@ allocates and initialises the closure queue. */
227 228 229 230 231 232 233

//@cindex InitClosureQueue
static inline void
InitClosureQueue(void)
{
  clq_pos = clq_size = 0;

234 235 236
  if (ClosureQueue==NULL)
    ClosureQueue = (StgClosure**) stgMallocWords(RTS_PACK_BUFFER_SIZE, 
						 "InitClosureQueue");
237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278
}

//@node Basic routines,  , Init routines, ADT of Closure Queues
//@subsubsection Basic routines

/*
  QueueEmpty returns rtsTrue if the closure queue is empty; rtsFalse otherwise.
*/

//@cindex QueueEmpty
static inline rtsBool
QueueEmpty(void)
{
  return(clq_pos >= clq_size);
}

/* QueueClosure adds its argument to the closure queue. */

//@cindex QueueClosure
static inline void
QueueClosure(closure)
StgClosure *closure;
{
  if(clq_size < RTS_PACK_BUFFER_SIZE )
    ClosureQueue[clq_size++] = closure;
  else
    barf("Closure Queue Overflow (EnQueueing %p (%s))", 
	 closure, info_type(closure));
}

/* DeQueueClosure returns the head of the closure queue. */

//@cindex DeQueueClosure
static inline StgClosure * 
DeQueueClosure(void)
{
  if(!QueueEmpty())
    return(ClosureQueue[clq_pos++]);
  else
    return((StgClosure*)NULL);
}

279 280 281 282 283 284 285 286 287 288 289 290 291 292 293
/* DeQueueClosure returns the head of the closure queue. */

//@cindex DeQueueClosure
static inline StgClosure * 
PrintQueueClosure(void)
{
  nat i;

  fputs("Closure queue:", stderr);
  for (i=clq_pos; i < clq_size; i++)
    fprintf(stderr, "%p (%s), ", 
	    ClosureQueue[clq_pos++], info_type(ClosureQueue[clq_pos++]));
  fputc('\n', stderr);
}

294 295 296 297 298 299 300 301 302 303 304 305 306 307
//@node Initialisation for packing, Packing Functions, ADT of Closure Queues, Graph packing
//@subsection Initialisation for packing
/*
  Simple Packing Routines

  About packet sizes in GrAnSim: In GrAnSim we use a malloced block of
  gransim_pack_buffer_size words to simulate a packet of pack_buffer_size
  words.  In the simulated PackBuffer we only keep the addresses of the
  closures that would be packed in the parallel system (see Pack). To
  decide if a packet overflow occurs pack_buffer_size must be compared
  versus unpacked_size (see RoomToPack).  Currently, there is no multi
  packet strategy implemented, so in the case of an overflow we just stop
  adding closures to the closure queue.  If an overflow of the simulated
  packet occurs, we just realloc some more space for it and carry on as
308 309
  usual.  -- HWL
*/
310 311 312 313

# if defined(GRAN)
rtsPackBuffer *
InstantiatePackBuffer (void) {
314
  extern rtsPackBuffer *globalPackBuffer;
315

316
  globalPackBuffer = (rtsPackBuffer *) stgMallocWords(sizeofW(rtsPackBuffer), 
317
			 "InstantiatePackBuffer: failed to alloc packBuffer");
318 319
  globalPackBuffer->size = RtsFlags.GranFlags.packBufferSize_internal;
  globalPackBuffer->buffer = (StgWord **) stgMallocWords(RtsFlags.GranFlags.packBufferSize_internal,
320 321 322 323
				 "InstantiatePackBuffer: failed to alloc GranSim internal packBuffer");
  /* NB: gransim_pack_buffer_size instead of pack_buffer_size -- HWL */
  /* stgMallocWords is now simple allocate in Storage.c */

324
  return (globalPackBuffer);
325 326 327 328 329 330 331 332 333
}

/* 
   Reallocate the GranSim internal pack buffer to make room for more closure
   pointers. This is independent of the check for packet overflow as in GUM
*/
static void
reallocPackBuffer (void) {

334
  ASSERT(pack_locn >= (int)globalPackBuffer->size+sizeofW(rtsPackBuffer));
335 336 337

  IF_GRAN_DEBUG(packBuffer,
		belch("** Increasing size of PackBuffer %p to %d words (PE %u @ %d)\n",
338
		      globalPackBuffer, globalPackBuffer->size+REALLOC_SZ,
339 340
		      CurrentProc, CurrentTime[CurrentProc]));
  
341
  globalPackBuffer = (rtsPackBuffer*)realloc(globalPackBuffer, 
342
				  sizeof(StgClosure*)*(REALLOC_SZ +
343
						       (int)globalPackBuffer->size +
344
						       sizeofW(rtsPackBuffer))) ;
345
  if (globalPackBuffer==(rtsPackBuffer*)NULL) 
346
    barf("Failing to realloc %d more words for PackBuffer %p (PE %u @ %d)\n", 
347
	 REALLOC_SZ, globalPackBuffer, CurrentProc, CurrentTime[CurrentProc]);
348
  
349
  globalPackBuffer->size += REALLOC_SZ;
350

351
  ASSERT(pack_locn < globalPackBuffer->size+sizeofW(rtsPackBuffer));
352 353 354 355 356
}
# endif

# if defined(PAR)
/* @initPacking@ initialises the packing buffer etc. */
357
//@cindex InitPackBuffer
358
rtsBool
359
InitPackBuffer(void)
360
{
361 362 363 364 365
  if (globalPackBuffer==(rtsPackBuffer*)NULL) {
    if ((globalPackBuffer = (rtsPackBuffer *) 
	 stgMallocWords(sizeofW(rtsPackBuffer)+RtsFlags.ParFlags.packBufferSize,
			"InitPackBuffer")) == NULL)
      return rtsFalse;
366 367 368 369
  }
  return rtsTrue;
}

370 371
# endif 
//@cindex InitPacking
372
static void
373
InitPacking(rtsBool unpack)
374 375
{
# if defined(GRAN)
376
  globalPackBuffer = InstantiatePackBuffer();     /* for GrAnSim only -- HWL */
377
                                       /* NB: free in UnpackGraph */
378 379 380 381 382 383 384 385
# elif defined(PAR)
  if (unpack) {
    /* allocate a GA-to-GA map (needed for ACK message) */
    InitPendingGABuffer(RtsFlags.ParFlags.packBufferSize);
  } else {
    /* allocate memory to pack the graph into */
    InitPackBuffer();
  }
386
# endif
387 388 389 390 391
  /* init queue of closures seen during packing */
  InitClosureQueue();

  if (unpack) 
    return;
392

393
  globalPackBuffer->id = buf_id++;  /* buffer id are only used for debugging! */
394 395
  pack_locn = 0;         /* the index into the actual pack buffer */
  unpacked_size = 0;     /* the size of the whole graph when unpacked */
396
  roomInBuffer = rtsTrue;
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 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442
  packed_thunks = 0;   /* total number of thunks packed so far */
# if defined(PAR)
  offsetTable = allocHashTable();
# endif
}

//@node Packing Functions, Low level packing routines, Initialisation for packing, Graph packing
//@subsection Packing Functions

//@menu
//* Packing Sections of Nearby Graph::	
//* Packing Closures::		
//@end menu

//@node Packing Sections of Nearby Graph, Packing Closures, Packing Functions, Packing Functions
//@subsubsection Packing Sections of Nearby Graph
/*
  Packing Sections of Nearby Graph

  @PackNearbyGraph@ packs a closure and associated graph into a static
  buffer (@PackBuffer@).  It returns the address of this buffer and the
  size of the data packed into the buffer (in its second parameter,
  @packBufferSize@).  The associated graph is packed in a depth first
  manner, hence it uses an explicit queue of closures to be packed rather
  than simply using a recursive algorithm.  Once the packet is full,
  closures (other than primitive arrays) are packed as FetchMes, and their
  children are not queued for packing.  */

//@cindex PackNearbyGraph

/* NB: this code is shared between GranSim and GUM;
       tso only used in GranSim */
rtsPackBuffer *
PackNearbyGraph(closure, tso, packBufferSize)
StgClosure* closure;
StgTSO* tso;
nat *packBufferSize;
{
  ASSERT(RTS_PACK_BUFFER_SIZE > 0);

  /* ToDo: check that we have enough heap for the packet
     ngoq ngo'
     if (Hp + PACK_HEAP_REQUIRED > HpLim) 
     return NULL;
  */

443
  InitPacking(rtsFalse);
444 445 446 447 448 449
# if defined(GRAN)
  graph_root = closure;
# endif

  IF_GRAN_DEBUG(pack,
		belch(">>> Packing <<%d>> (buffer @ %p); graph root @ %p [PE %d]\n    demanded by TSO %d (%p) [PE %u]",
450
		      globalPackBuffer->id, globalPackBuffer, closure, where_is(closure), 
451 452 453 454 455 456
		      tso->id, tso, where_is((StgClosure*)tso)));

  IF_GRAN_DEBUG(pack,
		belch("** PrintGraph of %p is:", closure); 
		PrintGraph(closure,0));

457
  IF_PAR_DEBUG(packet,
458
	       belch(">>> Packing <<%d>> (buffer @ %p); graph root @ %p [%x]\n    demanded by TSO %d (%p)",
459
		     globalPackBuffer->id, globalPackBuffer, closure, mytid,
460 461
		     tso->id, tso)); 

462
  IF_PAR_DEBUG(packet,
463 464 465 466 467 468 469 470 471 472 473 474
	       belch("** PrintGraph of %p is:", closure); 
	       belch("** pack_locn=%d", pack_locn);
	       PrintGraph(closure,0));

  QueueClosure(closure);
  do {
    PackClosure(DeQueueClosure());
  } while (!QueueEmpty());
  
# if defined(PAR)

  /* Record how much space is needed to unpack the graph */
475 476 477
  globalPackBuffer->tso = tso; // ToDo: check: used in GUM or only for debugging?
  globalPackBuffer->unpacked_size = unpacked_size;
  globalPackBuffer->size = pack_locn;
478 479 480 481 482 483 484 485 486

  /* Set the size parameter */
  ASSERT(pack_locn <= RtsFlags.ParFlags.packBufferSize);
  *packBufferSize = pack_locn;

# else  /* GRAN */

  /* Record how much space is needed to unpack the graph */
  // PackBuffer[PACK_FLAG_LOCN] = (P_) MAGIC_PACK_FLAG;  for testing
487 488
  globalPackBuffer->tso = tso;
  globalPackBuffer->unpacked_size = unpacked_size;
489 490 491 492 493 494

  // ASSERT(pack_locn <= PackBuffer[PACK_SIZE_LOCN]+PACK_HDR_SIZE);
  /* ToDo: Print an earlier, more meaningful message */
  if (pack_locn==0)   /* i.e. packet is empty */
    barf("EMPTY PACKET! Can't transfer closure %p at all!!\n",
	 closure);
495
  globalPackBuffer->size = pack_locn;
496 497 498 499 500 501 502 503 504
  *packBufferSize = pack_locn;

# endif

  DonePacking();                               /* {GrAnSim}vaD 'ut'Ha' */

# if defined(GRAN)
  IF_GRAN_DEBUG(pack ,
		belch("** Finished <<%d>> packing graph %p; closures packed: %d; thunks packed: %d; size of graph: %d",
505
		      globalPackBuffer->id, closure, globalPackBuffer->size, packed_thunks, globalPackBuffer->unpacked_size));
506 507 508 509 510
  if (RtsFlags.GranFlags.GranSimStats.Global) {
    globalGranStats.tot_packets++; 
    globalGranStats.tot_packet_size += pack_locn; 
  }
  
511
  IF_GRAN_DEBUG(pack, PrintPacket(globalPackBuffer));
512
# elif defined(PAR)
513
  IF_PAR_DEBUG(packet,
514
		belch("** Finished <<%d>> packing graph %p; closures packed: %d; thunks packed: %d; size of graph: %d",
515 516
		      globalPackBuffer->id, closure, globalPackBuffer->size, packed_thunks, globalPackBuffer->unpacked_size);
		PrintPacket(globalPackBuffer));
517

518 519 520 521 522
  IF_DEBUG(sanity, // do a sanity check on the packet just constructed 
	   checkPacket(globalPackBuffer));
# endif   /* GRAN */
  
  return (globalPackBuffer);
523 524 525 526 527 528 529 530 531 532 533 534 535
}

//@cindex PackOneNode

# if defined(GRAN)
/* This version is used when the node is already local */

rtsPackBuffer *
PackOneNode(closure, tso, packBufferSize)
StgClosure* closure;
StgTSO* tso;
nat *packBufferSize;
{
536
  extern rtsPackBuffer *globalPackBuffer;
537 538
  int i, clpack_locn;

539
  InitPacking(rtsFalse);
540 541 542 543 544 545 546 547 548

  IF_GRAN_DEBUG(pack,
		belch("** PackOneNode: %p (%s)[PE %d] requested by TSO %d (%p) [PE %d]",
		      closure, info_type(closure),
		      where_is(closure), tso->id, tso, where_is((StgClosure *)tso)));

  Pack(closure);

  /* Record how much space is needed to unpack the graph */
549 550
  globalPackBuffer->tso = tso;
  globalPackBuffer->unpacked_size = unpacked_size;
551 552 553

  /* Set the size parameter */
  ASSERT(pack_locn <= RTS_PACK_BUFFER_SIZE);
554
  globalPackBuffer->size =  pack_locn;
555 556 557 558 559 560 561
  *packBufferSize = pack_locn;

  if (RtsFlags.GranFlags.GranSimStats.Global) {
    globalGranStats.tot_packets++; 
    globalGranStats.tot_packet_size += pack_locn; 
  }
  IF_GRAN_DEBUG(pack,
562
    PrintPacket(globalPackBuffer));
563

564
  return (globalPackBuffer);
565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582
}
# endif  /* GRAN */

#if defined(GRAN)

/*
   PackTSO and PackStkO are entry points for two special kinds of closure
   which are used in the parallel RTS.  Compared with other closures they
   are rather awkward to pack because they don't follow the normal closure
   layout (where all pointers occur before all non-pointers).  Luckily,
   they're only needed when migrating threads between processors.  */

//@cindex PackTSO
rtsPackBuffer*
PackTSO(tso, packBufferSize)
StgTSO *tso;
nat *packBufferSize;
{
583
  extern rtsPackBuffer *globalPackBuffer;
584 585 586 587
  IF_GRAN_DEBUG(pack,
		belch("** Packing TSO %d (%p)", tso->id, tso));
  *packBufferSize = 0;
  // PackBuffer[0] = PackBuffer[1] = 0; ???
588
  return(globalPackBuffer);
589 590 591
}

//@cindex PackStkO
592
static rtsPackBuffer*
593 594 595 596
PackStkO(stko, packBufferSize)
StgPtr stko;
nat *packBufferSize;
{
597
  extern rtsPackBuffer *globalPackBuffer;
598 599 600 601
  IF_GRAN_DEBUG(pack,
		belch("** Packing STKO %p", stko));
  *packBufferSize = 0;
  // PackBuffer[0] = PackBuffer[1] = 0;
602
  return(globalPackBuffer);
603 604
}

605
static void
606 607 608 609 610 611 612
PackFetchMe(StgClosure *closure)
{
  barf("{PackFetchMe}Daq Qagh: no FetchMe closures in GRAN!");
}

#elif defined(PAR)

613
static rtsPackBuffer*
614 615 616 617
PackTSO(tso, packBufferSize)
StgTSO *tso;
nat *packBufferSize;
{
618 619
  barf("{PackTSO}Daq Qagh: trying to pack a TSO %d (%p) of size %d; thread migrations not supported, yet",
       tso->id, tso, packBufferSize);
620 621 622 623 624 625 626
}

rtsPackBuffer*
PackStkO(stko, packBufferSize)
StgPtr stko;
nat *packBufferSize;
{
627 628
  barf("{PackStkO}Daq Qagh: trying to pack a STKO (%p) of size %d; thread migrations not supported, yet",
       stko, packBufferSize);
629 630 631
}

//@cindex PackFetchMe
632
static void
633 634 635 636
PackFetchMe(StgClosure *closure)
{
  StgInfoTable *ip;
  nat i;
637
  int offset;
638 639 640 641

#if defined(GRAN)
  barf("{PackFetchMe}Daq Qagh: no FetchMe closures in GRAN!");
#else
642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662
  offset = OffsetFor(closure);
  if (!NotYetPacking(offset)) {
    IF_PAR_DEBUG(pack,
		 belch("*>.. Packing FETCH_ME for closure %p (s) as offset to %d",
		       closure, info_type(closure), offset));
    PackOffset(offset);
    unpacked_size += 2;
    return;
  }

  /* Need a GA even when packing a constructed FETCH_ME (cruel world!) */
  AmPacking(closure);
  GlobaliseAndPackGA(closure);

  IF_PAR_DEBUG(pack,
	       belch("*>.. Packing FETCH_ME for closure %p (%s) with GA: ((%x, %d, %x))",
		     closure, info_type(closure), 
		     globalPackBuffer->buffer[pack_locn-2],
		     globalPackBuffer->buffer[pack_locn-1],
		     globalPackBuffer->buffer[pack_locn-3]));

663 664 665 666 667 668 669
  /* Pack a FetchMe closure instead of closure */
  ip = &FETCH_ME_info;
  /* this assumes that the info ptr is always the first word in a closure*/
  Pack((StgWord)ip);
  for (i = 1; i < _HS; ++i)               // pack rest of fixed header
    Pack((StgWord)*(((StgPtr)closure)+i));
  
670
  unpacked_size += PACK_FETCHME_SIZE;
671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703
#endif
}

#endif

//@node Packing Closures,  , Packing Sections of Nearby Graph, Packing Functions
//@subsubsection Packing Closures
/*
  Packing Closures

  @PackClosure@ is the heart of the normal packing code.  It packs a single
  closure into the pack buffer, skipping over any indirections and
  globalising it as necessary, queues any child pointers for further
  packing, and turns it into a @FetchMe@ or revertible black hole (@RBH@)
  locally if it was a thunk.  Before the actual closure is packed, a
  suitable global address (GA) is inserted in the pack buffer.  There is
  always room to pack a fetch-me to the closure (guaranteed by the
  RoomToPack calculation), and this is packed if there is no room for the
  entire closure.

  Space is allocated for any primitive array children of a closure, and
  hence a primitive array can always be packed along with it's parent
  closure.  */

//@cindex PackClosure

# if defined(PAR)

void
PackClosure(closure)
StgClosure *closure;
{
  StgInfoTable *info;
704 705
  StgClosure *indirectee;
  nat clpack_locn;
706

707 708 709 710 711
  ASSERT(LOOKS_LIKE_GHC_INFO(get_itbl(closure)));

  closure = UNWIND_IND(closure);
  /* now closure is the thing we want to pack */
  info = get_itbl(closure);
712 713 714 715 716 717 718 719 720 721

  clpack_locn = OffsetFor(closure);

  /* If the closure has been packed already, just pack an indirection to it
     to guarantee that the graph doesn't become a tree when unpacked */
  if (!NotYetPacking(clpack_locn)) {
    PackOffset(clpack_locn);
    return;
  }

722
  switch (info->type) {
723 724

  case CONSTR_CHARLIKE:
725 726 727 728 729 730 731 732 733 734 735 736 737 738 739
    {
      StgChar val = ((StgIntCharlikeClosure*)closure)->data;
      
      if ((val <= MAX_CHARLIKE) && (val >= MIN_CHARLIKE)) {
	IF_PAR_DEBUG(pack,
		     belch("*>^^ Packing a small charlike %d as a PLC", val));
	PackPLC((StgPtr)CHARLIKE_CLOSURE(val));
      } else {
	IF_PAR_DEBUG(pack,
		     belch("*>^^ Packing a big charlike %d as a normal closure", 
			   val));
	PackGeneric(closure);
      }
      return;
    }
740 741 742 743 744 745 746
      
  case CONSTR_INTLIKE:
    {
      StgInt val = ((StgIntCharlikeClosure*)closure)->data;
      
      if ((val <= MAX_INTLIKE) && (val >= MIN_INTLIKE)) {
	IF_PAR_DEBUG(pack,
747 748
		     belch("*>^^ Packing a small intlike %d as a PLC", val));
	PackPLC((StgPtr)INTLIKE_CLOSURE(val));
749 750
      } else {
	IF_PAR_DEBUG(pack,
751
		     belch("*>^^ Packing a big intlike %d as a normal closure", 
752
			   val));
753
	PackGeneric(closure);
754
      }
755
      return;
756 757 758 759 760 761 762 763
    }

  case CONSTR:
  case CONSTR_1_0:
  case CONSTR_0_1:
  case CONSTR_2_0:
  case CONSTR_1_1:
  case CONSTR_0_2:
764
    /* it's a constructor (i.e. plain data) */
765
    IF_PAR_DEBUG(pack,
766
		 belch("*>^^ Packing a CONSTR %p (%s) using generic packing", 
767
		       closure, info_type(closure)));
768 769
    PackGeneric(closure);
    return;
770

771 772
  case THUNK_STATIC:       // ToDo: check whether that's ok
  case FUN_STATIC:       // ToDo: check whether that's ok
773 774 775 776
  case CONSTR_STATIC:
  case CONSTR_NOCAF_STATIC:// For now we ship indirections to CAFs: They are
			   // evaluated on each PE if needed
    IF_PAR_DEBUG(pack,
777
      belch("*>~~ Packing a %p (%s) as a PLC", 
778 779
	    closure, info_type(closure)));

780
    PackPLC((StgPtr)closure);
781 782
    return;

783 784 785
  case THUNK_SELECTOR: 
    {
      StgClosure *selectee = ((StgSelector *)closure)->selectee;
786

787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824
      IF_PAR_DEBUG(pack,
		   belch("*>** Found THUNK_SELECTOR at %p (%s) pointing to %p (%s); using PackGeneric", 
			 closure, info_type(closure), 
			 selectee, info_type(selectee)));
      PackGeneric(closure);
      /* inlined code; probably could use PackGeneric
      Pack((StgWord)(*(StgPtr)closure));  
      Pack((StgWord)(selectee));
      QueueClosure(selectee);
      unpacked_size += 2;
      */
    }
    return;

  case  FUN:
  case	FUN_1_0:
  case	FUN_0_1:
  case	FUN_2_0:
  case	FUN_1_1:
  case	FUN_0_2:
  case  THUNK:
  case	THUNK_1_0:
  case	THUNK_0_1:
  case	THUNK_2_0:
  case	THUNK_1_1:
  case	THUNK_0_2:
    PackGeneric(closure);
    return;

  case AP_UPD:
  case PAP:
    /* 
    barf("*>   Packing of PAP not implemented %p (%s)",
		       closure, info_type(closure));
	 
       Currently we don't pack PAPs; we pack a FETCH_ME to the closure, 
       instead. Note that since PAPs contain a chunk of stack as payload,
       implementing packing of PAPs is a first step towards thread migration.
825
    IF_PAR_DEBUG(pack,
826
		 belch("*>.. Packing a PAP closure at %p (%s) as a FETCH_ME", 
827
		       closure, info_type(closure)));
828 829 830 831
    PackFetchMe(closure);
    */
    PackPAP((StgPAP *)closure);
    return;
832

833 834
  case CAF_UNENTERED:
  case CAF_ENTERED:
835 836
  case CAF_BLACKHOLE:
  case BLACKHOLE:
837 838 839
  case BLACKHOLE_BQ:
  case SE_BLACKHOLE:
  case SE_CAF_BLACKHOLE:
840 841 842 843 844 845 846 847
  case RBH:
  case FETCH_ME:
  case FETCH_ME_BQ:

    /* If it's a (revertible) black-hole, pack a FetchMe closure to it */
    //ASSERT(pack_locn > PACK_HDR_SIZE);
    
    IF_PAR_DEBUG(pack,
848 849 850 851 852 853
		 belch("*>.. Packing a BH-like closure at %p (%s) as a FETCH_ME", 
		       closure, info_type(closure)));
    /* NB: in case of a FETCH_ME this might build up a chain of FETCH_MEs;
           phps short-cut the GA here */
    PackFetchMe(closure);
    return;
854

855 856 857 858 859 860 861 862 863 864 865 866 867 868
  case MVAR:
    barf("*>   Pack: packing of MVARs not implemented",
		       closure, info_type(closure));
	 
    /* MVARs may not be copied; they are sticky objects in the new RTS */
    /* therefore we treat them just as RBHs etc (what a great system!) 
    IF_PAR_DEBUG(pack,
		 belch("** Found an MVar at %p (%s)", 
		 closure, info_type(closure))); */
    IF_PAR_DEBUG(pack,
		 belch("*>.. Packing an MVAR at %p (%s) as a FETCH_ME", 
		       closure, info_type(closure)));
    /* NB: in case of a FETCH_ME this might build up a chain of FETCH_MEs;
           phps short-cut the GA here */
869 870 871
    PackFetchMe(closure);
    return;

872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936
  case ARR_WORDS:
    PackArray(closure);
    return;

  case MUT_ARR_PTRS:
  case MUT_ARR_PTRS_FROZEN:
  case MUT_VAR:
    /* 
       Eventually, this should use the same packing routine as ARR_WRODS

       GlobaliseAndPackGA(closure);
       PackArray(closure);
       return;
    */
    barf("Qagh{Pack}Doq: packing of mutable closures not yet implemented: %p (%s)",
	 closure, info_type(closure));

#  ifdef DEBUG
  case BCO:
    barf("{Pack}Daq Qagh: found BCO closure %p (%s); GUM hates interpreted code", 
	 closure, info_type(closure));
    /* never reached */
    
    // check error cases only in a debugging setup
  case RET_BCO:
  case RET_SMALL:
  case RET_VEC_SMALL:
  case RET_BIG:
  case RET_VEC_BIG:
  case RET_DYN:
    barf("{Pack}Daq Qagh: found return vector %p (%s) when packing (thread migration not implemented)", 
	 closure, info_type(closure));
    /* never reached */
    
  case UPDATE_FRAME:
  case STOP_FRAME:
  case CATCH_FRAME:
  case SEQ_FRAME:
    barf("{Pack}Daq Qagh: found stack frame %p (%s) when packing (thread migration not implemented)", 
	 closure, info_type(closure));
    /* never reached */

  case TSO:
  case BLOCKED_FETCH:
  case EVACUATED:
    /* something's very wrong */
    barf("{Pack}Daq Qagh: found %s (%p) when packing", 
	 info_type(closure), closure);
    /* never reached */

  case IND:
  case IND_OLDGEN:
  case IND_PERM:
  case IND_OLDGEN_PERM:
  case IND_STATIC:
    barf("Pack: found IND_... after shorting out indirections %d (%s)", 
	 (nat)(info->type), info_type(closure));

  case WEAK:
  case FOREIGN:
  case STABLE_NAME:
    barf("Pack: found foreign thingy; not yet implemented in %d (%s)", 
	 (nat)(info->type), info_type(closure));
#endif

937
  default:
938
    barf("Pack: strange closure %d", (nat)(info->type));
939
  } /* switch */
940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955
}

/*
  Pack a constructor of unknown size.
  Similar to PackGeneric but without creating GAs.
*/
#if 0
//@cindex PackConstr
static void
PackConstr(StgClosure *closure)
{
  StgInfoTable *info;
  nat size, ptrs, nonptrs, vhs, i;
  char str[80];

  ASSERT(LOOKS_LIKE_GHC_INFO(closure->header.info));
956 957 958 959

  /* get info about basic layout of the closure */
  info = get_closure_info(closure, &size, &ptrs, &nonptrs, &vhs, str);

960 961 962 963 964 965
  ASSERT(info->type == CONSTR ||
         info->type == CONSTR_1_0 ||
         info->type == CONSTR_0_1 ||
         info->type == CONSTR_2_0 ||
         info->type == CONSTR_1_1 ||
         info->type == CONSTR_0_2);
966 967

  IF_PAR_DEBUG(pack,
968
	       fprintf(stderr, "*>^^ packing a constructor at %p (%s) (size=%d, ptrs=%d, nonptrs=%d)\n",
969 970
		       closure, info_type(closure), size, ptrs, nonptrs));

971
  /* Primitive arrays have gone; now we have (MUT_)ARR_WORDS etc */
972

973
  if (!RoomToPack(PACK_GA_SIZE + _HS + vhs + nonptrs, ptrs)) {
974
    IF_PAR_DEBUG(pack,
975
		 belch("*>&& pack buffer is full; packing FETCH_ME for closure %p (%s)",
976
		       closure, info_type(closure)));
977 978
    PackFetchMe(closure);
    return;
979 980
  }

981 982
  /* Record the location of the GA */
  AmPacking(closure);
983

984 985
  /* Pack Constructor marker */
  Pack((StgWord)2);
986

987 988 989
  /* pack fixed and variable header */
  for (i = 0; i < _HS + vhs; ++i)
    Pack((StgWord)*(((StgPtr)closure)+i));
990
      
991 992 993
  /* register all ptrs for further packing */
  for (i = 0; i < ptrs; ++i)
    QueueClosure(((StgClosure *) *(((StgPtr)closure)+(_HS+vhs)+i)));
994

995 996 997 998 999
  /* pack non-ptrs */
  for (i = 0; i < nonptrs; ++i)
    Pack((StgWord)*(((StgPtr)closure)+(_HS+vhs)+ptrs+i));
}
#endif
1000

1001 1002 1003 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 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041
/*
  Generic packing code.
  This code is performed for `ordinary' closures such as CONSTR, THUNK etc.
*/
//@cindex PackGeneric
static void
PackGeneric(StgClosure *closure)
{
  StgInfoTable *info;
  StgClosure *rbh;
  nat size, ptrs, nonptrs, vhs, i, m;
  char str[80];

  ASSERT(LOOKS_LIKE_COOL_CLOSURE(closure));

  /* get info about basic layout of the closure */
  info = get_closure_info(closure, &size, &ptrs, &nonptrs, &vhs, str);

  ASSERT(!IS_BLACK_HOLE(closure));

  IF_PAR_DEBUG(pack,
	       fprintf(stderr, "*>== generic packing of %p (%s) (size=%d, ptrs=%d, nonptrs=%d)\n",
		       closure, info_type(closure), size, ptrs, nonptrs));

  /* Primitive arrays have gone; now we have (MUT_)ARR_WORDS etc */

  if (!RoomToPack(PACK_GA_SIZE + _HS + vhs + nonptrs, ptrs)) {
    IF_PAR_DEBUG(pack,
		 belch("*>&& pack buffer is full; packing FETCH_ME for closure %p (%s)",
		       closure, info_type(closure)));
    PackFetchMe(closure);
    return;
  }

  /* Record the location of the GA */
  AmPacking(closure);
  /* Allocate a GA for this closure and put it into the buffer */
  GlobaliseAndPackGA(closure);

  ASSERT(!(info->type == ARR_WORDS || info->type == MUT_ARR_PTRS ||
	   info->type == MUT_ARR_PTRS_FROZEN || info->type == MUT_VAR));
1042 1043 1044

  /* At last! A closure we can actually pack! */
  if (ip_MUTABLE(info) && (info->type != FETCH_ME))
1045
    barf("*>// PackClosure: trying to replicate a Mutable closure!");
1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058
      
  /* 
     Remember, the generic closure layout is as follows:
        +-------------------------------------------------+
	| FIXED HEADER | VARIABLE HEADER | PTRS | NON-PRS |
        +-------------------------------------------------+
  */
  /* pack fixed and variable header */
  for (i = 0; i < _HS + vhs; ++i)
    Pack((StgWord)*(((StgPtr)closure)+i));
      
  /* register all ptrs for further packing */
  for (i = 0; i < ptrs; ++i)
1059
    QueueClosure(((StgClosure *) *(((StgPtr)closure)+(_HS+vhs)+i)));
1060 1061 1062

  /* pack non-ptrs */
  for (i = 0; i < nonptrs; ++i)
1063
    Pack((StgWord)*(((StgPtr)closure)+(_HS+vhs)+ptrs+i));
1064
      
1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075
  // ASSERT(_HS+vhs+ptrs+nonptrs==size);
  if ((m=_HS+vhs+ptrs+nonptrs)<size) {
    IF_PAR_DEBUG(pack,
		 belch("*>** WARNING: slop in closure %p (%s); filling %d words; SHOULD NEVER HAPPEN",
		       closure, info_type(closure), size-m));
    for (i=m; i<size; i++) 
      Pack((StgWord)*(((StgPtr)closure)+i));
  }

  unpacked_size += size;
  // unpacked_size += (size < MIN_UPD_SIZE) ? MIN_UPD_SIZE : size;
1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090

  /*
   * Record that this is a revertable black hole so that we can fill in
   * its address from the fetch reply.  Problem: unshared thunks may cause
   * space leaks this way, their GAs should be deallocated following an
   * ACK.
   */
      
  // IS_UPDATABLE(closure) == !closure_UNPOINTED(closure) !? HWL
  if (closure_THUNK(closure) && !closure_UNPOINTED(closure)) { 
    rbh = convertToRBH(closure);
    ASSERT(rbh == closure); // rbh at the same position (minced version)
    packed_thunks++;
  }
}
1091 1092 1093 1094
/*
  Pack an array of words.
  ToDo: implement packing of MUT_ARRAYs
*/
1095

1096 1097 1098 1099 1100 1101 1102
//@cindex PackArray
static void
PackArray(StgClosure *closure)
{
  StgInfoTable *info;
  nat size, ptrs, nonptrs, vhs, i, n;
  char str[80];
1103

1104 1105 1106
#if DEBUG
  /* we don't really need all that get_closure_info delivers; however, for
     debugging it's useful to have the stuff anyway */
1107

1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210
  /* get info about basic layout of the closure */
  info = get_closure_info(closure, &size, &ptrs, &nonptrs, &vhs, str);

  ASSERT(info->type == ARR_WORDS || info->type == MUT_ARR_PTRS ||
	 info->type == MUT_ARR_PTRS_FROZEN || info->type == MUT_VAR);
#endif
  /* record offset of the closure and allocate a GA */
  AmPacking(closure);
  GlobaliseAndPackGA(closure);

  n = ((StgArrWords *)closure)->words;
  // this includes the header!: arr_words_sizeW(stgCast(StgArrWords*,q)); 

  IF_PAR_DEBUG(pack,
	       belch("*>== packing an array of %d words %p (%s) (size=%d)\n",
		     n, closure, info_type(closure), 
		     arr_words_sizeW((StgArrWords *)closure)));

  /* Pack the header (2 words: info ptr and the number of words to follow) */
  Pack((StgWord)*(StgPtr)closure);
  Pack(((StgArrWords *)closure)->words);

  /* pack the payload of the closure (all non-ptrs) */
  for (i=0; i<n; i++)
    Pack((StgWord)((StgArrWords *)closure)->payload[i]);

  unpacked_size += arr_words_sizeW((StgArrWords *)closure);
}

/*
   Pack a PAP closure.
   Note that the representation of a PAP in the buffer is different from
   its representation in the heap. In particular, pointers to local
   closures are packed directly as FETCHME closures, using
   PACK_FETCHME_SIZE words to represent q 1 word pointer in the orig graph
   structure. To account for the difference in size we store the packed
   size of the closure as part of the PAP's variable header in the buffer.
*/

//@cindex PackPAP
static void
PackPAP(StgPAP *pap) {
  nat m, n, i, j, pack_start;
  StgPtr p, q,  end/*dbg*/;
  const StgInfoTable* info;
  StgWord32 bitmap;
  /* debugging only */
  nat size, ptrs, nonptrs, vhs;
  char str[80];

  /* This is actually a setup invariant; checked here 'cause it affects PAPs*/
  ASSERT(PACK_FETCHME_SIZE == 1 + sizeofW(StgFetchMe));
  ASSERT(NotYetPacking(OffsetFor((StgClosure *)pap)));

  /* record offset of the closure and allocate a GA */
  AmPacking((StgClosure *)pap);
  GlobaliseAndPackGA((StgClosure *)pap);

  /* get info about basic layout of the closure */
  info = get_closure_info((StgClosure *)pap, &size, &ptrs, &nonptrs, &vhs, str);
  ASSERT(ptrs==0 && nonptrs==0 && size==pap_sizeW(pap));

  n = (nat)(pap->n_args);

  IF_PAR_DEBUG(pack,
	       belch("*>** PackPAP: packing PAP @ %p with %d words (size=%d; ptrs=%d; nonptrs=%d:", 
			 (StgClosure *)pap, n,  size, ptrs, nonptrs);
               printClosure((StgClosure *)pap));

  /* Pack the PAP header */
  Pack((StgWord)(pap->header.info));
  Pack((StgWord)(pap->n_args));
  Pack((StgWord)(pap->fun));
  pack_start = pack_locn;   // to compute size of PAP in buffer
  Pack((StgWord)0);    // this will be filled in later (size of PAP in buffer)

  /* Pack the payload of a PAP i.e. a stack chunk */
  /* pointers to start of stack chunk */
  p = (StgPtr)(pap->payload);
  end = (StgPtr)((nat)pap+pap_sizeW(pap)*sizeof(StgWord)); // (StgPtr)((nat)pap+sizeof(StgPAP)+sizeof(StgPtr)*n);
  while (p<end) {
    /* the loop body has been borrowed from scavenge_stack */
    q = (StgPtr)*p;

    /* If we've got a tag, pack all words in that block */
    if (IS_ARG_TAG((W_)q)) {   // q stands for the no. of non-ptrs to follow
      nat m = ARG_TAG(q);      // first word after this block
      IF_PAR_DEBUG(pack,
		   belch("*>** PackPAP @ %p: packing %d words (tagged), starting @ %p", 
			 p, m, p));
      for (i=0; i<m+1; i++)
	Pack((StgWord)*(p+i));
      p += m+1;                // m words + the tag
      continue;
    }
     
    /* If q is is a pointer to a (heap allocated) closure we pack a FETCH_ME
       ToDo: provide RTS flag to also pack these closures
    */
    if (! LOOKS_LIKE_GHC_INFO(q) ) {
      /* distinguish static closure (PLC) from other closures (FM) */
      switch (get_itbl((StgClosure*)q)->type) {
      case CONSTR_CHARLIKE:
1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227
	{
	  StgChar val = ((StgIntCharlikeClosure*)q)->data;
      
	  if ((val <= MAX_CHARLIKE) && (val >= MIN_CHARLIKE)) {
	    IF_PAR_DEBUG(pack,
			 belch("*>** PackPAP: Packing ptr to a small charlike %d as a PLC", val));
	    PackPLC((StgPtr)CHARLIKE_CLOSURE(val));
	  } else {
	    IF_PAR_DEBUG(pack,
			 belch("*>** PackPAP: Packing a ptr to a big charlike %d as a FM", 
			       val));
	    Pack((StgWord)(ARGTAG_MAX+1));
	    PackFetchMe((StgClosure *)q);
	  }
	  p++;
	  break;
	}
1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243
      
      case CONSTR_INTLIKE:
	{
	  StgInt val = ((StgIntCharlikeClosure*)q)->data;
      
	  if ((val <= MAX_INTLIKE) && (val >= MIN_INTLIKE)) {
	    IF_PAR_DEBUG(pack,
			 belch("*>** PackPAP: Packing ptr to a small intlike %d as a PLC", val));
	    PackPLC((StgPtr)INTLIKE_CLOSURE(val));
	  } else {
	    IF_PAR_DEBUG(pack,
			 belch("*>** PackPAP: Packing a ptr to a big intlike %d as a FM", 
			       val));
	    Pack((StgWord)(ARGTAG_MAX+1));
	    PackFetchMe((StgClosure *)q);
	  }
1244 1245
	  p++;
	  break;
1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456
	}
	case THUNK_STATIC:       // ToDo: check whether that's ok
	case FUN_STATIC:       // ToDo: check whether that's ok
	case CONSTR_STATIC:
	case CONSTR_NOCAF_STATIC:
	  {
	    IF_PAR_DEBUG(pack,
			 belch("*>** PackPAP: packing a ptr to a %p (%s) as a PLC", 
			       q, info_type((StgClosure *)q)));
	    
	    PackPLC((StgPtr)q);
	    p++;
	    break;
	  }
      default:
	  IF_PAR_DEBUG(pack,
		       belch("*>** PackPAP @ %p: packing FM to %p (%s)", 
			     p, q, info_type((StgClosure*)q)));
	  Pack((StgWord)(ARGTAG_MAX+1));
	  PackFetchMe((StgClosure *)q);
	  p++;
	  break;
      }
      continue;
    }
	
    /* 
     * Otherwise, q must be the info pointer of an activation
     * record.  All activation records have 'bitmap' style layout
     * info.
     */
    info  = get_itbl((StgClosure *)p);
    switch (info->type) {
	
      /* Dynamic bitmap: the mask is stored on the stack */
    case RET_DYN:
      IF_PAR_DEBUG(pack,
		   belch("*>** PackPAP @ %p: RET_DYN", 
			 p));

      /* Pack the header as is */
      Pack((StgWord)(((StgRetDyn *)p)->info));
      Pack((StgWord)(((StgRetDyn *)p)->liveness));
      Pack((StgWord)(((StgRetDyn *)p)->ret_addr));

      bitmap = ((StgRetDyn *)p)->liveness;
      p      = (P_)&((StgRetDyn *)p)->payload[0];
      goto small_bitmap;

      /* probably a slow-entry point return address: */
    case FUN:
    case FUN_STATIC:
      {
      IF_PAR_DEBUG(pack,
		   belch("*>** PackPAP @ %p: FUN or FUN_STATIC", 
			 p));

      Pack((StgWord)(((StgClosure *)p)->header.info));
      p++;

      goto follow_srt; //??
      }

      /* Using generic code here; could inline as in scavenge_stack */
    case UPDATE_FRAME:
      {
	StgUpdateFrame *frame = (StgUpdateFrame *)p;
	nat type = get_itbl(frame->updatee)->type;

	ASSERT(type==BLACKHOLE || type==CAF_BLACKHOLE || type==BLACKHOLE_BQ);

	IF_PAR_DEBUG(pack,
		     belch("*>** PackPAP @ %p: UPDATE_FRAME (updatee=%p; link=%p)", 
			   p, frame->updatee, frame->link));

	Pack((StgWord)(frame->header.info));
	Pack((StgWord)(frame->link));     // ToDo: fix intra-stack pointer
	Pack((StgWord)(frame->updatee));  // ToDo: follow link 

	p += 3;
      }

      /* small bitmap (< 32 entries, or 64 on a 64-bit machine) */
    case STOP_FRAME:
      {
	IF_PAR_DEBUG(pack,
		     belch("*>** PackPAP @ %p: STOP_FRAME", 
			   p));
	Pack((StgWord)((StgStopFrame *)p)->header.info);
	p++;
      }

    case CATCH_FRAME:
      {
	IF_PAR_DEBUG(pack,
		     belch("*>** PackPAP @ %p: CATCH_FRAME (handler=%p)", 
			   p, ((StgCatchFrame *)p)->handler));

	Pack((StgWord)((StgCatchFrame *)p)->header.info);
	Pack((StgWord)((StgCatchFrame *)p)->link); // ToDo: fix intra-stack pointer
	Pack((StgWord)((StgCatchFrame *)p)->exceptions_blocked);
	Pack((StgWord)((StgCatchFrame *)p)->handler);
	p += 4;
      }

    case SEQ_FRAME:
      {
	IF_PAR_DEBUG(pack,
		     belch("*>** PackPAP @ %p: UPDATE_FRAME (link=%p)", 
			   p, ((StgSeqFrame *)p)->link));

	Pack((StgWord)((StgSeqFrame *)p)->header.info);
	Pack((StgWord)((StgSeqFrame *)p)->link); // ToDo: fix intra-stack pointer

        // ToDo: handle bitmap
        bitmap = info->layout.bitmap;

        p = (StgPtr)&(((StgClosure *)p)->payload);
        goto small_bitmap;
      }
    case RET_BCO:
    case RET_SMALL:
    case RET_VEC_SMALL:
      IF_PAR_DEBUG(pack,
		   belch("*>** PackPAP @ %p: RET_{BCO,SMALL,VEC_SMALL} (bitmap=%o)", 
			 p, info->layout.bitmap));


      Pack((StgWord)((StgClosure *)p)->header.info);
      p++;
      // ToDo: handle bitmap
      bitmap = info->layout.bitmap;
      /* this assumes that the payload starts immediately after the info-ptr */

    small_bitmap:
      while (bitmap != 0) {
	if ((bitmap & 1) == 0) {
	  Pack((StgWord)(ARGTAG_MAX+1));
	  PackFetchMe((StgClosure *)*p++); // pack a FetchMe to the closure
	} else {
	  Pack((StgWord)*p++);
	}
	bitmap = bitmap >> 1;
      }
      
    follow_srt:
      belch("*>-- PackPAP: nothing to do for follow_srt");
      continue;

      /* large bitmap (> 32 entries) */
    case RET_BIG:
    case RET_VEC_BIG:
      {
	StgPtr q;
	StgLargeBitmap *large_bitmap;

	IF_PAR_DEBUG(pack,
		     belch("*>** PackPAP @ %p: RET_{BIG,VEC_BIG} (large_bitmap=%p)", 
			   p, info->layout.large_bitmap));


	Pack((StgWord)((StgClosure *)p)->header.info);
	p++;

	large_bitmap = info->layout.large_bitmap;

	for (j=0; j<large_bitmap->size; j++) {
	  bitmap = large_bitmap->bitmap[j];
	  q = p + sizeof(W_) * 8;
	  while (bitmap != 0) {
	    if ((bitmap & 1) == 0) {
	      Pack((StgWord)(ARGTAG_MAX+1));
	      PackFetchMe((StgClosure *)*p++); // ToDo: pack pointer(StgClosure *)*p = evacuate((StgClosure *)*p);
	    } else {
	      Pack((StgWord)*p++);
	    }
	    bitmap = bitmap >> 1;
	  }
	  if (j+1 < large_bitmap->size) {
	    while (p < q) {
	      Pack((StgWord)(ARGTAG_MAX+1));
	      PackFetchMe((StgClosure *)*p++); // ToDo: pack pointer (StgClosure *)*p = evacuate((StgClosure *)*p);
	    }
	  }
	}

	/* and don't forget to follow the SRT */
	goto follow_srt;
      }

    default:
      barf("PackPAP: weird activation record found on stack (@ %p): %d", 
	   p, (int)(info->type));
    }
  }
  // fill in size of the PAP (only the payload!) in buffer
  globalPackBuffer->buffer[pack_start] = (StgWord)(pack_locn - pack_start - 1*sizeofW(StgWord));
  // add the size of the whole packed closure; this relies on the fact that
  // the size of the unpacked PAP + size of all unpacked FMs is the same as
  // the size of the packed PAP!!
  unpacked_size += sizeofW(pap) + (nat)(globalPackBuffer->buffer[pack_start]);
}
# else  /* GRAN */

/* Fake the packing of a closure */

void
PackClosure(closure)
StgClosure *closure;
{
  StgInfoTable *info, *childInfo;
1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522
  nat size, ptrs, nonptrs, vhs;
  char info_hdr_ty[80];
  nat i;
  StgClosure *indirectee, *rbh;
  char str[80];
  rtsBool is_mutable, will_be_rbh, no_more_thunks_please;

  is_mutable = rtsFalse;

  /* In GranSim we don't pack and unpack closures -- we just simulate
     packing by updating the bitmask. So, the graph structure is unchanged
     i.e. we don't short out indirections here. -- HWL */

  /* Nothing to do with packing but good place to (sanity) check closure;
     if the closure is a thunk, it must be unique; otherwise we have copied
     work at some point before that which violates one of our main global
     assertions in GranSim/GUM */
  ASSERT(!closure_THUNK(closure) || is_unique(closure));

  IF_GRAN_DEBUG(pack,
		belch("**  Packing closure %p (%s)",
		      closure, info_type(closure)));

  if (where_is(closure) != where_is(graph_root)) {
    IF_GRAN_DEBUG(pack,
		  belch("**   faking a FETCHME [current PE: %d, closure's PE: %d]",
			where_is(graph_root), where_is(closure)));

    /* GUM would pack a FETCHME here; simulate that by increasing the */
    /* unpacked size accordingly but don't pack anything -- HWL */
    unpacked_size += _HS + 2 ; // sizeofW(StgFetchMe);
    return; 
  }

  /* If the closure's not already being packed */
  if (!NotYetPacking(closure)) 
    /* Don't have to do anything in GrAnSim if closure is already */
    /* packed -- HWL */
    {
      IF_GRAN_DEBUG(pack,
		    belch("**    Closure %p is already packed and omitted now!",
			    closure));
      return;
    }

  switch (get_itbl(closure)->type) {
    /* ToDo: check for sticky bit here? */
    /* BH-like closures which must not be moved to another PE */
    case CAF_BLACKHOLE:       /* # of ptrs, nptrs: 0,2 */
    case SE_BLACKHOLE:        /* # of ptrs, nptrs: 0,2 */
    case SE_CAF_BLACKHOLE:    /* # of ptrs, nptrs: 0,2 */
    case BLACKHOLE:           /* # of ptrs, nptrs: 0,2 */
    case BLACKHOLE_BQ:        /* # of ptrs, nptrs: 1,1 */
    case RBH:                 /* # of ptrs, nptrs: 1,1 */
      /* same for these parallel specific closures */
    case BLOCKED_FETCH:
    case FETCH_ME:
    case FETCH_ME_BQ:
      IF_GRAN_DEBUG(pack,
	belch("**    Avoid packing BH-like closures (%p, %s)!", 
	      closure, info_type(closure)));
      /* Just ignore RBHs i.e. they stay where they are */
      return;

    case THUNK_SELECTOR:
      {
1523
	StgClosure *selectee = ((StgSelector *)closure)->selectee;
1524 1525 1526

	IF_GRAN_DEBUG(pack,
		      belch("**    Avoid packing THUNK_SELECTOR (%p, %s) but queuing %p (%s)!", 
1527 1528
			    closure, info_type(closure), selectee, info_type(selectee)));
	QueueClosure(selectee);
1529 1530
	IF_GRAN_DEBUG(pack,
		      belch("**    [%p (%s) (Queueing closure) ....]",
1531
			    selectee, info_type(selectee)));
1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715
      }
      return;

    case CONSTR_STATIC:
    case CONSTR_NOCAF_STATIC:
                                  /* For now we ship indirections to CAFs:
				   * They are evaluated on each PE if needed */
      IF_GRAN_DEBUG(pack,
	belch("**    Nothing to pack for %p (%s)!", 
	      closure, info_type(closure)));
      // Pack(closure); GUM only
      return;

    case CONSTR_CHARLIKE:
    case CONSTR_INTLIKE:
      IF_GRAN_DEBUG(pack,
	belch("**    Nothing to pack for %s (%p)!", 
	      closure, info_type(closure)));
      // PackPLC(((StgIntCharlikeClosure *)closure)->data); GUM only
      return;

    case AP_UPD:   
    case PAP:
      /* partial applications; special treatment necessary? */
      break;

    case CAF_UNENTERED:    /* # of ptrs, nptrs: 1,3 */
    case CAF_ENTERED:      /* # of ptrs, nptrs: 0,4  (allegedly bogus!!) */
      /* CAFs; special treatment necessary? */
      break;

    case MVAR:
      barf("{PackClosure}Daq Qagh: found an MVAR (%p, %s); ToDo: implement proper treatment of MVARs",
	   closure, info_type(closure));

    case ARR_WORDS:
    case MUT_VAR:
    case MUT_ARR_PTRS:
    case MUT_ARR_PTRS_FROZEN:
      /* Mutable objects; require special treatment to ship all data */
      is_mutable = rtsTrue;
      break;	  

    case WEAK:
    case FOREIGN:
    case STABLE_NAME:
	  /* weak pointers and other FFI objects */
      barf("{PackClosure}Daq Qagh: found an FFI object (%p, %s); FFI not yet supported by GranSim, sorry",
	   closure, info_type(closure));

    case TSO:
      /* parallel objects */
      barf("{PackClosure}Daq Qagh: found a TSO when packing (%p, %s); thread migration not yet implemented, sorry",
	   closure, info_type(closure));

    case BCO:
      /* Hugs objects (i.e. closures used by the interpreter) */
      barf("{PackClosure}Daq Qagh: found a Hugs closure when packing (%p, %s); GranSim not yet integrated with Hugs, sorry",
	   closure, info_type(closure));
      
    case IND:              /* # of ptrs, nptrs: 1,0 */
    case IND_STATIC:       /* # of ptrs, nptrs: 1,0 */
    case IND_PERM:         /* # of ptrs, nptrs: 1,1 */
    case IND_OLDGEN:       /* # of ptrs, nptrs: 1,1 */
    case IND_OLDGEN_PERM:  /* # of ptrs, nptrs: 1,1 */
      /* we shouldn't find an indirection here, because we have shorted them
	 out at the beginning of this functions already.
      */
      break;
      /* should be:
      barf("{PackClosure}Daq Qagh: found indirection when packing (%p, %s)",
	   closure, info_type(closure));
      */

    case UPDATE_FRAME:
    case CATCH_FRAME:
    case SEQ_FRAME:
    case STOP_FRAME:
      /* stack frames; should never be found when packing for now;
	 once we support thread migration these have to be covered properly
      */
      barf("{PackClosure}Daq Qagh: found stack frame when packing (%p, %s)",
	   closure, info_type(closure));

    case RET_BCO:
    case RET_SMALL:
    case RET_VEC_SMALL:
    case RET_BIG:
    case RET_VEC_BIG:
    case RET_DYN:
      /* vectored returns; should never be found when packing; */
      barf("{PackClosure}Daq Qagh: found vectored return (%p, %s)",
	   closure, info_type(closure));

    case INVALID_OBJECT:
      barf("{PackClosure}Daq Qagh: found Invalid object (%p, %s)",
	   closure, info_type(closure));

    default:
      /* 
	 Here we know that the closure is a CONSTR, FUN or THUNK (maybe
	 a specialised version with wired in #ptr/#nptr info; currently
	 we treat these specialised versions like the generic version)
      */
    }     /* switch */

    /* Otherwise it's not Fixed */

    info = get_closure_info(closure, &size, &ptrs, &nonptrs, &vhs, str);
    will_be_rbh = closure_THUNK(closure) && !closure_UNPOINTED(closure);

    IF_GRAN_DEBUG(pack,
		belch("**    Info on closure %p (%s): size=%d; ptrs=%d",
		      closure, info_type(closure),
		      size, ptrs, 
		      (will_be_rbh) ? "will become RBH" : "will NOT become RBH"));
    
    // check whether IS_UPDATABLE(closure) == !closure_UNPOINTED(closure) -- HWL
    no_more_thunks_please = 
      (RtsFlags.GranFlags.ThunksToPack>0) && 
      (packed_thunks>=RtsFlags.GranFlags.ThunksToPack);

    /*
      should be covered by get_closure_info
    if (info->type == FETCH_ME || info->type == FETCH_ME_BQ || 
	info->type == BLACKHOLE || info->type == RBH )
      size = ptrs = nonptrs = vhs = 0;
    */
    /* Now peek ahead to see whether the closure has any primitive */
    /* array children */ 
    /* 
       ToDo: fix this code
       for (i = 0; i < ptrs; ++i) {
       P_ childInfo;
       W_ childSize, childPtrs, childNonPtrs, childVhs;
       
       childInfo = get_closure_info(((StgPtrPtr) (closure))[i + FIXED_HS + vhs],
       &childSize, &childPtrs, &childNonPtrs,
       &childVhs, junk_str);
       if (IS_BIG_MOTHER(childInfo)) {
       reservedPAsize += PACK_GA_SIZE + FIXED_HS + 
       childVhs + childNonPtrs +
       childPtrs * PACK_FETCHME_SIZE;
       PAsize += PACK_GA_SIZE + FIXED_HS + childSize;
       PAptrs += childPtrs;
       }
       }
    */
    /* Don't pack anything (GrAnSim) if it's a black hole, or the buffer
     * is full and it isn't a primitive array. N.B. Primitive arrays are
     * always packed (because their parents index into them directly) */

    if (IS_BLACK_HOLE(closure))
	/*
	  ToDo: fix this code
	  || 
	  !(RoomToPack(PACK_GA_SIZE + FIXED_HS + vhs + nonptrs, ptrs) 
	  || IS_BIG_MOTHER(info))) 
	  */
      return;

    /* At last! A closure we can actually pack! */

    if (closure_MUTABLE(closure)) // not nec. && (info->type != FETCHME))
      belch("ghuH: Replicated a Mutable closure!");

    if (RtsFlags.GranFlags.GranSimStats.Global &&  
	no_more_thunks_please && will_be_rbh) {
      globalGranStats.tot_cuts++;
      if ( RtsFlags.GranFlags.Debug.pack ) 
	belch("**    PackClosure (w/ ThunksToPack=%d): Cutting tree with root at %#x\n",
		RtsFlags.GranFlags.ThunksToPack, closure);
    } else if (will_be_rbh || (closure==graph_root) ) {
      packed_thunks++;
      globalGranStats.tot_thunks++;
    }

    if (no_more_thunks_please && will_be_rbh) 
      return; /* don't pack anything */

    /* actual PACKING done here --  HWL */
    Pack(closure);         
    for (i = 0; i < ptrs; ++i) {
      /* extract i-th pointer from closure */
1716
      QueueClosure((StgClosure *)(closure->payload[i]));
1717 1718
      IF_GRAN_DEBUG(pack,
		    belch("**    [%p (%s) (Queueing closure) ....]",
1719
			  closure->payload[i], info_type(payloadPtr(closure,i))));
1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746
    }

    /* 
       for packing words (GUM only) do something like this:

       for (i = 0; i < ptrs; ++i) {
         Pack(payloadWord(obj,i+j));
       }
    */
    /* Turn thunk into a revertible black hole. */
    if (will_be_rbh) { 
	rbh = convertToRBH(closure);
	ASSERT(rbh != NULL);
    }
}
# endif  /* PAR */

//@node Low level packing routines, Unpacking routines, Packing Functions, Graph packing
//@subsection Low level packing routines

/*
   @Pack@ is the basic packing routine.  It just writes a word of data into
   the pack buffer and increments the pack location.  */

//@cindex Pack

# if defined(PAR)
1747
static  void
1748 1749 1750 1751
Pack(data)
StgWord data;
{
  ASSERT(pack_locn < RtsFlags.ParFlags.packBufferSize);
1752
  globalPackBuffer->buffer[pack_locn++] = data;
1753 1754 1755 1756
}
#endif

#if defined(GRAN)
1757
static  void
1758 1759 1760 1761 1762 1763 1764 1765 1766
Pack(closure)
StgClosure *closure;
{
  StgInfoTable *info;
  nat size, ptrs, nonptrs, vhs;
  char str[80];

  /* This checks the size of the GrAnSim internal pack buffer. The simulated
     pack buffer is checked via RoomToPack (as in GUM) */
1767
  if (pack_locn >= (int)globalPackBuffer->size+sizeofW(rtsPackBuffer)) 
1768 1769 1770 1771
    reallocPackBuffer();

  if (closure==(StgClosure*)NULL) 
    belch("Qagh {Pack}Daq: Trying to pack 0");
1772
  globalPackBuffer->buffer[pack_locn++] = closure;
1773 1774
  /* ASSERT: Data is a closure in GrAnSim here */
  info = get_closure_info(closure, &size, &ptrs, &nonptrs, &vhs, str);
1775
  // ToDo: is check for MIN_UPD_SIZE really needed? */
1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786
  unpacked_size += _HS + (size < MIN_UPD_SIZE ? 
				        MIN_UPD_SIZE : 
				        size);
}
# endif  /* GRAN */

/*
   If a closure is local, make it global.  Then, divide its weight for
   export.  The GA is then packed into the pack buffer.  */

# if defined(PAR)
1787
//@cindex GlobaliseAndPackGA
1788 1789 1790 1791 1792 1793 1794 1795 1796
static void
GlobaliseAndPackGA(closure)
StgClosure *closure;
{
  globalAddr *ga;
  globalAddr packGA;

  if ((ga = LAGAlookup(closure)) == NULL)
    ga = makeGlobal(closure, rtsTrue);
1797
  ASSERT(ga->weight==MAX_GA_WEIGHT || ga->weight > 2);
1798 1799 1800 1801
  splitWeight(&packGA, ga);
  ASSERT(packGA.weight > 0);

  IF_PAR_DEBUG(pack,
1802
	       fprintf(stderr, "*>## Globalising closure %p (%s) with GA ", 
1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835
		       closure, info_type(closure));
	       printGA(&packGA);
	       fputc('\n', stderr));


  Pack((StgWord) packGA.weight);
  Pack((StgWord) packGA.payload.gc.gtid);
  Pack((StgWord) packGA.payload.gc.slot);
}

/*
   @PackPLC@ makes up a bogus GA for a PLC. Weight 0 implies that a PLC
   address follows instead of PE, slot.  */

//@cindex PackPLC

static void
PackPLC(addr)
StgPtr addr;
{
  Pack(0L);			/* weight */
  Pack((StgWord) addr);		/* address */
}

/*
   @PackOffset@ packs a special GA value that will be interpreted as an
   offset to a closure in the pack buffer.  This is used to avoid unfolding
   the graph structure into a tree.  */

static void
PackOffset(offset)
int offset;
{
1836
  /*
1837 1838 1839
  IF_PAR_DEBUG(pack,
	       belch("** Packing Offset %d at pack location %u",
		     offset, pack_locn));
1840
  */
1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871
  Pack(1L);			/* weight */
  Pack(0L);			/* pe */
  Pack(offset);		        /* slot/offset */
}
# endif  /* PAR */

//@node Unpacking routines, Aux fcts for packing, Low level packing routines, Graph packing
//@subsection Unpacking routines

/*
  This was formerly in the (now deceased) module Unpack.c

  Unpacking closures which have been exported to remote processors

  This module defines routines for unpacking closures in the parallel
  runtime system (GUM).

  In the case of GrAnSim, this module defines routines for *simulating* the
  unpacking of closures as it is done in the parallel runtime system.
*/

//@node GUM code, Local Definitions, Unpacking routines, Unpacking routines
//@subsubsection GUM code

#if defined(PAR) 

//@cindex InitPendingGABuffer
void
InitPendingGABuffer(size)
nat size; 
{
1872 1873 1874 1875 1876 1877 1878
  if (PendingGABuffer==(globalAddr *)NULL)
    PendingGABuffer = (globalAddr *) 
      stgMallocBytes(size*2*sizeof(globalAddr),
		     "InitPendingGABuffer");

  /* current location in the buffer */
  gaga = PendingGABuffer; 
1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893
}

/*
  @CommonUp@ commons up two closures which we have discovered to be
  variants of the same object.  One is made an indirection to the other.  */

//@cindex CommonUp
void
CommonUp(StgClosure *src, StgClosure *dst)
{
  StgBlockingQueueElement *bqe;

  ASSERT(src != (StgClosure *)NULL && dst != (StgClosure *)NULL);
  ASSERT(src != dst);

1894 1895
  IF_PAR_DEBUG(pack,
	       belch("*___ CommonUp %p (%s) --> %p (%s)",
1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915
		     src, info_type(src), dst, info_type(dst)));
  
  switch (get_itbl(src)->type) {
  case BLACKHOLE_BQ:
    bqe = ((StgBlockingQueue *)src)->blocking_queue;
    break;

  case FETCH_ME_BQ:
    bqe = ((StgFetchMeBlockingQueue *)src)->blocking_queue;
    break;
    
  case RBH:
    bqe = ((StgRBH *)src)->blocking_queue;
    break;
    
  case BLACKHOLE:
  case FETCH_ME:
    bqe = END_BQ_QUEUE;
    break;

1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930
    /* currently we also common up 2 CONSTRs; this should reduce heap 
     * consumption but also does more work; not sure whether it's worth doing 
     */ 
  case CONSTR:
  case CONSTR_1_0:
  case CONSTR_0_1:
  case CONSTR_2_0:
  case CONSTR_1_1:
  case CONSTR_0_2:
  case ARR_WORDS:
  case MUT_ARR_PTRS:
  case MUT_ARR_PTRS_FROZEN:
  case MUT_VAR:
    break;

1931 1932 1933 1934 1935 1936 1937 1938 1939 1940
  default:
    /* Don't common up anything else */
    return;
  }
  /* NB: this also awakens the blocking queue for src */
  UPD_IND(src, dst);
  // updateWithIndirection(src, dst);
  /*
    ASSERT(!IS_BIG_MOTHER(INFO_PTR(dst)));
    if (bqe != END_BQ_QUEUE)
1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098
    awakenBlockedQueue(bqe, src);
  */
}

/*
 * Common up the new closure with any existing closure having the same
 * GA
 */
//@cindex SetGAandCommonUp
static StgClosure *
SetGAandCommonUp(globalAddr *ga, StgClosure *closure, rtsBool hasGA)
{
  StgClosure *existing;
  StgInfoTable *ip, *oldip;
  globalAddr *newGA;

  if (!hasGA)
    return closure;

  ip = get_itbl(closure);
  if ((existing = GALAlookup(ga)) == NULL) {
    /* Just keep the new object */
    IF_PAR_DEBUG(pack,
		 belch("*<## Unpacking new GA ((%x, %d, %x))", 
		       ga->payload.gc.gtid, ga->payload.gc.slot, ga->weight));

    // make an entry binding closure to ga in the RemoteGA table
    newGA = setRemoteGA(closure, ga, rtsTrue);
    if (ip->type == FETCH_ME)
      ((StgFetchMe *)closure)->ga = newGA;
  } else {
    /* Two closures, one global name.  Someone loses */
    oldip = get_itbl(existing);
    if ((oldip->type == FETCH_ME || 
	 /* If we pack GAs for CONSTRs we have to check for them, too */
	 IS_BLACK_HOLE(existing)) &&
	ip->type != FETCH_ME) 
    {
      IF_PAR_DEBUG(pack,
		   belch("*<#- Unpacking old GA ((%x, %d, %x)); redirecting %p -> %p",
			 ga->payload.gc.gtid, ga->payload.gc.slot, ga->weight,
			 existing, closure));

      /* 
       * What we had wasn't worth keeping, so make the old closure an
       * indirection to the new closure (copying BQs if necessary) and
       * make sure that the old entry is not the preferred one for this
       * closure.
       */
      CommonUp(existing, closure);
      //GALAdeprecate(ga);
      /* now ga indirectly refers to the new closure */
      ASSERT(UNWIND_IND(GALAlookup(ga))==closure);
    } else {
      /*
       * Either we already had something worthwhile by this name or
       * the new thing is just another FetchMe.  However, the thing we
       * just unpacked has to be left as-is, or the child unpacking
       * code will fail.  Remember that the way pointer words are
       * filled in depends on the info pointers of the parents being
       * the same as when they were packed.
       */
      IF_PAR_DEBUG(pack,
		   belch("*<#@ Unpacking old GA ((%x, %d, %x)); keeping %p (%s) nuking unpacked %p (%s)", 
			 ga->payload.gc.gtid, ga->payload.gc.slot, ga->weight,
			 existing, info_type(existing), closure, info_type(closure)));

      closure = existing;
#if 0
      // HACK
      ty = get_itbl(closure)->type;
      if (ty == CONSTR ||
	  ty == CONSTR_1_0 ||
	  ty == CONSTR_0_1 ||
	  ty == CONSTR_2_0 ||
	  ty == CONSTR_1_1 ||
	  ty == CONSTR_0_2)
	CommonUp(closure, graph);
#endif
    }
    /* Pool the total weight in the stored ga */
    (void) addWeight(ga);
  }

  /* ToDo: check this assertion!!
     if we have unpacked a FETCH_ME, we have a GA, too 
  ASSERT(get_itbl(*closureP)->type!=FETCH_ME || 
	 looks_like_ga(((StgFetchMe *)*closureP)->ga));
  */
  /* Sort out the global address mapping */
  if (ip_THUNK(ip)){ 
    // || // (ip_THUNK(ip) && !ip_UNPOINTED(ip)) || 
    //(ip_MUTABLE(ip) && ip->type != FETCH_ME)) {
    /* Make up new GAs for single-copy closures */
    globalAddr *newGA = makeGlobal(closure, rtsTrue);
    
    // It's a new GA and therefore has the full weight
    ASSERT(newGA->weight==0);

    /* Create an old GA to new GA mapping */
    *gaga++ = *ga;
    splitWeight(gaga, newGA);
    /* inlined splitWeight; we know that newGALA has full weight 
    newGA->weight = gaga->weight = 1L << (BITS_IN(unsigned) - 1);    
    gaga->payload = newGA->payload;
    */
    ASSERT(gaga->weight == 1L << (BITS_IN(unsigned) - 1));
    gaga++;
  }
  return closure;
}

/*
  Copies a segment of the buffer, starting at @bufptr@, representing a closure
  into the heap at @graph@.
 */
//@cindex FillInClosure
static nat
FillInClosure(StgWord ***bufptrP, StgClosure *graph)
{
  StgInfoTable *ip;
  StgWord **bufptr = *bufptrP;
  nat ptrs, nonptrs, vhs, i, size;
  char str[80];

  ASSERT(LOOKS_LIKE_GHC_INFO(((StgClosure*)bufptr)->header.info));

  /*
   * Close your eyes.  You don't want to see where we're looking. You
   * can't get closure info until you've unpacked the variable header,
   * but you don't know how big it is until you've got closure info.
   * So...we trust that the closure in the buffer is organized the
   * same way as they will be in the heap...at least up through the
   * end of the variable header.
   */
  ip = get_closure_info((StgClosure *)bufptr, &size, &ptrs, &nonptrs, &vhs, str);
	  
  /* Make sure that nothing sans the fixed header is filled in
     The ga field of the FETCH_ME is filled in in SetGAandCommonUp */
  if (ip->type == FETCH_ME) {
    ASSERT(size>=MIN_UPD_SIZE);    // size of the FM in the heap
    ptrs = nonptrs = vhs = 0;      // i.e. only unpack FH from buffer
  }
  /* ToDo: check whether this is really needed */
  if (