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