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