25021c4a221eec31eb31c8f986bc41cb234a1936
[ghc-hetmet.git] / docs / rts / rts.verb
1 %
2 % (c) The OBFUSCATION-THROUGH-GRATUITOUS-PREPROCESSOR-ABUSE Project,
3 %     Glasgow University, 1990-1994
4 %
5
6 % TODO:
7 %
8 % o I think it would be worth making the connection with CPS explicit.
9 %   Now that we have explicit activation records (on the stack), we can
10 %   explain the whole system in terms of CPS and tail calls --- with the
11 %   one requirement that we carefuly distinguish stack-allocated objects
12 %   from heap-allocated objects.
13
14
15 % \documentstyle[preprint]{acmconf}
16 \documentclass[11pt]{article}
17 \oddsidemargin 0.1 in       %   Note that \oddsidemargin = \evensidemargin
18 \evensidemargin 0.1 in
19 \marginparwidth 0.85in    %   Narrow margins require narrower marginal notes
20 \marginparsep 0 in 
21 \sloppy
22
23 \newcommand{\note}[1]{{\em Note: #1}}
24 % DIMENSION OF TEXT:
25 \textheight 8.5 in
26 \textwidth 6.25 in
27
28 \topmargin 0 in
29 \headheight 0 in
30 \headsep .25 in
31
32
33 \setlength{\parskip}{0.15cm}
34 \setlength{\parsep}{0.15cm}
35 \setlength{\topsep}{0cm}        % Reduces space before and after verbatim,
36                                 % which is implemented using trivlist 
37 \setlength{\parindent}{0cm}
38
39 \renewcommand{\textfraction}{0.2}
40 \renewcommand{\floatpagefraction}{0.7}
41
42 \begin{document}
43
44 \newcommand{\ToDo}[1]{{{\bf ToDo:}\sl #1}}
45 \newcommand{\Arg}[1]{\mbox{${\tt arg}_{#1}$}}
46 \newcommand{\bottom}{bottom} % foo, can't remember the symbol name
47
48 \title{The STG runtime system (revised)}
49 \author{Simon Peyton Jones \\ Glasgow University and Oregon Graduate Institute \and
50 Alastair Reid \\ Yale University} 
51
52 \maketitle
53
54 \tableofcontents
55 \newpage
56
57 \section{Introduction}
58
59 This document describes the GHC/Hugs run-time system.  It serves as 
60 a Glasgow/Yale/Nottingham ``contract'' about what the RTS does.
61
62 \subsection{New features compared to GHC 2.04}
63
64 \begin{itemize}
65 \item The RTS supports mixed compiled/interpreted execution, so
66 that a program can consist of a mixture of GHC-compiled and Hugs-interpreted
67 code.
68
69 \item CAFs are only retained if they are
70 reachable.  Since they are referred to by implicit references buried
71 in code, this means that the garbage collector must traverse the whole
72 accessible code tree.  This feature eliminates a whole class of painful
73 space leaks.
74
75 \item A running thread has only one stack, which contains a mixture
76 of pointers and non-pointers.  Section~\ref{sect:stacks} describes how
77 we find out which is which.  (GHC has used two stacks for some while.
78 Using one stack instead of two reduces register pressure, reduces the
79 size of update frames, and eliminates
80 ``stack-stubbing'' instructions.)
81
82 \end{itemize} 
83
84 \subsection{Wish list}
85
86 Here's a list of things we'd like to support in the future.
87 \begin{itemize}
88 \item Interrupts, speculative computation.
89
90 \item
91 The SM could tune the size of the allocation arena, the number of
92 generations, etc taking into account residency, GC rate and page fault
93 rate.
94
95 \item
96 There should be no need to specify the amnount of stack/heap space to
97 allocate when you started a program - let it just take as much or as
98 little as it wants.  (It might be useful to be able to specify maximum
99 sizes and to be able to suggest an initial size.)
100
101 \item 
102 We could trigger a GC when all threads are blocked waiting for IO if
103 the allocation arena (or some of the generations) are nearly full.
104
105 \end{itemize}
106
107 \subsection{Configuration}
108
109 Some of the above features are expensive or less portable, so we
110 envision building a number of different configurations supporting
111 different subsets of the above features.
112
113 You can make the following choices:
114 \begin{itemize}
115 \item
116 Support for concurrency or parallelism.  There are four 
117 mutually-exclusive choices.
118
119 \begin{description}
120 \item[@SEQUENTIAL@] No concurrency or parallelism support.
121   This configuration might not support interrupt recovery.
122 \item[@CONCURRENT@]  Support for concurrency but not for parallelism.
123 \item[@CONCURRENT@+@GRANSIM@] Concurrency support and simulated parallelism.
124 \item[@CONCURRENT@+@PARALLEL@]     Concurrency support and real parallelism.
125 \end{description}
126
127 \item @PROFILING@ adds cost-centre profiling.
128
129 \item @TICKY@ gathers internal statistics (often known as ``ticky-ticky'' code).
130
131 \item @DEBUG@ does internal consistency checks.
132
133 \item Persistence. (well, not yet).
134
135 \item
136 Which garbage collector to use.  At the moment we
137 only anticipate one, however.
138 \end{itemize}
139
140 \subsection{Terminology}
141
142 \begin{itemize}
143
144 \item A {\em word} is (at least) 32 bits and can hold either a signed
145 or an unsigned int.
146
147 \item A {\em pointer} is (at least) 32 bits and big enough to hold a
148 function pointer or a data pointer.  
149
150 \item A {\em closure} is a (representation of) a value of a {\em pointed}
151  type.  It may be in HNF or it may be unevaluated --- in either case, you can
152  try to evaluate it again.
153
154 \item A {\em thunk} is a (representation of) a value of a {\em pointed}
155  type which is {\em not} in HNF.
156
157 \end{itemize}
158
159 Occasionally, a field of a data structure must hold either a word or a
160 pointer.  In such circumstances, it is {\em not safe} to assume that
161 words and pointers are the same size.
162
163 % Todo:
164 % More terminology to mention.
165 % unboxed, unpointed
166
167 There are a few other system invariants which need to be mentioned ---
168 though not necessarily here:
169
170 \begin{itemize}
171
172 \item The garbage collector never expands an object when it promotes
173 it to the old generation.  This is important because the GC avoids
174 performing heap overflow checks by assuming that the amount added to
175 the old generation is no bigger than the current new generation.
176
177 \end{itemize}
178
179
180 \section{The Scheduler}
181
182 The Scheduler is the heart of the run-time system.  A running program
183 consists of a single running thread, and a list of runnable and
184 blocked threads.  The running thread returns to the scheduler when any
185 of the following conditions arises:
186
187 \begin{itemize}
188 \item A heap check fails, and a garbage collection is required
189 \item Compiled code needs to switch to interpreted code, and vice
190 versa.
191 \item The thread becomes blocked.
192 \item The thread is preempted.
193 \end{itemize}
194
195 A running system has a global state, consisting of
196
197 \begin{itemize}
198 \item @Hp@, the current heap pointer, which points to the next
199 available address in the Heap.
200 \item @HpLim@, the heap limit pointer, which points to the end of the
201 heap.
202 \item The Thread Preemption Flag, which is set whenever the currently
203 running thread should be preempted at the next opportunity.
204 \end{itemize}
205
206 Each thread has a thread-local state, which consists of
207
208 \begin{itemize}
209 \item @TSO@, the Thread State Object for this thread.  This is a heap
210 object that is used to store the current thread state when the thread
211 is blocked or sleeping.
212 \item @Sp@, the current stack pointer.
213 \item @Su@, the current stack update frame pointer.  This register
214 points to the most recent update frame on the stack, and is used to
215 calculate the number of arguments available when entering a function.
216 \item @SpLim@, the stack limit pointer.  This points to the end of the
217 current stack chunk.
218 \item Several general purpose registers, used for passing arguments to
219 functions.
220 \end{itemize}
221
222 \noindent and various other bits of information used in specialised
223 circumstances, such as profiling and parallel execution.  These are
224 described in the appropriate sections.
225
226 The following is pseudo-code for the inner loop of the scheduler
227 itself.
228
229 @
230 while (threads_exist) {
231   // handle global problems: GC, parallelism, etc
232   if (need_gc) gc();  
233   if (external_message) service_message();
234   // deal with other urgent stuff
235
236   pick a runnable thread;
237   do {
238     switch (thread->whatNext) {
239       case (RunGHC  pc): status=runGHC(pc);  break;
240       case (RunHugs bc): status=runHugs(bc); break;
241     }
242     switch (status) {  // handle local problems
243       case (StackOverflow): enlargeStack; break;
244       case (Error e)      : error(thread,e); break;
245       case (ExitWith e)   : exit(e); break;
246       case (Yield)        : break;
247     }
248   } while (thread_runnable);
249 }
250 @
251
252 Optimisations to avoid excess trampolining from Hugs into itself.
253 How do we invoke GC, ccalls, etc.
254 General ccall (@ccall-GC@) and optimised ccall.
255
256 \section{Evaluation}
257
258 This section describes the framework in which compiled code evaluates
259 expressions.  Only at certain points will compiled code need to be
260 able to talk to the interpreted world; these are discussed in Section
261 \ref{sec:hugs-ghc-interaction}.
262
263 \subsection{Calling conventions}
264
265 \subsubsection{The call/return registers}
266
267 One of the problems in designing a virtual machine is that we want it
268 abstract away from tedious machine details but still reveal enough of
269 the underlying hardware that we can make sensible decisions about code
270 generation.  A major problem area is the use of registers in
271 call/return conventions.  On a machine with lots of registers, it's
272 cheaper to pass arguments and results in registers than to pass them
273 on the stack.  On a machine with very few registers, it's cheaper to
274 pass arguments and results on the stack than to use ``virtual
275 registers'' in memory.  We therefore use a hybrid system: the first
276 $n$ arguments or results are passed in registers; and the remaining
277 arguments or results are passed on the stack.  For register-poor
278 architectures, it is important that we allow $n=0$.
279
280 We'll label the arguments and results \Arg{1} \ldots \Arg{m} --- with
281 the understanding that \Arg{1} \ldots \Arg{n} are in registers and
282 \Arg{n+1} \ldots \Arg{m} are on top of the stack.
283
284 Note that the mapping of arguments \Arg{1} \ldots \Arg{n} to machine
285 registers depends on the {\em kinds} of the arguments.  For example,
286 if the first argument is a Float, we might pass it in a different
287 register from if it is an Int.  In fact, we might find that a given
288 architecture lets us pass varying numbers of arguments according to
289 their types.  For example, if a CPU has 2 Int registers and 2 Float
290 registers then we could pass between 2 and 4 arguments in machine
291 registers --- depending on whether they all have the same kind or they
292 have different kinds.
293
294 \subsubsection{Entering closures}
295
296 To evaluate a closure we jump to the entry code for the closure
297 passing a pointer to the closure in \Arg{1} so that the entry code can
298 access its environment.
299
300 \subsubsection{Function call}
301
302 The function-call mechanism is obviously crucial.  There are five different
303 cases to consider:
304 \begin{enumerate}
305
306 \item {\em Known combinator (function with no free variables) and enough arguments.}  
307
308 A fast call can be made: push excess arguments onto stack and jump to
309 function's {\em fast entry point} passing arguments in \Arg{1} \ldots
310 \Arg{m}.  
311
312 The {\em fast entry point} is only called with exactly the right
313 number of arguments (in \Arg{1} \ldots \Arg{m}) so it can instantly
314 start doing useful work without first testing whether it has enough
315 registers or having to pop them off the stack first.
316
317 \item {\em Known combinator and insufficient arguments.}
318
319 A slow call can be made: push all arguments onto stack and jump to
320 function's {\em slow entry point}.
321
322 Any unpointed arguments which are pushed on the stack must be tagged.
323 This means pushing an extra word on the stack below the unpointed
324 words, containing the number of unpointed words above it.
325
326 %Todo: forward ref about tagging?
327 %Todo: picture?
328
329 The {\em slow entry point} might be called with insufficient arguments
330 and so it must test whether there are enough arguments on the stack.
331 This {\em argument satisfaction check} consists of checking that
332 @Su-Sp@ is big enough to hold all the arguments (including any tags).
333
334 \begin{itemize} 
335
336 \item If the argument satisfaction check fails, it is because there is
337 one or more update frames on the stack before the rest of the
338 arguments that the function needs.  In this case, we construct a PAP
339 (partial application, section~\ref{sect:PAP}) containing the arguments
340 which are on the stack.  The PAP construction code will return to the
341 update frame with the address of the PAP in \Arg{1}.
342
343 \item If the argument satisfaction check succeeds, we jump to the fast
344 entry point with the arguments in \Arg{1} \ldots \Arg{arity}.
345
346 If the fast entry point expects to receive some of \Arg{i} on the
347 stack, we can reduce the amount of movement required by making the
348 stack layout for the fast entry point look like the stack layout for
349 the slow entry point.  Since the slow entry point is entered with the
350 first argument on the top of the stack and with tags in front of any
351 unpointed arguments, this means that if \Arg{i} is unpointed, there
352 should be space below it for a tag and that the highest numbered
353 argument should be passed on the top of the stack.
354
355 We usually arrange that the fast entry point is placed immediately
356 after the slow entry point --- so we can just ``fall through'' to the
357 fast entry point without performing a jump.
358
359 \end{itemize}
360
361
362 \item {\em Known function closure (function with free variables) and enough arguments.}
363
364 A fast call can be made: push excess arguments onto stack and jump to
365 function's {\em fast entry point} passing a pointer to closure in
366 \Arg{1} and arguments in \Arg{2} \ldots \Arg{m+1}.
367
368 Like the fast entry point for a combinator, the fast entry point for a
369 closure is only called with appropriate values in \Arg{1} \ldots
370 \Arg{m+1} so we can start work straight away.  The pointer to the
371 closure is used to access the free variables of the closure.
372
373
374 \item {\em Known function closure and insufficient arguments.}
375
376 A slow call can be made: push all arguments onto stack and jump to the
377 closure's slow entry point passing a pointer to the closure in \Arg{1}.
378
379 Again, the slow entry point performs an argument satisfaction check
380 and either builds a PAP or pops the arguments off the stack into
381 \Arg{2} \ldots \Arg{m+1} and jumps to the fast entry point.
382
383
384 \item {\em Unknown function closure or thunk.}
385
386 Sometimes, the function being called is not statically identifiable.
387 Consider, for example, the @compose@ function:
388 @
389   compose f g x = f (g x)
390 @
391 Since @f@ and @g@ are passed as arguments to @compose@, the latter has
392 to make a heap call.  In a heap call the arguments are pushed onto the
393 stack, and the closure bound to the function is entered.  In the
394 example, a thunk for @(g x)@ will be allocated, (a pointer to it)
395 pushed on the stack, and the closure bound to @f@ will be
396 entered. That is, we will jump to @f@s entry point passing @f@ in
397 \Arg{1}.  If \Arg{1} is passed on the stack, it is pushed on top of
398 the thunk for @(g x)@.
399
400 The {\em entry code} for an updateable thunk (which must have arity 0)
401 pushes an update frame on the stack and starts executing the body of
402 the closure --- using \Arg{1} to access any free variables.  This is
403 described in more detail in section~\ref{sect:data-updates}.
404
405 The {\em entry code} for a non-updateable closure is just the
406 closure's slow entry point.
407
408 \end{enumerate}
409
410 In addition to the above considerations, if there are \emph{too many}
411 arguments then the extra arguments are simply pushed on the stack with
412 appropriate tags.
413
414 To summarise, a closure's standard (slow) entry point performs the following:
415 \begin{description}
416 \item[Argument satisfaction check.] (function closure only)
417 \item[Stack overflow check.]
418 \item[Heap overflow check.]
419 \item[Copy free variables out of closure.] %Todo: why?
420 \item[Eager black holing.] (updateable thunk only) %Todo: forward ref.
421 \item[Push update frame.]
422 \item[Evaluate body of closure.]
423 \end{description}
424
425
426 \subsection{Case expressions and return conventions}
427 \label{sect:return-conventions}
428
429 The {\em evaluation} of a thunk is always initiated by
430 a @case@ expression.  For example:
431 @
432   case x of (a,b) -> E
433 @
434
435 The code for a @case@ expression looks like this:
436
437 \begin{itemize}
438 \item Push the free variables of the branches on the stack (fv(@E@) in
439 this case).
440 \item  Push a \emph{return address} on the stack.
441 \item  Evaluate the scrutinee (@x@ in this case).
442 \end{itemize}
443
444 Once evaluation of the scrutinee is complete, execution resumes at the
445 return address, which points to the code for the expression @E@.
446
447 When execution resumes at the return point, there must be some {\em
448 return convention} that defines where the components of the pair, @a@
449 and @b@, can be found.  The return convention varies according to the
450 type of the scrutinee @x@:
451
452 \begin{itemize}
453
454 \item 
455
456 (A space for) the return address is left on the top of the stack.
457 Leaving the return address on the stack ensures that the top of the
458 stack contains a valid activation record
459 (section~\ref{sect:activation-records}) --- should a garbage collection
460 be required.
461
462 \item If @x@ has a pointed type (e.g.~a data constructor or a function),
463 a pointer to @x@ is returned in \Arg{1}.
464
465 \ToDo{Warn that components of E should be extracted as soon as
466 possible to avoid a space leak.}
467
468 \item If @x@ is an unpointed type (e.g.~@Int#@ or @Float#@), @x@ is
469 returned in \Arg{1}
470
471 \item If @x@ is an unpointed tuple constructor, the components of @x@
472 are returned in \Arg{1} \ldots \Arg{n} but no object is constructed in
473 the heap.  Unboxed tuple constructors are useful for functions which
474 want to return multiple values such as those used in an (explicitly
475 encoded) state monad:
476
477 \ToDo{Move stuff about unboxed tuples to a separate section}
478
479 @
480 data unpointed AAndState a = AnS a State
481 type S a = State -> AAndState a
482
483 bindS m k s0 = case m s0 of { AnS s1 a -> k s1 a }
484 returnS a s  = AnS a s
485 @
486
487 Note that unboxed datatypes can only have one constructor and that
488 thunks never have unboxed types --- so we'll never try to update an
489 unboxed constructor.  Unboxed tuples are \emph{never} built on the
490 heap.
491
492 When passing an unboxed tuple to a function, the components are
493 flattened out and passed in \Arg{1} \ldots \Arg{n} as usual.
494
495 \end{itemize}
496
497 \subsection{Vectored Returns}
498
499 Many algebraic data types have more than one constructor.  For
500 example, the @Maybe@ type is defined like this:
501 @
502   data Maybe a = Nothing | Just a
503 @
504 How does the return convention encode which of the two constructors is
505 being returned?  A @case@ expression scrutinising a value of @Maybe@
506 type would look like this: 
507 @
508   case E of 
509     Nothing -> ...
510     Just a  -> ...
511 @
512 Rather than pushing a return address before evaluating the scrutinee,
513 @E@, the @case@ expression pushes (a pointer to) a {\em return
514 vector}, a static table consisting of two code pointers: one for the
515 @Just@ alternative, and one for the @Nothing@ alternative.  
516
517 \begin{itemize}
518
519 \item
520
521 The constructor @Nothing@ returns by jumping to the first item in the
522 return vector with a pointer to a (statically built) Nothing closure
523 in \Arg{1}.  
524
525 It might seem that we could avoid loading \Arg{1} in this case since the
526 first item in the return vector will know that @Nothing@ was returned
527 (and can easily access the Nothing closure in the (unlikely) event
528 that it needs it.  The only reason we load \Arg{1} is in case we have to
529 perform an update (section~\ref{sect:data-updates}).
530
531 \item 
532
533 The constructor @Just@ returns by jumping to the second element of the
534 return vector with a pointer to the closure in \Arg{1}.  
535
536 \end{itemize}
537
538 In this way no test need be made to see which constructor returns;
539 instead, execution resumes immediately in the appropriate branch of
540 the @case@.
541
542 \subsection{Direct Returns}
543
544 When a datatype has a large number of constructors, it may be
545 inappropriate to use vectored returns.  The vector tables may be
546 large and sparse, and it may be better to identify the constructor
547 using a test-and-branch sequence on the tag.  For this reason, we
548 provide an alternative return convention, called a \emph{direct
549 return}.
550
551 In a direct return, the return address pushed on the stack really is a
552 code pointer.  The returning code loads a pointer to the closure being
553 returned in \Arg{1} as usual, and also loads the tag into \Arg{2}.
554 The code at the return address will test the tag and jump to the
555 appropriate code for the case branch.
556
557 The choice of whether to use a vectored return or a direct return is
558 made on a type-by-type basis --- up to a certain maximum number of
559 constructors imposed by the update mechanism
560 (section~\ref{sect:data-updates}).
561
562 Single-constructor data types also use direct returns, although in
563 that case there is no need to return a tag in \Arg{2}.
564
565 \ToDo{Say whether we pop the return address before returning}
566
567 \ToDo{Stack stubbing?}
568
569 \subsection{Updates}
570 \label{sect:data-updates}
571
572 The entry code for an updatable thunk (which must also be of arity 0):
573
574 \begin{itemize}
575 \item copies the free variables out of the thunk into registers or
576   onto the stack.
577 \item pushes an {\em update frame} onto the stack.
578
579 An update frame is a small activation record consisting of
580 \begin{center}
581 \begin{tabular}{|l|l|l|}
582 \hline
583 {\em Fixed header} & {\em Update Frame link} & {\em Updatee} \\
584 \hline
585 \end{tabular}
586 \end{center}
587
588 \note{In the semantics part of the STG paper (section 5.6), an update
589 frame consists of everything down to the last update frame on the
590 stack.  This would make sense too --- and would fit in nicely with
591 what we're going to do when we add support for speculative
592 evaluation.}
593 \ToDo{I think update frames contain cost centres sometimes}
594
595 \item 
596 If we are doing ``eager blackholing,'' we then overwrite the thunk
597 with a black hole.  Otherwise, we leave it to the garbage collector to
598 black hole the thunk.
599
600 \item 
601 Start evaluating the body of the expression.
602
603 \end{itemize}
604
605 When the expression finishes evaluation, it will enter the update
606 frame on the top of the stack.  Since the returner doesn't know
607 whether it is entering a normal return address/vector or an update
608 frame, we follow exactly the same conventions as return addresses and
609 return vectors.  That is, on entering the update frame:
610
611 \begin{itemize} 
612 \item The value of the thunk is in \Arg{1}.  (Recall that only thunks
613 are updateable and that thunks return just one value.)
614
615 \item If the data type is a direct-return type rather than a
616 vectored-return type, then the tag is in \Arg{2}.
617
618 \item The update frame is still on the stack.
619 \end{itemize}
620
621 We can safely share a single statically-compiled update function
622 between all types.  However, the code must be able to handle both
623 vectored and direct-return datatypes.  This is done by arranging that
624 the update code looks like this:
625
626 @
627                 |       ^       |
628                 | return vector |
629                 |---------------|
630                 |  fixed-size   |
631                 |  info table   |
632                 |---------------|  <- update code pointer
633                 |  update code  |
634                 |       v       |
635 @
636
637 Each entry in the return vector (which is large enough to cover the
638 largest vectored-return type) points to the update code.
639
640 The update code:
641 \begin{itemize}
642 \item overwrites the {\em updatee} with an indirection to \Arg{1};
643 \item loads @Su@ from the Update Frame link;
644 \item removes the update frame from the stack; and 
645 \item enters \Arg{1}.
646 \end{itemize}
647
648 We enter \Arg{1} again, having probably just come from there, because
649 it knows whether to perform a direct or vectored return.  This could
650 be optimised by compiling special update code for each slot in the
651 return vector, which performs the correct return.
652
653 \subsection{Semi-tagging}
654 \label{sect:semi-tagging}
655
656 When a @case@ expression evaluates a variable that might be bound
657 to a thunk it is often the case that the scrutinee is already evaluated.
658 In this case we have paid the penalty of (a) pushing the return address (or
659 return vector address) on the stack, (b) jumping through the info pointer
660 of the scrutinee, and (c) returning by an indirect jump through the
661 return address on the stack.
662
663 If we knew that the scrutinee was already evaluated we could generate
664 (better) code which simply jumps to the appropriate branch of the @case@
665 with a pointer to the scrutinee in \Arg{1}.
666
667 An obvious idea, therefore, is to test dynamically whether the heap
668 closure is a value (using the tag in the info table).  If not, we
669 enter the closure as usual; if so, we jump straight to the appropriate
670 alternative.  Here, for example, is pseudo-code for the expression
671 @(case x of { (a,_,c) -> E }@:
672 @
673       \Arg{1} = <pointer to x>;
674       tag = \Arg{1}->entry->tag;
675       if (isWHNF(tag)) {
676           Sp--;  \\ insert space for return address
677           goto ret;
678       }
679       push(ret);           
680       goto \Arg{1}->entry;
681       
682       <info table for return address goes here>
683 ret:  a = \Arg{1}->data1; \\ suck out a and c to avoid space leak
684       c = \Arg{1}->data3;
685       <code for E2>
686 @
687 and here is the code for the expression @(case x of { [] -> E1; x:xs -> E2 }@:
688 @
689       \Arg{1} = <pointer to x>;
690       tag = \Arg{1}->entry->tag;
691       if (isWHNF(tag)) {
692           Sp--;  \\ insert space for return address
693           goto retvec[tag];
694       }
695       push(retinfo);          
696       goto \Arg{1}->entry;
697       
698       .addr ret2
699       .addr ret1
700 retvec:           \\ reversed return vector
701       <return info table for case goes here>
702 retinfo:
703       panic("Direct return into vectored case");
704       
705 ret1: <code for E1>
706
707 ret2: x  = \Arg{1}->head;
708       xs = \Arg{1}->tail;
709       <code for E2>
710 @
711 There is an obvious cost in compiled code size (but none in the size
712 of the bytecodes).  There is also a cost in execution time if we enter
713 more thunks than data constructors.
714
715 Both the direct and vectored returns are easily modified to chase chains
716 of indirections too.  In the vectored case, this is most easily done by
717 making sure that @IND = TAG_1 - 1@, and adding an extra field to every
718 return vector.  In the above example, the indirection code would be
719 @
720 ind:  \Arg{1} = \Arg{1}->next;
721       goto ind_loop;
722 @
723 where @ind_loop@ is the second line of code.
724
725 Note that we have to leave space for a return address since the return
726 address expects to find one.  If the body of the expression requires a
727 heap check, we will actually have to write the return address before
728 entering the garbage collector.
729
730
731 \subsection{Heap and Stack Checks}
732
733 \note{I reckon these deserve a subsection of their own}
734
735 Don't move heap pointer before success occurs.
736 Talk about how stack check looks ahead into the branches of case expressions.
737
738 \subsection{Handling interrupts/signals}
739
740 @
741 May have to keep C stack pointer in register to placate OS?
742 May have to revert black holes - ouch!
743 @
744
745 \section{Switching Worlds}
746 \label{sect:switching-worlds}
747
748 Because this is a combined compiled/interpreted system, the
749 interpreter will sometimes encounter compiled code, and vice-versa.
750
751 All world-switches go via the scheduler, ensuring that the world is in
752 a known state ready to enter either compiled code or the interpreter.
753 When a thread is run from the scheduler, the @whatNext@ field is
754 checked to find out how to execute the thread.
755
756 \begin{itemize}
757 \item If @whatNext@ is set to @RunGHC@, we load up the required
758 registers from the TSO and jump to the address at the top of the user
759 stack.
760 \item If @whatNext@ is set to @RunHugs@, we execute the byte-code
761 object pointed to by the top word of the stack.
762 \end{itemize}
763
764 Sometimes instead of returning to the address at the top of the stack,
765 we need to enter a closure instead.  This is achieved by pushing a
766 pointer to the closure to be entered on the stack, followed by a
767 pointer to a canned code sequence called @ghc_entertop@, or the dual
768 byte-code object @hugs_entertop@.  Both code sequences do the following:
769
770 \begin{itemize}
771 \item pop the top word (either @ghc_entertop@ or @hugs_entertop@) from
772 the stack.
773 \item pop the next word off the stack and enter it.
774 \end{itemize}
775
776 There are six cases we need to consider:
777
778 \begin{enumerate}
779 \item A GHC thread enters a Hugs-built closure.
780 \item A GHC thread calls a Hugs-compiled function.
781 \item A GHC thread returns to a Hugs-compiled return address.
782 \item A Hugs thread enters a GHC-built closure.
783 \item A Hugs thread calls a GHC-compiled function.
784 \item A Hugs thread returns to a Hugs-compiled return address.
785 \end{enumerate}
786
787 We now examine the various cases one by one and describe how the
788 switch happens in each situation.
789
790 \subsection{A GHC thread enters a Hugs-built closure}
791
792 All Hugs-built closures look like this:
793
794 \begin{center}
795 \begin{tabular}{|l|l|}
796 \hline
797 \emph{Hugs} & \emph{Hugs-specific payload} \\
798 \hline 
799 \end{tabular}
800 \end{center}
801
802 \noindent where \emph{Hugs} is a pointer to a small statically
803 compiled-piece of code that does the following:
804
805 \begin{itemize}
806 \item Push the address of this thunk on the stack.
807 \item Push @hugs_entertop@ on the stack.
808 \item Save the current state of the thread in the TSO.
809 \item Return to the scheduler, with @whatNext@ set to @RunHugs@.
810 \end{itemize}
811
812 \ToDo{What about static thunks?  If all code lives on the heap, we'll
813 need an extra level of indirection for GHC references to Hugs
814 closures.}
815
816 \subsection{A GHC thread calls a Hugs-compiled function}
817
818 In order to call the fast entry point for a function, GHC needs arity
819 information from the defining module's interface file.  Hugs doesn't
820 supply this information, so GHC will always call the slow entry point
821 for functions in Hugs-compiled modules.
822
823 When a GHC module is linked into a running system, the calls to
824 external Hugs-compiled functions will be resolved to point to
825 dynamically-generated code that does the following:
826
827 \begin{itemize}
828 \item Push a pointer to the Hugs byte code object for the function on
829 the stack.
830 \item Push @hugs_entertop@ on the stack.
831 \item Save the current thread state in the TSO.
832 \item Return to the scheduler with @whatNext@ set to @RunHugs@
833 \end{itemize}
834
835 Ok, but how does Hugs find the byte code object for the function?
836 These live on the heap, and can therefore move around.  One solution
837 is to use a jump table, where each element in the table has two
838 elements:
839
840 \begin{itemize}
841 \item A call instruction pointing to the code fragment above.
842 \item A pointer to the byte-code object for the function.
843 \end{itemize}
844
845 When GHC jumps to the address in the jump table, the call takes it to
846 the statically-compiled code fragment, leaving a pointer to a pointer
847 to the byte-code object on the C stack, which can then be retrieved.
848
849 \subsection{A GHC thread returns to a Hugs-compiled return address}
850
851 When Hugs pushes return addresses on the stack, they look like this:
852
853 @
854         |               |
855         |_______________|
856         |               |  -----> bytecode object
857         |_______________|
858         |               |  _____
859         |_______________|       | 
860                                 |       _____
861                                 |       |    | Info Table
862                                 |       |    | 
863                                 |_____\ |____| hugs_return
864                                       / .    .
865                                         .    . Code
866                                         .    .
867 @
868
869 If GHC is returning, it will return to the address at the top of the
870 stack.  This address a pointer to a statically compiled code fragment
871 called @hugs_return@, which:
872
873 \begin{itemize}
874 \item pops the return address off the user stack.
875 \item saves the thread state in the TSO
876 \item returns to the scheduler with @whatNext@ set to @RunHugs@.
877 \end{itemize}
878
879 \subsection{A Hugs thread enters a GHC-compiled closure}
880
881 When Hugs is called on to enter a GHC closure (these are recognisable
882 by the lack of a \emph{Hugs} pointer at the front), the following
883 sequence of instructions is executed:
884
885 \begin{itemize}
886 \item Push the address of the thunk on the stack.
887 \item Push @ghc_entertop@ on the stack.
888 \item Save the current state of the thread in the TSO.
889 \item Return to the scheduler, with the @whatNext@ field set to
890 @RunGHC@.
891 \end{itemize}
892
893 \subsection{A Hugs thread calls a GHC-compiled function}
894
895 Hugs never calls GHC-functions directly, it only enters closures
896 (which point to the slow entry point for the function).  Hence in this
897 case, we just push the arguments on the stack and proceed as above.
898
899 \subsection{A Hugs thread returns to a GHC-compiled return address}
900
901 The return address at the top of the stack is recognisable as a
902 GHC-return address by virtue of not being @hugs_return@.  In this
903 case, hugs recognises that it needs to do a world-switch and performs
904 the following sequence:
905
906 \begin{itemize}
907 \item save the state of the thread in the TSO.
908 \item return to the scheduler, setting @whatNext@ to @RunGHC@.
909 \end{itemize}
910
911 \section{Heap objects}
912 \label{sect:fixed-header}
913
914 \ToDo{Fix this picture}
915
916 \begin{figure}
917 \begin{center}
918 \input{closure}
919 \end{center}
920 \caption{A closure}
921 \label{fig:closure}
922 \end{figure}
923
924 Every {\em heap object}, or {\em closure} is a contiguous block
925 of memory, consisting of a fixed-format {\em header} followed
926 by zero or more {\em data words}.
927 The header consists of
928 the following fields:
929 \begin{itemize}
930 \item A one-word {\em info pointer}, which points to
931 the object's static {\em info table}.
932 \item Zero or more {\em admin words} that support
933 \begin{itemize}
934 \item Profiling (notably a {\em cost centre} word).
935   \note{We could possibly omit the cost centre word from some 
936   administrative objects.}
937 \item Parallelism (e.g. GranSim keeps the object's global address here,
938 though GUM keeps a separate hash table).
939 \item Statistics (e.g. a word to track how many times a thunk is entered.).
940
941 We add a Ticky word to the fixed-header part of closures.  This is
942 used to record indicate if a closure has been updated but not yet
943 entered. It is set when the closure is updated and cleared when
944 subsequently entered.
945
946 NB: It is {\em not} an ``entry count'', it is an
947 ``entries-after-update count.''  The commoning up of @CONST@,
948 @CHARLIKE@ and @INTLIKE@ closures is turned off(?) if this is
949 required. This has only been done for 2s collection.
950
951
952
953 \end{itemize}
954 \end{itemize}
955 Most of the RTS is completely insensitive to the number of admin words.
956 The total size of the fixed header is @FIXED_HS@.
957
958 Many heap objects contain fields allowing them to be inserted onto lists
959 during evaluation or during garbage collection. The lists required by
960 the evaluator and storage manager are as follows.
961
962 \begin{itemize}
963 \item 2 lists of threads: runnable threads and sleeping threads.
964
965 \item The {\em static object list} is a list of all statically
966 allocated objects which might contain pointers into the heap.
967 (Section~\ref{sect:static-objects}.)
968
969 \item The {\em updated thunk list} is a list of all thunks in the old
970 generation which have been updated with an indirection.  
971 (Section~\ref{sect:IND_OLDGEN}.)
972
973 \item The {\em mutables list} is a list of all other objects in the
974 old generation which might contain pointers into the new generation.
975 Most of the object on this list are ``mutable.''
976 (Section~\ref{sect:mutables}.)
977
978 \item The {\em Foreign Object list} is a list of all foreign objects
979  which have not yet been deallocated. (Section~\ref{sect:FOREIGN}.)
980
981 \item The {\em Spark pool} is a doubly(?) linked list of Spark objects
982 maintained by the parallel system.  (Section~\ref{sect:SPARK}.)
983
984 \item The {\em Blocked Fetch list} (or
985 lists?). (Section~\ref{sect:BLOCKED_FETCH}.)
986
987 \item For each thread, there is a list of all update frames on the
988 stack.  (Section~\ref{sect:data-updates}.)
989
990
991 \end{itemize}
992
993 \ToDo{The links for these fields are usually inserted immediately
994 after the fixed header except ...}
995
996 \subsection{Info Tables}
997
998 An {\em info table} is a contiguous block of memory, {\em laid out
999 backwards}.  That is, the first field in the list that follows
1000 occupies the highest memory address, and the successive fields occupy
1001 successive decreasing memory addresses.
1002
1003 \begin{center}
1004 \begin{tabular}{|c|}
1005    \hline Parallelism Info 
1006 \\ \hline Profile Info 
1007 \\ \hline Debug Info 
1008 \\ \hline Tag/bytecode pointer
1009 \\ \hline Static reference table 
1010 \\ \hline Storage manager layout info
1011 \\ \hline Closure type 
1012 \\ \hline entry code \ldots
1013 \\ \hline
1014 \end{tabular}
1015 \end{center}
1016 An info table has the following contents (working backwards in memory
1017 addresses):
1018 \begin{itemize}
1019 \item The {\em entry code} for the closure.
1020 This code appears literally as the (large) last entry in the
1021 info table, immediately preceded by the rest of the info table.
1022 An {\em info pointer} always points to the first byte of the entry code.
1023
1024 \item A one-word {\em closure type field}, @INFO_TYPE@, identifies what kind
1025 of closure the object is.  The various types of closure are described
1026 in Section~\ref{sect:closures}.
1027 In some configurations, some useful properties of 
1028 closures (is it a HNF?  can it be sparked?)
1029 are represented as high-order bits so they can be tested quickly.
1030
1031 \item A single pointer or word --- the {\em storage manager info field},
1032 @INFO_SM@, contains auxiliary information describing the closure's
1033 precise layout, for the benefit of the garbage collector and the code
1034 that stuffs graph into packets for transmission over the network.
1035
1036 \item A one-pointer {\em Static Reference Table (SRT) pointer}, @INFO_SRT@, points to
1037 a table which enables the garbage collector to identify all accessible
1038 code and CAFs.  They are fully described in Section~\ref{sect:srt}.
1039
1040 \item A one-pointer {\em tag/bytecode-pointer} field, @INFO_TAG@ or @INFO_BC@.  
1041 For data constructors this field contains the constructor tag, in the
1042 range $0..n-1$ where $n$ is the number of constructors.
1043
1044 For other objects that can be entered this field points to the byte
1045 codes for the object.  For the constructor case you can think of the
1046 tag as the name of a a suitable bytecode sequence but it can also be used to
1047 implement semi-tagging (section~\ref{sect:semi-tagging}).
1048
1049 One awkward question (which may not belong here) is ``how does the
1050 bytecode interpreter know whether to do a vectored return?''  The
1051 answer is it examines the @INFO_TYPE@ field of the return address:
1052 @RET_VEC_@$sz$ requires a vectored return and @RET_@$sz$ requires a
1053 direct return.
1054
1055 \item {\em Profiling info\/}
1056
1057 Closure category records are attached to the info table of the
1058 closure. They are declared with the info table. We put pointers to
1059 these ClCat things in info tables.  We need these ClCat things because
1060 they are mutable, whereas info tables are immutable.  Hashing will map
1061 similar categories to the same hash value allowing statistics to be
1062 grouped by closure category.
1063
1064 Cost Centres and Closure Categories are hashed to provide indexes
1065 against which arbitrary information can be stored. These indexes are
1066 memoised in the appropriate cost centre or category record and
1067 subsequent hashes avoided by the index routine (it simply returns the
1068 memoised index).
1069
1070 There are different features which can be hashed allowing information
1071 to be stored for different groupings. Cost centres have the cost
1072 centre recorded (using the pointer), module and group. Closure
1073 categories have the closure description and the type
1074 description. Records with the same feature will be hashed to the same
1075 index value.
1076
1077 The initialisation routines, @init_index_<feature>@, allocate a hash
1078 table in which the cost centre / category records are stored. The
1079 lower bound for the table size is taken from @max_<feature>_no@. They
1080 return the actual table size used (the next power of 2). Unused
1081 locations in the hash table are indicated by a 0 entry. Successive
1082 @init_index_<feature>@ calls just return the actual table size.
1083
1084 Calls to @index_<feature>@ will insert the cost centre / category
1085 record in the @<feature>@ hash table, if not already inserted. The hash
1086 index is memoised in the record and returned. 
1087
1088 CURRENTLY ONLY ONE MEMOISATION SLOT IS AVILABLE IN EACH RECORD SO
1089 HASHING CAN ONLY BE DONE ON ONE FEATURE FOR EACH RECORD. This can be
1090 easily relaxed at the expense of extra memoisation space or continued
1091 rehashing.
1092
1093 The initialisation routines must be called before initialisation of
1094 the stacks and heap as they require to allocate storage. It is also
1095 expected that the caller may want to allocate additional storage in
1096 which to store profiling information based on the return table size
1097 value(s).
1098
1099 \begin{center}
1100 \begin{tabular}{|l|}
1101    \hline Hash Index
1102 \\ \hline Selected
1103 \\ \hline Kind
1104 \\ \hline Description String
1105 \\ \hline Type String
1106 \\ \hline
1107 \end{tabular}
1108 \end{center}
1109
1110 \begin{description}
1111 \item[Hash Index] Memoised copy
1112 \item[Selected] 
1113   Is this category selected (-1 == not memoised, selected? 0 or 1)
1114 \item[Kind]
1115 One of the following values (defined in CostCentre.lh):
1116
1117 \begin{description}
1118 \item[@CON_K@]
1119 A constructor.
1120 \item[@FN_K@]
1121 A literal function.
1122 \item[@PAP_K@]
1123 A partial application.
1124 \item[@THK_K@]
1125 A thunk, or suspension.
1126 \item[@BH_K@]
1127 A black hole.
1128 \item[@ARR_K@]
1129 An array.
1130 \item[@ForeignObj_K@]
1131 A Foreign object (non-Haskell heap resident).
1132 \item[@SPT_K@]
1133 The Stable Pointer table.  (There should only be one of these but it
1134 represents a form of weak space leak since it can't shrink to meet
1135 non-demand so it may be worth watching separately? ADR)
1136 \item[@INTERNAL_KIND@]
1137 Something internal to the runtime system.
1138 \end{description}
1139
1140
1141 \item[Description] Source derived string detailing closure description.
1142 \item[Type] Source derived string detailing closure type.
1143 \end{description}
1144
1145 \item {\em Parallelism info\/}
1146 \ToDo{}
1147
1148 \item {\em Debugging info\/}
1149 \ToDo{}
1150
1151 \end{itemize}
1152
1153
1154
1155 \section{Kinds of Heap Object}
1156 \label{sect:closures}
1157
1158 Heap objects can be classified in several ways, but one useful one is
1159 this:
1160 \begin{itemize}
1161 \item 
1162 {\em Static closures} occupy fixed, statically-allocated memory
1163 locations, with globally known addresses.
1164
1165 \item 
1166 {\em Dynamic closures} are individually allocated in the heap.
1167
1168 \item 
1169 {\em Stack closures} are closures allocated within a thread's stack
1170 (which is itself a heap object).  Unlike other closures, there are
1171 never any pointers to stack closures.  Stack closures are discussed in
1172 Section~\ref{sect:stacks}.
1173
1174 \end{itemize}
1175 A second useful classification is this:
1176 \begin{itemize}
1177 \item 
1178 {\em Executive closures}, such as thunks and data constructors,
1179 participate directly in a program's execution.  They can be subdivided into
1180 two kinds of objects according to their type:
1181 \begin{itemize}
1182 \item 
1183 {\em Pointed objects}, represent values of a {\em pointed} type
1184 (<.pointed types launchbury.>) --i.e.~a type that includes $\bottom$ such as @Int@ or @Int# -> Int#@.
1185
1186 \item {\em Unpointed objects}, represent values of a {\em unpointed} type --i.e.~a type that does not include $\bottom$ such as @Int#@ or @Array#@.
1187
1188 \item {\em Activation frames}, represent ``continuations''.  They are
1189 always stored on the stack and are never pointed to by heap objects or
1190 passed as arguments.  \note{It's not clear if this will still be true
1191 once we support speculative evaluation.}
1192
1193 \end{itemize}
1194
1195 \item {\em Administrative closures}, such as stack objects and thread
1196 state objects, do not represent values in the original program.
1197 \end{itemize}
1198
1199 Only pointed objects can be entered.  All pointed objects share a
1200 common header format: the ``pointed header''; while all unpointed
1201 objects share a common header format: the ``unpointed header''.
1202 \ToDo{Describe the difference and update the diagrams to mention
1203 an appropriate header type.}
1204
1205 This section enumerates all the kinds of heap objects in the system.
1206 Each is identified by a distinct @INFO_TYPE@ tag in its info table.
1207
1208 \ToDo{Check this table very carefully}
1209
1210 \begin{tabular}{|l|l|l|l|l|l|l|l|l|l|l|}
1211 \hline
1212
1213 closure kind          & HNF & UPD & NS & STA & THU & MUT & UPT & BH & IND & Section \\
1214
1215 \hline                                                              
1216 {\em Pointed} \\ 
1217 \hline 
1218
1219 @CONSTR@              & 1   &     & 1  &     &     &     &     &    &     & \ref{sect:CONSTR}    \\
1220 @CONSTR_STATIC@       & 1   &     & 1  & 1   &     &     &     &    &     & \ref{sect:CONSTR}    \\
1221 @CONSTR_STATIC_NOCAF@ & 1   &     & 1  & 1   &     &     &     &    &     & \ref{sect:CONSTR}    \\
1222                                                                                                  
1223 @FUN@                 & 1   &     & ?  &     &     &     &     &    &     & \ref{sect:FUN}       \\
1224 @FUN_STATIC@          & 1   &     & ?  & 1   &     &     &     &    &     & \ref{sect:FUN}       \\
1225                                                                                                  
1226 @THUNK@               & 1   & 1   &    &     & 1   &     &     &    &     & \ref{sect:THUNK}     \\
1227 @THUNK_STATIC@        & 1   & 1   &    & 1   & 1   &     &     &    &     & \ref{sect:THUNK}     \\
1228 @THUNK_SELECTOR@      & 1   & 1   & 1  &     & 1   &     &     &    &     & \ref{sect:THUNK_SEL}     \\
1229                                                                                                  
1230 @PAP@                 & 1   &     & ?  &     &     &     &     &    &     & \ref{sect:PAP}       \\
1231                                                                                                  
1232 @IND@                 &     &     & 1  &     & ?   &     &     &    & 1   & \ref{sect:IND}       \\
1233 @IND_OLDGEN@          & 1   &     & 1  &     & ?   &     &     &    & 1   & \ref{sect:IND}       \\
1234 @IND_PERM@            &     &     & 1  &     & ?   &     &     &    & 1   & \ref{sect:IND}       \\
1235 @IND_OLDGEN_PERM@     & 1   &     & 1  &     & ?   &     &     &    & 1   & \ref{sect:IND}       \\
1236 @IND_STATIC@          & ?   &     & 1  & 1   & ?   &     &     &    & 1   & \ref{sect:IND}       \\
1237
1238 \hline
1239 {\em Unpointed} \\ 
1240 \hline
1241
1242
1243 @ARR_WORDS@           & 1   &     & 1  &     &     & 1   & 1   &    &     & \ref{sect:ARR_WORDS1},\ref{sect:ARR_WORDS2} \\
1244 @ARR_PTRS@            & 1   &     & 1  &     &     & 1   & 1   &    &     & \ref{sect:ARR_PTRS}  \\
1245 @MUTVAR@              & 1   &     & 1  &     &     & 1   & 1   &    &     & \ref{sect:MUTVAR}    \\
1246 @MUTARR_PTRS@         & 1   &     & 1  &     &     & 1   & 1   &    &     & \ref{sect:MUTARR_PTRS} \\
1247 @MUTARR_PTRS_FROZEN@  & 1   &     & 1  &     &     & 1   & 1   &    &     & \ref{sect:MUTARR_PTRS_FROZEN} \\
1248
1249 @FOREIGN@             & 1   &     & 1  &     &     &     & 1   &    &     & \ref{sect:FOREIGN}   \\
1250
1251 @BH@                  & ?   & 0/1 & 1  &     & ?   & ?   &     & 1  & ?   & \ref{sect:BH}        \\
1252 @MVAR@                &     &     &    &     &     &     &     &    &     & \ref{sect:MVAR}      \\
1253 @IVAR@                &     &     &    &     &     &     &     &    &     & \ref{sect:IVAR}      \\
1254 @FETCHME@             &     &     &    &     &     &     &     &    &     & \ref{sect:FETCHME}   \\
1255 \hline
1256 \end{tabular}
1257
1258 Activation frames do not live (directly) on the heap --- but they have
1259 a similar organisation.  The classification bits are all zero in
1260 activation frames.
1261
1262 \begin{tabular}{|l|l|}\hline
1263 closure kind            & Section                       \\ \hline
1264 @RET_SMALL@             & \ref{sect:activation-records} \\
1265 @RET_VEC_SMALL@         & \ref{sect:activation-records} \\
1266 @RET_BIG@               & \ref{sect:activation-records} \\
1267 @RET_VEC_BIG@           & \ref{sect:activation-records} \\
1268 @UPDATE_FRAME@          & \ref{sect:activation-records} \\
1269 \hline
1270 \end{tabular}
1271
1272 There are also a number of administrative objects.  The classification bits are
1273 all zero in administrative objects.
1274
1275 \begin{tabular}{|l|l|}\hline
1276 closure kind            & Section                       \\ \hline
1277 @TSO@                   & \ref{sect:TSO}                \\
1278 @STACK_OBJECT@          & \ref{sect:STACK_OBJECT}       \\
1279 @STABLEPTR_TABLE@       & \ref{sect:STABLEPTR_TABLE}    \\
1280 @SPARK_OBJECT@          & \ref{sect:SPARK}              \\
1281 @BLOCKED_FETCH@         & \ref{sect:BLOCKED_FETCH}      \\
1282 \hline
1283 \end{tabular}
1284
1285 \ToDo{I guess the parallel system has something like a stable ptr
1286 table.  Is there any opportunity for sharing code/data structures
1287 here?}
1288
1289
1290 \subsection{Classification bits}
1291
1292 The top bits of the @INFO_TYPE@ tag tells what sort of animal the
1293 closure is.
1294
1295 \begin{tabular}{|l|l|l|}                                                        \hline
1296 Abbrev & Bit & Interpretation                                                   \\ \hline
1297 HNF    & 0   & 1 $\Rightarrow$ Head normal form                                 \\
1298 UPD    & 4   & 1 $\Rightarrow$ May be updated (inconsistent with being a HNF)   \\ 
1299 NS     & 1   & 1 $\Rightarrow$ Don't spark me  (Any HNF will have this set to 1)\\
1300 STA    & 2   & 1 $\Rightarrow$ This is a static closure                         \\
1301 THU    & 8   & 1 $\Rightarrow$ Is a thunk                                       \\
1302 MUT    & 3   & 1 $\Rightarrow$ Has mutable pointer fields                       \\ 
1303 UPT    & 5   & 1 $\Rightarrow$ Has an unpointed type (eg a primitive array)     \\
1304 BH     & 6   & 1 $\Rightarrow$ Is a black hole                                  \\
1305 IND    & 7   & 1 $\Rightarrow$ Is an indirection                                \\
1306 \hline
1307 \end{tabular}
1308
1309 Updatable structures (@_UP@) are thunks that may be shared.  Primitive
1310 arrays (@_BM@ -- Big Mothers) are structures that are always held
1311 in-memory (basically extensions of a closure).  Because there may be
1312 offsets into these arrays, a primitive array cannot be handled as a
1313 FetchMe in the parallel system, but must be shipped in its entirety if
1314 its parent closure is shipped.
1315
1316 The other bits in the info-type field simply give a unique bit-pattern
1317 to identify the closure type.
1318
1319 \iffalse
1320 @
1321 #define _NF                     0x0001  /* Normal form  */
1322 #define _NS                     0x0002  /* Don't spark  */
1323 #define _ST                     0x0004  /* Is static    */
1324 #define _MU                     0x0008  /* Is mutable   */
1325 #define _UP                     0x0010  /* Is updatable (but not mutable) */
1326 #define _BM                     0x0020  /* Is a "primitive" array */
1327 #define _BH                     0x0040  /* Is a black hole */
1328 #define _IN                     0x0080  /* Is an indirection */
1329 #define _TH                     0x0100  /* Is a thunk */
1330
1331
1332
1333 SPEC    
1334 SPEC_N          SPEC | _NF | _NS
1335 SPEC_S          SPEC | _TH
1336 SPEC_U          SPEC | _UP | _TH
1337                 
1338 GEN     
1339 GEN_N           GEN | _NF | _NS
1340 GEN_S           GEN | _TH
1341 GEN_U           GEN | _UP | _TH
1342                 
1343 DYN             _NF | _NS
1344 TUPLE           _NF | _NS | _BM
1345 DATA            _NF | _NS | _BM
1346 MUTUPLE         _NF | _NS | _MU | _BM
1347 IMMUTUPLE       _NF | _NS | _BM
1348 STATIC          _NS | _ST
1349 CONST           _NF | _NS
1350 CHARLIKE        _NF | _NS
1351 INTLIKE         _NF | _NS
1352
1353 BH              _NS | _BH
1354 BH_N            BH
1355 BH_U            BH | _UP
1356                 
1357 BQ              _NS | _MU | _BH
1358 IND             _NS | _IN
1359 CAF             _NF | _NS | _ST | _IN
1360
1361 FM              
1362 FETCHME         FM | _MU
1363 FMBQ            FM | _MU | _BH
1364
1365 TSO             _MU
1366
1367 STKO    
1368 STKO_DYNAMIC    STKO | _MU
1369 STKO_STATIC     STKO | _ST
1370                 
1371 SPEC_RBH        _NS | _MU | _BH
1372 GEN_RBH         _NS | _MU | _BH
1373 BF              _NS | _MU | _BH
1374 INTERNAL        
1375
1376 @
1377 \fi
1378
1379 Notes:
1380
1381 An indirection either points to HNF (post update); or is result of
1382 overwriting a FetchMe, in which case the thing fetched is either
1383 under evaluation (BH), or by now an HNF.  Thus, indirections get NoSpark flag.
1384
1385
1386
1387 \subsection{Pointed Objects}
1388
1389 All pointed objects can be entered.
1390
1391 \subsubsection{Function closures}\label{sect:FUN}
1392
1393 Function closures represent lambda abstractions.  For example,
1394 consider the top-level declaration:
1395 @
1396   f = \x -> let g = \y -> x+y
1397             in g x
1398 @
1399 Both @f@ and @g@ are represented by function closures.  The closure
1400 for @f@ is {\em static} while that for @g@ is {\em dynamic}.
1401
1402 The layout of a function closure is as follows:
1403 \begin{center}
1404 \begin{tabular}{|l|l|l|l|}\hline
1405 {\em Fixed header}  & {\em Pointers} & {\em Non-pointers} \\ \hline
1406 \end{tabular}
1407 \end{center}
1408 The data words (pointers and non-pointers) are the free variables of
1409 the function closure.  
1410 The number of pointers
1411 and number of non-pointers are stored in the @INFO_SM@ word, in the least significant
1412 and most significant half-word respectively.
1413
1414 There are several different sorts of function closure, distinguished
1415 by their @INFO_TYPE@ field:
1416 \begin{itemize}
1417 \item @FUN@: a vanilla, dynamically allocated on the heap. 
1418
1419 \item $@FUN_@p@_@np$: to speed up garbage collection a number of
1420 specialised forms of @FUN@ are provided, for particular $(p,np)$ pairs,
1421 where $p$ is the number of pointers and $np$ the number of non-pointers.
1422
1423 \item @FUN_STATIC@.  Top-level, static, function closures (such as
1424 @f@ above) have a different
1425 layout than dynamic ones:
1426 \begin{center}
1427 \begin{tabular}{|l|l|l|}\hline
1428 {\em Fixed header}  & {\em Static object link} \\ \hline
1429 \end{tabular}
1430 \end{center}
1431 Static function closurs have no free variables.  (However they may refer to other 
1432 static closures; these references are recorded in the function closure's SRT.)
1433 They have one field that is not present in dynamic closures, the {\em static object
1434 link} field.  This is used by the garbage collector in the same way that to-space
1435 is, to gather closures that have been determined to be live but that have not yet
1436 been scavenged.
1437 \note{Static function closures that have no static references, and hence
1438 a null SRT pointer, don't need the static object link field.  Is it worth
1439 taking advantage of this?  See @CONSTR_STATIC_NOCAF@.}
1440 \end{itemize}
1441
1442 Each lambda abstraction, $f$, in the STG program has its own private info table.
1443 The following labels are relevant:
1444 \begin{itemize}
1445 \item $f$@_info@  is $f$'s info table.
1446 \item $f$@_entry@ is $f$'s slow entry point (i.e. the entry code of its
1447 info table; so it will label the same byte as $f$@_info@).
1448 \item $f@_fast_@k$ is $f$'s fast entry point.  $k$ is the number of arguments
1449 $f$ takes; encoding this number in the fast-entry label occasionally catches some nasty
1450 code-generation errors.
1451 \end{itemize}
1452
1453 \subsubsection{Data Constructors}\label{sect:CONSTR}
1454
1455 Data-constructor closures represent values constructed with
1456 algebraic data type constructors.
1457 The general layout of data constructors is the same as that for function
1458 closures.  That is
1459 \begin{center}
1460 \begin{tabular}{|l|l|l|l|}\hline
1461 {\em Fixed header}  & {\em Pointers} & {\em Non-pointers} \\ \hline
1462 \end{tabular}
1463 \end{center}
1464
1465 The SRT pointer in a data constructor's info table is never used --- the
1466 code for a constructor does not make any static references.
1467 \note{Use it for something else??  E.g. tag?}
1468
1469 There are several different sorts of constructor:
1470 \begin{itemize}
1471 \item @CONSTR@: a vanilla, dynamically allocated constructor.
1472 \item @CONSTR_@$p$@_@$np$: just like $@FUN_@p@_@np$.
1473 \item @CONSTR_INTLIKE@.
1474 A dynamically-allocated heap object that looks just like an @Int@.  The 
1475 garbage collector checks to see if it can common it up with one of a fixed
1476 set of static int-like closures, thus getting it out of the dynamic heap
1477 altogether.
1478
1479 \item @CONSTR_CHARLIKE@:  same deal, but for @Char@.
1480
1481 \item @CONSTR_STATIC@ is similar to @FUN_STATIC@, with the complication that
1482 the layout of the constructor must mimic that of a dynamic constructor,
1483 because a static constructor might be returned to some code that unpacks it.
1484 So its layout is like this:
1485 \begin{center}
1486 \begin{tabular}{|l|l|l|l|l|}\hline
1487 {\em Fixed header}  & {\em Pointers} & {\em Non-pointers} & {\em Static object link}\\ \hline
1488 \end{tabular}
1489 \end{center}
1490 The static object link, at the end of the closure, serves the same purpose
1491 as that for @FUN_STATIC@.  The pointers in the static constructor can point
1492 only to other static closures.
1493
1494 The static object link occurs last in the closure so that static
1495 constructors can store their data fields in exactly the same place as
1496 dynamic constructors.
1497
1498 \item @CONSTR_STATIC_NOCAF@.  A statically allocated data constructor
1499 that guarantees not to point (directly or indirectly) to any CAF
1500 (section~\ref{sect:CAF}).  This means it does not need a static object
1501 link field.  Since we expect that there might be quite a lot of static
1502 constructors this optimisation makes sense.  Furthermore, the @NOCAF@
1503 tag allows the compiler to indicate that no CAFs can be reached
1504 anywhere {\em even indirectly}.
1505
1506
1507 \end{itemize}
1508
1509 For each data constructor $Con$, two
1510 info tables are generated:
1511 \begin{itemize}
1512 \item $Con$@_info@ labels $Con$'s dynamic info table, 
1513 shared by all dynamic instances of the constructor.
1514 \item $Con$@_static@ labels $Con$'s static info table, 
1515 shared by all static instances of the constructor.
1516 \end{itemize}
1517
1518 \subsubsection{Thunks}
1519 \label{sect:THUNK}
1520 \label{sect:THUNK_SEL}
1521
1522 A thunk represents an expression that is not obviously in head normal 
1523 form.  For example, consider the following top-level definitions:
1524 @
1525   range = between 1 10
1526   f = \x -> let ys = take x range
1527             in sum ys
1528 @
1529 Here the right-hand sides of @range@ and @ys@ are both thunks; the former
1530 is static while the latter is dynamic.
1531
1532 The layout of a thunk is the same as that for a function closure,
1533 except that it may have some words of ``slop'' at the end to make sure
1534 that it has 
1535 at least @MIN_UPD_PAYLOAD@ words in addition to its
1536 fixed header.
1537 \begin{center}
1538 \begin{tabular}{|l|l|l|l|l|}\hline
1539 {\em Fixed header}  & {\em Pointers} & {\em Non-pointers} & {\em Slop} \\ \hline
1540 \end{tabular}
1541 \end{center}
1542 The @INFO_SM@ word contains the same information as for function
1543 closures; that is, number of pointers and number of non-pointers (excluding slop).
1544
1545 A thunk differs from a function closure in that it can be updated.
1546
1547 There are several forms of thunk:
1548 \begin{itemize}
1549 \item @THUNK@: a vanilla, dynamically allocated thunk.
1550 The garbage collection code for thunks whose
1551 pointer + non-pointer words is less than @MIN_UPD_PAYLOAD@ differs from
1552 that for function closures and data constructors, because the GC code
1553 has to account for the slop.
1554 \item $@THUNK_@p@_@np$.  Similar comments apply.
1555 \item @THUNK_STATIC@.  A static thunk is also known as 
1556 a {\em constant applicative form}, or {\em CAF}.
1557
1558 \begin{center}
1559 \begin{tabular}{|l|l|l|l|l|}\hline
1560 {\em Fixed header}  & {\em Pointers} & {\em Non-pointers} & {\em Slop} & {\em Static object link}\\ \hline
1561 \end{tabular}
1562 \end{center}
1563
1564 \item @THUNK_SELECTOR@ is a (dynamically allocated) thunk
1565 whose entry code performs a simple selection operation from
1566 a data constructor drawn from a single-constructor type.  For example,
1567 the thunk
1568 @
1569         x = case y of (a,b) -> a
1570 @
1571 is a selector thunk.  A selector thunk is laid out like this:
1572 \begin{center}
1573 \begin{tabular}{|l|l|l|l|}\hline
1574 {\em Fixed header}  & {\em Selectee pointer} \\ \hline
1575 \end{tabular}
1576 \end{center}
1577 The @INFO_SM@ word contains the byte offset of the desired word in
1578 the selectee.  Note that this is different from all other thunks.
1579
1580 The garbage collector ``peeks'' at the selectee's
1581 tag (in its info table).  If it is evaluated, then it goes ahead and do
1582 the selection, and then behaves just as if the selector thunk was an
1583 indirection to the selected field.
1584 If it is not
1585 evaluated, it treats the selector thunk like any other thunk of that
1586 shape.  [Implementation notes.  
1587 Copying: only the evacuate routine needs to be special.
1588 Compacting: only the PRStart (marking) routine needs to be special.]
1589 \end{itemize}
1590
1591
1592 The only label associated with a thunk is its info table:
1593 \begin{description}
1594 \item[$f$@_info@] is $f$'s info table.
1595 \end{description}
1596
1597
1598 \subsubsection{Partial applications (PAPs)}\label{sect:PAP}
1599
1600 A partial application (PAP) represents a function applied to too few arguments.
1601 It is only built as a result of updating after an argument-satisfaction
1602 check failure.  A PAP has the following shape:
1603 \begin{center}
1604 \begin{tabular}{|l|l|l|l|}\hline
1605 {\em Fixed header}  & {\em No of arg words} & {\em Function closure} & {\em Arg stack} \\ \hline
1606 \end{tabular}
1607 \end{center}
1608 The ``arg stack'' is a copy of of the chunk of stack above the update
1609 frame; ``no of arg words'' tells how many words it consists of.  The
1610 function closure is (a pointer to) the closure for the function whose
1611 argument-satisfaction check failed.
1612
1613 There is just one standard form of PAP with @INFO_TYPE@ = @PAP@.
1614 There is just one info table too, called @PAP_info@.
1615 Its entry code simply copies the arg stack chunk back on top of the
1616 stack and enters the function closure.  (It has to do a stack overflow test first.)
1617
1618 There are no static PAPs.
1619
1620 \subsubsection{Indirections}
1621 \label{sect:IND}
1622 \label{sect:IND_OLDGEN}
1623
1624 Indirection closures just point to other closures. They are introduced
1625 when a thunk is updated to point to its value. 
1626 The entry code for all indirections simply enters the closure it points to.
1627
1628 There are several forms of indirection:
1629 \begin{description}
1630 \item[@IND@] is the vanilla, dynamically-allocated indirection.
1631 It is removed by the garbage collector. It has the following
1632 shape:
1633 \begin{center}
1634 \begin{tabular}{|l|l|l|}\hline
1635 {\em Fixed header} & {\em Target closure} \\ \hline
1636 \end{tabular}
1637 \end{center}
1638
1639 \item[@IND_OLDGEN@] is the indirection used to update an old-generation
1640 thunk. Its shape is like this:
1641 \begin{center}
1642 \begin{tabular}{|l|l|l|}\hline
1643 {\em Fixed header} & {\em Mutable link field} & {\em Target closure} \\ \hline
1644 \end{tabular}
1645 \end{center}
1646 It contains a {\em mutable link field} that is used to string together
1647 all old-generation indirections that might have a pointer into
1648 the new generation.
1649
1650
1651 \item[@IND_PERMANENT@ and @IND_OLDGEN_PERMANENT@.]
1652 for lexical profiling, it is necessary to maintain cost centre
1653 information in an indirection, so ``permanent indirections'' are
1654 retained forever.  Otherwise they are just like vanilla indirections.
1655 \note{If a permanent indirection points to another permanent
1656 indirection or a @CONST@ closure, it is possible to elide the indirection
1657 since it will have no effect on the profiler.}
1658 \note{Do we still need @IND@ and @IND_OLDGEN@
1659 in the profiling build, or can we just make
1660 do with one pair whose behaviour changes when profiling is built?}
1661
1662 \item[@IND_STATIC@] is used for overwriting CAFs when they have been
1663 evaluated.  Static indirections are not removed by the garbage
1664 collector; and are statically allocated outside the heap (and should
1665 stay there).  Their static object link field is used just as for
1666 @FUN_STATIC@ closures.
1667
1668 \begin{center}
1669 \begin{tabular}{|l|l|l|}
1670 \hline
1671 {\em Fixed header} & {\em Target closure} & {\em Static object link} \\
1672 \hline
1673 \end{tabular}
1674 \end{center}
1675
1676 \end{description}
1677
1678 \subsubsection{Activation Records}
1679
1680 Activation records are parts of the stack described by return address
1681 info tables (closures with @INFO_TYPE@ values of @RET_SMALL@,
1682 @RET_VEC_SMALL@, @RET_BIG@ and @RET_VEC_BIG@). They are described in
1683 section~\ref{sect:activation-records}.
1684
1685
1686 \subsubsection{Black holes, MVars and IVars}
1687 \label{sect:BH}
1688 \label{sect:MVAR}
1689 \label{sect:IVAR}
1690
1691 Black hole closures are used to overwrite closures currently being
1692 evaluated. They inform the garbage collector that there are no live
1693 roots in the closure, thus removing a potential space leak.  
1694
1695 Black holes also become synchronization points in the threaded world.
1696 They contain a pointer to a list of blocked threads to be awakened
1697 when the black hole is updated (or @NULL@ if the list is empty).
1698 \begin{center}
1699 \begin{tabular}{|l|l|l|}
1700 \hline 
1701 {\em Fixed header} & {\em Mutable link} & {\em Blocked thread link} \\
1702 \hline
1703 \end{tabular}
1704 \end{center}
1705 The {\em Blocked thread link} points to the TSO of the first thread
1706 waiting for the value of this thunk.  All subsequent TSOs in the list
1707 are linked together using their @TSO_LINK@ field.
1708
1709 When the blocking queue is non-@NULL@, the black hole must be added to
1710 the mutables list since the TSOs on the list may contain pointers into
1711 the new generation.  There is no need to clutter up the mutables list
1712 with black holes with empty blocking queues.
1713
1714 \ToDo{MVars}
1715
1716
1717 \subsubsection{FetchMes}\label{sect:FETCHME}
1718
1719 In the parallel systems, FetchMes are used to represent pointers into
1720 the global heap.  When evaluated, the value they point to is read from
1721 the global heap.
1722
1723 \ToDo{Describe layout}
1724
1725
1726 \subsection{Unpointed Objects}
1727
1728 A variable of unpointed type is always bound to a {\em value}, never to a {\em thunk}.
1729 For this reason, unpointed objects cannot be entered.
1730
1731 A {\em value} may be:
1732 \begin{itemize}
1733 \item {\em Boxed}, i.e.~represented indirectly by a pointer to a heap object (e.g.~foreign objects, arrays); or
1734 \item {\em Unboxed}, i.e.~represented directly by a bit-pattern in one or more registers (e.g.~@Int#@ and @Float#@).
1735 \end{itemize}
1736 All {\em pointed} values are {\em boxed}.  
1737
1738 \subsubsection{Immutable Objects}
1739 \label{sect:ARR_WORDS1}
1740 \label{sect:ARR_PTRS}
1741
1742 \begin{description}
1743 \item[@ARR_WORDS@] is a variable-sized object consisting solely of
1744 non-pointers.  It is used for arrays of all
1745 sorts of things (bytes, words, floats, doubles... it doesn't matter).
1746 \begin{center}
1747 \begin{tabular}{|c|c|c|c|}
1748 \hline
1749 {\em Fixed Hdr} & {\em No of non-pointers} & {\em Non-pointers\ldots}   \\ \hline
1750 \end{tabular}
1751 \end{center}
1752
1753 \item[@ARR_PTRS@] is an immutable, variable sized array of pointers.
1754 \begin{center}
1755 \begin{tabular}{|c|c|c|c|}
1756 \hline
1757 {\em Fixed Hdr} & {\em Mutable link} & {\em No of pointers} & {\em Pointers\ldots}      \\ \hline
1758 \end{tabular}
1759 \end{center}
1760 The mutable link is present so that we can easily freeze and thaw an
1761 array (by changing the header and adding/removing the array to the
1762 mutables list).
1763
1764 \end{description}
1765
1766 \subsubsection{Mutable Objects}
1767 \label{sect:mutables}
1768 \label{sect:ARR_WORDS2}
1769 \label{sect:MUTVAR}
1770 \label{sect:MUTARR_PTRS}
1771 \label{sect:MUTARR_PTRS_FROZEN}
1772
1773 Some of these objects are {\em mutable}; they represent objects which
1774 are explicitly mutated by Haskell code through the @ST@ monad.
1775 They're not used for thunks which are updated precisely once.
1776 Depending on the garbage collector, mutable closures may contain extra
1777 header information which allows a generational collector to implement
1778 the ``write barrier.''
1779
1780 \begin{description}
1781
1782 \item[@ARR_WORDS@] is also used to represent {\em mutable} arrays of
1783 bytes, words, floats, doubles, etc.  It's possible to use the same
1784 object type because even generational collectors don't need to
1785 distinguish them.
1786
1787 \item[@MUTVAR@] is a mutable variable.
1788 \begin{center}
1789 \begin{tabular}{|c|c|c|}
1790 \hline
1791 {\em Fixed Hdr} & {\em Mutable link} & {\em Pointer} \\ \hline
1792 \end{tabular}
1793 \end{center}
1794
1795 \item[@MUTARR_PTRS@] is a mutable array of pointers.
1796 Such an array may be {\em frozen}, becoming an @SM_MUTARR_PTRS_FROZEN@, with a
1797 different info-table.
1798 \begin{center}
1799 \begin{tabular}{|c|c|c|c|}
1800 \hline
1801 {\em Fixed Hdr} & {\em Mutable link} & {\em No of ptrs} & {\em Pointers\ldots} \\ \hline
1802 \end{tabular}
1803 \end{center}
1804
1805 \item[@MUTARR_PTRS_FROZEN@] is a frozen @MUTARR_PTRS@ closure.
1806 The garbage collector converts @MUTARR_PTRS_FROZEN@ to @ARR_PTRS@ as it removes them from
1807 the mutables list.
1808
1809 \end{description}
1810
1811
1812 \subsubsection{Foreign Objects}\label{sect:FOREIGN}
1813
1814 Here's what a ForeignObj looks like:
1815
1816 \begin{center}
1817 \begin{tabular}{|l|l|l|l|}
1818 \hline 
1819 {\em Fixed header} & {\em Data} & {\em Free Routine} & {\em Foreign object link} \\
1820 \hline
1821 \end{tabular}
1822 \end{center}
1823
1824 The @FreeRoutine@ is a reference to the finalisation routine to call
1825 when the @ForeignObj@ becomes garbage.  If @freeForeignObject@ is
1826 called on a Foreign Object, the @FreeRoutine@ is set to zero and the
1827 garbage collector will not attempt to call @FreeRoutine@ when the 
1828 object becomes garbage.
1829
1830 The Foreign object link is a link to the next foreign object in the
1831 list.  This list is traversed at the end of garbage collection: if an
1832 object is about to be deallocated (e.g.~it was not marked or
1833 evacuated), the free routine is called and the object is deleted from
1834 the list.  
1835
1836
1837 The remaining objects types are all administrative --- none of them may be entered.
1838
1839 \subsection{Thread State Objects (TSOs)}\label{sect:TSO}
1840
1841 In the multi-threaded system, the state of a suspended thread is
1842 packed up into a Thread State Object (TSO) which contains all the
1843 information needed to restart the thread and for the garbage collector
1844 to find all reachable objects.  When a thread is running, it may be
1845 ``unpacked'' into machine registers and various other memory locations
1846 to provide faster access.
1847
1848 Single-threaded systems don't really {\em need\/} TSOs --- but they do
1849 need some way to tell the storage manager about live roots so it is
1850 convenient to use a single TSO to store the mutator state even in
1851 single-threaded systems.
1852
1853 Rather than manage TSOs' alloc/dealloc, etc., in some {\em ad hoc}
1854 way, we instead alloc/dealloc/etc them in the heap; then we can use
1855 all the standard garbage-collection/fetching/flushing/etc machinery on
1856 them.  So that's why TSOs are ``heap objects,'' albeit very special
1857 ones.
1858 \begin{center}
1859 \begin{tabular}{|l|l|}
1860    \hline {\em Fixed header}
1861 \\ \hline @TSO_LINK@
1862 \\ \hline @TSO_WHATNEXT@
1863 \\ \hline @TSO_WHATNEXT_INFO@ 
1864 \\ \hline @TSO_STACK@ 
1865 \\ \hline {\em Exception Handlers}
1866 \\ \hline {\em Ticky Info}
1867 \\ \hline {\em Profiling Info}
1868 \\ \hline {\em Parallel Info}
1869 \\ \hline {\em GranSim Info}
1870 \\ \hline
1871 \end{tabular}
1872 \end{center}
1873 The contents of a TSO are:
1874 \begin{itemize}
1875
1876 \item A pointer (@TSO_LINK@) used to maintain a list of threads with a similar
1877   state (e.g.~all runable, all sleeping, all blocked on the same black
1878   hole, all blocked on the same MVar, etc.)
1879
1880 \item A word (@TSO_WHATNEXT@) which is in suspended threads to record
1881  how to awaken it.  This typically requires a program counter which is stored
1882  in the pointer @TSO_WHATNEXT_INFO@
1883
1884 \item A pointer (@TSO_STACK@) to the top stack block.
1885
1886 \item Optional information for ``Ticky Ticky'' statistics: @TSO_STK_HWM@ is
1887   the maximum number of words allocated to this thread.
1888
1889 \item Optional information for profiling: 
1890   @TSO_CCC@ is the current cost centre.
1891
1892 \item Optional information for parallel execution:
1893 \begin{itemize}
1894
1895 \item The types of threads (@TSO_TYPE@):
1896 \begin{description}
1897 \item[@T_MAIN@]     Must be executed locally.
1898 \item[@T_REQUIRED@] A required thread  -- may be exported.
1899 \item[@T_ADVISORY@] An advisory thread -- may be exported.
1900 \item[@T_FAIL@]     A failure thread   -- may be exported.
1901 \end{description}
1902
1903 \item I've no idea what else
1904
1905 \end{itemize}
1906
1907 \item Optional information for GranSim execution:
1908 \begin{itemize}
1909 \item locked         
1910 \item sparkname  
1911 \item started at         
1912 \item exported   
1913 \item basic blocks       
1914 \item allocs     
1915 \item exectime   
1916 \item fetchtime  
1917 \item fetchcount         
1918 \item blocktime  
1919 \item blockcount         
1920 \item global sparks      
1921 \item local sparks       
1922 \item queue              
1923 \item priority   
1924 \item clock          (gransim light only)
1925 \end{itemize}
1926
1927
1928 Here are the various queues for GrAnSim-type events.
1929 @
1930 Q_RUNNING   
1931 Q_RUNNABLE  
1932 Q_BLOCKED   
1933 Q_FETCHING  
1934 Q_MIGRATING 
1935 @
1936
1937 \end{itemize}
1938
1939 \subsection{Other weird objects}
1940 \label{sect:SPARK}
1941 \label{sect:BLOCKED_FETCH}
1942
1943 \begin{description}
1944 \item[@BlockedFetch@ heap objects (`closures')] (parallel only)
1945
1946 @BlockedFetch@s are inbound fetch messages blocked on local closures.
1947 They arise as entries in a local blocking queue when a fetch has been
1948 received for a local black hole.  When awakened, we look at their
1949 contents to figure out where to send a resume.
1950
1951 A @BlockedFetch@ closure has the form:
1952 \begin{center}
1953 \begin{tabular}{|l|l|l|l|l|l|}\hline
1954 {\em Fixed header} & link & node & gtid & slot & weight \\ \hline
1955 \end{tabular}
1956 \end{center}
1957
1958 \item[Spark Closures] (parallel only)
1959
1960 Spark closures are used to link together all closures in the spark pool.  When
1961 the current processor is idle, it may choose to speculatively evaluate some of
1962 the closures in the pool.  It may also choose to delete sparks from the pool.
1963 \begin{center}
1964 \begin{tabular}{|l|l|l|l|l|l|}\hline
1965 {\em Fixed header} & {\em Spark pool link} & {\em Sparked closure} \\ \hline
1966 \end{tabular}
1967 \end{center}
1968
1969
1970 \end{description}
1971
1972
1973 \subsection{Stack Objects}
1974 \label{sect:STACK_OBJECT}
1975 \label{sect:stacks}
1976
1977 These are ``stack objects,'' which are used in the threaded world as
1978 the stack for each thread is allocated from the heap in smallish
1979 chunks.  (The stack in the sequential world is allocated outside of
1980 the heap.)
1981
1982 Each reduction thread has to have its own stack space.  As there may
1983 be many such threads, and as any given one may need quite a big stack,
1984 a naive give-'em-a-big-stack-and-let-'em-run approach will cost a {\em
1985 lot} of memory.
1986
1987 Our approach is to give a thread a small stack space, and then link
1988 on/off extra ``chunks'' as the need arises.  Again, this is a
1989 storage-management problem, and, yet again, we choose to graft the
1990 whole business onto the existing heap-management machinery.  So stack
1991 objects will live in the heap, be garbage collected, etc., etc..
1992
1993 A stack object is laid out like this:
1994
1995 \begin{center}
1996 \begin{tabular}{|l|}
1997 \hline
1998 {\em Fixed header} 
1999 \\ \hline
2000 {\em Link to next stack object (0 for last)}
2001 \\ \hline
2002 {\em N, the payload size in words}
2003 \\ \hline
2004 {\em @Sp@ (byte offset from head of object)}
2005 \\ \hline
2006 {\em @Su@ (byte offset from head of object)}
2007 \\ \hline
2008 {\em Payload (N words)}
2009 \\ \hline
2010 \end{tabular}
2011 \end{center}
2012
2013 \ToDo{Are stack objects on the mutable list?}
2014
2015 The stack grows downwards, towards decreasing
2016 addresses.  This makes it easier to print out the stack
2017 when debugging, and it means that a return address is
2018 at the lowest address of the chunk of stack it ``knows about''
2019 just like an info pointer on a closure.
2020
2021 The garbage collector needs to be able to find all the
2022 pointers in a stack.  How does it do this?
2023
2024 \begin{itemize}
2025
2026 \item Within the stack there are return addresses, pushed
2027 by @case@ expressions.  Below a return address (i.e. at higher
2028 memory addresses, since the stack grows downwards) is a chunk
2029 of stack that the return address ``knows about'', namely the
2030 activation record of the currently running function.
2031
2032 \item Below each such activation record is a {\em pending-argument
2033 section}, a chunk of
2034 zero or more words that are the arguments to which the result
2035 of the function should be applied.  The return address does not
2036 statically
2037 ``know'' how many pending arguments there are, or their types.
2038 (For example, the function might return a result of type $\alpha$.)
2039
2040 \item Below each pending-argument section is another return address,
2041 and so on.  Actually, there might be an update frame instead, but we
2042 can consider update frames as a special case of a return address with
2043 a well-defined activation record.
2044
2045 \ToDo{Doesn't it {\em have} to be an update frame?  After all, the arg
2046 satisfaction check is @Su - Sp >= ...@.}
2047
2048 \end{itemize}
2049
2050 The game plan is this.  The garbage collector
2051 walks the stack from the top, traversing pending-argument sections and
2052 activation records alternately.  Next we discuss how it finds
2053 the pointers in each of these two stack regions.
2054
2055
2056 \subsubsection{Activation records}\label{sect:activation-records}
2057
2058 An {\em activation record} is a contiguous chunk of stack,
2059 with a return address as its first word, followed by as many
2060 data words as the return address ``knows about''.  The return
2061 address is actually a fully-fledged info pointer.  It points
2062 to an info table, replete with:
2063
2064 \begin{itemize}
2065 \item entry code (i.e. the code to return to).
2066 \item @INFO_TYPE@ is either @RET_SMALL/RET_VEC_SMALL@ or @RET_BIG/RET_VEC_BIG@, depending
2067 on whether the activation record has more than 32 data words (\note{64 for 8-byte-word architectures}) and on whether 
2068 to use a direct or a vectored return.
2069 \item @INFO_SM@ for @RET_SMALL@ is a bitmap telling the layout
2070 of the activation record, one bit per word.  The least-significant bit
2071 describes the first data word of the record (adjacent to the fixed
2072 header) and so on.  A ``@1@'' indicates a non-pointer, a ``@0@''
2073 indicates
2074 a pointer.  We don't need to indicate exactly how many words there
2075 are,
2076 because when we get to all zeros we can treat the rest of the 
2077 activation record as part of the next pending-argument region.
2078
2079 For @RET_BIG@ the @INFO_SM@ field points to a block of bitmap
2080 words, starting with a word that tells how many words are in
2081 the block.
2082
2083 \item @INFO_SRT@ is the Static Reference Table for the return
2084 address (Section~\ref{sect:srt}).
2085 \end{itemize}
2086
2087 The activation record is a fully fledged closure too.
2088 As well as an info pointer, it has all the other attributes of
2089 a fixed header (Section~\ref{sect:fixed-header}) including a saved cost
2090 centre which is reloaded when the return address is entered.
2091
2092 In other words, all the attributes of closures are needed for
2093 activation records, so it's very convenient to make them look alike.
2094
2095
2096 \subsubsection{Pending arguments}
2097
2098 So that the garbage collector can correctly identify pointers
2099 in pending-argument sections we explicitly tag all non-pointers.
2100 Every non-pointer in a pending-argument section is preceded
2101 (at the next lower memory word) by a one-word byte count that
2102 says how many bytes to skip over (excluding the tag word).
2103
2104 The garbage collector traverses a pending argument section from 
2105 the top (i.e. lowest memory address).  It looks at each word in turn:
2106
2107 \begin{itemize}
2108 \item If it is less than or equal to a small constant @MAX_STACK_TAG@
2109 then
2110 it treats it as a tag heralding zero or more words of non-pointers,
2111 so it just skips over them.
2112
2113 \item If it points to the code segment, it must be a return
2114 address, so we have come to the end of the pending-argument section.
2115
2116 \item Otherwise it must be a bona fide heap pointer.
2117 \end{itemize}
2118
2119
2120 \subsection{The Stable Pointer Table}\label{sect:STABLEPTR_TABLE}
2121
2122 A stable pointer is a name for a Haskell object which can be passed to
2123 the external world.  It is ``stable'' in the sense that the name does
2124 not change when the Haskell garbage collector runs---in contrast to
2125 the address of the object which may well change.
2126
2127 A stable pointer is represented by an index into the
2128 @StablePointerTable@.  The Haskell garbage collector treats the
2129 @StablePointerTable@ as a source of roots for GC.
2130
2131 In order to provide efficient access to stable pointers and to be able
2132 to cope with any number of stable pointers (eg $0 \ldots 100000$), the
2133 table of stable pointers is an array stored on the heap and can grow
2134 when it overflows.  (Since we cannot compact the table by moving
2135 stable pointers about, it seems unlikely that a half-empty table can
2136 be reduced in size---this could be fixed if necessary by using a
2137 hash table of some sort.)
2138
2139 In general a stable pointer table closure looks like this:
2140
2141 \begin{center}
2142 \begin{tabular}{|l|l|l|l|l|l|l|l|l|l|l|}
2143 \hline
2144 {\em Fixed header} & {\em No of pointers} & {\em Free} & $SP_0$ & \ldots & $SP_{n-1}$ 
2145 \\\hline
2146 \end{tabular}
2147 \end{center}
2148
2149 The fields are:
2150 \begin{description}
2151
2152 \item[@NPtrs@:] number of (stable) pointers.
2153
2154 \item[@Free@:] the byte offset (from the first byte of the object) of the first free stable pointer.
2155
2156 \item[$SP_i$:] A stable pointer slot.  If this entry is in use, it is
2157 an ``unstable'' pointer to a closure.  If this entry is not in use, it
2158 is a byte offset of the next free stable pointer slot.
2159
2160 \end{description}
2161
2162 When a stable pointer table is evacuated
2163 \begin{enumerate}
2164 \item the free list entries are all set to @NULL@ so that the evacuation
2165   code knows they're not pointers;
2166
2167 \item The stable pointer slots are scanned linearly: non-@NULL@ slots
2168 are evacuated and @NULL@-values are chained together to form a new free list.
2169 \end{enumerate}
2170
2171 There's no need to link the stable pointer table onto the mutable
2172 list because we always treat it as a root.
2173
2174
2175
2176 \section{The Storage Manager}
2177
2178 The generational collector remembers the depth of the last generation
2179 collected and the value of the heap pointer at the end of the last GC.
2180 If the mutator has not moved the heap pointer, that means that the
2181 amount of space recovered is insufficient to satisfy even one request
2182 and it is time to collect an older generation or report a heap overflow.
2183
2184 A deeper collection is also triggered when a minor collection fails to
2185 recover at least @...@ bytes of space.
2186
2187 When can a GC happen?
2188
2189 @
2190 - During updates (ie during returns)
2191 - When a heap check fails
2192 - When a stack check fails (concurrent system only)
2193 - When a context switch happens (concurrent system only)
2194
2195 When do heap checks occur?
2196 - Immediately after entering a thunk
2197 - Immediately after entering a case alternative
2198
2199 When do stack checks occur?
2200 - We calculate the worst-case stack usage of an entire
2201   thunk so there's no need to put a check inside each alternative.
2202 - Immediately after entering a thunk
2203   We can't make a similar worst-case calculation for heap usage
2204   because the heap isn't used in a stacklike manner so any
2205   evaluation inside a case might steal some of the heap we've
2206   checked for.
2207
2208 Concurrency
2209 - Threads can be blocked
2210 - Threads can be put to sleep
2211   - Heap may move while we sleep
2212   - Black holing may happen while we sleep (ie during GC)
2213 @
2214
2215 \subsection{The SM state}
2216
2217 Contains @Hp@, @HpLim@, @StablePtrTable@ plus version-specific info.
2218
2219 \begin{itemize}
2220
2221 \item Static Object list 
2222 \item Foreign Object list
2223 \item Stable Pointer Table
2224
2225 \end{itemize}
2226
2227 In addition, the generational collector requires:
2228
2229 \begin{itemize}
2230
2231 \item Old Generation Indirection list
2232 \item Mutables list --- list of mutable objects in the old generation.
2233 \item @OldLim@ --- the boundary between the generations
2234 \item Old Foreign Object list --- foreign objects in the old generation
2235
2236 \end{itemize}
2237
2238 It is passed a table of {\em roots\/} containing
2239
2240 \begin{itemize}
2241
2242 \item All runnable TSOs
2243
2244 \end{itemize}
2245
2246
2247 In the parallel system, there must be some extra magic associated with
2248 global GC.
2249
2250 \subsection{The SM interface}
2251
2252 @initSM@ finalizes any runtime parameters of the storage manager.
2253
2254 @exitSM@ does any cleaning up required by the storage manager before
2255 the program is executed. Its main purpose is to print any summary
2256 statistics.
2257
2258 @initHeap@ allocates the heap. It initialises the @hp@ and @hplim@
2259 fields of @sm@ to represent an empty heap for the compiled-in garbage
2260 collector.  It also initialises @CAFlist@ to be the empty list. If we
2261 are using Appel's collector it also initialises the @OldLim@ field.
2262 It also initialises the stable pointer table and the @ForeignObjList@
2263 (and @OldForeignObjList@) fields.
2264
2265 @collectHeap@ invokes the garbage collector.  @collectHeap@ requires
2266 all the fields of @sm@ to be initialised appropriately (from the
2267 STG-machine registers).  The following are identified as heap roots:
2268 \begin{itemize}
2269 \item The updated CAFs recorded in @CAFlist@.
2270 \item Any pointers found on the stack.
2271 \item All runnable and sleeping TSOs.
2272 \item The stable pointer table.
2273 \end{itemize}
2274
2275 There are two possible results from a garbage collection:
2276 \begin{description} 
2277 \item[@GC_FAIL@] 
2278 The garbage collector is unable to free up any more space.
2279
2280 \item[@GC_SUCCESS@]
2281 The garbage collector managed to free up more space.
2282
2283 \begin{itemize} 
2284 \item @hp@ and @hplim@ will indicate the new space available for
2285 allocation.
2286
2287 \item The elements of @CAFlist@ and the stable pointers will be
2288 updated to point to the new locations of the closures they reference.
2289
2290 \item Any members of @ForeignObjList@ which became garbage should have
2291 been reported (by calling their finalising routines; and the
2292 @(Old)ForeignObjList@ updated to contain only those Foreign objects
2293 which are still live.  
2294
2295 \end{itemize}
2296
2297 \end{description}
2298
2299
2300 %************************************************************************
2301 %*                                                                      *
2302 \subsection{``What really happens in a garbage collection?''}
2303 %*                                                                      *
2304 %************************************************************************
2305
2306 This is a brief tutorial on ``what really happens'' going to/from the
2307 storage manager in a garbage collection.
2308
2309 \begin{description}
2310 %------------------------------------------------------------------------
2311 \item[The heap check:]
2312
2313 [OLD-ISH: WDP]
2314
2315 If you gaze into the C output of GHC, you see many macros calls like:
2316 \begin{verbatim}
2317 HEAP_CHK_2PtrsLive((_FHS+2));
2318 \end{verbatim}
2319
2320 This expands into the C (roughly speaking...):
2321 @
2322 Hp = Hp + (_FHS+2);     /* optimistically move heap pointer forward */
2323
2324 GC_WHILE_OR_IF (HEAP_OVERFLOW_OP(Hp, HpLim) OR_INTERVAL_EXPIRED) {
2325         STGCALL2_GC(PerformGC, <liveness-bits>, (_FHS+2));
2326 }
2327 @
2328
2329 In the parallel world, where we will need to re-try the heap check,
2330 @GC_WHILE_OR_IF@ will be a ``while''; in the sequential world, it will
2331 be an ``if''.
2332
2333 The ``heap lookahead'' checks, which are similar and used for
2334 multi-precision @Integer@ ops, have some further complications.  See
2335 the commentary there (@StgMacros.lh@).
2336
2337 %------------------------------------------------------------------------
2338 \item[Into @callWrapper_GC@...:]
2339
2340 When we failed the heap check (above), we were inside the
2341 GCC-registerised ``threaded world.''  @callWrapper_GC@ is all about
2342 getting in and out of the threaded world.  On SPARCs, with register
2343 windows, the name of the game is not shifting windows until we have
2344 what we want out of the old one.  In tricky cases like this, it's best
2345 written in assembly language.
2346
2347 Performing a GC (potentially) means giving up the thread of control.
2348 So we must fill in the thread-state-object (TSO) [and its associated
2349 stk object] with enough information for later resumption:
2350 \begin{enumerate}
2351 \item
2352 Save the return address in the TSO's PC field.
2353 \item
2354 Save the machine registers used in the STG threaded world in their
2355 corresponding TSO fields.  We also save the pointer-liveness
2356 information in the TSO.
2357 \item
2358 The registers that are not thread-specific, notably @Hp@ and
2359 @HpLim@, are saved in the @StorageMgrInfo@ structure.
2360 \item
2361 Call the routine it was asked to call; in this example, call
2362 @PerformGC@ with arguments @<liveness>@ and @_FHS+2@ (some constant)...
2363
2364 \end{enumerate}
2365
2366 %------------------------------------------------------------------------
2367 \item[Into the heap overflow wrapper, @PerformGC@ [parallel]:]
2368
2369 Most information has already been saved in the TSO.
2370
2371 \begin{enumerate}
2372 \item
2373 The first argument (@<liveness>@, in our example) say what registers
2374 are live, i.e., are ``roots'' the storage manager needs to know.
2375 \begin{verbatim}
2376 StorageMgrInfo.rootno   = 2;
2377 StorageMgrInfo.roots[0] = (P_) Ret1_SAVE;
2378 StorageMgrInfo.roots[1] = (P_) Ret2_SAVE;
2379 \end{verbatim}
2380
2381 \item
2382 We move the heap-pointer back [we had optimistically
2383 advanced it, in the initial heap check]
2384
2385 \item 
2386 We load up the @smInfo@ data from the STG registers' @*_SAVE@ locations.
2387
2388 \item
2389 We mark on the scheduler's big ``blackboard'' that a GC is
2390 required.
2391
2392 \item
2393 We reschedule, i.e., this thread gives up control.  (The scheduler
2394 will presumably initiate a garbage-collection, but it may have to do
2395 any number of other things---flushing, for example---before ``normal
2396 execution'' resumes; and it most certainly may not be this thread that
2397 resumes at that point!)
2398 \end{enumerate}
2399
2400 IT IS AT THIS POINT THAT THE WORLD IS COMPLETELY TIDY.
2401
2402 %------------------------------------------------------------------------
2403 \item[Out of @callWrapper_GC@ [parallel]:]
2404
2405 When this thread is finally resumed after GC (and who knows what
2406 else), it will restart by the normal enter-TSO/enter-stack-object
2407 sequence, which has the effect of re-loading the registers, etc.,
2408 (i.e., restoring the state).
2409
2410 Because the address we saved in the TSO's PC field was that at the end
2411 of the heap check, and because the check is a while-loop in the
2412 parallel system, we will now loop back around, and make sure there is
2413 enough space before continuing.
2414 \end{description}
2415
2416
2417
2418 \subsection{Static Reference Tables (SRTs)}
2419 \label{sect:srt}
2420 \label{sect:CAF}
2421 \label{sect:static-objects}
2422
2423 In the above, we assumed that objects always contained pointers to all
2424 their free variables.  In fact, this isn't quite true: GHC omits
2425 pointers to top-level objects and allocates their closures in static
2426 memory.  This optimisation reduces the number of free variables in
2427 heap objects - reducing memory usage and the effort needed to put them
2428 into heap objects.  However, this optimisation comes at a cost: we
2429 need to complicate the garbage collector with machinery for tracing
2430 these static references.
2431
2432 Early versions of GHC used a very simple algorithm: it treated all
2433 static objects as roots.  This is safe in the sense that no object is
2434 ever deallocated if there's a chance that it might be required later
2435 but can lead to some terrible space leaks.  For example, this program
2436 ought to be able to run in constant space but, because @xs@ is never
2437 deallocated, it runs in linear space.
2438
2439 @
2440 main = print xs
2441 xs = [1..]
2442 @
2443
2444 The correct behaviour is for the garbage collector to keep a static
2445 object alive iff it might be required later in execution.  That is, if
2446 it is reachable from any live heap objects {\em or\/} from any return
2447 addresses found on the stack or from the current program counter.
2448 Since it is obviously infeasible for the garbage collector to scan
2449 machine code looking for static references, the code generator must
2450 generate a table of all static references in any piece of code (and we
2451 must place a pointer to this table next to any piece of code we
2452 generate).
2453
2454 Here's what the SRT has to contain:
2455
2456 @
2457 ...
2458 @
2459
2460 Here's how we represent it:
2461
2462 @
2463 ...
2464 must be able to handle 0 references well
2465 @
2466
2467 @
2468 Other trickery:
2469 o The CAF list
2470 o The scavenge list
2471 o Generational GC trickery
2472 @
2473
2474 \subsection{Space leaks and black holes}
2475 \label{sect:black-hole}
2476
2477 \iffalse
2478
2479 \ToDo{Insert text stolen from update paper}
2480
2481 \else
2482
2483 A program exhibits a {\em space leak} if it retains storage that is
2484 sure not to be used again.  Space leaks are becoming increasingly
2485 common in imperative programs that @malloc@ storage and fail
2486 subsequently to @free@ it.  They are, however, also common in
2487 garbage-collected systems, especially where lazy evaluation is
2488 used.[.wadler leak, runciman heap profiling jfp.]
2489
2490 Quite a bit of experience has now accumulated suggesting that
2491 implementors must be very conscientious about avoiding gratuitous
2492 space leaks --- that is, ones which are an accidental artefact of some
2493 implementation technique.[.appel book.]  The update mechanism is
2494 a case in point, as <.jones jfp leak.> points out.  Consider a thunk for
2495 the expression
2496 @
2497   let xs = [1..1000] in last xs
2498
2499 where @last@ is a function that returns the last element of its
2500 argument list.  When the thunk is entered it will call @last@, which
2501 will consume @xs@ until it finds the last element.  Since the list
2502 @[1..1000]@ is produced lazily one might reasonably expect the
2503 expression to evaluate in constant space.  But {\em until the moment
2504 of update, the thunk itself still retains a pointer to the beginning
2505 of the list @xs@}.  So, until the update takes place the whole list
2506 will be retained!
2507
2508 Of course, this is completely gratuitous.  The pointer to @xs@ in the
2509 thunk will never be used again.  In <.peyton stock hardware.> the solution to
2510 this problem that we advocated was to overwrite a thunk's info with a
2511 fixed ``black hole'' info pointer, {\em at the moment of entry}.  The
2512 storage management information attached to a black-hole info pointer
2513 tells the garbage collector that the closure contains no pointers,
2514 thereby plugging the space leak.
2515
2516 \subsubsection{Lazy black-holing}
2517
2518 Black-holing is a well-known idea.  The trouble is that it is
2519 gallingly expensive.  To avoid the occasional space leak, for every
2520 single thunk entry we have to load a full-word literal constant into a
2521 register (often two instructions) and then store that register into a
2522 memory location.  
2523
2524 Fortunately, this cost can easily be avoided.  The
2525 idea is simple: {\em instead of black-holing every thunk on entry,
2526 wait until the garbage collector is called, and then black-hole all
2527 (and only) the thunks whose evaluation is in progress at that moment}.
2528 There is no benefit in black-holing a thunk that is updated before
2529 garbage collection strikes!  In effect, the idea is to perform the
2530 black-holing operation lazily, only when it is needed.  This
2531 dramatically cuts down the number of black-holing operations, as our
2532 results show {\em forward ref}.
2533
2534 How can we find all the thunks whose evaluation is in progress?  They
2535 are precisely the ones for which update frames are on the stack.  So
2536 all we need do is find all the update frames (via the @Su@ chain) and
2537 black-hole their thunks right at the start of garbage collection.
2538 Notice that it is not enough to refrain from treating update frames as
2539 roots: firstly because the thunks to which they point may need to be
2540 moved in a copying collector, but more importantly because the thunk
2541 might be accessible via some other route.
2542
2543 \subsubsection{Detecting loops}
2544
2545 Black-holing has a second minor advantage: evaluation of a thunk whose
2546 value depends on itself will cause a black hole closure to be entered,
2547 which can cause a suitable error message to be displayed. For example,
2548 consider the definition
2549 @
2550   x = 1+x
2551 @
2552 The code to evaluate @x@'s right hand side will evaluate @x@.  In the
2553 absence of black-holing, the result will be a stack overflow, as the
2554 evaluator repeatedly pushes a return address and enters @x@.  If
2555 thunks are black-holed on entry, then this infinite loop can be caught
2556 almost instantly.
2557
2558 With our new method of lazy black-holing, a self-referential program
2559 might cause either stack overflow or a black-hole error message,
2560 depending on exactly when garbage collection strikes.  It is quite
2561 easy to conceal these differences, however.  If stack overflow occurs,
2562 all we need do is examine the update frames on the stack to see if
2563 more than one refers to the same thunk.  If so, there is a loop that
2564 would have been detected by eager black-holing.
2565
2566 \subsubsection{Lazy locking}
2567 \label{sect:lock}
2568
2569 In a parallel implementation, it is necessary somehow to ``lock'' a
2570 thunk that is under evaluation, so that other parallel evaluators
2571 cannot simultaneously evaluate it and thereby duplicate work.
2572 Instead, an evaluator that enters a locked thunk should be blocked,
2573 and made runnable again when the thunk is updated.
2574
2575 This locking is readily arranged in the same way as black-holing, by
2576 overwriting the thunk's info pointer with a special ``locked'' info
2577 pointer, at the moment of entry.  If another evaluator enters the
2578 thunk before it has been updated, it will land in the entry code for
2579 the ``locked'' info pointer, which blocks the evaluator and queues it
2580 on the locked thunk.
2581
2582 The details are given by <.portable parallel trinder.>.  However, the close similarity
2583 between locking and black holing suggests the following question: can
2584 locking be done lazily too?  The answer is that it can, except that
2585 locking can be postponed only until the next {\em context switch},
2586 rather than the next {\em garbage collection}.  We are assuming here
2587 that the parallel implementation does not use shared memory to allow
2588 two processors to access the same closure.  If such access is
2589 permitted then every thunk entry requires a hardware lock, and becomes
2590 much too expensive.
2591
2592 Is lazy locking worth while, given that it requires extra work every
2593 context switch?  We believe it is, because contexts switches are
2594 relatively infrequent, and thousands of thunk-entries typically take
2595 place between each.
2596
2597 {\em Measurements elsewhere.  Omit this section? If so, fix cross refs to here.}
2598
2599 \fi
2600
2601
2602 \subsection{Squeezing identical updates}
2603
2604 \iffalse
2605
2606 \ToDo{Insert text stolen from update paper}
2607
2608 \else
2609
2610 Consider the following Haskell definition of the standard
2611 function @partition@ that divides a list into two, those elements
2612 that satisfy a predicate @p@ and those that do not:
2613 @
2614   partition :: (a->Bool) -> [a] -> ([a],[a])
2615   partition p [] = ([],[])
2616   partition p (x:xs) = if p x then (x:ys, zs)
2617                               else (ys, x:zs)
2618                      where
2619                        (ys,zs) = partition p xs
2620 @
2621 By the time this definition has been desugared, it looks like this:
2622 @
2623   partition p xs
2624     = case xs of
2625         [] -> ([],[])
2626         (x:xs) -> let
2627                     t = partition p xs
2628                     ys = fst t
2629                     zs = snd t
2630                   in
2631                   if p x then (x:ys,zs)
2632                          else (ys,x:zs)
2633 @
2634 Lazy evaluation demands that the recursive call is bound to an
2635 intermediate variable, @t@, from which @ys@ and @zs@ are lazily
2636 selected. (The functions @fst@ and @snd@ select the first and second
2637 elements of a pair, respectively.)
2638
2639 Now, suppose that @partition@ is applied to a list @[x1,x2]@,
2640 all of whose
2641 elements satisfy @p@.  We can get a good idea of what will happen
2642 at runtime by unrolling the recursion a few times in our heads.
2643 Unrolling once, and remembering that @(p x1)@ is @True@, we get this:
2644 @
2645   partition p [x1,x2]
2646 =
2647   let t1 = partition [x2]
2648       ys1 = fst t1
2649       zs1 = snd t1
2650   in (x1:ys1, zs1)
2651 @
2652 Unrolling the rest of the way gives this:
2653 @
2654   partition p [x1,x2]
2655 =
2656   let t2  = ([],[])
2657       ys2 = fst t2
2658       zs2 = snd t2
2659       t1  = (x2:ys2,zs2)
2660       ys1 = fst t1
2661       zs1 = snd t1
2662    in (x1:ys1,zs1)
2663 @
2664 Now consider what happens if @zs1@ is evaluated.  It is bound to a
2665 thunk, which will push an update frame before evaluating the
2666 expression @snd t1@.  This expression in turn forces evaluation of
2667 @zs2@, which pushes an update frame before evaluating @snd t2@.
2668 Indeed the stack of update frames will grow as deep as the list is
2669 long when @zs1@ is evaluated.  This is rather galling, since all the
2670 thunks @zs1@, @zs2@, and so on, have the same value.
2671
2672 \ToDo{Describe the state-transformer case in which we get a space leak from
2673 pending update frames.}
2674
2675 The solution is simple.  The garbage collector, which is going to traverse the
2676 update stack in any case, can easily identify two update frames that are directly
2677 on top of each other.  The second of these will update its target with the same
2678 value as the first.  Therefore, the garbage collector can perform the update 
2679 right away, by overwriting one update target with an indirection to the second,
2680 and eliminate the corresponding update frame.  In this way ever-growing stacks of
2681 update frames are reduced to a single representative at garbage collection time.
2682 If this is done at the start of garbage collection then, if it turns out that
2683 some of these update targets are garbage they will be collected right away.
2684
2685 \fi
2686
2687 \subsection{Space leaks and selectors}
2688
2689 \iffalse
2690
2691 \ToDo{Insert text stolen from update paper}
2692
2693 \else
2694
2695 In 1987, Wadler identified an important source of space leaks in
2696 lazy functional programs.  Consider the Haskell function definition:
2697 @
2698   f p = (g1 a, g2 b) where (a,b) = p
2699 @
2700 The pattern-matching in the @where@ clause is known as
2701 {\em lazy pattern-matching}, because it is performed only if @a@
2702 or @b@ is actually evaluated.  The desugarer translates lazy pattern matching
2703 to the use of selectors, @fst@ and @snd@ in this case:
2704 @
2705   f p = let a = fst p
2706             b = snd p
2707         in
2708         (b, a)
2709 @
2710 Now suppose that the second component of the pair @(f p)@, namely @a@,
2711 is evaluated and discarded, but the first is not although it remains
2712 reachable.  The garbage collector will find that the thunk for @b@ refers
2713 to @p@ and hence to @a@.  Thus, although @a@ cannot ever be used again, its
2714 space is retained.  It turns out that this space leak can have a very bad effect
2715 indeed on a program's space behaviour (Section~\ref{sect:selector-results}).
2716
2717 Wadler's paper also proposed a solution: if the garbage collector
2718 encounters a thunk of the form @snd p@, where @p@ is evaluated, then
2719 the garbage collector should perform the selection and overwrite the
2720 thunk with a pointer to the second component of the pair.  In effect, the
2721 garbage collector thereby performs a bounded amount of as-yet-undemanded evaluation
2722 in the hope of improving space behaviour.
2723 We implement this idea directly, by making the garbage collector
2724 eagerly execute all selector thunks\footnote{A word of caution: it is rather easy 
2725 to make a mistake in the implementation, especially if the garbage collector
2726 uses pointer reversal to traverse the reachable graph.},
2727 with results 
2728 reported in Section~\ref{sect:THUNK_SEL}.
2729
2730 One could easily imagine generalisations of this idea, with the garbage 
2731 collector performing bounded amounts of space-saving work.  One example is
2732 this:
2733 @
2734   f x []     = (x,x)
2735   f x (y:ys) = f (x+1) ys
2736 @
2737 Most lazy evaluators will build up a chain of thunks for the accumulating
2738 parameter, @x@, each of which increments @x@.  It is not safe to evaluate
2739 any of these thunks eagerly, since @f@ is not strict in @x@, and we know nothing
2740 about the value of @x@ passed in the initial call to @f@.
2741 On the other hand, if the garbage collector found a thunk @(x+1)@ where
2742 @x@ happened to be evaluated, then it could ``execute'' it eagerly.
2743 If done carefully, the entire chain could be eliminated in a single
2744 garbage collection.   We have not (yet) implemented this idea.
2745 A very similar idea, dubbed ``stingy evaluation'', is described 
2746 by <.stingy.>.
2747
2748 <.sparud lazy pattern matching.> describes another solution to the
2749 lazy-pattern-matching
2750 problem.  His solution involves adding code to the two thunks for
2751 @a@ and @b@ so that if either is evaluated it arranges to update the
2752 other as well as itself.  The garbage-collector solution is a little
2753 more general, since it applies whether or not the selectors were
2754 generated by lazy pattern matching, and in our setting it was easier
2755 to implement than Sparud's.
2756
2757 \fi
2758
2759
2760 \subsection{Internal workings of the Compacting Collector}
2761
2762 \subsection{Internal workings of the Copying Collector}
2763
2764 \subsection{Internal workings of the Generational Collector}
2765
2766
2767
2768 \section{Profiling}
2769
2770 Registering costs centres looks awkward - can we tidy it up?
2771
2772 \section{Parallelism}
2773
2774 Something about global GC, inter-process messages and fetchmes.
2775
2776 \section{Debugging}
2777
2778 \section{Ticky Ticky profiling}
2779
2780 Measure what proportion of ...:
2781 \begin{itemize}
2782 \item
2783 ... Enters are to data values, function values, thunks.
2784 \item
2785 ... allocations are for data values, functions values, thunks.
2786 \item
2787 ... updates are for data values, function values.
2788 \item
2789 ... updates ``fit''
2790 \item
2791 ... return-in-heap (dynamic)
2792 \item
2793 ... vectored return (dynamic)
2794 \item
2795 ... updates are wasted (never re-entered).
2796 \item
2797 ... constructor returns get away without hitting an update.
2798 \end{itemize}
2799
2800 %************************************************************************
2801 %*                                                                      *
2802 \subsubsection[ticky-stk-heap-use]{Stack and heap usage}
2803 %*                                                                      *
2804 %************************************************************************
2805
2806 Things we are interested in here:
2807 \begin{itemize}
2808 \item
2809 How many times we do a heap check and move @Hp@; comparing this with
2810 the allocations gives an indication of how many things we get per trip
2811 to the well:
2812
2813 If we do a ``heap lookahead,'' we haven't really allocated any
2814 heap, so we need to undo the effects of an @ALLOC_HEAP@:
2815
2816 \item
2817 The stack high-water mark.
2818
2819 \item
2820 Re-use of stack slots, and stubbing of stack slots:
2821
2822 \end{itemize}
2823
2824 %************************************************************************
2825 %*                                                                      *
2826 \subsubsection[ticky-allocs]{Allocations}
2827 %*                                                                      *
2828 %************************************************************************
2829
2830 We count things every time we allocate something in the dynamic heap.
2831 For each, we count the number of words of (1)~``admin'' (header),
2832 (2)~good stuff (useful pointers and data), and (3)~``slop'' (extra
2833 space, in hopes it will allow an in-place update).
2834
2835 The first five macros are inserted when the compiler generates code
2836 to allocate something; the categories correspond to the @ClosureClass@
2837 datatype (manifest functions, thunks, constructors, big tuples, and
2838 partial applications).
2839
2840 We may also allocate space when we do an update, and there isn't
2841 enough space.  These macros suffice (for: updating with a partial
2842 application and a constructor):
2843
2844 In the threaded world, we allocate space for the spark pool, stack objects,
2845 and thread state objects.
2846
2847 The histogrammy bit is fairly straightforward; the @-2@ is: one for
2848 0-origin C arrays; the other one because we do {\em no} one-word
2849 allocations, so we would never inc that histogram slot; so we shift
2850 everything over by one.
2851
2852 Some hard-to-account-for words are allocated by/for primitives,
2853 includes Integer support.  @ALLOC_PRIM2@ tells us about these.  We
2854 count everything as ``goods'', which is not strictly correct.
2855 (@ALLOC_PRIM@ is the same sort of stuff, but we know the
2856 admin/goods/slop breakdown.)
2857
2858 %************************************************************************
2859 %*                                                                      *
2860 \subsubsection[ticky-enters]{Enters}
2861 %*                                                                      *
2862 %************************************************************************
2863
2864 We do more magical things with @ENT_FUN_DIRECT@.  Besides simply knowing
2865 how many ``fast-entry-point'' enters there were, we'd like {\em simple}
2866 information about where those enters were, and the properties thereof.
2867 @
2868 struct ent_counter {
2869     unsigned    registeredp:16, /* 0 == no, 1 == yes */
2870                 arity:16,       /* arity (static info) */
2871                 Astk_args:16,   /* # of args off A stack */
2872                 Bstk_args:16;   /* # of args off B stack */
2873                                 /* (rest of args are in registers) */
2874     StgChar     *f_str;         /* name of the thing */
2875     StgChar     *f_arg_kinds;   /* info about the args types */
2876     StgChar     *wrap_str;      /* name of its wrapper (if any) */
2877     StgChar     *wrap_arg_kinds;/* info about the orig wrapper's arg types */
2878     I_          ctr;            /* the actual counter */
2879     struct ent_counter *link;   /* link to chain them all together */
2880 };
2881 @
2882
2883 %************************************************************************
2884 %*                                                                      *
2885 \subsubsection[ticky-returns]{Returns}
2886 %*                                                                      *
2887 %************************************************************************
2888
2889 Whenever a ``return'' occurs, it is returning the constituent parts of
2890 a data constructor.  The parts can be returned either in registers, or
2891 by allocating some heap to put it in (the @ALLOC_*@ macros account for
2892 the allocation).  The constructor can either be an existing one
2893 (@*OLD*@) or we could have {\em just} figured out this stuff
2894 (@*NEW*@).
2895
2896 Here's some special magic that Simon wants [edited to match names
2897 actually used]:
2898
2899 @
2900 From: Simon L Peyton Jones <simonpj>
2901 To: partain, simonpj
2902 Subject: counting updates
2903 Date: Wed, 25 Mar 92 08:39:48 +0000
2904
2905 I'd like to count how many times we update in place when actually Node
2906 points to the thing.  Here's how:
2907
2908 @RET_OLD_IN_REGS@ sets the variable @ReturnInRegsNodeValid@ to @True@;
2909 @RET_NEW_IN_REGS@ sets it to @False@.
2910
2911 @RET_SEMI_???@ sets it to??? ToDo [WDP]
2912
2913 @UPD_CON_IN_PLACE@ tests the variable, and increments @UPD_IN_PLACE_COPY_ctr@
2914 if it is true.
2915
2916 Then we need to report it along with the update-in-place info.
2917 @
2918
2919
2920 Of all the returns (sum of four categories above), how many were
2921 vectored?  (The rest were obviously unvectored).
2922
2923 %************************************************************************
2924 %*                                                                      *
2925 \subsubsection[ticky-update-frames]{Update frames}
2926 %*                                                                      *
2927 %************************************************************************
2928
2929 These macros count up the following update information.
2930
2931 \begin{tabular}{|l|l|} \hline
2932 Macro                   &       Counts                                  \\ \hline
2933                         &                                               \\
2934 @UPDF_STD_PUSHED@       &       Update frame pushed                     \\
2935 @UPDF_CON_PUSHED@       &       Constructor update frame pushed         \\
2936 @UPDF_HOLE_PUSHED@      &       An update frame to update a black hole  \\
2937 @UPDF_OMITTED@          &       A thunk decided not to push an update frame \\
2938                         &       (all subsets of @ENT_THK@)              \\
2939 @UPDF_RCC_PUSHED@       &       Cost Centre restore frame pushed        \\
2940 @UPDF_RCC_OMITTED@      &       Cost Centres not required -- not pushed \\\hline
2941 \end{tabular}
2942
2943 %************************************************************************
2944 %*                                                                      *
2945 \subsubsection[ticky-updates]{Updates}
2946 %*                                                                      *
2947 %************************************************************************
2948
2949 These macros record information when we do an update.  We always
2950 update either with a data constructor (CON) or a partial application
2951 (PAP).
2952
2953 \begin{tabular}{|l|l|}\hline
2954 Macro                   &       Where                                           \\ \hline
2955                         &                                                       \\
2956 @UPD_EXISTING@          &       Updating with an indirection to something       \\
2957                         &       already in the heap                             \\
2958 @UPD_SQUEEZED@          &       Same as @UPD_EXISTING@ but because              \\
2959                         &       of stack-squeezing                              \\
2960 @UPD_CON_W_NODE@        &       Updating with a CON: by indirecting to Node     \\
2961 @UPD_CON_IN_PLACE@      &       Ditto, but in place                             \\
2962 @UPD_CON_IN_NEW@        &       Ditto, but allocating the object                \\
2963 @UPD_PAP_IN_PLACE@      &       Same, but updating w/ a PAP                     \\
2964 @UPD_PAP_IN_NEW@        &                                                       \\\hline
2965 \end{tabular}
2966
2967 %************************************************************************
2968 %*                                                                      *
2969 \subsubsection[ticky-selectors]{Doing selectors at GC time}
2970 %*                                                                      *
2971 %************************************************************************
2972
2973 @GC_SEL_ABANDONED@: we could've done the selection, but we gave up
2974 (e.g., to avoid overflowing the C stack); @GC_SEL_MINOR@: did a
2975 selection in a minor GC; @GC_SEL_MAJOR@: ditto, but major GC.
2976
2977
2978
2979 \section{History}
2980
2981 We're nuking the following:
2982
2983 \begin{itemize}
2984 \item
2985   Two stacks
2986
2987 \item
2988   Return in registers.
2989   This lets us remove update code pointers from info tables,
2990   removes the need for phantom info tables, simplifies 
2991   semi-tagging, etc.
2992
2993 \item
2994   Threaded GC.
2995   Careful analysis suggests that it doesn't buy us very much
2996   and it is hard to work with.
2997
2998   Eliminating threaded GCs eliminates the desire to share SMReps
2999   so they are (once more) part of the Info table.
3000
3001 \item
3002   RetReg.
3003   Doesn't buy us anything on a register-poor architecture and
3004   isn't so important if we have semi-tagging.
3005
3006 @
3007     - Probably bad on register poor architecture 
3008     - Can avoid need to write return address to stack on reg rich arch.
3009       - when a function does a small amount of work, doesn't 
3010         enter any other thunks and then returns.
3011         eg entering a known constructor (but semitagging will catch this)
3012     - Adds complications
3013 @
3014
3015 \item
3016   Update in place
3017
3018   This lets us drop CONST closures and CHARLIKE closures (assuming we
3019   don't support Unicode).  The only point of these closures was to 
3020   avoid updating with an indirection.
3021
3022   We also drop @MIN_UPD_SIZE@ --- all we need is space to insert an
3023   indirection or a black hole.
3024
3025 \item
3026   STATIC SMReps are now called CONST
3027
3028 \item
3029   @SM_MUTVAR@ is new
3030
3031 \item The profiling ``kind'' field is now encoded in the @INFO_TYPE@ field.
3032 This identifies the general sort of the closure for profiling purposes.
3033
3034 \item Various papers describe deleting update frames for unreachable objects.
3035   This has never been implemented and we don't plan to anytime soon.
3036
3037 \end{itemize}
3038
3039 \section{Old tricks}
3040
3041 @CAF@ indirections:
3042
3043 These are statically defined closures which have been updated with a
3044 heap-allocated result.  Initially these are exactly the same as a
3045 @STATIC@ closure but with special entry code. On entering the closure
3046 the entry code must:
3047
3048 \begin{itemize}
3049 \item Allocate a black hole in the heap which will be updated with
3050       the result.
3051 \item Overwrite the static closure with a special @CAF@ indirection.
3052
3053 \item Link the static indirection onto the list of updated @CAF@s.
3054 \end{itemize}
3055
3056 The indirection and the link field require the initial @STATIC@
3057 closure to be of at least size @MIN_UPD_SIZE@ (excluding the fixed
3058 header).
3059
3060 @CAF@s are treated as special garbage collection roots.  These roots
3061 are explicitly collected by the garbage collector, since they may
3062 appear in code even if they are not linked with the main heap.  They
3063 consequently represent potentially enormous space-leaks.  A @CAF@
3064 closure retains a fixed location in statically allocated data space.
3065 When updated, the contents of the @CAF@ indirection are changed to
3066 reflect the new closure. @CAF@ indirections require special garbage
3067 collection code.
3068
3069 \section{Old stuff about SRTs}
3070
3071 Garbage collection of @CAF@s is tricky.  We have to cope with explicit
3072 collection from the @CAFlist@ as well as potential references from the
3073 stack and heap which will cause the @CAF@ evacuation code to be
3074 called.  They are treated like indirections which are shorted out.
3075 However they must also be updated to point to the new location of the
3076 new closure as the @CAF@ may still be used by references which
3077 reside in the code.
3078
3079 {\bf Copying Collection}
3080
3081 A first scheme might use evacuation code which evacuates the reference
3082 and updates the indirection. This is no good as subsequent evacuations
3083 will result in an already evacuated closure being evacuated. This will
3084 leave a forward reference in to-space!
3085
3086 An alternative scheme evacuates the @CAFlist@ first. The closures
3087 referenced are evacuated and the @CAF@ indirection updated to point to
3088 the evacuated closure. The @CAF@ evacuation code simply returns the
3089 updated indirection pointer --- the pointer to the evacuated closure.
3090 Unfortunately the closure the @CAF@ references may be a static
3091 closure, in fact, it may be another @CAF@. This will cause the second
3092 @CAF@'s evacuation code to be called before the @CAF@ has been
3093 evacuated, returning an unevacuated pointer.
3094
3095 Another scheme leaves updating the @CAF@ indirections to the end of
3096 the garbage collection.  All the references are evacuated and
3097 scavenged as usual (including the @CAFlist@). Once collection is
3098 complete the @CAFlist@ is traversed updating the @CAF@ references with
3099 the result of evacuating the referenced closure again. This will
3100 immediately return as it must be a forward reference, a static
3101 closure, or a @CAF@ which will indirect by evacuating its reference.
3102
3103 The crux of the problem is that the @CAF@ evacuation code needs to
3104 know if its reference has already been evacuated and updated. If not,
3105 then the reference can be evacuated, updated and returned safely
3106 (possibly evacuating another @CAF@). If it has, then the updated
3107 reference can be returned. This can be done using two @CAF@
3108 info-tables. At the start of a collection the @CAFlist@ is traversed
3109 and set to an internal {\em evacuate and update} info-table. During
3110 collection, evacution of such a @CAF@ also results in the info-table
3111 being reset back to the standard @CAF@ info-table. Thus subsequent
3112 evacuations will simply return the updated reference. On completion of
3113 the collection all @CAF@s will have {\em return reference} info-tables
3114 again.
3115
3116 This is the scheme we adopt. A @CAF@ indirection has evacuation code
3117 which returns the evacuated and updated reference. During garbage
3118 collection, all the @CAF@s are overwritten with an internal @CAF@ info
3119 table which has evacuation code which performs this evacuate and
3120 update and restores the original @CAF@ code. At some point during the
3121 collection we must ensure that all the @CAF@s are indeed evacuated.
3122
3123 The only potential problem with this scheme is a cyclic list of @CAF@s
3124 all directly referencing (possibly via indirections) another @CAF@!
3125 Evacuation of the first @CAF@ will fail in an infinite loop of @CAF@
3126 evacuations. This is solved by ensuring that the @CAF@ info-table is
3127 updated to a {\em return reference} info-table before performing the
3128 evacuate and update. If this {\em return reference} evacuation code is
3129 called before the actual evacuation is complete it must be because
3130 such a cycle of references exists. Returning the still unevacuated
3131 reference is OK --- all the @CAF@s will now reference the same
3132 @CAF@ which will reference itself! Construction of such a structure
3133 indicates the program must be in an infinite loop.
3134
3135 {\bf Compacting Collector}
3136
3137 When shorting out a @CAF@, its reference must be marked. A first
3138 attempt might explicitly mark the @CAF@s, updating the reference with
3139 the marked reference (possibly short circuting indirections). The
3140 actual @CAF@ marking code can indicate that they have already been
3141 marked (though this might not have actually been done yet) and return
3142 the indirection pointer so it is shorted out. Unfortunately the @CAF@
3143 reference might point to an indirection which will be subsequently
3144 shorted out. Rather than returning the @CAF@ reference we treat the
3145 @CAF@ as an indirection, calling the mark code of the reference, which
3146 will return the appropriately shorted reference.
3147
3148 Problem: Cyclic list of @CAF@s all directly referencing (possibly via
3149 indirections) another @CAF@!
3150
3151 Before compacting, the locations of the @CAF@ references are
3152 explicitly linked to the closures they reference (if they reference
3153 heap allocated closures) so that the compacting process will update
3154 them to the closure's new location. Unfortunately these locations'
3155 @CAF@ indirections are static.  This causes premature termination
3156 since the test to find the info pointer at the end of the location
3157 list will match more than one value.  This can be solved by using an
3158 auxiliary dynamic array (on the top of the A stack).  One location for
3159 each @CAF@ indirection is linked to the closure that the @CAF@
3160 references. Once collection is complete this array is traversed and
3161 the corresponding @CAF@ is then updated with the updated pointer from
3162 the auxiliary array.
3163
3164
3165 It is possible to use an alternative marking scheme, using a similar
3166 idea to the copying solution. This scheme avoids the need to update
3167 the @CAF@ references explicitly. We introduce an auxillary {\em mark
3168 and update} @CAF@ info-table which is used to update all @CAF@s at the
3169 start of a collection. The new code marks the @CAF@ reference,
3170 updating it with the returned reference.  The returned reference is
3171 itself returned so the @CAF@ is shorted out.  The code also modifies the
3172 @CAF@ info-table to be a {\em return reference}.  Subsequent attempts to
3173 mark the @CAF@ simply return the updated reference.
3174
3175 A cyclic @CAF@ reference will result in an attempt to mark the @CAF@
3176 before the marking has been completed and the reference updated. We
3177 cannot start marking the @CAF@ as it is already being marked. Nor can
3178 we return the reference as it has not yet been updated. Neither can we
3179 treat the CAF as an indirection since the @CAF@ reference has been
3180 obscured by the pointer reversal stack. All we can do is return the
3181 @CAF@ itself. This will result in some @CAF@ references not being
3182 shorted out.
3183
3184 This scheme has not been adopted but has been implemented. The code is
3185 commented out with @#if 0@.
3186
3187 \subsection{The virtual register set}
3188
3189 We refer to any (atomic) part of the virtual machine state as a ``register.''
3190 These ``registers'' may be shared between all threads in the system or may be
3191 specific to each thread.
3192
3193 Global: 
3194 @
3195   Hp
3196   HpLim
3197   Thread preemption flag
3198 @
3199
3200 Thread specific:
3201 @
3202   TSO - pointer to the TSO for when we have to pack thread away
3203   Sp
3204   SpLim
3205   Su - used to calculate number of arguments on stack
3206      - this is a more convenient representation
3207   Call/return registers (aka General purpose registers)
3208   Cost centre (and other debug/profile info)
3209   Statistic gathering (not in production system)
3210   Exception handlers 
3211     Heap overflow  - possible global?
3212     Stack overflow - possibly global?
3213     Pattern match failure
3214     maybe a failWith handler?
3215     maybe an exitWith handler?
3216     ...
3217 @
3218
3219 Some of these virtual ``registers'' are used very frequently and should
3220 be mapped onto machine registers if at all possible.  Others are used
3221 very infrequently and can be kept in memory to free up registers for
3222 other uses.
3223
3224 On register-poor architectures, we can play a few tricks to reduce the
3225 number of virtual registers which need to be accessed on a regular
3226 basis:
3227
3228 @
3229 - HpLim trick
3230 - Grow stack and heap towards each other (single-threaded system only)
3231 - We might need to keep the C stack pointer in a register if that
3232   is what the OS expects when a signal occurs.
3233 - Preemption flag trick
3234 - If any of the frequently accessed registers cannot be mapped onto
3235   machine registers we should keep the TSO in a machine register to
3236   allow faster access to all the other non-machine registers.
3237 @
3238
3239
3240 \end{document}
3241
3242