2 % (c) The OBFUSCATION-THROUGH-GRATUITOUS-PREPROCESSOR-ABUSE Project,
3 % Glasgow University, 1990-1994
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.
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
23 \newcommand{\note}[1]{{\em Note: #1}}
33 \setlength{\parskip}{0.15cm}
34 \setlength{\parsep}{0.15cm}
35 \setlength{\topsep}{0cm} % Reduces space before and after verbatim,
36 % which is implemented using trivlist
37 \setlength{\parindent}{0cm}
39 \renewcommand{\textfraction}{0.2}
40 \renewcommand{\floatpagefraction}{0.7}
44 \newcommand{\ToDo}[1]{{{\bf ToDo:}\sl #1}}
45 \newcommand{\Arg}[1]{\mbox{${\tt arg}_{#1}$}}
46 \newcommand{\bottom}{bottom} % foo, can't remember the symbol name
48 \title{The STG runtime system (revised)}
49 \author{Simon Peyton Jones \\ Glasgow University and Oregon Graduate Institute \and
50 Alastair Reid \\ Yale University}
57 \section{Introduction}
59 This document describes the GHC/Hugs run-time system. It serves as
60 a Glasgow/Yale/Nottingham ``contract'' about what the RTS does.
62 \subsection{New features compared to GHC 2.04}
65 \item The RTS supports mixed compiled/interpreted execution, so
66 that a program can consist of a mixture of GHC-compiled and Hugs-interpreted
69 \item CAFs are only retained if they are
70 reachable. Since they are referred to by implicit references buried
71 in code, this means that the garbage collector must traverse the whole
72 accessible code tree. This feature eliminates a whole class of painful
75 \item A running thread has only one stack, which contains a mixture
76 of pointers and non-pointers. Section~\ref{sect:stacks} describes how
77 we find out which is which. (GHC has used two stacks for some while.
78 Using one stack instead of two reduces register pressure, reduces the
79 size of update frames, and eliminates
80 ``stack-stubbing'' instructions.)
84 \subsection{Wish list}
86 Here's a list of things we'd like to support in the future.
88 \item Interrupts, speculative computation.
91 The SM could tune the size of the allocation arena, the number of
92 generations, etc taking into account residency, GC rate and page fault
96 There should be no need to specify the amnount of stack/heap space to
97 allocate when you started a program - let it just take as much or as
98 little as it wants. (It might be useful to be able to specify maximum
99 sizes and to be able to suggest an initial size.)
102 We could trigger a GC when all threads are blocked waiting for IO if
103 the allocation arena (or some of the generations) are nearly full.
107 \subsection{Configuration}
109 Some of the above features are expensive or less portable, so we
110 envision building a number of different configurations supporting
111 different subsets of the above features.
113 You can make the following choices:
116 Support for concurrency or parallelism. There are four
117 mutually-exclusive choices.
120 \item[@SEQUENTIAL@] No concurrency or parallelism support.
121 This configuration might not support interrupt recovery.
122 \item[@CONCURRENT@] Support for concurrency but not for parallelism.
123 \item[@CONCURRENT@+@GRANSIM@] Concurrency support and simulated parallelism.
124 \item[@CONCURRENT@+@PARALLEL@] Concurrency support and real parallelism.
127 \item @PROFILING@ adds cost-centre profiling.
129 \item @TICKY@ gathers internal statistics (often known as ``ticky-ticky'' code).
131 \item @DEBUG@ does internal consistency checks.
133 \item Persistence. (well, not yet).
136 Which garbage collector to use. At the moment we
137 only anticipate one, however.
140 \subsection{Terminology}
144 \item A {\em word} is (at least) 32 bits and can hold either a signed
147 \item A {\em pointer} is (at least) 32 bits and big enough to hold a
148 function pointer or a data pointer.
150 \item A {\em closure} is a (representation of) a value of a {\em pointed}
151 type. It may be in HNF or it may be unevaluated --- in either case, you can
152 try to evaluate it again.
154 \item A {\em thunk} is a (representation of) a value of a {\em pointed}
155 type which is {\em not} in HNF.
159 Occasionally, a field of a data structure must hold either a word or a
160 pointer. In such circumstances, it is {\em not safe} to assume that
161 words and pointers are the same size.
164 % More terminology to mention.
167 There are a few other system invariants which need to be mentioned ---
168 though not necessarily here:
172 \item The garbage collector never expands an object when it promotes
173 it to the old generation. This is important because the GC avoids
174 performing heap overflow checks by assuming that the amount added to
175 the old generation is no bigger than the current new generation.
180 \section{The Scheduler}
182 The Scheduler is the heart of the run-time system. A running program
183 consists of a single running thread, and a list of runnable and
184 blocked threads. The running thread returns to the scheduler when any
185 of the following conditions arises:
188 \item A heap check fails, and a garbage collection is required
189 \item Compiled code needs to switch to interpreted code, and vice
191 \item The thread becomes blocked.
192 \item The thread is preempted.
195 A running system has a global state, consisting of
198 \item @Hp@, the current heap pointer, which points to the next
199 available address in the Heap.
200 \item @HpLim@, the heap limit pointer, which points to the end of the
202 \item The Thread Preemption Flag, which is set whenever the currently
203 running thread should be preempted at the next opportunity.
204 \item A list of runnable threads.
205 \item A list of blocked threads.
208 Each thread is represented by a Thread State Object (TSO), which is
209 described in detail in Section \ref{sect:TSO}.
211 The following is pseudo-code for the inner loop of the scheduler
215 while (threads_exist) {
216 // handle global problems: GC, parallelism, etc
218 if (external_message) service_message();
219 // deal with other urgent stuff
221 pick a runnable thread;
223 switch (thread->whatNext) {
224 case (RunGHC pc): status=runGHC(pc); break;
225 case (RunHugs bc): status=runHugs(bc); break;
227 switch (status) { // handle local problems
228 case (StackOverflow): enlargeStack; break;
229 case (Error e) : error(thread,e); break;
230 case (ExitWith e) : exit(e); break;
231 case (Yield) : break;
233 } while (thread_runnable);
237 Optimisations to avoid excess trampolining from Hugs into itself.
238 How do we invoke GC, ccalls, etc.
239 General ccall (@ccall-GC@) and optimised ccall.
241 \section{Compiled Execution}
243 This section describes the framework in which compiled code evaluates
244 expressions. Only at certain points will compiled code need to be
245 able to talk to the interpreted world; these are discussed in Section
246 \ref{sec:hugs-ghc-interaction}.
248 \subsection{Calling conventions}
250 \subsubsection{The call/return registers}
252 One of the problems in designing a virtual machine is that we want it
253 abstract away from tedious machine details but still reveal enough of
254 the underlying hardware that we can make sensible decisions about code
255 generation. A major problem area is the use of registers in
256 call/return conventions. On a machine with lots of registers, it's
257 cheaper to pass arguments and results in registers than to pass them
258 on the stack. On a machine with very few registers, it's cheaper to
259 pass arguments and results on the stack than to use ``virtual
260 registers'' in memory. We therefore use a hybrid system: the first
261 $n$ arguments or results are passed in registers; and the remaining
262 arguments or results are passed on the stack. For register-poor
263 architectures, it is important that we allow $n=0$.
265 We'll label the arguments and results \Arg{1} \ldots \Arg{m} --- with
266 the understanding that \Arg{1} \ldots \Arg{n} are in registers and
267 \Arg{n+1} \ldots \Arg{m} are on top of the stack.
269 Note that the mapping of arguments \Arg{1} \ldots \Arg{n} to machine
270 registers depends on the {\em kinds} of the arguments. For example,
271 if the first argument is a Float, we might pass it in a different
272 register from if it is an Int. In fact, we might find that a given
273 architecture lets us pass varying numbers of arguments according to
274 their types. For example, if a CPU has 2 Int registers and 2 Float
275 registers then we could pass between 2 and 4 arguments in machine
276 registers --- depending on whether they all have the same kind or they
277 have different kinds.
279 \subsubsection{Entering closures}
281 To evaluate a closure we jump to the entry code for the closure
282 passing a pointer to the closure in \Arg{1} so that the entry code can
283 access its environment.
285 \subsubsection{Function call}
287 The function-call mechanism is obviously crucial. There are five different
291 \item {\em Known combinator (function with no free variables) and enough arguments.}
293 A fast call can be made: push excess arguments onto stack and jump to
294 function's {\em fast entry point} passing arguments in \Arg{1} \ldots
297 The {\em fast entry point} is only called with exactly the right
298 number of arguments (in \Arg{1} \ldots \Arg{m}) so it can instantly
299 start doing useful work without first testing whether it has enough
300 registers or having to pop them off the stack first.
302 \item {\em Known combinator and insufficient arguments.}
304 A slow call can be made: push all arguments onto stack and jump to
305 function's {\em slow entry point}.
307 Any unpointed arguments which are pushed on the stack must be tagged.
308 This means pushing an extra word on the stack below the unpointed
309 words, containing the number of unpointed words above it.
311 %Todo: forward ref about tagging?
314 The {\em slow entry point} might be called with insufficient arguments
315 and so it must test whether there are enough arguments on the stack.
316 This {\em argument satisfaction check} consists of checking that
317 @Su-Sp@ is big enough to hold all the arguments (including any tags).
321 \item If the argument satisfaction check fails, it is because there is
322 one or more update frames on the stack before the rest of the
323 arguments that the function needs. In this case, we construct a PAP
324 (partial application, section~\ref{sect:PAP}) containing the arguments
325 which are on the stack. The PAP construction code will return to the
326 update frame with the address of the PAP in \Arg{1}.
328 \item If the argument satisfaction check succeeds, we jump to the fast
329 entry point with the arguments in \Arg{1} \ldots \Arg{arity}.
331 If the fast entry point expects to receive some of \Arg{i} on the
332 stack, we can reduce the amount of movement required by making the
333 stack layout for the fast entry point look like the stack layout for
334 the slow entry point. Since the slow entry point is entered with the
335 first argument on the top of the stack and with tags in front of any
336 unpointed arguments, this means that if \Arg{i} is unpointed, there
337 should be space below it for a tag and that the highest numbered
338 argument should be passed on the top of the stack.
340 We usually arrange that the fast entry point is placed immediately
341 after the slow entry point --- so we can just ``fall through'' to the
342 fast entry point without performing a jump.
347 \item {\em Known function closure (function with free variables) and enough arguments.}
349 A fast call can be made: push excess arguments onto stack and jump to
350 function's {\em fast entry point} passing a pointer to closure in
351 \Arg{1} and arguments in \Arg{2} \ldots \Arg{m+1}.
353 Like the fast entry point for a combinator, the fast entry point for a
354 closure is only called with appropriate values in \Arg{1} \ldots
355 \Arg{m+1} so we can start work straight away. The pointer to the
356 closure is used to access the free variables of the closure.
359 \item {\em Known function closure and insufficient arguments.}
361 A slow call can be made: push all arguments onto stack and jump to the
362 closure's slow entry point passing a pointer to the closure in \Arg{1}.
364 Again, the slow entry point performs an argument satisfaction check
365 and either builds a PAP or pops the arguments off the stack into
366 \Arg{2} \ldots \Arg{m+1} and jumps to the fast entry point.
369 \item {\em Unknown function closure or thunk.}
371 Sometimes, the function being called is not statically identifiable.
372 Consider, for example, the @compose@ function:
374 compose f g x = f (g x)
376 Since @f@ and @g@ are passed as arguments to @compose@, the latter has
377 to make a heap call. In a heap call the arguments are pushed onto the
378 stack, and the closure bound to the function is entered. In the
379 example, a thunk for @(g x)@ will be allocated, (a pointer to it)
380 pushed on the stack, and the closure bound to @f@ will be
381 entered. That is, we will jump to @f@s entry point passing @f@ in
382 \Arg{1}. If \Arg{1} is passed on the stack, it is pushed on top of
383 the thunk for @(g x)@.
385 The {\em entry code} for an updateable thunk (which must have arity 0)
386 pushes an update frame on the stack and starts executing the body of
387 the closure --- using \Arg{1} to access any free variables. This is
388 described in more detail in section~\ref{sect:data-updates}.
390 The {\em entry code} for a non-updateable closure is just the
391 closure's slow entry point.
395 In addition to the above considerations, if there are \emph{too many}
396 arguments then the extra arguments are simply pushed on the stack with
399 To summarise, a closure's standard (slow) entry point performs the following:
401 \item[Argument satisfaction check.] (function closure only)
402 \item[Stack overflow check.]
403 \item[Heap overflow check.]
404 \item[Copy free variables out of closure.] %Todo: why?
405 \item[Eager black holing.] (updateable thunk only) %Todo: forward ref.
406 \item[Push update frame.]
407 \item[Evaluate body of closure.]
411 \subsection{Case expressions and return conventions}
412 \label{sect:return-conventions}
414 The {\em evaluation} of a thunk is always initiated by
415 a @case@ expression. For example:
420 The code for a @case@ expression looks like this:
423 \item Push the free variables of the branches on the stack (fv(@E@) in
425 \item Push a \emph{return address} on the stack.
426 \item Evaluate the scrutinee (@x@ in this case).
429 Once evaluation of the scrutinee is complete, execution resumes at the
430 return address, which points to the code for the expression @E@.
432 When execution resumes at the return point, there must be some {\em
433 return convention} that defines where the components of the pair, @a@
434 and @b@, can be found. The return convention varies according to the
435 type of the scrutinee @x@:
441 (A space for) the return address is left on the top of the stack.
442 Leaving the return address on the stack ensures that the top of the
443 stack contains a valid activation record
444 (section~\ref{sect:activation-records}) --- should a garbage collection
447 \item If @x@ has a pointed type (e.g.~a data constructor or a function),
448 a pointer to @x@ is returned in \Arg{1}.
450 \ToDo{Warn that components of E should be extracted as soon as
451 possible to avoid a space leak.}
453 \item If @x@ is an unpointed type (e.g.~@Int#@ or @Float#@), @x@ is
456 \item If @x@ is an unpointed tuple constructor, the components of @x@
457 are returned in \Arg{1} \ldots \Arg{n} but no object is constructed in
458 the heap. Unboxed tuple constructors are useful for functions which
459 want to return multiple values such as those used in an (explicitly
460 encoded) state monad:
462 \ToDo{Move stuff about unboxed tuples to a separate section}
465 data unpointed AAndState a = AnS a State
466 type S a = State -> AAndState a
468 bindS m k s0 = case m s0 of { AnS s1 a -> k s1 a }
469 returnS a s = AnS a s
472 Note that unboxed datatypes can only have one constructor and that
473 thunks never have unboxed types --- so we'll never try to update an
474 unboxed constructor. Unboxed tuples are \emph{never} built on the
477 When passing an unboxed tuple to a function, the components are
478 flattened out and passed in \Arg{1} \ldots \Arg{n} as usual.
482 \subsection{Vectored Returns}
484 Many algebraic data types have more than one constructor. For
485 example, the @Maybe@ type is defined like this:
487 data Maybe a = Nothing | Just a
489 How does the return convention encode which of the two constructors is
490 being returned? A @case@ expression scrutinising a value of @Maybe@
491 type would look like this:
497 Rather than pushing a return address before evaluating the scrutinee,
498 @E@, the @case@ expression pushes (a pointer to) a {\em return
499 vector}, a static table consisting of two code pointers: one for the
500 @Just@ alternative, and one for the @Nothing@ alternative.
506 The constructor @Nothing@ returns by jumping to the first item in the
507 return vector with a pointer to a (statically built) Nothing closure
510 It might seem that we could avoid loading \Arg{1} in this case since the
511 first item in the return vector will know that @Nothing@ was returned
512 (and can easily access the Nothing closure in the (unlikely) event
513 that it needs it. The only reason we load \Arg{1} is in case we have to
514 perform an update (section~\ref{sect:data-updates}).
518 The constructor @Just@ returns by jumping to the second element of the
519 return vector with a pointer to the closure in \Arg{1}.
523 In this way no test need be made to see which constructor returns;
524 instead, execution resumes immediately in the appropriate branch of
527 \subsection{Direct Returns}
529 When a datatype has a large number of constructors, it may be
530 inappropriate to use vectored returns. The vector tables may be
531 large and sparse, and it may be better to identify the constructor
532 using a test-and-branch sequence on the tag. For this reason, we
533 provide an alternative return convention, called a \emph{direct
536 In a direct return, the return address pushed on the stack really is a
537 code pointer. The returning code loads a pointer to the closure being
538 returned in \Arg{1} as usual, and also loads the tag into \Arg{2}.
539 The code at the return address will test the tag and jump to the
540 appropriate code for the case branch.
542 The choice of whether to use a vectored return or a direct return is
543 made on a type-by-type basis --- up to a certain maximum number of
544 constructors imposed by the update mechanism
545 (section~\ref{sect:data-updates}).
547 Single-constructor data types also use direct returns, although in
548 that case there is no need to return a tag in \Arg{2}.
550 \ToDo{Say whether we pop the return address before returning}
552 \ToDo{Stack stubbing?}
555 \label{sect:data-updates}
557 The entry code for an updatable thunk (which must also be of arity 0):
560 \item copies the free variables out of the thunk into registers or
562 \item pushes an {\em update frame} onto the stack.
564 An update frame is a small activation record consisting of
566 \begin{tabular}{|l|l|l|}
568 {\em Fixed header} & {\em Update Frame link} & {\em Updatee} \\
573 \note{In the semantics part of the STG paper (section 5.6), an update
574 frame consists of everything down to the last update frame on the
575 stack. This would make sense too --- and would fit in nicely with
576 what we're going to do when we add support for speculative
578 \ToDo{I think update frames contain cost centres sometimes}
581 If we are doing ``eager blackholing,'' we then overwrite the thunk
582 with a black hole. Otherwise, we leave it to the garbage collector to
583 black hole the thunk.
586 Start evaluating the body of the expression.
590 When the expression finishes evaluation, it will enter the update
591 frame on the top of the stack. Since the returner doesn't know
592 whether it is entering a normal return address/vector or an update
593 frame, we follow exactly the same conventions as return addresses and
594 return vectors. That is, on entering the update frame:
597 \item The value of the thunk is in \Arg{1}. (Recall that only thunks
598 are updateable and that thunks return just one value.)
600 \item If the data type is a direct-return type rather than a
601 vectored-return type, then the tag is in \Arg{2}.
603 \item The update frame is still on the stack.
606 We can safely share a single statically-compiled update function
607 between all types. However, the code must be able to handle both
608 vectored and direct-return datatypes. This is done by arranging that
609 the update code looks like this:
617 |---------------| <- update code pointer
622 Each entry in the return vector (which is large enough to cover the
623 largest vectored-return type) points to the update code.
627 \item overwrites the {\em updatee} with an indirection to \Arg{1};
628 \item loads @Su@ from the Update Frame link;
629 \item removes the update frame from the stack; and
630 \item enters \Arg{1}.
633 We enter \Arg{1} again, having probably just come from there, because
634 it knows whether to perform a direct or vectored return. This could
635 be optimised by compiling special update code for each slot in the
636 return vector, which performs the correct return.
638 \subsection{Semi-tagging}
639 \label{sect:semi-tagging}
641 When a @case@ expression evaluates a variable that might be bound
642 to a thunk it is often the case that the scrutinee is already evaluated.
643 In this case we have paid the penalty of (a) pushing the return address (or
644 return vector address) on the stack, (b) jumping through the info pointer
645 of the scrutinee, and (c) returning by an indirect jump through the
646 return address on the stack.
648 If we knew that the scrutinee was already evaluated we could generate
649 (better) code which simply jumps to the appropriate branch of the @case@
650 with a pointer to the scrutinee in \Arg{1}.
652 An obvious idea, therefore, is to test dynamically whether the heap
653 closure is a value (using the tag in the info table). If not, we
654 enter the closure as usual; if so, we jump straight to the appropriate
655 alternative. Here, for example, is pseudo-code for the expression
656 @(case x of { (a,_,c) -> E }@:
658 \Arg{1} = <pointer to x>;
659 tag = \Arg{1}->entry->tag;
661 Sp--; \\ insert space for return address
667 <info table for return address goes here>
668 ret: a = \Arg{1}->data1; \\ suck out a and c to avoid space leak
672 and here is the code for the expression @(case x of { [] -> E1; x:xs -> E2 }@:
674 \Arg{1} = <pointer to x>;
675 tag = \Arg{1}->entry->tag;
677 Sp--; \\ insert space for return address
685 retvec: \\ reversed return vector
686 <return info table for case goes here>
688 panic("Direct return into vectored case");
692 ret2: x = \Arg{1}->head;
696 There is an obvious cost in compiled code size (but none in the size
697 of the bytecodes). There is also a cost in execution time if we enter
698 more thunks than data constructors.
700 Both the direct and vectored returns are easily modified to chase chains
701 of indirections too. In the vectored case, this is most easily done by
702 making sure that @IND = TAG_1 - 1@, and adding an extra field to every
703 return vector. In the above example, the indirection code would be
705 ind: \Arg{1} = \Arg{1}->next;
708 where @ind_loop@ is the second line of code.
710 Note that we have to leave space for a return address since the return
711 address expects to find one. If the body of the expression requires a
712 heap check, we will actually have to write the return address before
713 entering the garbage collector.
716 \subsection{Heap and Stack Checks}
718 \note{I reckon these deserve a subsection of their own}
720 Don't move heap pointer before success occurs.
721 Talk about how stack check looks ahead into the branches of case expressions.
723 \subsection{Handling interrupts/signals}
726 May have to keep C stack pointer in register to placate OS?
727 May have to revert black holes - ouch!
730 \section{Interpreted Execution}
732 \subsection{Hugs Heap Objects}
733 \label{sect:hugs-heap-objects}
735 Compiled byte code lives on the global heap, in objects called
736 Byte-Code Objects (or BCOs). The layout of BCOs is described in
737 detail in Section \ref{sect:BCO}, in this section we will describe
740 Since byte-code lives on the heap, it can be garbage collected just
741 like any other heap-resident data. Hugs maintains a table of
742 currently live BCOs, which is treated as a table of live pointers by
743 the garbage collector. When a module is unloaded, the pointers to its
744 BCOs are removed from the table, and the code will be garbage
745 collected some time later.
747 A BCO represents a basic block of code - all entry points are at the
748 beginning of a BCO, and it is impossible to jump into the middle of
749 one. A BCO represents not only the code for a function, but also its
750 closure; a BCO can be entered just like any other closure. The
751 calling convention for any BCO is:
754 \item Push any arguments on the stack.
755 \item If the code has free variables, push their values on the stack
756 (in a pre-defined order, pointers first).
757 \item Begin interpreting the byte code.
760 If the code has free variables, it cannot be entered directly. The
761 values for the free variables come from a thunk, which is represented
762 by an AP object (Section \ref{sect:AP}). The AP object contains a
763 pointer to a BCO and a number of values. When entered, it pushes the
764 values on the stack and enters the BCO.
766 The AP object can be used for both thunks and partial applications,
767 since the calling convention is the same in each case. The AP object
768 has a counterpart which is used for Hugs return addresses, as we shall
769 see in Section \ref{ghc-to-hugs-return}.
771 \section{Switching Worlds}
773 \label{sect:switching-worlds}
775 Because this is a combined compiled/interpreted system, the
776 interpreter will sometimes encounter compiled code, and vice-versa.
778 All world-switches go via the scheduler, ensuring that the world is in
779 a known state ready to enter either compiled code or the interpreter.
780 When a thread is run from the scheduler, the @whatNext@ field in the
781 TSO (Section \ref{sect:TSO}) is checked to find out how to execute the
785 \item If @whatNext@ is set to @ReturnGHC@, we load up the required
786 registers from the TSO and jump to the address at the top of the user
788 \item If @whatNext@ is set to @EnterGHC@, we load up the required
789 registers from the TSO and enter the closure pointed to by the top
791 \item If @whatNext@ is set to @EnterHugs@, we enter the top thing on
792 the stack, using the interpreter.
795 There are four cases we need to consider:
798 \item A GHC thread enters a Hugs-built closure.
799 \item A GHC thread returns to a Hugs-compiled return address.
800 \item A Hugs thread enters a GHC-built closure.
801 \item A Hugs thread returns to a Hugs-compiled return address.
804 GHC-compiled modules cannot call functions in a Hugs-compiled module
805 directly, because the compiler has no information about arities in the
806 external module. Therefore it must assume any top-level objects are
807 CAFs, and enter their closures.
809 \ToDo{dynamic linking stuff}
810 \ToDo{Hugs-built constructors?}
812 We now examine the various cases one by one and describe how the
813 switch happens in each situation.
815 \subsection{A GHC thread enters a Hugs-built closure}
816 \label{sect:ghc-to-hugs-closure}
818 There are two possibilities: GHC has entered the BCO directly (for a
819 top-level function closure), or it has entered an AP.
821 The code for both objects is the same:
824 \item Push the address of the BCO on the stack.
825 \item Save the current state of the thread in its TSO.
826 \item Return to the scheduler, setting @whatNext@ to @EnterHugs@.
829 \subsection{A GHC thread returns to a Hugs-compiled return address}
830 \label{ghc-to-hugs-return}
832 When Hugs pushes return addresses on the stack, they look like this:
837 | | -----> bytecode object
844 |_____\ |____| hugs_return
850 If GHC is returning, it will return to the address at the top of the
851 stack. This address is a pointer to a statically compiled code
852 fragment called @hugs_return@, which:
855 \item pushes \Arg{1} (the return value) on the stack.
856 \item saves the thread state in the TSO
857 \item returns to the scheduler with @whatNext@ set to @EnterHugs@.
860 \noindent When Hugs runs, it will enter the return value, which will
861 return using the correct Hugs convention to the return address
862 underneath it on the stack.
864 \subsection{A Hugs thread enters a GHC-compiled closure}
865 \label{sect:hugs-to-ghc-closure}
867 Hugs can recognise a GHC-built closure as not being one of the
868 following types of object:
876 When Hugs is called on to enter a GHC closure, it executes the
877 following sequence of instructions:
880 \item Push the address of the closure on the stack.
881 \item Save the current state of the thread in the TSO.
882 \item Return to the scheduler, with the @whatNext@ field set to
886 \subsection{A Hugs thread returns to a GHC-compiled return address}
887 \label{sect:hugs-to-ghc-return}
889 When Hugs is about to return, the stack looks like this:
894 | | -----> return address
896 | | -----> object being returned
901 The return address is recognisable as a GHC-return address by virtue
902 of not being @hugs_return@. Hugs recognises that it needs to do a
903 world-switch and performs the following sequence:
906 \item save the state of the thread in the TSO.
907 \item return to the scheduler, setting @whatNext@ to @EnterGHC@.
910 The first thing that GHC will do is enter the object on the top of the
911 stack, which is a pointer to the value being returned. This value
912 will then return itself to the return address using the GHC return
915 \section{Heap objects}
916 \label{sect:fixed-header}
918 \ToDo{Fix this picture}
928 Every {\em heap object}, or {\em closure} is a contiguous block
929 of memory, consisting of a fixed-format {\em header} followed
930 by zero or more {\em data words}.
931 The header consists of
932 the following fields:
934 \item A one-word {\em info pointer}, which points to
935 the object's static {\em info table}.
936 \item Zero or more {\em admin words} that support
938 \item Profiling (notably a {\em cost centre} word).
939 \note{We could possibly omit the cost centre word from some
940 administrative objects.}
941 \item Parallelism (e.g. GranSim keeps the object's global address here,
942 though GUM keeps a separate hash table).
943 \item Statistics (e.g. a word to track how many times a thunk is entered.).
945 We add a Ticky word to the fixed-header part of closures. This is
946 used to record indicate if a closure has been updated but not yet
947 entered. It is set when the closure is updated and cleared when
948 subsequently entered.
950 NB: It is {\em not} an ``entry count'', it is an
951 ``entries-after-update count.'' The commoning up of @CONST@,
952 @CHARLIKE@ and @INTLIKE@ closures is turned off(?) if this is
953 required. This has only been done for 2s collection.
959 Most of the RTS is completely insensitive to the number of admin words.
960 The total size of the fixed header is @FIXED_HS@.
962 Many heap objects contain fields allowing them to be inserted onto lists
963 during evaluation or during garbage collection. The lists required by
964 the evaluator and storage manager are as follows.
967 \item 2 lists of threads: runnable threads and sleeping threads.
969 \item The {\em static object list} is a list of all statically
970 allocated objects which might contain pointers into the heap.
971 (Section~\ref{sect:static-objects}.)
973 \item The {\em updated thunk list} is a list of all thunks in the old
974 generation which have been updated with an indirection.
975 (Section~\ref{sect:IND_OLDGEN}.)
977 \item The {\em mutables list} is a list of all other objects in the
978 old generation which might contain pointers into the new generation.
979 Most of the object on this list are ``mutable.''
980 (Section~\ref{sect:mutables}.)
982 \item The {\em Foreign Object list} is a list of all foreign objects
983 which have not yet been deallocated. (Section~\ref{sect:FOREIGN}.)
985 \item The {\em Spark pool} is a doubly(?) linked list of Spark objects
986 maintained by the parallel system. (Section~\ref{sect:SPARK}.)
988 \item The {\em Blocked Fetch list} (or
989 lists?). (Section~\ref{sect:BLOCKED_FETCH}.)
991 \item For each thread, there is a list of all update frames on the
992 stack. (Section~\ref{sect:data-updates}.)
997 \ToDo{The links for these fields are usually inserted immediately
998 after the fixed header except ...}
1000 \subsection{Info Tables}
1002 An {\em info table} is a contiguous block of memory, {\em laid out
1003 backwards}. That is, the first field in the list that follows
1004 occupies the highest memory address, and the successive fields occupy
1005 successive decreasing memory addresses.
1008 \begin{tabular}{|c|}
1009 \hline Parallelism Info
1010 \\ \hline Profile Info
1011 \\ \hline Debug Info
1012 \\ \hline Tag/bytecode pointer
1013 \\ \hline Static reference table
1014 \\ \hline Storage manager layout info
1015 \\ \hline Closure type
1016 \\ \hline entry code \ldots
1020 An info table has the following contents (working backwards in memory
1023 \item The {\em entry code} for the closure.
1024 This code appears literally as the (large) last entry in the
1025 info table, immediately preceded by the rest of the info table.
1026 An {\em info pointer} always points to the first byte of the entry code.
1028 \item A one-word {\em closure type field}, @INFO_TYPE@, identifies what kind
1029 of closure the object is. The various types of closure are described
1030 in Section~\ref{sect:closures}.
1031 In some configurations, some useful properties of
1032 closures (is it a HNF? can it be sparked?)
1033 are represented as high-order bits so they can be tested quickly.
1035 \item A single pointer or word --- the {\em storage manager info field},
1036 @INFO_SM@, contains auxiliary information describing the closure's
1037 precise layout, for the benefit of the garbage collector and the code
1038 that stuffs graph into packets for transmission over the network.
1040 \item A one-pointer {\em Static Reference Table (SRT) pointer}, @INFO_SRT@, points to
1041 a table which enables the garbage collector to identify all accessible
1042 code and CAFs. They are fully described in Section~\ref{sect:srt}.
1044 \item A one-pointer {\em tag/bytecode-pointer} field, @INFO_TAG@ or @INFO_BC@.
1045 For data constructors this field contains the constructor tag, in the
1046 range $0..n-1$ where $n$ is the number of constructors.
1048 For other objects that can be entered this field points to the byte
1049 codes for the object. For the constructor case you can think of the
1050 tag as the name of a a suitable bytecode sequence but it can also be used to
1051 implement semi-tagging (section~\ref{sect:semi-tagging}).
1053 One awkward question (which may not belong here) is ``how does the
1054 bytecode interpreter know whether to do a vectored return?'' The
1055 answer is it examines the @INFO_TYPE@ field of the return address:
1056 @RET_VEC_@$sz$ requires a vectored return and @RET_@$sz$ requires a
1059 \item {\em Profiling info\/}
1061 Closure category records are attached to the info table of the
1062 closure. They are declared with the info table. We put pointers to
1063 these ClCat things in info tables. We need these ClCat things because
1064 they are mutable, whereas info tables are immutable. Hashing will map
1065 similar categories to the same hash value allowing statistics to be
1066 grouped by closure category.
1068 Cost Centres and Closure Categories are hashed to provide indexes
1069 against which arbitrary information can be stored. These indexes are
1070 memoised in the appropriate cost centre or category record and
1071 subsequent hashes avoided by the index routine (it simply returns the
1074 There are different features which can be hashed allowing information
1075 to be stored for different groupings. Cost centres have the cost
1076 centre recorded (using the pointer), module and group. Closure
1077 categories have the closure description and the type
1078 description. Records with the same feature will be hashed to the same
1081 The initialisation routines, @init_index_<feature>@, allocate a hash
1082 table in which the cost centre / category records are stored. The
1083 lower bound for the table size is taken from @max_<feature>_no@. They
1084 return the actual table size used (the next power of 2). Unused
1085 locations in the hash table are indicated by a 0 entry. Successive
1086 @init_index_<feature>@ calls just return the actual table size.
1088 Calls to @index_<feature>@ will insert the cost centre / category
1089 record in the @<feature>@ hash table, if not already inserted. The hash
1090 index is memoised in the record and returned.
1092 CURRENTLY ONLY ONE MEMOISATION SLOT IS AVILABLE IN EACH RECORD SO
1093 HASHING CAN ONLY BE DONE ON ONE FEATURE FOR EACH RECORD. This can be
1094 easily relaxed at the expense of extra memoisation space or continued
1097 The initialisation routines must be called before initialisation of
1098 the stacks and heap as they require to allocate storage. It is also
1099 expected that the caller may want to allocate additional storage in
1100 which to store profiling information based on the return table size
1104 \begin{tabular}{|l|}
1108 \\ \hline Description String
1109 \\ \hline Type String
1115 \item[Hash Index] Memoised copy
1117 Is this category selected (-1 == not memoised, selected? 0 or 1)
1119 One of the following values (defined in CostCentre.lh):
1127 A partial application.
1129 A thunk, or suspension.
1134 \item[@ForeignObj_K@]
1135 A Foreign object (non-Haskell heap resident).
1137 The Stable Pointer table. (There should only be one of these but it
1138 represents a form of weak space leak since it can't shrink to meet
1139 non-demand so it may be worth watching separately? ADR)
1140 \item[@INTERNAL_KIND@]
1141 Something internal to the runtime system.
1145 \item[Description] Source derived string detailing closure description.
1146 \item[Type] Source derived string detailing closure type.
1149 \item {\em Parallelism info\/}
1152 \item {\em Debugging info\/}
1159 \section{Kinds of Heap Object}
1160 \label{sect:closures}
1162 Heap objects can be classified in several ways, but one useful one is
1166 {\em Static closures} occupy fixed, statically-allocated memory
1167 locations, with globally known addresses.
1170 {\em Dynamic closures} are individually allocated in the heap.
1173 {\em Stack closures} are closures allocated within a thread's stack
1174 (which is itself a heap object). Unlike other closures, there are
1175 never any pointers to stack closures. Stack closures are discussed in
1176 Section~\ref{sect:stacks}.
1179 A second useful classification is this:
1182 {\em Executive closures}, such as thunks and data constructors,
1183 participate directly in a program's execution. They can be subdivided into
1184 two kinds of objects according to their type:
1187 {\em Pointed objects}, represent values of a {\em pointed} type
1188 (<.pointed types launchbury.>) --i.e.~a type that includes $\bottom$ such as @Int@ or @Int# -> Int#@.
1190 \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#@.
1192 \item {\em Activation frames}, represent ``continuations''. They are
1193 always stored on the stack and are never pointed to by heap objects or
1194 passed as arguments. \note{It's not clear if this will still be true
1195 once we support speculative evaluation.}
1199 \item {\em Administrative closures}, such as stack objects and thread
1200 state objects, do not represent values in the original program.
1203 Only pointed objects can be entered. All pointed objects share a
1204 common header format: the ``pointed header''; while all unpointed
1205 objects share a common header format: the ``unpointed header''.
1206 \ToDo{Describe the difference and update the diagrams to mention
1207 an appropriate header type.}
1209 This section enumerates all the kinds of heap objects in the system.
1210 Each is identified by a distinct @INFO_TYPE@ tag in its info table.
1212 \ToDo{Check this table very carefully}
1214 \begin{tabular}{|l|l|l|l|l|l|l|l|l|l|l|}
1217 closure kind & HNF & UPD & NS & STA & THU & MUT & UPT & BH & IND & Section \\
1223 @CONSTR@ & 1 & & 1 & & & & & & & \ref{sect:CONSTR} \\
1224 @CONSTR_STATIC@ & 1 & & 1 & 1 & & & & & & \ref{sect:CONSTR} \\
1225 @CONSTR_STATIC_NOCAF@ & 1 & & 1 & 1 & & & & & & \ref{sect:CONSTR} \\
1227 @FUN@ & 1 & & ? & & & & & & & \ref{sect:FUN} \\
1228 @FUN_STATIC@ & 1 & & ? & 1 & & & & & & \ref{sect:FUN} \\
1230 @THUNK@ & 1 & 1 & & & 1 & & & & & \ref{sect:THUNK} \\
1231 @THUNK_STATIC@ & 1 & 1 & & 1 & 1 & & & & & \ref{sect:THUNK} \\
1232 @THUNK_SELECTOR@ & 1 & 1 & 1 & & 1 & & & & & \ref{sect:THUNK_SEL} \\
1234 @PAP@ & 1 & & ? & & & & & & & \ref{sect:PAP} \\
1236 @IND@ & & & 1 & & ? & & & & 1 & \ref{sect:IND} \\
1237 @IND_OLDGEN@ & 1 & & 1 & & ? & & & & 1 & \ref{sect:IND} \\
1238 @IND_PERM@ & & & 1 & & ? & & & & 1 & \ref{sect:IND} \\
1239 @IND_OLDGEN_PERM@ & 1 & & 1 & & ? & & & & 1 & \ref{sect:IND} \\
1240 @IND_STATIC@ & ? & & 1 & 1 & ? & & & & 1 & \ref{sect:IND} \\
1247 @ARR_WORDS@ & 1 & & 1 & & & 1 & 1 & & & \ref{sect:ARR_WORDS1},\ref{sect:ARR_WORDS2} \\
1248 @ARR_PTRS@ & 1 & & 1 & & & 1 & 1 & & & \ref{sect:ARR_PTRS} \\
1249 @MUTVAR@ & 1 & & 1 & & & 1 & 1 & & & \ref{sect:MUTVAR} \\
1250 @MUTARR_PTRS@ & 1 & & 1 & & & 1 & 1 & & & \ref{sect:MUTARR_PTRS} \\
1251 @MUTARR_PTRS_FROZEN@ & 1 & & 1 & & & 1 & 1 & & & \ref{sect:MUTARR_PTRS_FROZEN} \\
1253 @FOREIGN@ & 1 & & 1 & & & & 1 & & & \ref{sect:FOREIGN} \\
1255 @BH@ & ? & 0/1 & 1 & & ? & ? & & 1 & ? & \ref{sect:BH} \\
1256 @MVAR@ & & & & & & & & & & \ref{sect:MVAR} \\
1257 @IVAR@ & & & & & & & & & & \ref{sect:IVAR} \\
1258 @FETCHME@ & & & & & & & & & & \ref{sect:FETCHME} \\
1262 Activation frames do not live (directly) on the heap --- but they have
1263 a similar organisation. The classification bits are all zero in
1266 \begin{tabular}{|l|l|}\hline
1267 closure kind & Section \\ \hline
1268 @RET_SMALL@ & \ref{sect:activation-records} \\
1269 @RET_VEC_SMALL@ & \ref{sect:activation-records} \\
1270 @RET_BIG@ & \ref{sect:activation-records} \\
1271 @RET_VEC_BIG@ & \ref{sect:activation-records} \\
1272 @UPDATE_FRAME@ & \ref{sect:activation-records} \\
1276 There are also a number of administrative objects. The classification bits are
1277 all zero in administrative objects.
1279 \begin{tabular}{|l|l|}\hline
1280 closure kind & Section \\ \hline
1281 @TSO@ & \ref{sect:TSO} \\
1282 @STACK_OBJECT@ & \ref{sect:STACK_OBJECT} \\
1283 @STABLEPTR_TABLE@ & \ref{sect:STABLEPTR_TABLE} \\
1284 @SPARK_OBJECT@ & \ref{sect:SPARK} \\
1285 @BLOCKED_FETCH@ & \ref{sect:BLOCKED_FETCH} \\
1289 \ToDo{I guess the parallel system has something like a stable ptr
1290 table. Is there any opportunity for sharing code/data structures
1294 \subsection{Classification bits}
1296 The top bits of the @INFO_TYPE@ tag tells what sort of animal the
1299 \begin{tabular}{|l|l|l|} \hline
1300 Abbrev & Bit & Interpretation \\ \hline
1301 HNF & 0 & 1 $\Rightarrow$ Head normal form \\
1302 UPD & 4 & 1 $\Rightarrow$ May be updated (inconsistent with being a HNF) \\
1303 NS & 1 & 1 $\Rightarrow$ Don't spark me (Any HNF will have this set to 1)\\
1304 STA & 2 & 1 $\Rightarrow$ This is a static closure \\
1305 THU & 8 & 1 $\Rightarrow$ Is a thunk \\
1306 MUT & 3 & 1 $\Rightarrow$ Has mutable pointer fields \\
1307 UPT & 5 & 1 $\Rightarrow$ Has an unpointed type (eg a primitive array) \\
1308 BH & 6 & 1 $\Rightarrow$ Is a black hole \\
1309 IND & 7 & 1 $\Rightarrow$ Is an indirection \\
1313 Updatable structures (@_UP@) are thunks that may be shared. Primitive
1314 arrays (@_BM@ -- Big Mothers) are structures that are always held
1315 in-memory (basically extensions of a closure). Because there may be
1316 offsets into these arrays, a primitive array cannot be handled as a
1317 FetchMe in the parallel system, but must be shipped in its entirety if
1318 its parent closure is shipped.
1320 The other bits in the info-type field simply give a unique bit-pattern
1321 to identify the closure type.
1325 #define _NF 0x0001 /* Normal form */
1326 #define _NS 0x0002 /* Don't spark */
1327 #define _ST 0x0004 /* Is static */
1328 #define _MU 0x0008 /* Is mutable */
1329 #define _UP 0x0010 /* Is updatable (but not mutable) */
1330 #define _BM 0x0020 /* Is a "primitive" array */
1331 #define _BH 0x0040 /* Is a black hole */
1332 #define _IN 0x0080 /* Is an indirection */
1333 #define _TH 0x0100 /* Is a thunk */
1338 SPEC_N SPEC | _NF | _NS
1340 SPEC_U SPEC | _UP | _TH
1343 GEN_N GEN | _NF | _NS
1345 GEN_U GEN | _UP | _TH
1348 TUPLE _NF | _NS | _BM
1349 DATA _NF | _NS | _BM
1350 MUTUPLE _NF | _NS | _MU | _BM
1351 IMMUTUPLE _NF | _NS | _BM
1363 CAF _NF | _NS | _ST | _IN
1372 STKO_DYNAMIC STKO | _MU
1373 STKO_STATIC STKO | _ST
1375 SPEC_RBH _NS | _MU | _BH
1376 GEN_RBH _NS | _MU | _BH
1385 An indirection either points to HNF (post update); or is result of
1386 overwriting a FetchMe, in which case the thing fetched is either
1387 under evaluation (BH), or by now an HNF. Thus, indirections get NoSpark flag.
1391 \subsection{Hugs Objects}
1393 \subsubsection{Byte-Code Objects}
1396 A Byte-Code Object (BCO) is a container for a a chunk of byte-code,
1397 which can be executed by Hugs. For a top-level function, the BCO also
1398 serves as the closure for the function.
1400 The semantics of BCOs are described in Section
1401 \ref{hugs-heap-objects}. A BCO has the following structure:
1404 \begin{tabular}{|l|l|l|l|l|l|}
1406 \emph{BCO} & \emph{Layout} & \emph{Offset} & \emph{Size} &
1407 \emph{Literals} & \emph{Byte code} \\
1414 \item \emph{BCO} is a pointer to a static code fragment/info table that
1415 returns to the scheduler to invoke Hugs (Section
1416 \ref{ghc-to-hugs-closure}).
1417 \item \emph{Layout} contains the number of pointer literals in the
1418 \emph{Literals} field.
1419 \item \emph{Offset} is the offset to the byte code from the start of
1421 \item \emph{Size} is the number of words of byte code in the object.
1422 \item \emph{Literals} contains any pointer and non-pointer literals used in
1423 the byte-codes (including jump addresses), pointers first.
1424 \item \emph{Byte code} contains \emph{Size} words of non-pointer byte
1428 \subsubsection{AP objects}
1431 Hugs uses a standard object for thunks, partial applications and
1432 return addresses. Thunks and partial applications live on the heap,
1433 whereas return addresses live on the stack.
1435 The layout of an AP is
1438 \begin{tabular}{|l|l|l|l|}
1440 \emph{AP} & \emph{BCO} & \emph{Layout} & \emph{Free Variables} \\
1448 \item \emph{AP} is a pointer to a statically-compiled code
1449 fragment/info table that returns to the scheduler to invoke Hugs
1450 (Sections \ref{ghc-to-hugs-closure}, \ref{ghc-to-hugs-return}).
1451 \item \emph{BCO} is a pointer to the BCO for the thunk.
1452 \item \emph{Layout} contains the number of pointers and the size of
1453 the \emph{Free Variables} field.
1454 \item \emph{Free Variables} contains the free variables of the
1455 thunk/partial application/return address, pointers first.
1458 \subsection{Pointed Objects}
1460 All pointed objects can be entered.
1462 \subsubsection{Function closures}\label{sect:FUN}
1464 Function closures represent lambda abstractions. For example,
1465 consider the top-level declaration:
1467 f = \x -> let g = \y -> x+y
1470 Both @f@ and @g@ are represented by function closures. The closure
1471 for @f@ is {\em static} while that for @g@ is {\em dynamic}.
1473 The layout of a function closure is as follows:
1475 \begin{tabular}{|l|l|l|l|}\hline
1476 {\em Fixed header} & {\em Pointers} & {\em Non-pointers} \\ \hline
1479 The data words (pointers and non-pointers) are the free variables of
1480 the function closure.
1481 The number of pointers
1482 and number of non-pointers are stored in the @INFO_SM@ word, in the least significant
1483 and most significant half-word respectively.
1485 There are several different sorts of function closure, distinguished
1486 by their @INFO_TYPE@ field:
1488 \item @FUN@: a vanilla, dynamically allocated on the heap.
1490 \item $@FUN_@p@_@np$: to speed up garbage collection a number of
1491 specialised forms of @FUN@ are provided, for particular $(p,np)$ pairs,
1492 where $p$ is the number of pointers and $np$ the number of non-pointers.
1494 \item @FUN_STATIC@. Top-level, static, function closures (such as
1495 @f@ above) have a different
1496 layout than dynamic ones:
1498 \begin{tabular}{|l|l|l|}\hline
1499 {\em Fixed header} & {\em Static object link} \\ \hline
1502 Static function closurs have no free variables. (However they may refer to other
1503 static closures; these references are recorded in the function closure's SRT.)
1504 They have one field that is not present in dynamic closures, the {\em static object
1505 link} field. This is used by the garbage collector in the same way that to-space
1506 is, to gather closures that have been determined to be live but that have not yet
1508 \note{Static function closures that have no static references, and hence
1509 a null SRT pointer, don't need the static object link field. Is it worth
1510 taking advantage of this? See @CONSTR_STATIC_NOCAF@.}
1513 Each lambda abstraction, $f$, in the STG program has its own private info table.
1514 The following labels are relevant:
1516 \item $f$@_info@ is $f$'s info table.
1517 \item $f$@_entry@ is $f$'s slow entry point (i.e. the entry code of its
1518 info table; so it will label the same byte as $f$@_info@).
1519 \item $f@_fast_@k$ is $f$'s fast entry point. $k$ is the number of arguments
1520 $f$ takes; encoding this number in the fast-entry label occasionally catches some nasty
1521 code-generation errors.
1524 \subsubsection{Data Constructors}\label{sect:CONSTR}
1526 Data-constructor closures represent values constructed with
1527 algebraic data type constructors.
1528 The general layout of data constructors is the same as that for function
1531 \begin{tabular}{|l|l|l|l|}\hline
1532 {\em Fixed header} & {\em Pointers} & {\em Non-pointers} \\ \hline
1536 The SRT pointer in a data constructor's info table is never used --- the
1537 code for a constructor does not make any static references.
1538 \note{Use it for something else?? E.g. tag?}
1540 There are several different sorts of constructor:
1542 \item @CONSTR@: a vanilla, dynamically allocated constructor.
1543 \item @CONSTR_@$p$@_@$np$: just like $@FUN_@p@_@np$.
1544 \item @CONSTR_INTLIKE@.
1545 A dynamically-allocated heap object that looks just like an @Int@. The
1546 garbage collector checks to see if it can common it up with one of a fixed
1547 set of static int-like closures, thus getting it out of the dynamic heap
1550 \item @CONSTR_CHARLIKE@: same deal, but for @Char@.
1552 \item @CONSTR_STATIC@ is similar to @FUN_STATIC@, with the complication that
1553 the layout of the constructor must mimic that of a dynamic constructor,
1554 because a static constructor might be returned to some code that unpacks it.
1555 So its layout is like this:
1557 \begin{tabular}{|l|l|l|l|l|}\hline
1558 {\em Fixed header} & {\em Pointers} & {\em Non-pointers} & {\em Static object link}\\ \hline
1561 The static object link, at the end of the closure, serves the same purpose
1562 as that for @FUN_STATIC@. The pointers in the static constructor can point
1563 only to other static closures.
1565 The static object link occurs last in the closure so that static
1566 constructors can store their data fields in exactly the same place as
1567 dynamic constructors.
1569 \item @CONSTR_STATIC_NOCAF@. A statically allocated data constructor
1570 that guarantees not to point (directly or indirectly) to any CAF
1571 (section~\ref{sect:CAF}). This means it does not need a static object
1572 link field. Since we expect that there might be quite a lot of static
1573 constructors this optimisation makes sense. Furthermore, the @NOCAF@
1574 tag allows the compiler to indicate that no CAFs can be reached
1575 anywhere {\em even indirectly}.
1580 For each data constructor $Con$, two
1581 info tables are generated:
1583 \item $Con$@_info@ labels $Con$'s dynamic info table,
1584 shared by all dynamic instances of the constructor.
1585 \item $Con$@_static@ labels $Con$'s static info table,
1586 shared by all static instances of the constructor.
1589 \subsubsection{Thunks}
1591 \label{sect:THUNK_SEL}
1593 A thunk represents an expression that is not obviously in head normal
1594 form. For example, consider the following top-level definitions:
1596 range = between 1 10
1597 f = \x -> let ys = take x range
1600 Here the right-hand sides of @range@ and @ys@ are both thunks; the former
1601 is static while the latter is dynamic.
1603 The layout of a thunk is the same as that for a function closure,
1604 except that it may have some words of ``slop'' at the end to make sure
1606 at least @MIN_UPD_PAYLOAD@ words in addition to its
1609 \begin{tabular}{|l|l|l|l|l|}\hline
1610 {\em Fixed header} & {\em Pointers} & {\em Non-pointers} & {\em Slop} \\ \hline
1613 The @INFO_SM@ word contains the same information as for function
1614 closures; that is, number of pointers and number of non-pointers (excluding slop).
1616 A thunk differs from a function closure in that it can be updated.
1618 There are several forms of thunk:
1620 \item @THUNK@: a vanilla, dynamically allocated thunk.
1621 The garbage collection code for thunks whose
1622 pointer + non-pointer words is less than @MIN_UPD_PAYLOAD@ differs from
1623 that for function closures and data constructors, because the GC code
1624 has to account for the slop.
1625 \item $@THUNK_@p@_@np$. Similar comments apply.
1626 \item @THUNK_STATIC@. A static thunk is also known as
1627 a {\em constant applicative form}, or {\em CAF}.
1630 \begin{tabular}{|l|l|l|l|l|}\hline
1631 {\em Fixed header} & {\em Pointers} & {\em Non-pointers} & {\em Slop} & {\em Static object link}\\ \hline
1635 \item @THUNK_SELECTOR@ is a (dynamically allocated) thunk
1636 whose entry code performs a simple selection operation from
1637 a data constructor drawn from a single-constructor type. For example,
1640 x = case y of (a,b) -> a
1642 is a selector thunk. A selector thunk is laid out like this:
1644 \begin{tabular}{|l|l|l|l|}\hline
1645 {\em Fixed header} & {\em Selectee pointer} \\ \hline
1648 The @INFO_SM@ word contains the byte offset of the desired word in
1649 the selectee. Note that this is different from all other thunks.
1651 The garbage collector ``peeks'' at the selectee's
1652 tag (in its info table). If it is evaluated, then it goes ahead and do
1653 the selection, and then behaves just as if the selector thunk was an
1654 indirection to the selected field.
1656 evaluated, it treats the selector thunk like any other thunk of that
1657 shape. [Implementation notes.
1658 Copying: only the evacuate routine needs to be special.
1659 Compacting: only the PRStart (marking) routine needs to be special.]
1663 The only label associated with a thunk is its info table:
1665 \item[$f$@_info@] is $f$'s info table.
1669 \subsubsection{Partial applications (PAPs)}\label{sect:PAP}
1671 A partial application (PAP) represents a function applied to too few arguments.
1672 It is only built as a result of updating after an argument-satisfaction
1673 check failure. A PAP has the following shape:
1675 \begin{tabular}{|l|l|l|l|}\hline
1676 {\em Fixed header} & {\em No of arg words} & {\em Function closure} & {\em Arg stack} \\ \hline
1679 The ``arg stack'' is a copy of of the chunk of stack above the update
1680 frame; ``no of arg words'' tells how many words it consists of. The
1681 function closure is (a pointer to) the closure for the function whose
1682 argument-satisfaction check failed.
1684 There is just one standard form of PAP with @INFO_TYPE@ = @PAP@.
1685 There is just one info table too, called @PAP_info@.
1686 Its entry code simply copies the arg stack chunk back on top of the
1687 stack and enters the function closure. (It has to do a stack overflow test first.)
1689 There are no static PAPs.
1691 \subsubsection{Indirections}
1693 \label{sect:IND_OLDGEN}
1695 Indirection closures just point to other closures. They are introduced
1696 when a thunk is updated to point to its value.
1697 The entry code for all indirections simply enters the closure it points to.
1699 There are several forms of indirection:
1701 \item[@IND@] is the vanilla, dynamically-allocated indirection.
1702 It is removed by the garbage collector. It has the following
1705 \begin{tabular}{|l|l|l|}\hline
1706 {\em Fixed header} & {\em Target closure} \\ \hline
1710 \item[@IND_OLDGEN@] is the indirection used to update an old-generation
1711 thunk. Its shape is like this:
1713 \begin{tabular}{|l|l|l|}\hline
1714 {\em Fixed header} & {\em Mutable link field} & {\em Target closure} \\ \hline
1717 It contains a {\em mutable link field} that is used to string together
1718 all old-generation indirections that might have a pointer into
1722 \item[@IND_PERMANENT@ and @IND_OLDGEN_PERMANENT@.]
1723 for lexical profiling, it is necessary to maintain cost centre
1724 information in an indirection, so ``permanent indirections'' are
1725 retained forever. Otherwise they are just like vanilla indirections.
1726 \note{If a permanent indirection points to another permanent
1727 indirection or a @CONST@ closure, it is possible to elide the indirection
1728 since it will have no effect on the profiler.}
1729 \note{Do we still need @IND@ and @IND_OLDGEN@
1730 in the profiling build, or can we just make
1731 do with one pair whose behaviour changes when profiling is built?}
1733 \item[@IND_STATIC@] is used for overwriting CAFs when they have been
1734 evaluated. Static indirections are not removed by the garbage
1735 collector; and are statically allocated outside the heap (and should
1736 stay there). Their static object link field is used just as for
1737 @FUN_STATIC@ closures.
1740 \begin{tabular}{|l|l|l|}
1742 {\em Fixed header} & {\em Target closure} & {\em Static object link} \\
1749 \subsubsection{Activation Records}
1751 Activation records are parts of the stack described by return address
1752 info tables (closures with @INFO_TYPE@ values of @RET_SMALL@,
1753 @RET_VEC_SMALL@, @RET_BIG@ and @RET_VEC_BIG@). They are described in
1754 section~\ref{sect:activation-records}.
1757 \subsubsection{Black holes, MVars and IVars}
1762 Black hole closures are used to overwrite closures currently being
1763 evaluated. They inform the garbage collector that there are no live
1764 roots in the closure, thus removing a potential space leak.
1766 Black holes also become synchronization points in the threaded world.
1767 They contain a pointer to a list of blocked threads to be awakened
1768 when the black hole is updated (or @NULL@ if the list is empty).
1770 \begin{tabular}{|l|l|l|}
1772 {\em Fixed header} & {\em Mutable link} & {\em Blocked thread link} \\
1776 The {\em Blocked thread link} points to the TSO of the first thread
1777 waiting for the value of this thunk. All subsequent TSOs in the list
1778 are linked together using their @TSO_LINK@ field.
1780 When the blocking queue is non-@NULL@, the black hole must be added to
1781 the mutables list since the TSOs on the list may contain pointers into
1782 the new generation. There is no need to clutter up the mutables list
1783 with black holes with empty blocking queues.
1788 \subsubsection{FetchMes}\label{sect:FETCHME}
1790 In the parallel systems, FetchMes are used to represent pointers into
1791 the global heap. When evaluated, the value they point to is read from
1794 \ToDo{Describe layout}
1797 \subsection{Unpointed Objects}
1799 A variable of unpointed type is always bound to a {\em value}, never to a {\em thunk}.
1800 For this reason, unpointed objects cannot be entered.
1802 A {\em value} may be:
1804 \item {\em Boxed}, i.e.~represented indirectly by a pointer to a heap object (e.g.~foreign objects, arrays); or
1805 \item {\em Unboxed}, i.e.~represented directly by a bit-pattern in one or more registers (e.g.~@Int#@ and @Float#@).
1807 All {\em pointed} values are {\em boxed}.
1809 \subsubsection{Immutable Objects}
1810 \label{sect:ARR_WORDS1}
1811 \label{sect:ARR_PTRS}
1814 \item[@ARR_WORDS@] is a variable-sized object consisting solely of
1815 non-pointers. It is used for arrays of all
1816 sorts of things (bytes, words, floats, doubles... it doesn't matter).
1818 \begin{tabular}{|c|c|c|c|}
1820 {\em Fixed Hdr} & {\em No of non-pointers} & {\em Non-pointers\ldots} \\ \hline
1824 \item[@ARR_PTRS@] is an immutable, variable sized array of pointers.
1826 \begin{tabular}{|c|c|c|c|}
1828 {\em Fixed Hdr} & {\em Mutable link} & {\em No of pointers} & {\em Pointers\ldots} \\ \hline
1831 The mutable link is present so that we can easily freeze and thaw an
1832 array (by changing the header and adding/removing the array to the
1837 \subsubsection{Mutable Objects}
1838 \label{sect:mutables}
1839 \label{sect:ARR_WORDS2}
1841 \label{sect:MUTARR_PTRS}
1842 \label{sect:MUTARR_PTRS_FROZEN}
1844 Some of these objects are {\em mutable}; they represent objects which
1845 are explicitly mutated by Haskell code through the @ST@ monad.
1846 They're not used for thunks which are updated precisely once.
1847 Depending on the garbage collector, mutable closures may contain extra
1848 header information which allows a generational collector to implement
1849 the ``write barrier.''
1853 \item[@ARR_WORDS@] is also used to represent {\em mutable} arrays of
1854 bytes, words, floats, doubles, etc. It's possible to use the same
1855 object type because even generational collectors don't need to
1858 \item[@MUTVAR@] is a mutable variable.
1860 \begin{tabular}{|c|c|c|}
1862 {\em Fixed Hdr} & {\em Mutable link} & {\em Pointer} \\ \hline
1866 \item[@MUTARR_PTRS@] is a mutable array of pointers.
1867 Such an array may be {\em frozen}, becoming an @SM_MUTARR_PTRS_FROZEN@, with a
1868 different info-table.
1870 \begin{tabular}{|c|c|c|c|}
1872 {\em Fixed Hdr} & {\em Mutable link} & {\em No of ptrs} & {\em Pointers\ldots} \\ \hline
1876 \item[@MUTARR_PTRS_FROZEN@] is a frozen @MUTARR_PTRS@ closure.
1877 The garbage collector converts @MUTARR_PTRS_FROZEN@ to @ARR_PTRS@ as it removes them from
1883 \subsubsection{Foreign Objects}\label{sect:FOREIGN}
1885 Here's what a ForeignObj looks like:
1888 \begin{tabular}{|l|l|l|l|}
1890 {\em Fixed header} & {\em Data} & {\em Free Routine} & {\em Foreign object link} \\
1895 The @FreeRoutine@ is a reference to the finalisation routine to call
1896 when the @ForeignObj@ becomes garbage. If @freeForeignObject@ is
1897 called on a Foreign Object, the @FreeRoutine@ is set to zero and the
1898 garbage collector will not attempt to call @FreeRoutine@ when the
1899 object becomes garbage.
1901 The Foreign object link is a link to the next foreign object in the
1902 list. This list is traversed at the end of garbage collection: if an
1903 object is about to be deallocated (e.g.~it was not marked or
1904 evacuated), the free routine is called and the object is deleted from
1908 The remaining objects types are all administrative --- none of them may be entered.
1910 \subsection{Thread State Objects (TSOs)}\label{sect:TSO}
1912 In the multi-threaded system, the state of a suspended thread is
1913 packed up into a Thread State Object (TSO) which contains all the
1914 information needed to restart the thread and for the garbage collector
1915 to find all reachable objects. When a thread is running, it may be
1916 ``unpacked'' into machine registers and various other memory locations
1917 to provide faster access.
1919 Single-threaded systems don't really {\em need\/} TSOs --- but they do
1920 need some way to tell the storage manager about live roots so it is
1921 convenient to use a single TSO to store the mutator state even in
1922 single-threaded systems.
1924 Rather than manage TSOs' alloc/dealloc, etc., in some {\em ad hoc}
1925 way, we instead alloc/dealloc/etc them in the heap; then we can use
1926 all the standard garbage-collection/fetching/flushing/etc machinery on
1927 them. So that's why TSOs are ``heap objects,'' albeit very special
1930 \begin{tabular}{|l|l|}
1931 \hline {\em Fixed header}
1932 \\ \hline @TSO_LINK@
1933 \\ \hline @TSO_WHATNEXT@
1934 \\ \hline @TSO_WHATNEXT_INFO@
1935 \\ \hline @TSO_STACK@
1936 \\ \hline {\em Exception Handlers}
1937 \\ \hline {\em Ticky Info}
1938 \\ \hline {\em Profiling Info}
1939 \\ \hline {\em Parallel Info}
1940 \\ \hline {\em GranSim Info}
1944 The contents of a TSO are:
1947 \item A pointer (@TSO_LINK@) used to maintain a list of threads with a similar
1948 state (e.g.~all runable, all sleeping, all blocked on the same black
1949 hole, all blocked on the same MVar, etc.)
1951 \item A word (@TSO_WHATNEXT@) which is in suspended threads to record
1952 how to awaken it. This typically requires a program counter which is stored
1953 in the pointer @TSO_WHATNEXT_INFO@
1955 \item A pointer (@TSO_STACK@) to the top stack block.
1957 \item Optional information for ``Ticky Ticky'' statistics: @TSO_STK_HWM@ is
1958 the maximum number of words allocated to this thread.
1960 \item Optional information for profiling:
1961 @TSO_CCC@ is the current cost centre.
1963 \item Optional information for parallel execution:
1966 \item The types of threads (@TSO_TYPE@):
1968 \item[@T_MAIN@] Must be executed locally.
1969 \item[@T_REQUIRED@] A required thread -- may be exported.
1970 \item[@T_ADVISORY@] An advisory thread -- may be exported.
1971 \item[@T_FAIL@] A failure thread -- may be exported.
1974 \item I've no idea what else
1978 \item Optional information for GranSim execution:
1995 \item clock (gransim light only)
1999 Here are the various queues for GrAnSim-type events.
2010 \subsection{Other weird objects}
2012 \label{sect:BLOCKED_FETCH}
2015 \item[@BlockedFetch@ heap objects (`closures')] (parallel only)
2017 @BlockedFetch@s are inbound fetch messages blocked on local closures.
2018 They arise as entries in a local blocking queue when a fetch has been
2019 received for a local black hole. When awakened, we look at their
2020 contents to figure out where to send a resume.
2022 A @BlockedFetch@ closure has the form:
2024 \begin{tabular}{|l|l|l|l|l|l|}\hline
2025 {\em Fixed header} & link & node & gtid & slot & weight \\ \hline
2029 \item[Spark Closures] (parallel only)
2031 Spark closures are used to link together all closures in the spark pool. When
2032 the current processor is idle, it may choose to speculatively evaluate some of
2033 the closures in the pool. It may also choose to delete sparks from the pool.
2035 \begin{tabular}{|l|l|l|l|l|l|}\hline
2036 {\em Fixed header} & {\em Spark pool link} & {\em Sparked closure} \\ \hline
2044 \subsection{Stack Objects}
2045 \label{sect:STACK_OBJECT}
2048 These are ``stack objects,'' which are used in the threaded world as
2049 the stack for each thread is allocated from the heap in smallish
2050 chunks. (The stack in the sequential world is allocated outside of
2053 Each reduction thread has to have its own stack space. As there may
2054 be many such threads, and as any given one may need quite a big stack,
2055 a naive give-'em-a-big-stack-and-let-'em-run approach will cost a {\em
2058 Our approach is to give a thread a small stack space, and then link
2059 on/off extra ``chunks'' as the need arises. Again, this is a
2060 storage-management problem, and, yet again, we choose to graft the
2061 whole business onto the existing heap-management machinery. So stack
2062 objects will live in the heap, be garbage collected, etc., etc..
2064 A stack object is laid out like this:
2067 \begin{tabular}{|l|}
2071 {\em Link to next stack object (0 for last)}
2073 {\em N, the payload size in words}
2075 {\em @Sp@ (byte offset from head of object)}
2077 {\em @Su@ (byte offset from head of object)}
2079 {\em Payload (N words)}
2084 \ToDo{Are stack objects on the mutable list?}
2086 The stack grows downwards, towards decreasing
2087 addresses. This makes it easier to print out the stack
2088 when debugging, and it means that a return address is
2089 at the lowest address of the chunk of stack it ``knows about''
2090 just like an info pointer on a closure.
2092 The garbage collector needs to be able to find all the
2093 pointers in a stack. How does it do this?
2097 \item Within the stack there are return addresses, pushed
2098 by @case@ expressions. Below a return address (i.e. at higher
2099 memory addresses, since the stack grows downwards) is a chunk
2100 of stack that the return address ``knows about'', namely the
2101 activation record of the currently running function.
2103 \item Below each such activation record is a {\em pending-argument
2104 section}, a chunk of
2105 zero or more words that are the arguments to which the result
2106 of the function should be applied. The return address does not
2108 ``know'' how many pending arguments there are, or their types.
2109 (For example, the function might return a result of type $\alpha$.)
2111 \item Below each pending-argument section is another return address,
2112 and so on. Actually, there might be an update frame instead, but we
2113 can consider update frames as a special case of a return address with
2114 a well-defined activation record.
2116 \ToDo{Doesn't it {\em have} to be an update frame? After all, the arg
2117 satisfaction check is @Su - Sp >= ...@.}
2121 The game plan is this. The garbage collector
2122 walks the stack from the top, traversing pending-argument sections and
2123 activation records alternately. Next we discuss how it finds
2124 the pointers in each of these two stack regions.
2127 \subsubsection{Activation records}\label{sect:activation-records}
2129 An {\em activation record} is a contiguous chunk of stack,
2130 with a return address as its first word, followed by as many
2131 data words as the return address ``knows about''. The return
2132 address is actually a fully-fledged info pointer. It points
2133 to an info table, replete with:
2136 \item entry code (i.e. the code to return to).
2137 \item @INFO_TYPE@ is either @RET_SMALL/RET_VEC_SMALL@ or @RET_BIG/RET_VEC_BIG@, depending
2138 on whether the activation record has more than 32 data words (\note{64 for 8-byte-word architectures}) and on whether
2139 to use a direct or a vectored return.
2140 \item @INFO_SM@ for @RET_SMALL@ is a bitmap telling the layout
2141 of the activation record, one bit per word. The least-significant bit
2142 describes the first data word of the record (adjacent to the fixed
2143 header) and so on. A ``@1@'' indicates a non-pointer, a ``@0@''
2145 a pointer. We don't need to indicate exactly how many words there
2147 because when we get to all zeros we can treat the rest of the
2148 activation record as part of the next pending-argument region.
2150 For @RET_BIG@ the @INFO_SM@ field points to a block of bitmap
2151 words, starting with a word that tells how many words are in
2154 \item @INFO_SRT@ is the Static Reference Table for the return
2155 address (Section~\ref{sect:srt}).
2158 The activation record is a fully fledged closure too.
2159 As well as an info pointer, it has all the other attributes of
2160 a fixed header (Section~\ref{sect:fixed-header}) including a saved cost
2161 centre which is reloaded when the return address is entered.
2163 In other words, all the attributes of closures are needed for
2164 activation records, so it's very convenient to make them look alike.
2167 \subsubsection{Pending arguments}
2169 So that the garbage collector can correctly identify pointers
2170 in pending-argument sections we explicitly tag all non-pointers.
2171 Every non-pointer in a pending-argument section is preceded
2172 (at the next lower memory word) by a one-word byte count that
2173 says how many bytes to skip over (excluding the tag word).
2175 The garbage collector traverses a pending argument section from
2176 the top (i.e. lowest memory address). It looks at each word in turn:
2179 \item If it is less than or equal to a small constant @MAX_STACK_TAG@
2181 it treats it as a tag heralding zero or more words of non-pointers,
2182 so it just skips over them.
2184 \item If it points to the code segment, it must be a return
2185 address, so we have come to the end of the pending-argument section.
2187 \item Otherwise it must be a bona fide heap pointer.
2191 \subsection{The Stable Pointer Table}\label{sect:STABLEPTR_TABLE}
2193 A stable pointer is a name for a Haskell object which can be passed to
2194 the external world. It is ``stable'' in the sense that the name does
2195 not change when the Haskell garbage collector runs---in contrast to
2196 the address of the object which may well change.
2198 A stable pointer is represented by an index into the
2199 @StablePointerTable@. The Haskell garbage collector treats the
2200 @StablePointerTable@ as a source of roots for GC.
2202 In order to provide efficient access to stable pointers and to be able
2203 to cope with any number of stable pointers (eg $0 \ldots 100000$), the
2204 table of stable pointers is an array stored on the heap and can grow
2205 when it overflows. (Since we cannot compact the table by moving
2206 stable pointers about, it seems unlikely that a half-empty table can
2207 be reduced in size---this could be fixed if necessary by using a
2208 hash table of some sort.)
2210 In general a stable pointer table closure looks like this:
2213 \begin{tabular}{|l|l|l|l|l|l|l|l|l|l|l|}
2215 {\em Fixed header} & {\em No of pointers} & {\em Free} & $SP_0$ & \ldots & $SP_{n-1}$
2223 \item[@NPtrs@:] number of (stable) pointers.
2225 \item[@Free@:] the byte offset (from the first byte of the object) of the first free stable pointer.
2227 \item[$SP_i$:] A stable pointer slot. If this entry is in use, it is
2228 an ``unstable'' pointer to a closure. If this entry is not in use, it
2229 is a byte offset of the next free stable pointer slot.
2233 When a stable pointer table is evacuated
2235 \item the free list entries are all set to @NULL@ so that the evacuation
2236 code knows they're not pointers;
2238 \item The stable pointer slots are scanned linearly: non-@NULL@ slots
2239 are evacuated and @NULL@-values are chained together to form a new free list.
2242 There's no need to link the stable pointer table onto the mutable
2243 list because we always treat it as a root.
2247 \section{The Storage Manager}
2249 The generational collector remembers the depth of the last generation
2250 collected and the value of the heap pointer at the end of the last GC.
2251 If the mutator has not moved the heap pointer, that means that the
2252 amount of space recovered is insufficient to satisfy even one request
2253 and it is time to collect an older generation or report a heap overflow.
2255 A deeper collection is also triggered when a minor collection fails to
2256 recover at least @...@ bytes of space.
2258 When can a GC happen?
2261 - During updates (ie during returns)
2262 - When a heap check fails
2263 - When a stack check fails (concurrent system only)
2264 - When a context switch happens (concurrent system only)
2266 When do heap checks occur?
2267 - Immediately after entering a thunk
2268 - Immediately after entering a case alternative
2270 When do stack checks occur?
2271 - We calculate the worst-case stack usage of an entire
2272 thunk so there's no need to put a check inside each alternative.
2273 - Immediately after entering a thunk
2274 We can't make a similar worst-case calculation for heap usage
2275 because the heap isn't used in a stacklike manner so any
2276 evaluation inside a case might steal some of the heap we've
2280 - Threads can be blocked
2281 - Threads can be put to sleep
2282 - Heap may move while we sleep
2283 - Black holing may happen while we sleep (ie during GC)
2286 \subsection{The SM state}
2288 Contains @Hp@, @HpLim@, @StablePtrTable@ plus version-specific info.
2292 \item Static Object list
2293 \item Foreign Object list
2294 \item Stable Pointer Table
2298 In addition, the generational collector requires:
2302 \item Old Generation Indirection list
2303 \item Mutables list --- list of mutable objects in the old generation.
2304 \item @OldLim@ --- the boundary between the generations
2305 \item Old Foreign Object list --- foreign objects in the old generation
2309 It is passed a table of {\em roots\/} containing
2313 \item All runnable TSOs
2318 In the parallel system, there must be some extra magic associated with
2321 \subsection{The SM interface}
2323 @initSM@ finalizes any runtime parameters of the storage manager.
2325 @exitSM@ does any cleaning up required by the storage manager before
2326 the program is executed. Its main purpose is to print any summary
2329 @initHeap@ allocates the heap. It initialises the @hp@ and @hplim@
2330 fields of @sm@ to represent an empty heap for the compiled-in garbage
2331 collector. It also initialises @CAFlist@ to be the empty list. If we
2332 are using Appel's collector it also initialises the @OldLim@ field.
2333 It also initialises the stable pointer table and the @ForeignObjList@
2334 (and @OldForeignObjList@) fields.
2336 @collectHeap@ invokes the garbage collector. @collectHeap@ requires
2337 all the fields of @sm@ to be initialised appropriately (from the
2338 STG-machine registers). The following are identified as heap roots:
2340 \item The updated CAFs recorded in @CAFlist@.
2341 \item Any pointers found on the stack.
2342 \item All runnable and sleeping TSOs.
2343 \item The stable pointer table.
2346 There are two possible results from a garbage collection:
2349 The garbage collector is unable to free up any more space.
2352 The garbage collector managed to free up more space.
2355 \item @hp@ and @hplim@ will indicate the new space available for
2358 \item The elements of @CAFlist@ and the stable pointers will be
2359 updated to point to the new locations of the closures they reference.
2361 \item Any members of @ForeignObjList@ which became garbage should have
2362 been reported (by calling their finalising routines; and the
2363 @(Old)ForeignObjList@ updated to contain only those Foreign objects
2364 which are still live.
2371 %************************************************************************
2373 \subsection{``What really happens in a garbage collection?''}
2375 %************************************************************************
2377 This is a brief tutorial on ``what really happens'' going to/from the
2378 storage manager in a garbage collection.
2381 %------------------------------------------------------------------------
2382 \item[The heap check:]
2386 If you gaze into the C output of GHC, you see many macros calls like:
2388 HEAP_CHK_2PtrsLive((_FHS+2));
2391 This expands into the C (roughly speaking...):
2393 Hp = Hp + (_FHS+2); /* optimistically move heap pointer forward */
2395 GC_WHILE_OR_IF (HEAP_OVERFLOW_OP(Hp, HpLim) OR_INTERVAL_EXPIRED) {
2396 STGCALL2_GC(PerformGC, <liveness-bits>, (_FHS+2));
2400 In the parallel world, where we will need to re-try the heap check,
2401 @GC_WHILE_OR_IF@ will be a ``while''; in the sequential world, it will
2404 The ``heap lookahead'' checks, which are similar and used for
2405 multi-precision @Integer@ ops, have some further complications. See
2406 the commentary there (@StgMacros.lh@).
2408 %------------------------------------------------------------------------
2409 \item[Into @callWrapper_GC@...:]
2411 When we failed the heap check (above), we were inside the
2412 GCC-registerised ``threaded world.'' @callWrapper_GC@ is all about
2413 getting in and out of the threaded world. On SPARCs, with register
2414 windows, the name of the game is not shifting windows until we have
2415 what we want out of the old one. In tricky cases like this, it's best
2416 written in assembly language.
2418 Performing a GC (potentially) means giving up the thread of control.
2419 So we must fill in the thread-state-object (TSO) [and its associated
2420 stk object] with enough information for later resumption:
2423 Save the return address in the TSO's PC field.
2425 Save the machine registers used in the STG threaded world in their
2426 corresponding TSO fields. We also save the pointer-liveness
2427 information in the TSO.
2429 The registers that are not thread-specific, notably @Hp@ and
2430 @HpLim@, are saved in the @StorageMgrInfo@ structure.
2432 Call the routine it was asked to call; in this example, call
2433 @PerformGC@ with arguments @<liveness>@ and @_FHS+2@ (some constant)...
2437 %------------------------------------------------------------------------
2438 \item[Into the heap overflow wrapper, @PerformGC@ [parallel]:]
2440 Most information has already been saved in the TSO.
2444 The first argument (@<liveness>@, in our example) say what registers
2445 are live, i.e., are ``roots'' the storage manager needs to know.
2447 StorageMgrInfo.rootno = 2;
2448 StorageMgrInfo.roots[0] = (P_) Ret1_SAVE;
2449 StorageMgrInfo.roots[1] = (P_) Ret2_SAVE;
2453 We move the heap-pointer back [we had optimistically
2454 advanced it, in the initial heap check]
2457 We load up the @smInfo@ data from the STG registers' @*_SAVE@ locations.
2460 We mark on the scheduler's big ``blackboard'' that a GC is
2464 We reschedule, i.e., this thread gives up control. (The scheduler
2465 will presumably initiate a garbage-collection, but it may have to do
2466 any number of other things---flushing, for example---before ``normal
2467 execution'' resumes; and it most certainly may not be this thread that
2468 resumes at that point!)
2471 IT IS AT THIS POINT THAT THE WORLD IS COMPLETELY TIDY.
2473 %------------------------------------------------------------------------
2474 \item[Out of @callWrapper_GC@ [parallel]:]
2476 When this thread is finally resumed after GC (and who knows what
2477 else), it will restart by the normal enter-TSO/enter-stack-object
2478 sequence, which has the effect of re-loading the registers, etc.,
2479 (i.e., restoring the state).
2481 Because the address we saved in the TSO's PC field was that at the end
2482 of the heap check, and because the check is a while-loop in the
2483 parallel system, we will now loop back around, and make sure there is
2484 enough space before continuing.
2489 \subsection{Static Reference Tables (SRTs)}
2492 \label{sect:static-objects}
2494 In the above, we assumed that objects always contained pointers to all
2495 their free variables. In fact, this isn't quite true: GHC omits
2496 pointers to top-level objects and allocates their closures in static
2497 memory. This optimisation reduces the number of free variables in
2498 heap objects - reducing memory usage and the effort needed to put them
2499 into heap objects. However, this optimisation comes at a cost: we
2500 need to complicate the garbage collector with machinery for tracing
2501 these static references.
2503 Early versions of GHC used a very simple algorithm: it treated all
2504 static objects as roots. This is safe in the sense that no object is
2505 ever deallocated if there's a chance that it might be required later
2506 but can lead to some terrible space leaks. For example, this program
2507 ought to be able to run in constant space but, because @xs@ is never
2508 deallocated, it runs in linear space.
2515 The correct behaviour is for the garbage collector to keep a static
2516 object alive iff it might be required later in execution. That is, if
2517 it is reachable from any live heap objects {\em or\/} from any return
2518 addresses found on the stack or from the current program counter.
2519 Since it is obviously infeasible for the garbage collector to scan
2520 machine code looking for static references, the code generator must
2521 generate a table of all static references in any piece of code (and we
2522 must place a pointer to this table next to any piece of code we
2525 Here's what the SRT has to contain:
2531 Here's how we represent it:
2535 must be able to handle 0 references well
2542 o Generational GC trickery
2545 \subsection{Space leaks and black holes}
2546 \label{sect:black-hole}
2550 \ToDo{Insert text stolen from update paper}
2554 A program exhibits a {\em space leak} if it retains storage that is
2555 sure not to be used again. Space leaks are becoming increasingly
2556 common in imperative programs that @malloc@ storage and fail
2557 subsequently to @free@ it. They are, however, also common in
2558 garbage-collected systems, especially where lazy evaluation is
2559 used.[.wadler leak, runciman heap profiling jfp.]
2561 Quite a bit of experience has now accumulated suggesting that
2562 implementors must be very conscientious about avoiding gratuitous
2563 space leaks --- that is, ones which are an accidental artefact of some
2564 implementation technique.[.appel book.] The update mechanism is
2565 a case in point, as <.jones jfp leak.> points out. Consider a thunk for
2568 let xs = [1..1000] in last xs
2570 where @last@ is a function that returns the last element of its
2571 argument list. When the thunk is entered it will call @last@, which
2572 will consume @xs@ until it finds the last element. Since the list
2573 @[1..1000]@ is produced lazily one might reasonably expect the
2574 expression to evaluate in constant space. But {\em until the moment
2575 of update, the thunk itself still retains a pointer to the beginning
2576 of the list @xs@}. So, until the update takes place the whole list
2579 Of course, this is completely gratuitous. The pointer to @xs@ in the
2580 thunk will never be used again. In <.peyton stock hardware.> the solution to
2581 this problem that we advocated was to overwrite a thunk's info with a
2582 fixed ``black hole'' info pointer, {\em at the moment of entry}. The
2583 storage management information attached to a black-hole info pointer
2584 tells the garbage collector that the closure contains no pointers,
2585 thereby plugging the space leak.
2587 \subsubsection{Lazy black-holing}
2589 Black-holing is a well-known idea. The trouble is that it is
2590 gallingly expensive. To avoid the occasional space leak, for every
2591 single thunk entry we have to load a full-word literal constant into a
2592 register (often two instructions) and then store that register into a
2595 Fortunately, this cost can easily be avoided. The
2596 idea is simple: {\em instead of black-holing every thunk on entry,
2597 wait until the garbage collector is called, and then black-hole all
2598 (and only) the thunks whose evaluation is in progress at that moment}.
2599 There is no benefit in black-holing a thunk that is updated before
2600 garbage collection strikes! In effect, the idea is to perform the
2601 black-holing operation lazily, only when it is needed. This
2602 dramatically cuts down the number of black-holing operations, as our
2603 results show {\em forward ref}.
2605 How can we find all the thunks whose evaluation is in progress? They
2606 are precisely the ones for which update frames are on the stack. So
2607 all we need do is find all the update frames (via the @Su@ chain) and
2608 black-hole their thunks right at the start of garbage collection.
2609 Notice that it is not enough to refrain from treating update frames as
2610 roots: firstly because the thunks to which they point may need to be
2611 moved in a copying collector, but more importantly because the thunk
2612 might be accessible via some other route.
2614 \subsubsection{Detecting loops}
2616 Black-holing has a second minor advantage: evaluation of a thunk whose
2617 value depends on itself will cause a black hole closure to be entered,
2618 which can cause a suitable error message to be displayed. For example,
2619 consider the definition
2623 The code to evaluate @x@'s right hand side will evaluate @x@. In the
2624 absence of black-holing, the result will be a stack overflow, as the
2625 evaluator repeatedly pushes a return address and enters @x@. If
2626 thunks are black-holed on entry, then this infinite loop can be caught
2629 With our new method of lazy black-holing, a self-referential program
2630 might cause either stack overflow or a black-hole error message,
2631 depending on exactly when garbage collection strikes. It is quite
2632 easy to conceal these differences, however. If stack overflow occurs,
2633 all we need do is examine the update frames on the stack to see if
2634 more than one refers to the same thunk. If so, there is a loop that
2635 would have been detected by eager black-holing.
2637 \subsubsection{Lazy locking}
2640 In a parallel implementation, it is necessary somehow to ``lock'' a
2641 thunk that is under evaluation, so that other parallel evaluators
2642 cannot simultaneously evaluate it and thereby duplicate work.
2643 Instead, an evaluator that enters a locked thunk should be blocked,
2644 and made runnable again when the thunk is updated.
2646 This locking is readily arranged in the same way as black-holing, by
2647 overwriting the thunk's info pointer with a special ``locked'' info
2648 pointer, at the moment of entry. If another evaluator enters the
2649 thunk before it has been updated, it will land in the entry code for
2650 the ``locked'' info pointer, which blocks the evaluator and queues it
2651 on the locked thunk.
2653 The details are given by <.portable parallel trinder.>. However, the close similarity
2654 between locking and black holing suggests the following question: can
2655 locking be done lazily too? The answer is that it can, except that
2656 locking can be postponed only until the next {\em context switch},
2657 rather than the next {\em garbage collection}. We are assuming here
2658 that the parallel implementation does not use shared memory to allow
2659 two processors to access the same closure. If such access is
2660 permitted then every thunk entry requires a hardware lock, and becomes
2663 Is lazy locking worth while, given that it requires extra work every
2664 context switch? We believe it is, because contexts switches are
2665 relatively infrequent, and thousands of thunk-entries typically take
2668 {\em Measurements elsewhere. Omit this section? If so, fix cross refs to here.}
2673 \subsection{Squeezing identical updates}
2677 \ToDo{Insert text stolen from update paper}
2681 Consider the following Haskell definition of the standard
2682 function @partition@ that divides a list into two, those elements
2683 that satisfy a predicate @p@ and those that do not:
2685 partition :: (a->Bool) -> [a] -> ([a],[a])
2686 partition p [] = ([],[])
2687 partition p (x:xs) = if p x then (x:ys, zs)
2690 (ys,zs) = partition p xs
2692 By the time this definition has been desugared, it looks like this:
2702 if p x then (x:ys,zs)
2705 Lazy evaluation demands that the recursive call is bound to an
2706 intermediate variable, @t@, from which @ys@ and @zs@ are lazily
2707 selected. (The functions @fst@ and @snd@ select the first and second
2708 elements of a pair, respectively.)
2710 Now, suppose that @partition@ is applied to a list @[x1,x2]@,
2712 elements satisfy @p@. We can get a good idea of what will happen
2713 at runtime by unrolling the recursion a few times in our heads.
2714 Unrolling once, and remembering that @(p x1)@ is @True@, we get this:
2718 let t1 = partition [x2]
2723 Unrolling the rest of the way gives this:
2735 Now consider what happens if @zs1@ is evaluated. It is bound to a
2736 thunk, which will push an update frame before evaluating the
2737 expression @snd t1@. This expression in turn forces evaluation of
2738 @zs2@, which pushes an update frame before evaluating @snd t2@.
2739 Indeed the stack of update frames will grow as deep as the list is
2740 long when @zs1@ is evaluated. This is rather galling, since all the
2741 thunks @zs1@, @zs2@, and so on, have the same value.
2743 \ToDo{Describe the state-transformer case in which we get a space leak from
2744 pending update frames.}
2746 The solution is simple. The garbage collector, which is going to traverse the
2747 update stack in any case, can easily identify two update frames that are directly
2748 on top of each other. The second of these will update its target with the same
2749 value as the first. Therefore, the garbage collector can perform the update
2750 right away, by overwriting one update target with an indirection to the second,
2751 and eliminate the corresponding update frame. In this way ever-growing stacks of
2752 update frames are reduced to a single representative at garbage collection time.
2753 If this is done at the start of garbage collection then, if it turns out that
2754 some of these update targets are garbage they will be collected right away.
2758 \subsection{Space leaks and selectors}
2762 \ToDo{Insert text stolen from update paper}
2766 In 1987, Wadler identified an important source of space leaks in
2767 lazy functional programs. Consider the Haskell function definition:
2769 f p = (g1 a, g2 b) where (a,b) = p
2771 The pattern-matching in the @where@ clause is known as
2772 {\em lazy pattern-matching}, because it is performed only if @a@
2773 or @b@ is actually evaluated. The desugarer translates lazy pattern matching
2774 to the use of selectors, @fst@ and @snd@ in this case:
2781 Now suppose that the second component of the pair @(f p)@, namely @a@,
2782 is evaluated and discarded, but the first is not although it remains
2783 reachable. The garbage collector will find that the thunk for @b@ refers
2784 to @p@ and hence to @a@. Thus, although @a@ cannot ever be used again, its
2785 space is retained. It turns out that this space leak can have a very bad effect
2786 indeed on a program's space behaviour (Section~\ref{sect:selector-results}).
2788 Wadler's paper also proposed a solution: if the garbage collector
2789 encounters a thunk of the form @snd p@, where @p@ is evaluated, then
2790 the garbage collector should perform the selection and overwrite the
2791 thunk with a pointer to the second component of the pair. In effect, the
2792 garbage collector thereby performs a bounded amount of as-yet-undemanded evaluation
2793 in the hope of improving space behaviour.
2794 We implement this idea directly, by making the garbage collector
2795 eagerly execute all selector thunks\footnote{A word of caution: it is rather easy
2796 to make a mistake in the implementation, especially if the garbage collector
2797 uses pointer reversal to traverse the reachable graph.},
2799 reported in Section~\ref{sect:THUNK_SEL}.
2801 One could easily imagine generalisations of this idea, with the garbage
2802 collector performing bounded amounts of space-saving work. One example is
2806 f x (y:ys) = f (x+1) ys
2808 Most lazy evaluators will build up a chain of thunks for the accumulating
2809 parameter, @x@, each of which increments @x@. It is not safe to evaluate
2810 any of these thunks eagerly, since @f@ is not strict in @x@, and we know nothing
2811 about the value of @x@ passed in the initial call to @f@.
2812 On the other hand, if the garbage collector found a thunk @(x+1)@ where
2813 @x@ happened to be evaluated, then it could ``execute'' it eagerly.
2814 If done carefully, the entire chain could be eliminated in a single
2815 garbage collection. We have not (yet) implemented this idea.
2816 A very similar idea, dubbed ``stingy evaluation'', is described
2819 <.sparud lazy pattern matching.> describes another solution to the
2820 lazy-pattern-matching
2821 problem. His solution involves adding code to the two thunks for
2822 @a@ and @b@ so that if either is evaluated it arranges to update the
2823 other as well as itself. The garbage-collector solution is a little
2824 more general, since it applies whether or not the selectors were
2825 generated by lazy pattern matching, and in our setting it was easier
2826 to implement than Sparud's.
2831 \subsection{Internal workings of the Compacting Collector}
2833 \subsection{Internal workings of the Copying Collector}
2835 \subsection{Internal workings of the Generational Collector}
2841 Registering costs centres looks awkward - can we tidy it up?
2843 \section{Parallelism}
2845 Something about global GC, inter-process messages and fetchmes.
2849 \section{Ticky Ticky profiling}
2851 Measure what proportion of ...:
2854 ... Enters are to data values, function values, thunks.
2856 ... allocations are for data values, functions values, thunks.
2858 ... updates are for data values, function values.
2862 ... return-in-heap (dynamic)
2864 ... vectored return (dynamic)
2866 ... updates are wasted (never re-entered).
2868 ... constructor returns get away without hitting an update.
2871 %************************************************************************
2873 \subsubsection[ticky-stk-heap-use]{Stack and heap usage}
2875 %************************************************************************
2877 Things we are interested in here:
2880 How many times we do a heap check and move @Hp@; comparing this with
2881 the allocations gives an indication of how many things we get per trip
2884 If we do a ``heap lookahead,'' we haven't really allocated any
2885 heap, so we need to undo the effects of an @ALLOC_HEAP@:
2888 The stack high-water mark.
2891 Re-use of stack slots, and stubbing of stack slots:
2895 %************************************************************************
2897 \subsubsection[ticky-allocs]{Allocations}
2899 %************************************************************************
2901 We count things every time we allocate something in the dynamic heap.
2902 For each, we count the number of words of (1)~``admin'' (header),
2903 (2)~good stuff (useful pointers and data), and (3)~``slop'' (extra
2904 space, in hopes it will allow an in-place update).
2906 The first five macros are inserted when the compiler generates code
2907 to allocate something; the categories correspond to the @ClosureClass@
2908 datatype (manifest functions, thunks, constructors, big tuples, and
2909 partial applications).
2911 We may also allocate space when we do an update, and there isn't
2912 enough space. These macros suffice (for: updating with a partial
2913 application and a constructor):
2915 In the threaded world, we allocate space for the spark pool, stack objects,
2916 and thread state objects.
2918 The histogrammy bit is fairly straightforward; the @-2@ is: one for
2919 0-origin C arrays; the other one because we do {\em no} one-word
2920 allocations, so we would never inc that histogram slot; so we shift
2921 everything over by one.
2923 Some hard-to-account-for words are allocated by/for primitives,
2924 includes Integer support. @ALLOC_PRIM2@ tells us about these. We
2925 count everything as ``goods'', which is not strictly correct.
2926 (@ALLOC_PRIM@ is the same sort of stuff, but we know the
2927 admin/goods/slop breakdown.)
2929 %************************************************************************
2931 \subsubsection[ticky-enters]{Enters}
2933 %************************************************************************
2935 We do more magical things with @ENT_FUN_DIRECT@. Besides simply knowing
2936 how many ``fast-entry-point'' enters there were, we'd like {\em simple}
2937 information about where those enters were, and the properties thereof.
2939 struct ent_counter {
2940 unsigned registeredp:16, /* 0 == no, 1 == yes */
2941 arity:16, /* arity (static info) */
2942 Astk_args:16, /* # of args off A stack */
2943 Bstk_args:16; /* # of args off B stack */
2944 /* (rest of args are in registers) */
2945 StgChar *f_str; /* name of the thing */
2946 StgChar *f_arg_kinds; /* info about the args types */
2947 StgChar *wrap_str; /* name of its wrapper (if any) */
2948 StgChar *wrap_arg_kinds;/* info about the orig wrapper's arg types */
2949 I_ ctr; /* the actual counter */
2950 struct ent_counter *link; /* link to chain them all together */
2954 %************************************************************************
2956 \subsubsection[ticky-returns]{Returns}
2958 %************************************************************************
2960 Whenever a ``return'' occurs, it is returning the constituent parts of
2961 a data constructor. The parts can be returned either in registers, or
2962 by allocating some heap to put it in (the @ALLOC_*@ macros account for
2963 the allocation). The constructor can either be an existing one
2964 (@*OLD*@) or we could have {\em just} figured out this stuff
2967 Here's some special magic that Simon wants [edited to match names
2971 From: Simon L Peyton Jones <simonpj>
2972 To: partain, simonpj
2973 Subject: counting updates
2974 Date: Wed, 25 Mar 92 08:39:48 +0000
2976 I'd like to count how many times we update in place when actually Node
2977 points to the thing. Here's how:
2979 @RET_OLD_IN_REGS@ sets the variable @ReturnInRegsNodeValid@ to @True@;
2980 @RET_NEW_IN_REGS@ sets it to @False@.
2982 @RET_SEMI_???@ sets it to??? ToDo [WDP]
2984 @UPD_CON_IN_PLACE@ tests the variable, and increments @UPD_IN_PLACE_COPY_ctr@
2987 Then we need to report it along with the update-in-place info.
2991 Of all the returns (sum of four categories above), how many were
2992 vectored? (The rest were obviously unvectored).
2994 %************************************************************************
2996 \subsubsection[ticky-update-frames]{Update frames}
2998 %************************************************************************
3000 These macros count up the following update information.
3002 \begin{tabular}{|l|l|} \hline
3003 Macro & Counts \\ \hline
3005 @UPDF_STD_PUSHED@ & Update frame pushed \\
3006 @UPDF_CON_PUSHED@ & Constructor update frame pushed \\
3007 @UPDF_HOLE_PUSHED@ & An update frame to update a black hole \\
3008 @UPDF_OMITTED@ & A thunk decided not to push an update frame \\
3009 & (all subsets of @ENT_THK@) \\
3010 @UPDF_RCC_PUSHED@ & Cost Centre restore frame pushed \\
3011 @UPDF_RCC_OMITTED@ & Cost Centres not required -- not pushed \\\hline
3014 %************************************************************************
3016 \subsubsection[ticky-updates]{Updates}
3018 %************************************************************************
3020 These macros record information when we do an update. We always
3021 update either with a data constructor (CON) or a partial application
3024 \begin{tabular}{|l|l|}\hline
3025 Macro & Where \\ \hline
3027 @UPD_EXISTING@ & Updating with an indirection to something \\
3028 & already in the heap \\
3029 @UPD_SQUEEZED@ & Same as @UPD_EXISTING@ but because \\
3030 & of stack-squeezing \\
3031 @UPD_CON_W_NODE@ & Updating with a CON: by indirecting to Node \\
3032 @UPD_CON_IN_PLACE@ & Ditto, but in place \\
3033 @UPD_CON_IN_NEW@ & Ditto, but allocating the object \\
3034 @UPD_PAP_IN_PLACE@ & Same, but updating w/ a PAP \\
3035 @UPD_PAP_IN_NEW@ & \\\hline
3038 %************************************************************************
3040 \subsubsection[ticky-selectors]{Doing selectors at GC time}
3042 %************************************************************************
3044 @GC_SEL_ABANDONED@: we could've done the selection, but we gave up
3045 (e.g., to avoid overflowing the C stack); @GC_SEL_MINOR@: did a
3046 selection in a minor GC; @GC_SEL_MAJOR@: ditto, but major GC.
3052 We're nuking the following:
3059 Return in registers.
3060 This lets us remove update code pointers from info tables,
3061 removes the need for phantom info tables, simplifies
3066 Careful analysis suggests that it doesn't buy us very much
3067 and it is hard to work with.
3069 Eliminating threaded GCs eliminates the desire to share SMReps
3070 so they are (once more) part of the Info table.
3074 Doesn't buy us anything on a register-poor architecture and
3075 isn't so important if we have semi-tagging.
3078 - Probably bad on register poor architecture
3079 - Can avoid need to write return address to stack on reg rich arch.
3080 - when a function does a small amount of work, doesn't
3081 enter any other thunks and then returns.
3082 eg entering a known constructor (but semitagging will catch this)
3083 - Adds complications
3089 This lets us drop CONST closures and CHARLIKE closures (assuming we
3090 don't support Unicode). The only point of these closures was to
3091 avoid updating with an indirection.
3093 We also drop @MIN_UPD_SIZE@ --- all we need is space to insert an
3094 indirection or a black hole.
3097 STATIC SMReps are now called CONST
3102 \item The profiling ``kind'' field is now encoded in the @INFO_TYPE@ field.
3103 This identifies the general sort of the closure for profiling purposes.
3105 \item Various papers describe deleting update frames for unreachable objects.
3106 This has never been implemented and we don't plan to anytime soon.
3110 \section{Old tricks}
3114 These are statically defined closures which have been updated with a
3115 heap-allocated result. Initially these are exactly the same as a
3116 @STATIC@ closure but with special entry code. On entering the closure
3117 the entry code must:
3120 \item Allocate a black hole in the heap which will be updated with
3122 \item Overwrite the static closure with a special @CAF@ indirection.
3124 \item Link the static indirection onto the list of updated @CAF@s.
3127 The indirection and the link field require the initial @STATIC@
3128 closure to be of at least size @MIN_UPD_SIZE@ (excluding the fixed
3131 @CAF@s are treated as special garbage collection roots. These roots
3132 are explicitly collected by the garbage collector, since they may
3133 appear in code even if they are not linked with the main heap. They
3134 consequently represent potentially enormous space-leaks. A @CAF@
3135 closure retains a fixed location in statically allocated data space.
3136 When updated, the contents of the @CAF@ indirection are changed to
3137 reflect the new closure. @CAF@ indirections require special garbage
3140 \section{Old stuff about SRTs}
3142 Garbage collection of @CAF@s is tricky. We have to cope with explicit
3143 collection from the @CAFlist@ as well as potential references from the
3144 stack and heap which will cause the @CAF@ evacuation code to be
3145 called. They are treated like indirections which are shorted out.
3146 However they must also be updated to point to the new location of the
3147 new closure as the @CAF@ may still be used by references which
3150 {\bf Copying Collection}
3152 A first scheme might use evacuation code which evacuates the reference
3153 and updates the indirection. This is no good as subsequent evacuations
3154 will result in an already evacuated closure being evacuated. This will
3155 leave a forward reference in to-space!
3157 An alternative scheme evacuates the @CAFlist@ first. The closures
3158 referenced are evacuated and the @CAF@ indirection updated to point to
3159 the evacuated closure. The @CAF@ evacuation code simply returns the
3160 updated indirection pointer --- the pointer to the evacuated closure.
3161 Unfortunately the closure the @CAF@ references may be a static
3162 closure, in fact, it may be another @CAF@. This will cause the second
3163 @CAF@'s evacuation code to be called before the @CAF@ has been
3164 evacuated, returning an unevacuated pointer.
3166 Another scheme leaves updating the @CAF@ indirections to the end of
3167 the garbage collection. All the references are evacuated and
3168 scavenged as usual (including the @CAFlist@). Once collection is
3169 complete the @CAFlist@ is traversed updating the @CAF@ references with
3170 the result of evacuating the referenced closure again. This will
3171 immediately return as it must be a forward reference, a static
3172 closure, or a @CAF@ which will indirect by evacuating its reference.
3174 The crux of the problem is that the @CAF@ evacuation code needs to
3175 know if its reference has already been evacuated and updated. If not,
3176 then the reference can be evacuated, updated and returned safely
3177 (possibly evacuating another @CAF@). If it has, then the updated
3178 reference can be returned. This can be done using two @CAF@
3179 info-tables. At the start of a collection the @CAFlist@ is traversed
3180 and set to an internal {\em evacuate and update} info-table. During
3181 collection, evacution of such a @CAF@ also results in the info-table
3182 being reset back to the standard @CAF@ info-table. Thus subsequent
3183 evacuations will simply return the updated reference. On completion of
3184 the collection all @CAF@s will have {\em return reference} info-tables
3187 This is the scheme we adopt. A @CAF@ indirection has evacuation code
3188 which returns the evacuated and updated reference. During garbage
3189 collection, all the @CAF@s are overwritten with an internal @CAF@ info
3190 table which has evacuation code which performs this evacuate and
3191 update and restores the original @CAF@ code. At some point during the
3192 collection we must ensure that all the @CAF@s are indeed evacuated.
3194 The only potential problem with this scheme is a cyclic list of @CAF@s
3195 all directly referencing (possibly via indirections) another @CAF@!
3196 Evacuation of the first @CAF@ will fail in an infinite loop of @CAF@
3197 evacuations. This is solved by ensuring that the @CAF@ info-table is
3198 updated to a {\em return reference} info-table before performing the
3199 evacuate and update. If this {\em return reference} evacuation code is
3200 called before the actual evacuation is complete it must be because
3201 such a cycle of references exists. Returning the still unevacuated
3202 reference is OK --- all the @CAF@s will now reference the same
3203 @CAF@ which will reference itself! Construction of such a structure
3204 indicates the program must be in an infinite loop.
3206 {\bf Compacting Collector}
3208 When shorting out a @CAF@, its reference must be marked. A first
3209 attempt might explicitly mark the @CAF@s, updating the reference with
3210 the marked reference (possibly short circuting indirections). The
3211 actual @CAF@ marking code can indicate that they have already been
3212 marked (though this might not have actually been done yet) and return
3213 the indirection pointer so it is shorted out. Unfortunately the @CAF@
3214 reference might point to an indirection which will be subsequently
3215 shorted out. Rather than returning the @CAF@ reference we treat the
3216 @CAF@ as an indirection, calling the mark code of the reference, which
3217 will return the appropriately shorted reference.
3219 Problem: Cyclic list of @CAF@s all directly referencing (possibly via
3220 indirections) another @CAF@!
3222 Before compacting, the locations of the @CAF@ references are
3223 explicitly linked to the closures they reference (if they reference
3224 heap allocated closures) so that the compacting process will update
3225 them to the closure's new location. Unfortunately these locations'
3226 @CAF@ indirections are static. This causes premature termination
3227 since the test to find the info pointer at the end of the location
3228 list will match more than one value. This can be solved by using an
3229 auxiliary dynamic array (on the top of the A stack). One location for
3230 each @CAF@ indirection is linked to the closure that the @CAF@
3231 references. Once collection is complete this array is traversed and
3232 the corresponding @CAF@ is then updated with the updated pointer from
3233 the auxiliary array.
3236 It is possible to use an alternative marking scheme, using a similar
3237 idea to the copying solution. This scheme avoids the need to update
3238 the @CAF@ references explicitly. We introduce an auxillary {\em mark
3239 and update} @CAF@ info-table which is used to update all @CAF@s at the
3240 start of a collection. The new code marks the @CAF@ reference,
3241 updating it with the returned reference. The returned reference is
3242 itself returned so the @CAF@ is shorted out. The code also modifies the
3243 @CAF@ info-table to be a {\em return reference}. Subsequent attempts to
3244 mark the @CAF@ simply return the updated reference.
3246 A cyclic @CAF@ reference will result in an attempt to mark the @CAF@
3247 before the marking has been completed and the reference updated. We
3248 cannot start marking the @CAF@ as it is already being marked. Nor can
3249 we return the reference as it has not yet been updated. Neither can we
3250 treat the CAF as an indirection since the @CAF@ reference has been
3251 obscured by the pointer reversal stack. All we can do is return the
3252 @CAF@ itself. This will result in some @CAF@ references not being
3255 This scheme has not been adopted but has been implemented. The code is
3256 commented out with @#if 0@.
3258 \subsection{The virtual register set}
3260 We refer to any (atomic) part of the virtual machine state as a ``register.''
3261 These ``registers'' may be shared between all threads in the system or may be
3262 specific to each thread.
3268 Thread preemption flag
3273 TSO - pointer to the TSO for when we have to pack thread away
3276 Su - used to calculate number of arguments on stack
3277 - this is a more convenient representation
3278 Call/return registers (aka General purpose registers)
3279 Cost centre (and other debug/profile info)
3280 Statistic gathering (not in production system)
3282 Heap overflow - possible global?
3283 Stack overflow - possibly global?
3284 Pattern match failure
3285 maybe a failWith handler?
3286 maybe an exitWith handler?
3290 Some of these virtual ``registers'' are used very frequently and should
3291 be mapped onto machine registers if at all possible. Others are used
3292 very infrequently and can be kept in memory to free up registers for
3295 On register-poor architectures, we can play a few tricks to reduce the
3296 number of virtual registers which need to be accessed on a regular
3301 - Grow stack and heap towards each other (single-threaded system only)
3302 - We might need to keep the C stack pointer in a register if that
3303 is what the OS expects when a signal occurs.
3304 - Preemption flag trick
3305 - If any of the frequently accessed registers cannot be mapped onto
3306 machine registers we should keep the TSO in a machine register to
3307 allow faster access to all the other non-machine registers.