[project @ 1998-01-08 14:40:22 by areid]
[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 (ADR) 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 % \documentstyle[preprint]{acmconf}
15 \documentclass[11pt]{article}
16 \oddsidemargin 0.1 in       %   Note that \oddsidemargin = \evensidemargin
17 \evensidemargin 0.1 in
18 \marginparwidth 0.85in    %   Narrow margins require narrower marginal notes
19 \marginparsep 0 in 
20 \sloppy
21
22 %\usepackage{epsfig}
23
24 \newcommand{\note}[1]{{\em Note: #1}}
25 % DIMENSION OF TEXT:
26 \textheight 8.5 in
27 \textwidth 6.25 in
28
29 \topmargin 0 in
30 \headheight 0 in
31 \headsep .25 in
32
33
34 \setlength{\parskip}{0.15cm}
35 \setlength{\parsep}{0.15cm}
36 \setlength{\topsep}{0cm}        % Reduces space before and after verbatim,
37                                 % which is implemented using trivlist 
38 \setlength{\parindent}{0cm}
39
40 \renewcommand{\textfraction}{0.2}
41 \renewcommand{\floatpagefraction}{0.7}
42
43 \begin{document}
44
45 \newcommand{\ToDo}[1]{{{\bf ToDo:}\sl #1}}
46 \newcommand{\Note}[1]{{{\bf Note:}\sl #1}}
47 \newcommand{\Arg}[1]{\mbox{${\tt arg}_{#1}$}}
48 \newcommand{\bottom}{bottom} % foo, can't remember the symbol name
49
50 \title{The STG runtime system (revised)}
51 \author{Simon Peyton Jones \\ Glasgow University and Oregon Graduate Institute \and
52 Simon Marlow \\ Glasgow University \and
53 Alastair Reid \\ Yale University} 
54
55 \maketitle
56
57 \tableofcontents
58 \newpage
59
60 \part{Introduction}
61 \section{Overview}
62
63 This document describes the GHC/Hugs run-time system.  It serves as 
64 a Glasgow/Yale/Nottingham ``contract'' about what the RTS does.
65
66 \subsection{New features compared to GHC 2.04}
67
68 \begin{itemize}
69 \item The RTS supports mixed compiled/interpreted execution, so
70 that a program can consist of a mixture of GHC-compiled and Hugs-interpreted
71 code.
72
73 \item CAFs are only retained if they are
74 reachable.  Since they are referred to by implicit references buried
75 in code, this means that the garbage collector must traverse the whole
76 accessible code tree.  This feature eliminates a whole class of painful
77 space leaks.
78
79 \item A running thread has only one stack, which contains a mixture
80 of pointers and non-pointers.  Section~\ref{sect:stacks} describes how
81 we find out which is which.  (GHC has used two stacks for some while.
82 Using one stack instead of two reduces register pressure, reduces the
83 size of update frames, and eliminates
84 ``stack-stubbing'' instructions.)
85
86 \item The ``return in registers'' return convention has been dropped
87 because it was complicated and doesn't work well on register-poor
88 architectures.  It has been partly replaced by unboxed tuples
89 (section~\ref{sect:unboxed-tuples}) which allow the programmer to
90 explicitly state where results should be returned in registers (or on
91 the stack) instead of on the heap.
92
93 \item
94
95 Lazy black-holing has been replaced by eager black-holing.  The
96 problem with lazy black-holing is that it leaves slop in the heap
97 which conflicts with the use of a mostly-copying collector.
98
99 \end{itemize} 
100
101 \subsection{Wish list}
102
103 Here's a list of things we'd like to support in the future.
104 \begin{itemize}
105 \item Interrupts, speculative computation.
106
107 \item
108 The SM could tune the size of the allocation arena, the number of
109 generations, etc taking into account residency, GC rate and page fault
110 rate.
111
112 \item
113 There should be no need to specify the amnount of stack/heap space to
114 allocate when you started a program - let it just take as much or as
115 little as it wants.  (It might be useful to be able to specify maximum
116 sizes and to be able to suggest an initial size.)
117
118 \item 
119 We could trigger a GC when all threads are blocked waiting for IO if
120 the allocation arena (or some of the generations) are nearly full.
121
122 \end{itemize}
123
124 \subsection{Configuration}
125
126 Some of the above features are expensive or less portable, so we
127 envision building a number of different configurations supporting
128 different subsets of the above features.
129
130 You can make the following choices:
131 \begin{itemize}
132 \item
133 Support for concurrency or parallelism.  There are four 
134 mutually-exclusive choices.
135
136 \begin{description}
137 \item[@SEQUENTIAL@] No concurrency or parallelism support.
138   This configuration might not support interrupt recovery.
139
140   \note{There's probably not much point in supporting this option.  If
141     we've gone to the effort of supporting concurency, we don't gain
142     much by being able to turn it off.}
143     
144 \item[@CONCURRENT@]  Support for concurrency but not for parallelism.
145 \item[@CONCURRENT@+@GRANSIM@] Concurrency support and simulated parallelism.
146 \item[@CONCURRENT@+@PARALLEL@]     Concurrency support and real parallelism.
147 \end{description}
148
149 \item @PROFILING@ adds cost-centre profiling.
150
151 \item @TICKY@ gathers internal statistics (often known as ``ticky-ticky'' code).
152
153 \item @DEBUG@ does internal consistency checks.
154
155 \item Persistence. (well, not yet).
156
157 \item
158 Which garbage collector to use.  At the moment we
159 only anticipate one, however.
160 \end{itemize}
161
162 \subsection{Glossary}
163
164 \ToDo{This terminology is not used consistently within the document.
165 If you find something which disagrees with this terminology, fix the
166 usage.}
167
168 \begin{itemize}
169
170 \item A {\em word} is (at least) 32 bits and can hold either a signed
171 or an unsigned int.
172
173 \item A {\em pointer} is (at least) 32 bits and big enough to hold a
174 function pointer or a data pointer.  
175
176 \item A {\em boxed} type is one whose elements are heap allocated.
177
178 \item An {\em unboxed} type is one whose elements are {\em not} heap allocated.
179
180 \item A {\em pointed} type is one that contains $\bot$.  Variables with
181 pointed types are the only things which can be lazily evaluated.  In
182 the STG machine, this means that they are the only things that can be 
183 {\em entered} or {\em updated} and it requires that they be boxed.
184
185 \item An {\em unpointed} type is one that does not contain $\bot$.
186 Variables with unpointed types are never delayed --- they are always
187 evaluated when they are constructed.  In the STG machine, this means
188 that they cannot be {\em entered} or {\em updated}.  Unpointed objects
189 may be boxed (like @Array#@) or unboxed (like @Int#@).
190
191 \item A {\em closure} is a (representation of) a value of a {\em pointed}
192 type.  It may be in HNF or it may be unevaluated --- in either case, you can
193 try to evaluate it again.
194
195 \item A {\em thunk} is a (representation of) a value of a {\em pointed}
196 type which is {\em not} in HNF.
197
198 \item A {\em value} is an object in HNF.  It can be pointed or unpointed.
199
200 \end{itemize}
201
202 Occasionally, a field of a data structure must hold either a word or a
203 pointer.  In such circumstances, it is {\em not safe} to assume that
204 words and pointers are the same size.
205
206 % Todo:
207 % More terminology to mention.
208 % unboxed, unpointed
209
210 \subsection{Subtle Dependencies}
211
212 Some decisions have very subtle consequences which should be written
213 down in case we want to change our minds.  
214
215 \begin{itemize}
216
217 \item The garbage collector never expands an object when it promotes
218 it to the old generation.  This is important because the GC avoids
219 performing heap overflow checks by assuming that the amount added to
220 the old generation is no bigger than the current new generation.
221
222 \item
223
224 If the garbage collector is allowed to shrink the stack of a thread,
225 we cannot omit the stack check in return continuations
226 (section~\ref{sect:heap-and-stack-checks}).
227
228 \item
229
230 When we return to the scheduler, the top object on the stack is a closure.
231 The scheduler restarts the thread by entering the closure.
232
233 Section~\ref{sect:hugs-return-convention} discusses how Hugs returns an
234 unboxed value to GHC and how GHC returns an unboxed value to Hugs.
235
236 \item 
237
238 When we return to the scheduler, we need a few empty words on the stack
239 to store a closure to reenter.  Section~\ref{sect:heap-and-stack-checks}
240 discusses who does the stack check and how much space they need.
241
242 \item
243
244 Heap objects never contain slop --- this is required if we want to
245 support mostly-copying garbage collection.
246
247 This is a big problem when updating since the updatee is usually
248 bigger than an indirection object.  The fix is to overwrite the end of
249 the updatee with ``slop objects'' (described in
250 section~\ref{sect:slop-objects}).
251 This is hard to arrange if we do \emph{lazy} blackholing
252 (section~\ref{sect:lazy-black-holing}) so we currently plan to
253 blackhole an object when we push the update frame.
254
255
256
257 \item
258
259 Info tables for constructors contain enough information to decide which
260 return convention they use.  This allows Hugs to use a single piece of
261 entry code for all constructors and insulates Hugs from changes in the
262 choice of return convention.
263
264 \end{itemize}
265
266 \section{Source Language}
267
268 \subsection{Explicit Allocation}\label{sect:explicit-allocation}
269
270 As in the original STG machine, (almost) all heap allocation is caused
271 by executing a let(rec).  Since we no longer support the return in
272 registers convention for data constructors, constructors now cause heap
273 allocation and so they should be let-bound.
274
275 For example, we now write
276 @
277 > cons = \ x xs -> let r = (:) x xs in r
278 @
279 instead of
280 @
281 > cons = \ x xs -> (:) x xs
282 @
283
284
285 \subsection{Unboxed tuples}\label{sect:unboxed-tuples}
286
287 Functions can take multiple arguments as easily as they can take one
288 argument: there's no cost for adding another argument.  But functions
289 can only return one result: the cost of adding a second ``result'' is
290 that the function must construct a tuple of ``results'' on the heap.
291 The assymetry is rather galling and can make certain programming
292 styles quite expensive.  For example, consider a simple state transformer
293 monad:
294 @
295 > type S a     = State -> (a,State)
296 > bindS m k s0 = case m s0 of { (a,s1) -> k a s1 }
297 > returnS a s  = (a,s)
298 > getS s       = (s,s)
299 > setS s _     = ((),s)
300 @
301 Here, every use of @returnS@, @getS@ or @setS@ constructs a new tuple
302 in the heap which is instantly taken apart (and becomes garbage) by
303 the case analysis in @bind@.  Even a short state-transformer program
304 will construct a lot of these temporary tuples.
305
306 Unboxed tuples provide a way for the programmer to indicate that they
307 do not expect a tuple to be shared and that they do not expect it to
308 be allocated in the heap.  Syntactically, unboxed tuples are just like
309 single constructor datatypes except for the annotation @unboxed@.
310 @
311 > data unboxed AAndState# a = AnS a State
312 > type S a = State -> AAndState# a
313 > bindS m k s0 = case m s0 of { AnS a s1 -> k a s1 }
314 > returnS a s  = AnS a s
315 > getS s       = AnS s s
316 > setS s _     = AnS () s
317 @
318 Semantically, unboxed tuples are just unlifted tuples and are subject
319 to the same restrictions as other unpointed types.
320
321 Operationally, unboxed tuples are never built on the heap.  When
322 unboxed tuples are returned, they are returned in multiple registers
323 or multiple stack slots.  At first sight, this seems a little strange
324 but it's no different from passing double precision floats in two
325 registers.
326
327 Notes:
328 \begin{itemize}
329 \item
330 Unboxed tuples can only have one constructor and that
331 thunks never have unboxed types --- so we'll never try to update an
332 unboxed constructor.  The restriction to a single constructor is
333 largely to avoid garbage collection complications.
334
335 \item
336 The core syntax does not allow variables to be bound to
337 unboxed tuples (ie in default case alternatives or as function arguments)
338 and does not allow unboxed tuples to be fields of other constructors.
339 However, there's no harm in allowing it in the source syntax as a
340 convenient, but easily removed, syntactic sugar.
341
342 \item
343 The compiler generates a closure of the form
344 @
345 > c = \ x y z -> C x y z
346 @
347 for every constructor (whether boxed or unboxed).  
348
349 This closure is normally used during desugaring to ensure that
350 constructors are saturated and to apply any strictness annotations.
351 They are also used when returning unboxed constructors to the machine
352 code evaluator from the bytecode evaluator and when a heap check fails
353 in a return continuation for an unboxed-tuple scrutinee.
354
355 \end{itemize}
356
357 \subsection{STG Syntax}
358
359 \ToDo{Insert STG syntax with appropriate changes.}
360
361
362 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
363 \part{System Overview}
364 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
365
366 This part is concerned with defining the external interfaces of the
367 major components of the system; the next part is concerned with their
368 inner workings.
369
370 The major components of the system are:
371 \begin{itemize}
372 \item The scheduler
373 \item The storage manager
374 \item The evaluators
375 \item The loader
376 \item The compilers
377 \end{itemize}
378
379 \ToDo{Insert diagram showing all components underneath the scheduler
380 and communicating only with the scheduler}
381
382 \section{Scheduler}
383
384 The Scheduler is the heart of the run-time system.  A running program
385 consists of a single running thread, and a list of runnable and
386 blocked threads.  All threads consist of a stack and a few words of
387 status information.  Except for the running thread, all threads have a
388 closure on top of their stack; the scheduler restarts a thread by
389 entering an evaluator which performs some reduction and returns.
390
391 \subsection{The scheduler's main loop}
392
393 The scheduler consists of a loop which chooses a runnable thread and
394 invokes one of the evaluators which performs some reduction and
395 returns.
396
397 The scheduler also takes care of system-wide issues such as heap
398 overflow or communication with other processors (in the parallel
399 system) and thread-specific problems such as stack overflow.
400
401 \subsection{Creating a thread}
402
403 Threads are created:
404
405 \begin{itemize}
406
407 \item
408
409 When the scheduler is first invoked.
410
411 \item
412
413 When a message is received from another processor (I think). (Parallel
414 system only.)
415
416 \item
417
418 When a C program calls some Haskell code.
419
420 \end{itemize}
421
422
423 \subsection{Restarting a thread}
424
425 The evaluators can reduce almost all types of closure except that only
426 the machine code evaluator can reduce GHC-compiled closures and only
427 the bytecode evaluator can reduce Hugs-compiled closures.
428 Consequently, the scheduler may use either evaluator to restart a
429 thread unless the top closure is a @BCO@ or contains machine code.
430
431 However, if the top of the stack contains a constructor, the scheduler
432 should use the machine code evaluator to restart the thread.  This
433 allows the bytecode evaluator to return a constructor to a machine
434 code return address by pushing the constructor on top of the stack and
435 returning to the scheduler.  If the return address under the
436 constructor is @HUGS_RET@, the entry code for @HUGS_RET@ will
437 rearrange the stack so that the return @BCO@ is on top of the stack
438 and return to the scheduler which will then call the bytecode
439 evaluator.  There is little point in trying to shorten this slightly
440 indirect route since it will happen very rarely if at all.
441
442 \subsection{Returning from a thread}
443
444 The evaluators return to the scheduler when any of the following
445 conditions arise:
446
447 \begin{itemize}
448 \item A heap check fails, and a garbage collection is required
449 \item Compiled code needs to switch to interpreted code, and vice versa.
450 \item The evaluator needs to perform an ``unsafe'' C call.
451 \item The thread becomes blocked.
452 \item The thread is preempted.
453 \item The thread terminates.
454 \end{itemize}
455
456 Except when the thread terminates, the thread always terminates with a
457 closure on the top of the stack.  
458
459 \subsection{Preempting a thread}
460
461 Strictly speaking, threads cannot be preempted --- the scheduler
462 merely sets a preemption request flag which the thread must arrange to
463 test on a regular basis.  When an evaluator finds that the preemption
464 request flag is set, it pushes an appropriate closure onto the stack
465 and returns to the scheduler.
466
467 In the bytecode interpreter, the flag is tested whenever we enter a
468 closure.  If the preemption flag is set, it leaves the closure on top
469 of the stack and returns to the scheduler.
470
471 In the machine code evaluator, the flag is only tested when a heap or
472 stack check fails.  This is less expensive than testing the flag on
473 entering every closure but runs the risk that a thread will enter an
474 infinite loop which does not allocate any space.  If the flag is set,
475 the evaluator returns to the scheduler exactly as if a heap check had
476 failed.
477
478 \subsection{``Safe'' and ``unsafe'' C calls}
479
480 There are two ways of calling C: 
481
482 \begin{description}
483
484 \item[``Safe'' C calls]
485 are used if the programer is certain that the C function will not
486 do anything dangerous such as calling a Haskell function or an
487 operating system call which blocks the thread for a long period of time.
488 \footnote{Warning: this use of ``safe'' and ``unsafe'' is the exact
489 opposite of the usage for functions like @unsafePerformIO@.}
490 Safe C calls are faster but must be hand-checked by the programmer.
491
492 Safe C calls are performed by pushing the arguments onto the C stack
493 and jumping to the C function's entry point.  On exit, the result of
494 the function is in a register which is returned to the Haskell code as
495 an unboxed value.
496
497 \item[``Unsafe'' C calls] are used if the programmer suspects that the
498 thread may do something dangerous like blocking or calling a Haskell
499 function.  Unsafe C calls are relatively slow but are less problematic.
500
501 Unsafe C calls are performed by pushing the arguments onto the Haskell
502 stack, pushing a return continuation and returning a \emph{C function
503 descriptor} to the scheduler.  The scheduler suspends the Haskell thread,
504 spawns a new operating system thread which pops the arguments off the
505 Haskell stack onto the C stack, calls the C function, pushes the
506 function result onto the Haskell stack and informs the scheduler that
507 the C function has completed and the Haskell thread is now runnable.
508
509 \end{description}
510
511 The bytecode evaluator will probably treat all C calls as being unsafe.
512
513 \ToDo{It might be good for the programmer to indicate how the program is 
514 unsafe.  For example, if we distinguish between C functions which might
515 call Haskell functions and those which might block, we could perform a 
516 safe call for blocking functions in a single-threaded system or, perhaps, in a multi-threaded system which only happens to have a single thread at the moment.}
517
518
519 \section{The Evaluators}
520
521 All the scheduler needs to know about evaluation is how to manipulate
522 threads and how to find the closure on top of the stack.  The
523 evaluators need to agree on the representations of certain objects and
524 on how to return from the scheduler.
525
526 \subsection{Returning to the Scheduler}
527 \label{sect:switching-worlds}
528
529 The evaluators return to the scheduler under three circumstances:
530 \begin{itemize}
531
532 \item
533
534 When they enter a closure built by the other evaluator.  That is, when
535 the bytecode interpreter enters a closure compiled by GHC or when the
536 machine code evaluator enters a BCO.
537
538 \item
539
540 When they return to a return continuation built by the other
541 evaluator.  That is, when the machine code evaluator returns to a
542 continuation built by Hugs or when the bytecode evaluator returns to a
543 continuation built by GHC.
544
545 \item
546
547 When a heap or stack check fails or when the preemption flag is set.
548
549 \end{itemize}
550
551 In all cases, they return to the scheduler with a closure on top of
552 the stack.  The mechanism used to trigger the world switch and the
553 choice of closure left on top of the stack varies according to which
554 world is being left and what is being returned.
555
556 \subsubsection{Leaving the bytecode evaluator}
557 \label{sect:hugs-to-ghc-switch}
558
559 \paragraph{Entering a machine code closure}
560
561 When it enters a closure, the bytecode evaluator performs a switch
562 based on the type of closure (@AP@, @PAP@, @Ind@, etc).  On entering a
563 machine code closure, it returns to the scheduler with the closure on
564 top of the stack.
565
566 \paragraph{Returning a constructor}
567
568 When it enters a constructor, the bytecode evaluator tests the return
569 continuation on top of the stack.  If it is a machine code
570 continuation, it returns to the scheduler with the constructor on top
571 of the stack.
572
573 \note{This is why the scheduler must enter the machine code evaluator
574 if it finds a constructor on top of the stack.}
575
576 \paragraph{Returning an unboxed value}
577
578 \note{Hugs doesn't support unboxed values in source programs but they
579 are used for a few complex primops.}
580
581 When it enters a constructor, the bytecode evaluator tests the return
582 continuation on top of the stack.  If it is a machine code
583 continuation, it returns to the scheduler with the unboxed value and a
584 special closure on top of the stack.  When the closure is entered (by
585 the machine code evaluator), it returns the unboxed value on top of
586 the stack to the return continuation under it.
587
588 The runtime system (or GHC?) provides one of these closures for each 
589 unboxed type.  Hugs cannot generate them itself since the entry code is
590 really very tricky.
591
592 \paragraph{Heap/Stack overflow and preemption}
593
594 The bytecode evaluator tests for heap/stack overflow and preemption
595 when entering a BCO and simply returns with the BCO on top of the
596 stack.
597
598 \subsubsection{Leaving the machine code evaluator}
599 \label{sect:ghc-to-hugs-switch}
600
601 \paragraph{Entering a BCO}
602
603 The entry code for a BCO pushes the BCO onto the stack and returns to
604 the scheduler.
605
606 \paragraph{Returning a constructor}
607
608 We avoid the need to test return addresses in the machine code
609 evaluator by pushing a special return address on top of a pointer to
610 the bytecode return continuation.  Figure~\ref{fig:hugs-return-stack}
611 shows the state of the stack just before evaluating the scrutinee.
612
613 \begin{figure}[ht]
614 \begin{center}
615 @
616 | stack    |
617 +----------+
618 | bco      |--> BCO
619 +----------+
620 | HUGS_RET |
621 +----------+
622 @
623 %\input{hugs_return1.pstex_t}
624 \end{center}
625 \caption{Stack layout for evaluating a scrutinee}
626 \label{fig:hugs-return-stack}
627 \end{figure}
628
629 This return address rearranges the stack so that the bco pointer is
630 above the constructor on the stack (as shown in
631 figure~\ref{fig:hugs-boxed-return}) and returns to the scheduler.
632
633 \begin{figure}[ht]
634 \begin{center}
635 @
636 | stack    |
637 +----------+
638 | con      |--> Constructor
639 +----------+
640 | bco      |--> BCO
641 +----------+
642 @
643 %\input{hugs_return2.pstex_t}
644 \end{center}
645 \caption{Stack layout for entering a Hugs return address}
646 \label{fig:hugs-boxed-return}
647 \end{figure}
648
649 \paragraph{Returning an unboxed value}
650
651 We avoid the need to test return addresses in the machine code
652 evaluator by pushing a special return address on top of a pointer to
653 the bytecode return continuation.  This return address rearranges the
654 stack so that the bco pointer is above the unboxed value (as shown in
655 figure~\ref{fig:hugs-entering-unboxed-return}) and returns to the scheduler.
656
657 \begin{figure}[ht]
658 \begin{center}
659 @
660 | stack    |
661 +----------+
662 | 1#       |
663 +----------+
664 | I#       |
665 +----------+
666 | bco      |--> BCO
667 +----------+
668 @
669 %\input{hugs_return2.pstex_t}
670 \end{center}
671 \caption{Stack layout for returning an unboxed value}
672 \label{fig:hugs-entering-unboxed-return}
673 \end{figure}
674
675 \paragraph{Heap/Stack overflow and preemption}
676
677 \ToDo{}
678
679 \subsection{Shared Representations}
680
681 We share @AP@s, @PAP@s, constructors, indirections, selectors(?) and
682 update frames.  These are described in section~\ref{sect:heap-objects}.
683
684
685 \section{The Storage Manager}
686
687 The storage manager is responsible for managing the heap and all
688 objects stored in it.  Most objects are just copied in the normal way
689 but a number receive special treatment by the storage manager:
690
691 \begin{itemize}
692 \item
693
694 Indirections are shorted out.
695
696 \item
697
698 Weak pointers and stable pointers are treated specially.
699
700 \item
701
702 Thread State Objects (TSOs) and the stacks within them are treated specially.
703 In particular:
704
705 \begin{itemize}
706 \item
707
708 Update frames pointing to unreachable objects are squeezed out.
709
710 \item
711
712 Adjacent update frames (for different closures) are compressed to a
713 single update frame pointing to a single black hole.
714
715 \item
716
717 If the stack contains a large amount of free space, the storage
718 manager may shrink the stack.  If it shrinks the stack, it guarantees
719 never to leave less than @MIN_SIZE_SHRUNKEN_STACK@ empty words on the
720 stack when it does so.
721
722 \ToDo{Would it be useful for the storage manager to enlarge the stack?}
723
724 \end{itemize}
725
726 \item
727
728 Very large objects (eg large arrays and TSOs) are not moved if
729 possible.
730
731 \end{itemize}
732
733
734 \section{The Compilers}
735
736 Need to describe interface files, format of bytecode files, symbols
737 defined by machine code files.
738
739 \subsection{Interface Files}
740
741 Here's an example - but I don't know the grammar - ADR.
742 @
743 _interface_ Main 1
744 _exports_
745 Main main ;
746 _declarations_
747 1 main _:_ IOBase.IO PrelBase.();;
748 @
749
750 \subsection{Bytecode files}
751
752 (All that matters here is what the loader sees.)
753
754 \subsection{Machine code files}
755
756 (Again, all that matters is what the loader sees.)
757
758
759 \subsection{Bytecode files}
760
761 (All that matters here is what the loader sees.)
762
763 \subsection{Machine code files}
764
765 (Again, all that matters is what the loader sees.)
766
767
768 \section{The Loader}
769
770 \ToDo{Is it ok to load code when threads are running?}
771
772 In a batch mode system, we can statically link all the modules
773 together.  In an interactive system we need a loader which will
774 explicitly load and unload individual modules (or, perhaps, blocks of
775 mutually dependent modules) and resolve references between modules.
776
777 While many operating systems provide support for dynamic loading and
778 will automatically resolve cross-module references for us, we generally
779 cannot rely on being able to load mutually dependent modules.
780
781 A portable solution is to perform some of the linking ourselves.  Each module
782 should provide three global symbols: 
783 \begin{itemize}
784 \item
785 An initialisation routine.  (Might also be used for finalisation.)
786 \item
787 A table of symbols it exports.
788 Entries in this table consist of the symbol name and the address of the
789 names value.
790 \item
791 A table of symbols it imports.
792 Entries in this table consist of the symbol name and a list of references
793 to that symbol.
794 \end{itemize}
795
796 On loading a group of modules, the loader adds the contents of the
797 export lists to a symbol table and then fills in all the references in the
798 import lists.
799
800 References in import lists are of two types:
801 \begin{description}
802 \item[ References in machine code ]
803
804 The most efficient approach is to patch the machine code directly, but
805 this will be a lot of work, very painful to port and rather fragile.
806
807 Alternatively, the loader could store the value of each symbol in the
808 import table for each module and the compiled code can access all
809 external objects through the import table.  This requires that the
810 import table be writable but does not require that the machine code or
811 info tables be writable.
812
813 \item[ References in data structures (SRTs and static data constructors) ]
814
815 Either we patch the SRTs and constructors directly or we somehow use
816 indirections through the symbol table.  Patching the SRTs requires
817 that we make them writable and prevents us from making effective use
818 of virtual memories that use copy-on-write policies.  Using an
819 indirection is possible but tricky.
820
821 Note: We could avoid patching machine code if all references to
822 eternal references went through the SRT --- then we just have one
823 thing to patch.  But the SRT always contains a pointer to the closure
824 rather than the fast entry point (say), so we'd take a big performance
825 hit for doing this.
826
827 \end{description}
828
829 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
830 \part{Internal details}
831 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
832
833 This part is concerned with the internal details of the components
834 described in the previous part.
835
836 The major components of the system are:
837 \begin{itemize}
838 \item The scheduler
839 \item The storage manager
840 \item The evaluators
841 \item The loader
842 \item The compilers
843 \end{itemize}
844
845 \section{The Scheduler}
846
847 \section{The Storage Manager}
848 \label{sect:storage-manager-internals}
849
850 \ToDo{Fix this picture}
851
852 \begin{figure}
853 \begin{center}
854 \input{closure}
855 \end{center}
856 \caption{A closure}
857 \label{fig:closure}
858 \end{figure}
859
860 Every {\em heap object} is a contiguous block
861 of memory, consisting of a fixed-format {\em header} followed
862 by zero or more {\em data words}.
863
864 \ToDo{I absolutely do not believe that every heap object has a header
865 like this - ADR.  I believe that they all have an info pointer but I
866 see no readon why stack objects and unpointed heap objects would have
867 an entry count since this will always be zero.}
868
869 The header consists of the following fields:
870 \begin{itemize}
871 \item A one-word {\em info pointer}, which points to
872 the object's static {\em info table}.
873 \item Zero or more {\em admin words} that support
874 \begin{itemize}
875 \item Profiling (notably a {\em cost centre} word).
876   \note{We could possibly omit the cost centre word from some 
877   administrative objects.}
878 \item Parallelism (e.g. GranSim keeps the object's global address here,
879 though GUM keeps a separate hash table).
880 \item Statistics (e.g. a word to track how many times a thunk is entered.).
881
882 We add a Ticky word to the fixed-header part of closures.  This is
883 used to indicate if a closure has been updated but not yet entered. It
884 is set when the closure is updated and cleared when subsequently
885 entered.
886
887 NB: It is {\em not} an ``entry count'', it is an
888 ``entries-after-update count.''  The commoning up of @CONST@,
889 @CHARLIKE@ and @INTLIKE@ closures is turned off(?) if this is
890 required. This has only been done for 2s collection.
891
892 \end{itemize}
893 \end{itemize}
894
895 Most of the RTS is completely insensitive to the number of admin words.
896 The total size of the fixed header is @FIXED_HS@.
897
898 Many heap objects contain fields allowing them to be inserted onto lists
899 during evaluation or during garbage collection. The lists required by
900 the evaluator and storage manager are as follows.
901
902 \begin{itemize}
903 \item 2 lists of threads: runnable threads and sleeping threads.
904
905 \item The {\em static object list} is a list of all statically
906 allocated objects which might contain pointers into the heap.
907 (Section~\ref{sect:static-objects}.)
908
909 \item The {\em updated thunk list} is a list of all thunks in the old
910 generation which have been updated with an indirection.  
911 (Section~\ref{sect:IND_OLDGEN}.)
912
913 \item The {\em mutables list} is a list of all other objects in the
914 old generation which might contain pointers into the new generation.
915 Most of the object on this list are ``mutable.''
916 (Section~\ref{sect:mutables}.)
917
918 \item The {\em Foreign Object list} is a list of all foreign objects
919  which have not yet been deallocated. (Section~\ref{sect:FOREIGN}.)
920
921 \item The {\em Spark pool} is a doubly(?) linked list of Spark objects
922 maintained by the parallel system.  (Section~\ref{sect:SPARK}.)
923
924 \item The {\em Blocked Fetch list} (or
925 lists?). (Section~\ref{sect:BLOCKED_FETCH}.)
926
927 \item For each thread, there is a list of all update frames on the
928 stack.  (Section~\ref{sect:data-updates}.)
929
930
931 \end{itemize}
932
933 \ToDo{The links for these fields are usually inserted immediately
934 after the fixed header except ...}
935
936 \subsection{Info Tables}
937
938 An {\em info table} is a contiguous block of memory, {\em laid out
939 backwards}.  That is, the first field in the list that follows
940 occupies the highest memory address, and the successive fields occupy
941 successive decreasing memory addresses.
942
943 \begin{center}
944 \begin{tabular}{|c|}
945    \hline Parallelism Info 
946 \\ \hline Profile Info 
947 \\ \hline Debug Info 
948 \\ \hline Tag / Static reference table
949 \\ \hline Storage manager layout info
950 \\ \hline Closure type 
951 \\ \hline entry code
952 \\       \vdots
953 \end{tabular}
954 \end{center}
955 An info table has the following contents (working backwards in memory
956 addresses):
957 \begin{itemize}
958 \item The {\em entry code} for the closure.
959 This code appears literally as the (large) last entry in the
960 info table, immediately preceded by the rest of the info table.
961 An {\em info pointer} always points to the first byte of the entry code.
962
963 \item A one-word {\em closure type field}, @INFO_TYPE@, identifies what kind
964 of closure the object is.  The various types of closure are described
965 in Section~\ref{sect:closures}.
966 In some configurations, some useful properties of 
967 closures (is it a HNF?  can it be sparked?)
968 are represented as high-order bits so they can be tested quickly.
969
970 \item A single pointer or word --- the {\em storage manager info field},
971 @INFO_SM@, contains auxiliary information describing the closure's
972 precise layout, for the benefit of the garbage collector and the code
973 that stuffs graph into packets for transmission over the network.
974
975 \item A one-word {\em Tag/Static Reference Table} field, @INFO_SRT@.
976 For data constructors, this field contains the constructor tag, in the
977 range $0..n-1$ where $n$ is the number of constructors.  For all other
978 objects it contains a pointer to a table which enables the garbage
979 collector to identify all accessible code and CAFs.  They are fully
980 described in Section~\ref{sect:srt}.
981
982 \item {\em Profiling info\/}
983
984 \ToDo{The profiling info is completely bogus.  I've not deleted it
985 from the document but I've commented it all out.}
986
987 % change to \iftrue to uncomment this section
988 \iffalse
989
990 Closure category records are attached to the info table of the
991 closure. They are declared with the info table. We put pointers to
992 these ClCat things in info tables.  We need these ClCat things because
993 they are mutable, whereas info tables are immutable.  Hashing will map
994 similar categories to the same hash value allowing statistics to be
995 grouped by closure category.
996
997 Cost Centres and Closure Categories are hashed to provide indexes
998 against which arbitrary information can be stored. These indexes are
999 memoised in the appropriate cost centre or category record and
1000 subsequent hashes avoided by the index routine (it simply returns the
1001 memoised index).
1002
1003 There are different features which can be hashed allowing information
1004 to be stored for different groupings. Cost centres have the cost
1005 centre recorded (using the pointer), module and group. Closure
1006 categories have the closure description and the type
1007 description. Records with the same feature will be hashed to the same
1008 index value.
1009
1010 The initialisation routines, @init_index_<feature>@, allocate a hash
1011 table in which the cost centre / category records are stored. The
1012 lower bound for the table size is taken from @max_<feature>_no@. They
1013 return the actual table size used (the next power of 2). Unused
1014 locations in the hash table are indicated by a 0 entry. Successive
1015 @init_index_<feature>@ calls just return the actual table size.
1016
1017 Calls to @index_<feature>@ will insert the cost centre / category
1018 record in the @<feature>@ hash table, if not already inserted. The hash
1019 index is memoised in the record and returned. 
1020
1021 CURRENTLY ONLY ONE MEMOISATION SLOT IS AVILABLE IN EACH RECORD SO
1022 HASHING CAN ONLY BE DONE ON ONE FEATURE FOR EACH RECORD. This can be
1023 easily relaxed at the expense of extra memoisation space or continued
1024 rehashing.
1025
1026 The initialisation routines must be called before initialisation of
1027 the stacks and heap as they require to allocate storage. It is also
1028 expected that the caller may want to allocate additional storage in
1029 which to store profiling information based on the return table size
1030 value(s).
1031
1032 \begin{center}
1033 \begin{tabular}{|l|}
1034    \hline Hash Index
1035 \\ \hline Selected
1036 \\ \hline Kind
1037 \\ \hline Description String
1038 \\ \hline Type String
1039 \\ \hline
1040 \end{tabular}
1041 \end{center}
1042
1043 \begin{description}
1044 \item[Hash Index] Memoised copy
1045 \item[Selected] 
1046   Is this category selected (-1 == not memoised, selected? 0 or 1)
1047 \item[Kind]
1048 One of the following values (defined in CostCentre.lh):
1049
1050 \begin{description}
1051 \item[@CON_K@]
1052 A constructor.
1053 \item[@FN_K@]
1054 A literal function.
1055 \item[@PAP_K@]
1056 A partial application.
1057 \item[@THK_K@]
1058 A thunk, or suspension.
1059 \item[@BH_K@]
1060 A black hole.
1061 \item[@ARR_K@]
1062 An array.
1063 \item[@ForeignObj_K@]
1064 A Foreign object (non-Haskell heap resident).
1065 \item[@SPT_K@]
1066 The Stable Pointer table.  (There should only be one of these but it
1067 represents a form of weak space leak since it can't shrink to meet
1068 non-demand so it may be worth watching separately? ADR)
1069 \item[@INTERNAL_KIND@]
1070 Something internal to the runtime system.
1071 \end{description}
1072
1073
1074 \item[Description] Source derived string detailing closure description.
1075 \item[Type] Source derived string detailing closure type.
1076 \end{description}
1077
1078 \fi % end of commented out stuff
1079
1080 \item {\em Parallelism info\/}
1081 \ToDo{}
1082
1083 \item {\em Debugging info\/}
1084 \ToDo{}
1085
1086 \end{itemize}
1087
1088
1089 %-----------------------------------------------------------------------------
1090 \subsection{Kinds of Heap Object}
1091 \label{sect:closures}
1092
1093 Heap objects can be classified in several ways, but one useful one is
1094 this:
1095 \begin{itemize}
1096 \item 
1097 {\em Static closures} occupy fixed, statically-allocated memory
1098 locations, with globally known addresses.
1099
1100 \item 
1101 {\em Dynamic closures} are individually allocated in the heap.
1102
1103 \item 
1104 {\em Stack closures} are closures allocated within a thread's stack
1105 (which is itself a heap object).  Unlike other closures, there are
1106 never any pointers to stack closures.  Stack closures are discussed in
1107 Section~\ref{sect:stacks}.
1108
1109 \end{itemize}
1110 A second useful classification is this:
1111 \begin{itemize}
1112 \item 
1113 {\em Executive objects}, such as thunks and data constructors,
1114 participate directly in a program's execution.  They can be subdivided into
1115 three kinds of objects according to their type:
1116 \begin{itemize}
1117 \item 
1118 {\em Pointed objects}, represent values of a {\em pointed} type
1119 (<.pointed types launchbury.>) --i.e.~a type that includes $\bottom$ such as @Int@ or @Int# -> Int#@.
1120
1121 \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#@.
1122
1123 \item {\em Activation frames}, represent ``continuations''.  They are
1124 always stored on the stack and are never pointed to by heap objects or
1125 passed as arguments.  \note{It's not clear if this will still be true
1126 once we support speculative evaluation.}
1127
1128 \end{itemize}
1129
1130 \item {\em Administrative objects}, such as stack objects and thread
1131 state objects, do not represent values in the original program.
1132 \end{itemize}
1133
1134 Only pointed objects can be entered.  All pointed objects share a
1135 common header format: the ``pointed header''; while all unpointed
1136 objects share a common header format: the ``unpointed header''.
1137 \ToDo{Describe the difference and update the diagrams to mention
1138 an appropriate header type.}
1139
1140 This section enumerates all the kinds of heap objects in the system.
1141 Each is identified by a distinct @INFO_TYPE@ tag in its info table.
1142
1143 \begin{tabular}{|l|l|l|l|l|l|l|l|l|l|l|}
1144 \hline
1145
1146 closure kind          & Section \\
1147                       
1148 \hline                          
1149 {\em Pointed} \\      
1150 \hline                
1151                       
1152 @CONSTR@              & \ref{sect:CONSTR}    \\
1153 @CONSTR_STATIC@       & \ref{sect:CONSTR}    \\
1154 @CONSTR_STATIC_NOCAF@ & \ref{sect:CONSTR}    \\
1155                       
1156 @FUN@                 & \ref{sect:FUN}       \\
1157 @FUN_STATIC@          & \ref{sect:FUN}       \\
1158                       
1159 @THUNK@               & \ref{sect:THUNK}     \\
1160 @THUNK_STATIC@        & \ref{sect:THUNK}     \\
1161 @THUNK_SELECTOR@      & \ref{sect:THUNK_SEL} \\
1162                       
1163 @BCO@                 & \ref{sect:BCO}       \\
1164 @BCO_CAF@             & \ref{sect:BCO}       \\
1165                       
1166 @AP@                  & \ref{sect:AP}            \\
1167 @PAP@                 & \ref{sect:PAP}       \\
1168                       
1169 @IND@                 & \ref{sect:IND}       \\
1170 @IND_OLDGEN@          & \ref{sect:IND}       \\
1171 @IND_PERM@            & \ref{sect:IND}       \\
1172 @IND_OLDGEN_PERM@     & \ref{sect:IND}       \\
1173 @IND_STATIC@          & \ref{sect:IND}       \\
1174                       
1175 \hline                
1176 {\em Unpointed} \\    
1177 \hline                
1178                                       
1179 @ARR_WORDS@           & \ref{sect:ARR_WORDS1},\ref{sect:ARR_WORDS2} \\
1180 @ARR_PTRS@            & \ref{sect:ARR_PTRS}  \\
1181 @MUTVAR@              & \ref{sect:MUTVAR}    \\
1182 @MUTARR_PTRS@         & \ref{sect:MUTARR_PTRS} \\
1183 @MUTARR_PTRS_FROZEN@  & \ref{sect:MUTARR_PTRS_FROZEN} \\
1184                       
1185 @FOREIGN@             & \ref{sect:FOREIGN}   \\
1186                       
1187 @BH@                  & \ref{sect:BH}        \\
1188 @MVAR@                & \ref{sect:MVAR}      \\
1189 @IVAR@                & \ref{sect:IVAR}      \\
1190 @FETCHME@             & \ref{sect:FETCHME}   \\
1191 \hline
1192 \end{tabular}
1193
1194 Activation frames do not live (directly) on the heap --- but they have
1195 a similar organisation.
1196
1197 \begin{tabular}{|l|l|}\hline
1198 closure kind            & Section                       \\ \hline
1199 @RET_SMALL@             & \ref{sect:activation-records} \\
1200 @RET_VEC_SMALL@         & \ref{sect:activation-records} \\
1201 @RET_BIG@               & \ref{sect:activation-records} \\
1202 @RET_VEC_BIG@           & \ref{sect:activation-records} \\
1203 @UPDATE_FRAME@          & \ref{sect:activation-records} \\
1204 \hline
1205 \end{tabular}
1206
1207 There are also a number of administrative objects.
1208
1209 \begin{tabular}{|l|l|}\hline
1210 closure kind            & Section                       \\ \hline
1211 @TSO@                   & \ref{sect:TSO}                \\
1212 @STACK_OBJECT@          & \ref{sect:STACK_OBJECT}       \\
1213 @STABLEPTR_TABLE@       & \ref{sect:STABLEPTR_TABLE}    \\
1214 @SPARK_OBJECT@          & \ref{sect:SPARK}              \\
1215 @BLOCKED_FETCH@         & \ref{sect:BLOCKED_FETCH}      \\
1216 \hline
1217 \end{tabular}
1218
1219 \ToDo{I guess the parallel system has something like a stable ptr
1220 table.  Is there any opportunity for sharing code/data structures
1221 here?}
1222
1223
1224 \subsection{Predicates}
1225
1226 \ToDo{The following is a first attempt at defining a useful set of
1227 predicates.  Some (such as @isWHNF@ and @isSparkable@) may need their
1228 definitions tweaked a little.}
1229
1230 The runtime system sometimes needs to be able to distinguish objects
1231 according to their properties: is the object updateable? is it in weak
1232 head normal form? etc.  These questions can be answered by examining
1233 the @INFO_TYPE@ field of the object's info table.  
1234
1235 We define the following predicates to detect families of related
1236 info types.  They are mutually exclusive and exhaustive.
1237
1238 \begin{itemize}
1239 \item @isCONSTR@ is true for @CONSTR@s.
1240 \item @isFUN@ is true for @FUN@s.
1241 \item @isTHUNK@ is true for @THUNK@s.
1242 \item @isBCO@ is true for @BCO@s.
1243 \item @isAP@ is true for @AP@s.
1244 \item @isPAP@ is true for @PAP@s.
1245 \item @isINDIRECTION@ is true for indirection objects. 
1246 \item @isBH@ is true for black holes.
1247 \item @isFOREIGN_OBJECT@ is true for foreign objects.
1248 \item @isARRAY@ is true for array objects.
1249 \item @isMVAR@ is true for @MVAR@s.
1250 \item @isIVAR@ is true for @IVAR@s.
1251 \item @isFETCHME@ is true for @FETCHME@s.
1252 \item @isSLOP@ is true for slop objects.
1253 \item @isRET_ADDR@ is true for return addresses.
1254 \item @isUPD_ADDR@ is true for update frames.
1255 \item @isTSO@ is true for @TSO@s.
1256 \item @isSTABLE_PTR_TABLE@ is true for the stable pointer table.
1257 \item @isSPARK_OBJECT@ is true for spark objects.
1258 \item @isBLOCKED_FETCH@ is true for blocked fetch objects.
1259 \item @isINVALID_INFOTYPE@ is true for all other info types.
1260
1261 \end{itemize}
1262
1263 The following predicates detect other interesting properties:
1264
1265 \begin{itemize}
1266
1267 \item @isPOINTED@ is true if an object has a pointed type.
1268
1269 If an object is pointed, the following predicates may be true
1270 (otherwise they are false).  @isWHNF@ and @isUPDATEABLE@ are
1271 mutually exclusive.
1272
1273 \begin{itemize} 
1274 \item @isWHNF@ is true if the object is in Weak Head Normal Form.  
1275 Note that unpointed objects are (arbitrarily) not considered to be in WHNF.
1276
1277 @isWHNF@ is true for @PAP@s, @CONSTR@s, @FUN@s and some @BCO@s.
1278
1279 \ToDo{Need to distinguish between whnf BCOs and non-whnf BCOs in their
1280 @INFO_TYPE@}
1281
1282 \item @isBOTTOM@ is true if the object is known to be $\bot$.  It is
1283 true of @BH@s.  \note{I suspect we'll want to add other kinds of
1284 infotype which are known to be bottom later.}
1285
1286 \item @isUPDATEABLE@ is true if the object may be overwritten with an
1287  indirection object.
1288
1289 @isUPDATEABLE@ is true for @THUNK@s, @AP@s and @BH@s.
1290
1291 \end{itemize}
1292
1293 It is possible for a pointed object to be neither updatable nor in
1294 WHNF.  For example, indirections.
1295
1296 \item @isUNPOINTED@ is true if an object has an unpointed type.
1297 All such objects are boxed since only boxed objects have info pointers.
1298
1299 It is true for @ARR_WORDS@, @ARR_PTRS@, @MUTVAR@, @MUTARR_PTRS@,
1300 @MUTARR_PTRS_FROZEN@, @FOREIGN@ objects, @MVAR@s and @IVAR@s.
1301
1302 \item @isACTIVATION_FRAME@ is true for activation frames of all sorts.
1303
1304 It is true for return addresses and update frames.
1305 \begin{itemize}
1306 \item @isVECTORED_RETADDR@ is true for vectored return addresses.
1307 \item @isDIRECT_RETADDR@ is true for direct return addresses.
1308 \end{itemize}
1309
1310 \item @isADMINISTRATIVE@ is true for administrative objects:
1311 @TSO@s, the stable pointer table, spark objects and blocked fetches.
1312
1313 \end{itemize}
1314
1315 \begin{itemize}
1316
1317 \item @isSTATIC@ is true for any statically allocated closure.
1318
1319 \item @isMUTABLE@ is true for objects with mutable pointer fields:
1320   @MUT_ARR@s, @MUTVAR@s, @MVAR@s and @IVAR@s.
1321
1322 \item @isSparkable@ is true if the object can (and should) be sparked.
1323 It is true of updateable objects which are not in WHNF with the
1324 exception of @THUNK_SELECTOR@s and black holes.
1325
1326 \end{itemize}
1327
1328 As a minor optimisation, we might use the top bits of the @INFO_TYPE@
1329 field to ``cache'' the answers to some of these predicates.
1330
1331 An indirection either points to HNF (post update); or is result of
1332 overwriting a FetchMe, in which case the thing fetched is either
1333 under evaluation (BH), or by now an HNF.  Thus, indirections get NoSpark flag.
1334
1335
1336 \iffalse
1337 @
1338 #define _NF                     0x0001  /* Normal form  */
1339 #define _NS                     0x0002  /* Don't spark  */
1340 #define _ST                     0x0004  /* Is static    */
1341 #define _MU                     0x0008  /* Is mutable   */
1342 #define _UP                     0x0010  /* Is updatable (but not mutable) */
1343 #define _BM                     0x0020  /* Is a "primitive" array */
1344 #define _BH                     0x0040  /* Is a black hole */
1345 #define _IN                     0x0080  /* Is an indirection */
1346 #define _TH                     0x0100  /* Is a thunk */
1347
1348
1349
1350 SPEC    
1351 SPEC_N          SPEC | _NF | _NS
1352 SPEC_S          SPEC | _TH
1353 SPEC_U          SPEC | _UP | _TH
1354                 
1355 GEN     
1356 GEN_N           GEN | _NF | _NS
1357 GEN_S           GEN | _TH
1358 GEN_U           GEN | _UP | _TH
1359                 
1360 DYN             _NF | _NS
1361 TUPLE           _NF | _NS | _BM
1362 DATA            _NF | _NS | _BM
1363 MUTUPLE         _NF | _NS | _MU | _BM
1364 IMMUTUPLE       _NF | _NS | _BM
1365 STATIC          _NS | _ST
1366 CONST           _NF | _NS
1367 CHARLIKE        _NF | _NS
1368 INTLIKE         _NF | _NS
1369
1370 BH              _NS | _BH
1371 BH_N            BH
1372 BH_U            BH | _UP
1373                 
1374 BQ              _NS | _MU | _BH
1375 IND             _NS | _IN
1376 CAF             _NF | _NS | _ST | _IN
1377
1378 FM              
1379 FETCHME         FM | _MU
1380 FMBQ            FM | _MU | _BH
1381
1382 TSO             _MU
1383
1384 STKO    
1385 STKO_DYNAMIC    STKO | _MU
1386 STKO_STATIC     STKO | _ST
1387                 
1388 SPEC_RBH        _NS | _MU | _BH
1389 GEN_RBH         _NS | _MU | _BH
1390 BF              _NS | _MU | _BH
1391 INTERNAL        
1392
1393 @
1394 \fi
1395
1396
1397 \subsection{Pointed Objects}
1398
1399 All pointed objects can be entered.
1400
1401 \subsubsection{Function closures}\label{sect:FUN}
1402
1403 Function closures represent lambda abstractions.  For example,
1404 consider the top-level declaration:
1405 @
1406   f = \x -> let g = \y -> x+y
1407             in g x
1408 @
1409 Both @f@ and @g@ are represented by function closures.  The closure
1410 for @f@ is {\em static} while that for @g@ is {\em dynamic}.
1411
1412 The layout of a function closure is as follows:
1413 \begin{center}
1414 \begin{tabular}{|l|l|l|l|}\hline
1415 {\em Fixed header}  & {\em Pointers} & {\em Non-pointers} \\ \hline
1416 \end{tabular}
1417 \end{center}
1418 The data words (pointers and non-pointers) are the free variables of
1419 the function closure.  
1420 The number of pointers
1421 and number of non-pointers are stored in the @INFO_SM@ word, in the least significant
1422 and most significant half-word respectively.
1423
1424 There are several different sorts of function closure, distinguished
1425 by their @INFO_TYPE@ field:
1426 \begin{itemize}
1427 \item @FUN@: a vanilla, dynamically allocated on the heap. 
1428
1429 \item $@FUN_@p@_@np$: to speed up garbage collection a number of
1430 specialised forms of @FUN@ are provided, for particular $(p,np)$ pairs,
1431 where $p$ is the number of pointers and $np$ the number of non-pointers.
1432
1433 \item @FUN_STATIC@.  Top-level, static, function closures (such as
1434 @f@ above) have a different
1435 layout than dynamic ones:
1436 \begin{center}
1437 \begin{tabular}{|l|l|l|}\hline
1438 {\em Fixed header}  & {\em Static object link} \\ \hline
1439 \end{tabular}
1440 \end{center}
1441 Static function closures have no free variables.  (However they may refer to other 
1442 static closures; these references are recorded in the function closure's SRT.)
1443 They have one field that is not present in dynamic closures, the {\em static object
1444 link} field.  This is used by the garbage collector in the same way that to-space
1445 is, to gather closures that have been determined to be live but that have not yet
1446 been scavenged.
1447 \note{Static function closures that have no static references, and hence
1448 a null SRT pointer, don't need the static object link field.  Is it worth
1449 taking advantage of this?  See @CONSTR_STATIC_NOCAF@.}
1450 \end{itemize}
1451
1452 Each lambda abstraction, $f$, in the STG program has its own private info table.
1453 The following labels are relevant:
1454 \begin{itemize}
1455 \item $f$@_info@  is $f$'s info table.
1456 \item $f$@_entry@ is $f$'s slow entry point (i.e. the entry code of its
1457 info table; so it will label the same byte as $f$@_info@).
1458 \item $f@_fast_@k$ is $f$'s fast entry point.  $k$ is the number of arguments
1459 $f$ takes; encoding this number in the fast-entry label occasionally catches some nasty
1460 code-generation errors.
1461 \end{itemize}
1462
1463 \subsubsection{Data Constructors}\label{sect:CONSTR}
1464
1465 Data-constructor closures represent values constructed with
1466 algebraic data type constructors.
1467 The general layout of data constructors is the same as that for function
1468 closures.  That is
1469 \begin{center}
1470 \begin{tabular}{|l|l|l|l|}\hline
1471 {\em Fixed header}  & {\em Pointers} & {\em Non-pointers} \\ \hline
1472 \end{tabular}
1473 \end{center}
1474
1475 The SRT pointer in a data constructor's info table is used for the
1476 constructor tag, since a constructor never has any static references.
1477
1478 There are several different sorts of constructor:
1479 \begin{itemize}
1480 \item @CONSTR@: a vanilla, dynamically allocated constructor.
1481 \item @CONSTR_@$p$@_@$np$: just like $@FUN_@p@_@np$.
1482 \item @CONSTR_INTLIKE@.
1483 A dynamically-allocated heap object that looks just like an @Int@.  The 
1484 garbage collector checks to see if it can common it up with one of a fixed
1485 set of static int-like closures, thus getting it out of the dynamic heap
1486 altogether.
1487
1488 \item @CONSTR_CHARLIKE@:  same deal, but for @Char@.
1489
1490 \item @CONSTR_STATIC@ is similar to @FUN_STATIC@, with the complication that
1491 the layout of the constructor must mimic that of a dynamic constructor,
1492 because a static constructor might be returned to some code that unpacks it.
1493 So its layout is like this:
1494 \begin{center}
1495 \begin{tabular}{|l|l|l|l|l|}\hline
1496 {\em Fixed header}  & {\em Pointers} & {\em Non-pointers} & {\em Static object link}\\ \hline
1497 \end{tabular}
1498 \end{center}
1499 The static object link, at the end of the closure, serves the same purpose
1500 as that for @FUN_STATIC@.  The pointers in the static constructor can point
1501 only to other static closures.
1502
1503 The static object link occurs last in the closure so that static
1504 constructors can store their data fields in exactly the same place as
1505 dynamic constructors.
1506
1507 \item @CONSTR_STATIC_NOCAF@.  A statically allocated data constructor
1508 that guarantees not to point (directly or indirectly) to any CAF
1509 (section~\ref{sect:CAF}).  This means it does not need a static object
1510 link field.  Since we expect that there might be quite a lot of static
1511 constructors this optimisation makes sense.  Furthermore, the @NOCAF@
1512 tag allows the compiler to indicate that no CAFs can be reached
1513 anywhere {\em even indirectly}.
1514
1515
1516 \end{itemize}
1517
1518 For each data constructor $Con$, two
1519 info tables are generated:
1520 \begin{itemize}
1521 \item $Con$@_info@ labels $Con$'s dynamic info table, 
1522 shared by all dynamic instances of the constructor.
1523 \item $Con$@_static@ labels $Con$'s static info table, 
1524 shared by all static instances of the constructor.
1525 \end{itemize}
1526
1527 \subsubsection{Thunks}
1528 \label{sect:THUNK}
1529 \label{sect:THUNK_SEL}
1530
1531 A thunk represents an expression that is not obviously in head normal 
1532 form.  For example, consider the following top-level definitions:
1533 @
1534   range = between 1 10
1535   f = \x -> let ys = take x range
1536             in sum ys
1537 @
1538 Here the right-hand sides of @range@ and @ys@ are both thunks; the former
1539 is static while the latter is dynamic.
1540
1541 The layout of a thunk is the same as that for a function closure,
1542 except that it may have some words of ``slop'' at the end to make sure
1543 that it has 
1544 at least @MIN_UPD_PAYLOAD@ words in addition to its
1545 fixed header.
1546 \begin{center}
1547 \begin{tabular}{|l|l|l|l|l|}\hline
1548 {\em Fixed header}  & {\em Pointers} & {\em Non-pointers} & {\em Slop} \\ \hline
1549 \end{tabular}
1550 \end{center}
1551 The @INFO_SM@ word contains the same information as for function
1552 closures; that is, number of pointers and number of non-pointers (excluding slop).
1553
1554 A thunk differs from a function closure in that it can be updated.
1555
1556 There are several forms of thunk:
1557 \begin{itemize}
1558 \item @THUNK@: a vanilla, dynamically allocated thunk.
1559 The garbage collection code for thunks whose
1560 pointer + non-pointer words is less than @MIN_UPD_PAYLOAD@ differs from
1561 that for function closures and data constructors, because the GC code
1562 has to account for the slop.
1563 \item $@THUNK_@p@_@np$.  Similar comments apply.
1564 \item @THUNK_STATIC@.  A static thunk is also known as 
1565 a {\em constant applicative form}, or {\em CAF}.
1566
1567 \begin{center}
1568 \begin{tabular}{|l|l|l|l|l|}\hline
1569 {\em Fixed header}  & {\em Pointers} & {\em Non-pointers} & {\em Slop} & {\em Static object link}\\ \hline
1570 \end{tabular}
1571 \end{center}
1572
1573 \item @THUNK_SELECTOR@ is a (dynamically allocated) thunk
1574 whose entry code performs a simple selection operation from
1575 a data constructor drawn from a single-constructor type.  For example,
1576 the thunk
1577 @
1578         x = case y of (a,b) -> a
1579 @
1580 is a selector thunk.  A selector thunk is laid out like this:
1581 \begin{center}
1582 \begin{tabular}{|l|l|l|l|}\hline
1583 {\em Fixed header}  & {\em Selectee pointer} \\ \hline
1584 \end{tabular}
1585 \end{center}
1586 The @INFO_SM@ word contains the byte offset of the desired word in
1587 the selectee.  Note that this is different from all other thunks.
1588
1589 The garbage collector ``peeks'' at the selectee's
1590 tag (in its info table).  If it is evaluated, then it goes ahead and do
1591 the selection, and then behaves just as if the selector thunk was an
1592 indirection to the selected field.
1593 If it is not
1594 evaluated, it treats the selector thunk like any other thunk of that
1595 shape.  [Implementation notes.  
1596 Copying: only the evacuate routine needs to be special.
1597 Compacting: only the PRStart (marking) routine needs to be special.]
1598 \end{itemize}
1599
1600
1601 The only label associated with a thunk is its info table:
1602 \begin{description}
1603 \item[$f$@_info@] is $f$'s info table.
1604 \end{description}
1605
1606
1607 \subsubsection{Byte-Code Objects}
1608 \label{sect:BCO}
1609
1610 A Byte-Code Object (BCO) is a container for a a chunk of byte-code,
1611 which can be executed by Hugs.  The byte-code represents a
1612 supercombinator in the program: when hugs compiles a module, it
1613 performs lambda lifting and each resulting supercombinator becomes a
1614 byte-code object in the heap.
1615
1616 There are two kinds of BCO: a standard @BCO@ which has an arity of one
1617 or more, and a @BCO_CAF@ which takes no arguments and can be updated.
1618 When a @BCO_CAF@ is updated, the code is thrown away!
1619
1620 The semantics of BCOs are described in Section
1621 \ref{sect:hugs-heap-objects}.  A BCO has the following structure:
1622
1623 \begin{center}
1624 \begin{tabular}{|l|l|l|l|l|l|}
1625 \hline 
1626 \emph{Fixed Header} & \emph{Layout} & \emph{Offset} & \emph{Size} &
1627 \emph{Literals} & \emph{Byte code} \\
1628 \hline
1629 \end{tabular}
1630 \end{center}
1631
1632 \noindent where:
1633 \begin{itemize}
1634 \item The entry code is a static code fragment/info table that
1635 returns to the scheduler to invoke Hugs (Section
1636 \ref{sect:ghc-to-hugs-switch}).
1637 \item \emph{Layout} contains the number of pointer literals in the
1638 \emph{Literals} field.
1639 \item \emph{Offset} is the offset to the byte code from the start of
1640 the object.
1641 \item \emph{Size} is the number of words of byte code in the object.
1642 \item \emph{Literals} contains any pointer and non-pointer literals used in
1643 the byte-codes (including jump addresses), pointers first.
1644 \item \emph{Byte code} contains \emph{Size} words of non-pointer byte
1645 code.
1646 \end{itemize}
1647
1648 \subsubsection{Partial applications (PAPs)}\label{sect:PAP}
1649
1650 A partial application (PAP) represents a function applied to too few arguments.
1651 It is only built as a result of updating after an argument-satisfaction
1652 check failure.  A PAP has the following shape:
1653 \begin{center}
1654 \begin{tabular}{|l|l|l|l|}\hline
1655 {\em Fixed header}  & {\em No of arg words} & {\em Function closure} & {\em Arg stack} \\ \hline
1656 \end{tabular}
1657 \end{center}
1658 The ``arg stack'' is a copy of the chunk of stack above the update
1659 frame; ``no of arg words'' tells how many words it consists of.  The
1660 function closure is (a pointer to) the closure for the function whose
1661 argument-satisfaction check failed.
1662
1663 There is just one standard form of PAP with @INFO_TYPE@ = @PAP@.
1664 There is just one info table too, called @PAP_info@.
1665 Its entry code simply copies the arg stack chunk back on top of the
1666 stack and enters the function closure.  (It has to do a stack overflow test first.)
1667
1668 PAPs are also used to implement Hugs functions (where the arguments are free variables).
1669 PAPs generated by Hugs can be static.
1670
1671 \subsubsection{@AP@ objects}
1672 \label{sect:AP}
1673
1674 @AP@ objects are used to represent thunks built by Hugs.  The only distintion between
1675 an @AP@ and a @PAP@ is that an @AP@ is updateable.
1676
1677 \begin{center}
1678 \begin{tabular}{|l|l|l|l|}
1679 \hline
1680 \emph{Fixed Header} & {\em No of arg words} & {\em Function closure} & {\em Arg stack} \\
1681 \hline
1682 \end{tabular}
1683 \end{center}
1684
1685 The entry code pushes an update frame, copies the arg stack chunk on
1686 top of the stack, and enters the function closure.  (It has to do a
1687 stack overflow test first.)
1688
1689 The ``arg stack'' is a block of (tagged) arguments representing the
1690 free variables of the thunk; ``no of arg words'' tells how many words
1691 it consists of.  The function closure is (a pointer to) the closure
1692 for the thunk.  The argument stack may be empty if the thunk has no
1693 free variables.
1694
1695
1696 \subsubsection{Indirections}
1697 \label{sect:IND}
1698 \label{sect:IND_OLDGEN}
1699
1700 Indirection closures just point to other closures. They are introduced
1701 when a thunk is updated to point to its value. 
1702 The entry code for all indirections simply enters the closure it points to.
1703
1704 There are several forms of indirection:
1705 \begin{description}
1706 \item[@IND@] is the vanilla, dynamically-allocated indirection.
1707 It is removed by the garbage collector. It has the following
1708 shape:
1709 \begin{center}
1710 \begin{tabular}{|l|l|l|}\hline
1711 {\em Fixed header} & {\em Target closure} \\ \hline
1712 \end{tabular}
1713 \end{center}
1714
1715 \item[@IND_OLDGEN@] is the indirection used to update an old-generation
1716 thunk. Its shape is like this:
1717 \begin{center}
1718 \begin{tabular}{|l|l|l|}\hline
1719 {\em Fixed header} & {\em Mutable link field} & {\em Target closure} \\ \hline
1720 \end{tabular}
1721 \end{center}
1722 It contains a {\em mutable link field} that is used to string together
1723 all old-generation indirections that might have a pointer into
1724 the new generation.
1725
1726
1727 \item[@IND_PERMANENT@ and @IND_OLDGEN_PERMANENT@.]
1728 for lexical profiling, it is necessary to maintain cost centre
1729 information in an indirection, so ``permanent indirections'' are
1730 retained forever.  Otherwise they are just like vanilla indirections.
1731 \note{If a permanent indirection points to another permanent
1732 indirection or a @CONST@ closure, it is possible to elide the indirection
1733 since it will have no effect on the profiler.}
1734 \note{Do we still need @IND@ and @IND_OLDGEN@
1735 in the profiling build, or can we just make
1736 do with one pair whose behaviour changes when profiling is built?}
1737
1738 \item[@IND_STATIC@] is used for overwriting CAFs when they have been
1739 evaluated.  Static indirections are not removed by the garbage
1740 collector; and are statically allocated outside the heap (and should
1741 stay there).  Their static object link field is used just as for
1742 @FUN_STATIC@ closures.
1743
1744 \begin{center}
1745 \begin{tabular}{|l|l|l|}
1746 \hline
1747 {\em Fixed header} & {\em Target closure} & {\em Static object link} \\
1748 \hline
1749 \end{tabular}
1750 \end{center}
1751
1752 \end{description}
1753
1754 \subsubsection{Activation Records}
1755
1756 Activation records are parts of the stack described by return address
1757 info tables (closures with @INFO_TYPE@ values of @RET_SMALL@,
1758 @RET_VEC_SMALL@, @RET_BIG@ and @RET_VEC_BIG@). They are described in
1759 section~\ref{sect:activation-records}.
1760
1761
1762 \subsubsection{Black holes, MVars and IVars}
1763 \label{sect:BH}
1764 \label{sect:MVAR}
1765 \label{sect:IVAR}
1766
1767 Black hole closures are used to overwrite closures currently being
1768 evaluated. They inform the garbage collector that there are no live
1769 roots in the closure, thus removing a potential space leak.  
1770
1771 Black holes also become synchronization points in the threaded world.
1772 They contain a pointer to a list of blocked threads to be awakened
1773 when the black hole is updated (or @NULL@ if the list is empty).
1774 \begin{center}
1775 \begin{tabular}{|l|l|l|}
1776 \hline 
1777 {\em Fixed header} & {\em Mutable link} & {\em Blocked thread link} \\
1778 \hline
1779 \end{tabular}
1780 \end{center}
1781 The {\em Blocked thread link} points to the TSO of the first thread
1782 waiting for the value of this thunk.  All subsequent TSOs in the list
1783 are linked together using their @TSO_LINK@ field.
1784
1785 When the blocking queue is non-@NULL@, the black hole must be added to
1786 the mutables list since the TSOs on the list may contain pointers into
1787 the new generation.  There is no need to clutter up the mutables list
1788 with black holes with empty blocking queues.
1789
1790 \ToDo{MVars}
1791
1792
1793 \subsubsection{FetchMes}\label{sect:FETCHME}
1794
1795 In the parallel systems, FetchMes are used to represent pointers into
1796 the global heap.  When evaluated, the value they point to is read from
1797 the global heap.
1798
1799 \ToDo{Describe layout}
1800
1801 Because there may be offsets into these arrays, a primitive array
1802 cannot be handled as a FetchMe in the parallel system, but must be
1803 shipped in its entirety if its parent closure is shipped.
1804
1805
1806
1807 \subsection{Unpointed Objects}
1808
1809 A variable of unpointed type is always bound to a {\em value}, never to a {\em thunk}.
1810 For this reason, unpointed objects cannot be entered.
1811
1812 A {\em value} may be:
1813 \begin{itemize}
1814 \item {\em Boxed}, i.e.~represented indirectly by a pointer to a heap object (e.g.~foreign objects, arrays); or
1815 \item {\em Unboxed}, i.e.~represented directly by a bit-pattern in one or more registers (e.g.~@Int#@ and @Float#@).
1816 \end{itemize}
1817 All {\em pointed} values are {\em boxed}.  
1818
1819 \subsubsection{Immutable Objects}
1820 \label{sect:ARR_WORDS1}
1821 \label{sect:ARR_PTRS}
1822
1823 \begin{description}
1824 \item[@ARR_WORDS@] is a variable-sized object consisting solely of
1825 non-pointers.  It is used for arrays of all
1826 sorts of things (bytes, words, floats, doubles... it doesn't matter).
1827 \begin{center}
1828 \begin{tabular}{|c|c|c|c|}
1829 \hline
1830 {\em Fixed Hdr} & {\em No of non-pointers} & {\em Non-pointers\ldots}   \\ \hline
1831 \end{tabular}
1832 \end{center}
1833
1834 \item[@ARR_PTRS@] is an immutable, variable sized array of pointers.
1835 \begin{center}
1836 \begin{tabular}{|c|c|c|c|}
1837 \hline
1838 {\em Fixed Hdr} & {\em Mutable link} & {\em No of pointers} & {\em Pointers\ldots}      \\ \hline
1839 \end{tabular}
1840 \end{center}
1841 The mutable link is present so that we can easily freeze and thaw an
1842 array (by changing the header and adding/removing the array to the
1843 mutables list).
1844
1845 \end{description}
1846
1847 \subsubsection{Mutable Objects}
1848 \label{sect:mutables}
1849 \label{sect:ARR_WORDS2}
1850 \label{sect:MUTVAR}
1851 \label{sect:MUTARR_PTRS}
1852 \label{sect:MUTARR_PTRS_FROZEN}
1853
1854 Some of these objects are {\em mutable}; they represent objects which
1855 are explicitly mutated by Haskell code through the @ST@ monad.
1856 They're not used for thunks which are updated precisely once.
1857 Depending on the garbage collector, mutable closures may contain extra
1858 header information which allows a generational collector to implement
1859 the ``write barrier.''
1860
1861 \begin{description}
1862
1863 \item[@ARR_WORDS@] is also used to represent {\em mutable} arrays of
1864 bytes, words, floats, doubles, etc.  It's possible to use the same
1865 object type because even generational collectors don't need to
1866 distinguish them.
1867
1868 \item[@MUTVAR@] is a mutable variable.
1869 \begin{center}
1870 \begin{tabular}{|c|c|c|}
1871 \hline
1872 {\em Fixed Hdr} & {\em Mutable link} & {\em Pointer} \\ \hline
1873 \end{tabular}
1874 \end{center}
1875
1876 \item[@MUTARR_PTRS@] is a mutable array of pointers.
1877 Such an array may be {\em frozen}, becoming an @SM_MUTARR_PTRS_FROZEN@, with a
1878 different info-table.
1879 \begin{center}
1880 \begin{tabular}{|c|c|c|c|}
1881 \hline
1882 {\em Fixed Hdr} & {\em Mutable link} & {\em No of ptrs} & {\em Pointers\ldots} \\ \hline
1883 \end{tabular}
1884 \end{center}
1885
1886 \item[@MUTARR_PTRS_FROZEN@] is a frozen @MUTARR_PTRS@ closure.
1887 The garbage collector converts @MUTARR_PTRS_FROZEN@ to @ARR_PTRS@ as it removes them from
1888 the mutables list.
1889
1890 \end{description}
1891
1892
1893 \subsubsection{Foreign Objects}\label{sect:FOREIGN}
1894
1895 Here's what a ForeignObj looks like:
1896
1897 \begin{center}
1898 \begin{tabular}{|l|l|l|l|}
1899 \hline 
1900 {\em Fixed header} & {\em Data} & {\em Free Routine} & {\em Foreign object link} \\
1901 \hline
1902 \end{tabular}
1903 \end{center}
1904
1905 The @FreeRoutine@ is a reference to the finalisation routine to call
1906 when the @ForeignObj@ becomes garbage.  If @freeForeignObject@ is
1907 called on a Foreign Object, the @FreeRoutine@ is set to zero and the
1908 garbage collector will not attempt to call @FreeRoutine@ when the 
1909 object becomes garbage.
1910
1911 The Foreign object link is a link to the next foreign object in the
1912 list.  This list is traversed at the end of garbage collection: if an
1913 object is about to be deallocated (e.g.~it was not marked or
1914 evacuated), the free routine is called and the object is deleted from
1915 the list.  
1916
1917
1918 The remaining objects types are all administrative --- none of them may be entered.
1919
1920 \subsection{Other weird objects}
1921 \label{sect:SPARK}
1922 \label{sect:BLOCKED_FETCH}
1923
1924 \begin{description}
1925 \item[@BlockedFetch@ heap objects (`closures')] (parallel only)
1926
1927 @BlockedFetch@s are inbound fetch messages blocked on local closures.
1928 They arise as entries in a local blocking queue when a fetch has been
1929 received for a local black hole.  When awakened, we look at their
1930 contents to figure out where to send a resume.
1931
1932 A @BlockedFetch@ closure has the form:
1933 \begin{center}
1934 \begin{tabular}{|l|l|l|l|l|l|}\hline
1935 {\em Fixed header} & link & node & gtid & slot & weight \\ \hline
1936 \end{tabular}
1937 \end{center}
1938
1939 \item[Spark Closures] (parallel only)
1940
1941 Spark closures are used to link together all closures in the spark pool.  When
1942 the current processor is idle, it may choose to speculatively evaluate some of
1943 the closures in the pool.  It may also choose to delete sparks from the pool.
1944 \begin{center}
1945 \begin{tabular}{|l|l|l|l|l|l|}\hline
1946 {\em Fixed header} & {\em Spark pool link} & {\em Sparked closure} \\ \hline
1947 \end{tabular}
1948 \end{center}
1949
1950 \item[Slop Objects]\label{sect:slop-objects}
1951
1952 Slop objects are used to overwrite the end of an updatee if it is
1953 larger than an indirection.  Normal slop objects consist of an info
1954 pointer a size word and a number of slop words.  
1955
1956 \begin{center}
1957 \begin{tabular}{|l|l|l|l|l|l|}\hline
1958 {\em Info Pointer} & {\em Size} & {\em Slop Words} \\ \hline
1959 \end{tabular}
1960 \end{center}
1961
1962 This is too large for single word slop objects which consist of a
1963 single info table.
1964
1965 Note that slop objects only contain an info pointer, not a standard
1966 fixed header.  This doesn't cause problems because slop objects are
1967 always unreachable --- they can only be accessed by linearly scanning
1968 the heap.
1969
1970 \end{description}
1971
1972 \subsection{Thread State Objects (TSOs)}\label{sect:TSO}
1973
1974 \ToDo{This is very out of date.  We now embed a single stack object
1975 within the TSO.  TSOs include an ID number which can be used to
1976 generate a hash value.  The gransim, profiling and ticky info is
1977 surely bogus.}
1978
1979 In the multi-threaded system, the state of a suspended thread is
1980 packed up into a Thread State Object (TSO) which contains all the
1981 information needed to restart the thread and for the garbage collector
1982 to find all reachable objects.  When a thread is running, it may be
1983 ``unpacked'' into machine registers and various other memory locations
1984 to provide faster access.
1985
1986 Single-threaded systems don't really {\em need\/} TSOs --- but they do
1987 need some way to tell the storage manager about live roots so it is
1988 convenient to use a single TSO to store the mutator state even in
1989 single-threaded systems.
1990
1991 Rather than manage TSOs' alloc/dealloc, etc., in some {\em ad hoc}
1992 way, we instead alloc/dealloc/etc them in the heap; then we can use
1993 all the standard garbage-collection/fetching/flushing/etc machinery on
1994 them.  So that's why TSOs are ``heap objects,'' albeit very special
1995 ones.
1996 \begin{center}
1997 \begin{tabular}{|l|l|}
1998    \hline {\em Fixed header}
1999 \\ \hline @TSO_LINK@
2000 \\ \hline @TSO_WHATNEXT@
2001 \\ \hline @TSO_WHATNEXT_INFO@ 
2002 \\ \hline @TSO_STACK@ 
2003 \\ \hline {\em Exception Handlers}
2004 \\ \hline {\em Ticky Info}
2005 \\ \hline {\em Profiling Info}
2006 \\ \hline {\em Parallel Info}
2007 \\ \hline {\em GranSim Info}
2008 \\ \hline
2009 \end{tabular}
2010 \end{center}
2011 The contents of a TSO are:
2012 \begin{itemize}
2013
2014 \item A pointer (@TSO_LINK@) used to maintain a list of threads with a similar
2015   state (e.g.~all runnable, all sleeping, all blocked on the same black
2016   hole, all blocked on the same MVar, etc.)
2017
2018 \item A word (@TSO_WHATNEXT@) which is in suspended threads to record
2019  how to awaken it.  This typically requires a program counter which is stored
2020  in the pointer @TSO_WHATNEXT_INFO@
2021
2022 \item A pointer (@TSO_STACK@) to the top stack block.
2023
2024 \item Optional information for ``Ticky Ticky'' statistics: @TSO_STK_HWM@ is
2025   the maximum number of words allocated to this thread.
2026
2027 \item Optional information for profiling: 
2028   @TSO_CCC@ is the current cost centre.
2029
2030 \item Optional information for parallel execution:
2031 \begin{itemize}
2032
2033 \item The types of threads (@TSO_TYPE@):
2034 \begin{description}
2035 \item[@T_MAIN@]     Must be executed locally.
2036 \item[@T_REQUIRED@] A required thread  -- may be exported.
2037 \item[@T_ADVISORY@] An advisory thread -- may be exported.
2038 \item[@T_FAIL@]     A failure thread   -- may be exported.
2039 \end{description}
2040
2041 \item I've no idea what else
2042
2043 \end{itemize}
2044
2045 \item Optional information for GranSim execution:
2046 \begin{itemize}
2047 \item locked         
2048 \item sparkname  
2049 \item started at         
2050 \item exported   
2051 \item basic blocks       
2052 \item allocs     
2053 \item exectime   
2054 \item fetchtime  
2055 \item fetchcount         
2056 \item blocktime  
2057 \item blockcount         
2058 \item global sparks      
2059 \item local sparks       
2060 \item queue              
2061 \item priority   
2062 \item clock          (gransim light only)
2063 \end{itemize}
2064
2065
2066 Here are the various queues for GrAnSim-type events.
2067 @
2068 Q_RUNNING   
2069 Q_RUNNABLE  
2070 Q_BLOCKED   
2071 Q_FETCHING  
2072 Q_MIGRATING 
2073 @
2074
2075 \end{itemize}
2076
2077 \subsection{Stack Objects}
2078 \label{sect:STACK_OBJECT}
2079 \label{sect:stacks}
2080
2081 These are ``stack objects,'' which are used in the threaded world as
2082 the stack for each thread is allocated from the heap in smallish
2083 chunks.  (The stack in the sequential world is allocated outside of
2084 the heap.)
2085
2086 Each reduction thread has to have its own stack space.  As there may
2087 be many such threads, and as any given one may need quite a big stack,
2088 a naive give-'em-a-big-stack-and-let-'em-run approach will cost a {\em
2089 lot} of memory.
2090
2091 Our approach is to give a thread a small stack space, and then link
2092 on/off extra ``chunks'' as the need arises.  Again, this is a
2093 storage-management problem, and, yet again, we choose to graft the
2094 whole business onto the existing heap-management machinery.  So stack
2095 objects will live in the heap, be garbage collected, etc., etc..
2096
2097 A stack object is laid out like this:
2098
2099 \begin{center}
2100 \begin{tabular}{|l|}
2101 \hline
2102 {\em Fixed header} 
2103 \\ \hline
2104 {\em Link to next stack object (0 for last)}
2105 \\ \hline
2106 {\em N, the payload size in words}
2107 \\ \hline
2108 {\em @Sp@ (byte offset from head of object)}
2109 \\ \hline
2110 {\em @Su@ (byte offset from head of object)}
2111 \\ \hline
2112 {\em Payload (N words)}
2113 \\ \hline
2114 \end{tabular}
2115 \end{center}
2116
2117 \ToDo{Are stack objects on the mutable list?}
2118
2119 The stack grows downwards, towards decreasing
2120 addresses.  This makes it easier to print out the stack
2121 when debugging, and it means that a return address is
2122 at the lowest address of the chunk of stack it ``knows about''
2123 just like an info pointer on a closure.
2124
2125 The garbage collector needs to be able to find all the
2126 pointers in a stack.  How does it do this?
2127
2128 \begin{itemize}
2129
2130 \item Within the stack there are return addresses, pushed
2131 by @case@ expressions.  Below a return address (i.e. at higher
2132 memory addresses, since the stack grows downwards) is a chunk
2133 of stack that the return address ``knows about'', namely the
2134 activation record of the currently running function.
2135
2136 \item Below each such activation record is a {\em pending-argument
2137 section}, a chunk of
2138 zero or more words that are the arguments to which the result
2139 of the function should be applied.  The return address does not
2140 statically
2141 ``know'' how many pending arguments there are, or their types.
2142 (For example, the function might return a result of type $\alpha$.)
2143
2144 \item Below each pending-argument section is another return address,
2145 and so on.  Actually, there might be an update frame instead, but we
2146 can consider update frames as a special case of a return address with
2147 a well-defined activation record.
2148
2149 \ToDo{Doesn't it {\em have} to be an update frame?  After all, the arg
2150 satisfaction check is @Su - Sp >= ...@.}
2151
2152 \end{itemize}
2153
2154 The game plan is this.  The garbage collector
2155 walks the stack from the top, traversing pending-argument sections and
2156 activation records alternately.  Next we discuss how it finds
2157 the pointers in each of these two stack regions.
2158
2159
2160 \subsubsection{Activation records}\label{sect:activation-records}
2161
2162 An {\em activation record} is a contiguous chunk of stack,
2163 with a return address as its first word, followed by as many
2164 data words as the return address ``knows about''.  The return
2165 address is actually a fully-fledged info pointer.  It points
2166 to an info table, replete with:
2167
2168 \begin{itemize}
2169 \item entry code (i.e. the code to return to).
2170 \item @INFO_TYPE@ is either @RET_SMALL/RET_VEC_SMALL@ or @RET_BIG/RET_VEC_BIG@, depending
2171 on whether the activation record has more than 32 data words (\note{64 for 8-byte-word architectures}) and on whether 
2172 to use a direct or a vectored return.
2173 \item @INFO_SM@ for @RET_SMALL@ is a bitmap telling the layout
2174 of the activation record, one bit per word.  The least-significant bit
2175 describes the first data word of the record (adjacent to the fixed
2176 header) and so on.  A ``@1@'' indicates a non-pointer, a ``@0@''
2177 indicates
2178 a pointer.  We don't need to indicate exactly how many words there
2179 are,
2180 because when we get to all zeros we can treat the rest of the 
2181 activation record as part of the next pending-argument region.
2182
2183 For @RET_BIG@ the @INFO_SM@ field points to a block of bitmap
2184 words, starting with a word that tells how many words are in
2185 the block.
2186
2187 \item @INFO_SRT@ is the Static Reference Table for the return
2188 address (Section~\ref{sect:srt}).
2189 \end{itemize}
2190
2191 The activation record is a fully fledged closure too.
2192 As well as an info pointer, it has all the other attributes of
2193 a fixed header (Section~\ref{sect:fixed-header}) including a saved cost
2194 centre which is reloaded when the return address is entered.
2195
2196 In other words, all the attributes of closures are needed for
2197 activation records, so it's very convenient to make them look alike.
2198
2199
2200 \subsubsection{Pending arguments}
2201
2202 So that the garbage collector can correctly identify pointers
2203 in pending-argument sections we explicitly tag all non-pointers.
2204 Every non-pointer in a pending-argument section is preceded
2205 (at the next lower memory word) by a one-word byte count that
2206 says how many bytes to skip over (excluding the tag word).
2207
2208 The garbage collector traverses a pending argument section from 
2209 the top (i.e. lowest memory address).  It looks at each word in turn:
2210
2211 \begin{itemize}
2212 \item If it is less than or equal to a small constant @MAX_STACK_TAG@
2213 then
2214 it treats it as a tag heralding zero or more words of non-pointers,
2215 so it just skips over them.
2216
2217 \item If it points to the code segment, it must be a return
2218 address, so we have come to the end of the pending-argument section.
2219
2220 \item Otherwise it must be a bona fide heap pointer.
2221 \end{itemize}
2222
2223
2224 \subsection{The Stable Pointer Table}\label{sect:STABLEPTR_TABLE}
2225
2226 A stable pointer is a name for a Haskell object which can be passed to
2227 the external world.  It is ``stable'' in the sense that the name does
2228 not change when the Haskell garbage collector runs---in contrast to
2229 the address of the object which may well change.
2230
2231 A stable pointer is represented by an index into the
2232 @StablePointerTable@.  The Haskell garbage collector treats the
2233 @StablePointerTable@ as a source of roots for GC.
2234
2235 In order to provide efficient access to stable pointers and to be able
2236 to cope with any number of stable pointers (eg $0 \ldots 100000$), the
2237 table of stable pointers is an array stored on the heap and can grow
2238 when it overflows.  (Since we cannot compact the table by moving
2239 stable pointers about, it seems unlikely that a half-empty table can
2240 be reduced in size---this could be fixed if necessary by using a
2241 hash table of some sort.)
2242
2243 In general a stable pointer table closure looks like this:
2244
2245 \begin{center}
2246 \begin{tabular}{|l|l|l|l|l|l|l|l|l|l|l|}
2247 \hline
2248 {\em Fixed header} & {\em No of pointers} & {\em Free} & $SP_0$ & \ldots & $SP_{n-1}$ 
2249 \\\hline
2250 \end{tabular}
2251 \end{center}
2252
2253 The fields are:
2254 \begin{description}
2255
2256 \item[@NPtrs@:] number of (stable) pointers.
2257
2258 \item[@Free@:] the byte offset (from the first byte of the object) of the first free stable pointer.
2259
2260 \item[$SP_i$:] A stable pointer slot.  If this entry is in use, it is
2261 an ``unstable'' pointer to a closure.  If this entry is not in use, it
2262 is a byte offset of the next free stable pointer slot.
2263
2264 \end{description}
2265
2266 When a stable pointer table is evacuated
2267 \begin{enumerate}
2268 \item the free list entries are all set to @NULL@ so that the evacuation
2269   code knows they're not pointers;
2270
2271 \item The stable pointer slots are scanned linearly: non-@NULL@ slots
2272 are evacuated and @NULL@-values are chained together to form a new free list.
2273 \end{enumerate}
2274
2275 There's no need to link the stable pointer table onto the mutable
2276 list because we always treat it as a root.
2277
2278
2279
2280 \section{The Bytecode Evaluator}
2281
2282 This section describes how the Hugs interpreter interprets code in the
2283 same environment as compiled code executes.  Both evaluation models
2284 use a common garbage collector, so they must agree on the form of
2285 objects in the heap.
2286
2287 Hugs interprets code by converting it to byte-code and applying a
2288 byte-code interpreter to it.  Wherever possible, we try to ensure that
2289 the byte-code is all that is required to interpret a section of code.
2290 This means not dynamically generating info tables, and hence we can
2291 only have a small number of possible heap objects each with a statically
2292 compiled info table.  Similarly for stack objects: in fact we only
2293 have one Hugs stack object, in which all information is tagged for the
2294 garbage collector.
2295
2296 There is, however, one exception to this rule.  Hugs must generate
2297 info tables for any constructors it is asked to compile, since the
2298 alternative is to force a context-switch each time compiled code
2299 enters a Hugs-built constructor, which would be prohibitively
2300 expensive.
2301
2302 We achieve this simplicity by forgoing some of the optimisations used
2303 by compiled code:
2304 \begin{itemize}
2305 \item
2306
2307 Whereas compiled code has five different ways of entering a closure
2308 (section~\ref{sect:entering-closures}), interpreted code has only one.
2309 The entry point for interpreted code behaves like slow entry points for
2310 compiled code.
2311
2312 \item
2313
2314 We use just one info table for {\em all\/} direct returns.  
2315 This introduces two problems:
2316 \begin{enumerate}
2317 \item How does the interpreter know what code to execute?
2318
2319 Instead of pushing just a return address, we push a return BCO and a 
2320 trivial return address which just enters the return BCO.
2321
2322 (In a purely interpreted system, we could avoid pushing the trivial
2323 return address.)
2324
2325 \item How can the garbage collector follow pointers within the
2326 activation record?
2327
2328 We could push a third word ---a bitmask describing the location of any
2329 pointers within the record--- but, since we're already tagging unboxed
2330 function arguments on the stack, we use the same mechanism for unboxed
2331 values within the activation record.
2332
2333 \ToDo{Do we have to stub out dead variables in the activation frame?}
2334
2335 \end{enumerate}
2336
2337 \item
2338
2339 We trivially support vectored returns by pushing a return vector whose
2340 entries are all the same.
2341
2342 \item
2343
2344 We avoid the need to build SRTs by putting bytecode objects on the
2345 heap and restricting BCOs to a single basic block.
2346
2347 \end{itemize}
2348
2349 \subsection{Hugs Info Tables}
2350
2351 Hugs requires the following info tables and closures:
2352 \begin{description}
2353 \item [@HUGS_RET@].
2354
2355 Contains both a vectored return table and a direct entry point.  All
2356 entry points are the same: they rearrange the stack to match the Hugs
2357 return convention (section~\label{sect:hugs-return-convention}) and return
2358 to the scheduler.  When the scheduler restarts the thread, it will
2359 find a BCO on top of the stack and will enter the Hugs interpreter.
2360
2361 \item [@UPD_RET@].
2362
2363 This is just the standard info table for an update frame.
2364
2365 \item [Constructors].
2366
2367 The entry code for a constructor jumps to a generic entry point in the
2368 runtime system which decides whether to do a vectored or unvectored
2369 return depending on the shape of the constructor/type.  This implies that
2370 info tables must have enough info to make that decision.
2371
2372 \item [@AP@ and @PAP@].
2373
2374 \item [Indirections].
2375
2376 \item [Selectors].
2377
2378 Hugs doesn't generate them itself but it ought to recognise them
2379
2380 \item [Complex primops].
2381
2382 Some of the primops are too complex for GHC to generate inline.
2383 Instead, these primops are hand-written and called as normal functions.
2384 Hugs only needs to know their names and types but doesn't care whether
2385 they are generated by GHC or by hand.  Two things to watch:
2386
2387 \begin{enumerate}
2388 \item
2389 Hugs must be able to enter these primops even if it is working on a
2390 standalone system that does not support genuine GHC generated code.
2391
2392 \item The complex primops often involve unboxed tuple types (which
2393 Hugs does not support at the source level) so we cannot specify their
2394 types in a Haskell source file.
2395
2396 \end{enumerate}
2397
2398 \end{description}
2399
2400 \subsection{Hugs Heap Objects}
2401 \label{sect:hugs-heap-objects}
2402
2403 \subsubsection{Byte-Code Objects}
2404
2405 Compiled byte code lives on the global heap, in objects called
2406 Byte-Code Objects (or BCOs).  The layout of BCOs is described in
2407 detail in Section \ref{sect:BCO}, in this section we will describe
2408 their semantics.
2409
2410 Since byte-code lives on the heap, it can be garbage collected just
2411 like any other heap-resident data.  Hugs arranges that any BCO's
2412 referred to by the Hugs symbol tables are treated as live objects by
2413 the garbage collector.  When a module is unloaded, the pointers to its
2414 BCOs are removed from the symbol table, and the code will be garbage
2415 collected some time later.
2416
2417 A BCO represents a basic block of code - all entry points are at the
2418 beginning of a BCO, and it is impossible to jump into the middle of
2419 one.  A BCO represents not only the code for a function, but also its
2420 closure; a BCO can be entered just like any other closure.  Hugs
2421 performs lambda-lifting during compilation to byte-code, and each
2422 top-level combinator becomes a BCO in the heap.
2423
2424 \ToDo{The phrase "all entry points..." suggests that BCOs have multiple 
2425 entry points.  If so, we need to say a lot more about it...}
2426
2427 \subsubsection{Thunks and partial applications}
2428
2429 A thunk consists of a code pointer, and values for the free variables
2430 of that code.  Since Hugs byte-code is lambda-lifted, free variables
2431 become arguments and are expected to be on the stack by the called
2432 function.
2433
2434 Hugs represents updateable thunks with @AP@ objects applying a closure
2435 to a list of arguments.  (As for @PAP@s, unboxed arguments should be
2436 preceded by a tag.)  When it is entered, it pushes an update frame
2437 followed by its payload on the stack, and enters the first word (which
2438 will be a pointer to a BCO).  The layout of @AP@ objects is described
2439 in more detail in Section \ref{sect:AP}.
2440
2441 Partial applications are represented by @PAP@ objects, which are
2442 non-updatable.
2443
2444 \ToDo{Hugs Constructors}.
2445
2446 \subsection{Calling conventions}
2447 \label{sect:hugs-calling-conventions}
2448 \label{sect:standard-closures}
2449
2450 The calling convention for any byte-code function is straightforward:
2451 \begin{itemize}
2452 \item Push any arguments on the stack.
2453 \item Push a pointer to the BCO.
2454 \item Begin interpreting the byte code.
2455 \end{itemize}
2456
2457 In a system containing both GHC and Hugs, the bytecode interpreter
2458 only has to be able to enter BCOs: everything else can be handled by
2459 returning to the compiled world (as described in
2460 Section~\ref{sect:hugs-to-ghc-switch}) and entering the closure
2461 there.
2462
2463 This would work but it would obviously be very inefficient if
2464 we entered a @AP@ by switching worlds, entering the @AP@,
2465 pushing the arguments and function onto the stack, and entering the
2466 function which, likely as not, will be a byte-code object which we
2467 will enter by \emph{returning} to the byte-code interpreter.  To avoid
2468 such gratuitious world switching, we choose to recognise certain
2469 closure types as being ``standard'' --- and duplicate the entry code
2470 for the ``standard closures'' in the bytecode interpreter.
2471
2472 A closure is said to be ``standard'' if its entry code is entirely
2473 determined by its info table.  \emph{Standard Closures} have the
2474 desirable property that the byte-code interpreter can enter
2475 the closure by simply ``interpreting'' the info table instead of
2476 switching to the compiled world.  The standard closures include:
2477
2478 \begin{description}
2479 \item[Constructor]
2480 To enter a constructor, we simply return (see Section
2481 \ref{sect:hugs-return-convention}).
2482
2483 \item[Indirection]
2484 To enter an indirection, we simply enter the object it points to
2485 after possibly adjusting the current cost centre.
2486
2487 \item[@AP@] 
2488
2489 To enter an @AP@, we push an update frame, push the
2490 arguments, push the function and enter the function.
2491 (Not forgetting a stack check at the start.)
2492
2493 \item[@PAP@]
2494
2495 To enter a @PAP@, we push the arguments, push the function and enter
2496 the function.  (Not forgetting a stack check at the start.)
2497
2498 \item[Selector] 
2499 To enter a selector, we test whether the selectee is a value.  If so,
2500 we simply select the appropriate component; if not, it's simplest to
2501 treat it as a GHC-built closure --- though we could interpret it if we
2502 wanted.
2503
2504 \end{description}
2505
2506 The most obvious omissions from the above list are @BCO@s (which we
2507 dealt with above) and GHC-built closures (which are covered in Section
2508 \ref{sect:hugs-to-ghc-switch}).
2509
2510
2511 \subsection{Return convention}
2512 \label{sect:hugs-return-convention}
2513
2514 When Hugs pushes a return address, it pushes both a pointer to the BCO
2515 to return to, and a pointer to a static code fragment @HUGS_RET@ (this
2516 is described in Section \ref{sect:ghc-to-hugs-switch}).  The
2517 stack layout is shown in Figure \ref{fig:hugs-return-stack}.
2518
2519 \begin{figure}[ht]
2520 \begin{center}
2521 @
2522 | stack    |
2523 +----------+
2524 | bco      |--> BCO
2525 +----------+
2526 | HUGS_RET |
2527 +----------+
2528 @
2529 %\input{hugs_ret.pstex_t}
2530 \end{center}
2531 \caption{Stack layout for a Hugs return address}
2532 \label{fig:hugs-return-stack}
2533 \end{figure}
2534
2535 \begin{figure}[ht]
2536 \begin{center}
2537 @
2538 | stack    |
2539 +----------+
2540 | con      |--> CON
2541 +----------+
2542 @
2543 %\input{hugs_ret2.pstex_t}
2544 \end{center}
2545 \caption{Stack layout on enterings a Hugs return address}
2546 \label{fig:hugs-return2}
2547 \end{figure}
2548
2549 \begin{figure}[ht]
2550 \begin{center}
2551 @
2552 | stack    |
2553 +----------+
2554 | 3#       |
2555 +----------+
2556 | I#       |
2557 +----------+
2558 @
2559 %\input{hugs_ret2.pstex_t}
2560 \end{center}
2561 \caption{Stack layout on entering a Hugs return address with an unboxed value}
2562 \label{fig:hugs-return-int}
2563 \end{figure}
2564
2565 \begin{figure}[ht]
2566 \begin{center}
2567 @
2568 | stack    |
2569 +----------+
2570 | ghc_ret  |
2571 +----------+
2572 | con      |--> CON
2573 +----------+
2574 @
2575 %\input{hugs_ret3.pstex_t}
2576 \end{center}
2577 \caption{Stack layout on enterings a GHC return address}
2578 \label{fig:hugs-return3}
2579 \end{figure}
2580
2581 \begin{figure}[ht]
2582 \begin{center}
2583 @
2584 | stack    |
2585 +----------+
2586 | ghc_ret  |
2587 +----------+
2588 | 3#       |
2589 +----------+
2590 | I#       |
2591 +----------+
2592 | restart  |--> id_Int#_closure
2593 +----------+
2594 @
2595 %\input{hugs_ret2.pstex_t}
2596 \end{center}
2597 \caption{Stack layout on enterings a GHC return address with an unboxed value}
2598 \label{fig:hugs-return-int}
2599 \end{figure}
2600
2601 When a Hugs byte-code sequence enters a closure, it examines the 
2602 return address on top of the stack.
2603
2604 \begin{itemize}
2605
2606 \item If the return address is @HUGS_RET@, pop the @HUGS_RET@ and the
2607 bco for the continuation off the stack, push a pointer to the constructor onto
2608 the stack and enter the BCO with the current object pointer set to the BCO
2609 (Figure \ref{fig:hugs-return2}).
2610
2611 \item If the top of the stack is not @HUGS_RET@, we need to do a world
2612 switch as described in Section \ref{sect:hugs-to-ghc-switch}.
2613
2614 \end{itemize}
2615
2616 \ToDo{This duplicates what we say about switching worlds
2617 (section~\ref{sect:switching-worlds}) - kill one or t'other.}
2618
2619
2620 \ToDo{This was in the evaluation model part but it really belongs in
2621 this part which is about the internal details of each of the major
2622 sections.}
2623
2624 \subsection{Addressing Modes}
2625
2626 To avoid potential alignment problems and simplify garbage collection,
2627 all literal constants are stored in two tables (one boxed, the other
2628 unboxed) within each BCO and are referred to by offsets into the tables.
2629 Slots in the constant tables are word aligned.
2630
2631 \ToDo{How big can the offsets be?  Is the offset specified in the
2632 address field or in the instruction?}
2633
2634 Literals can have the following types: char, int, nat, float, double,
2635 and pointer to boxed object.  There is no real difference between
2636 char, int, nat and float since they all occupy 32 bits --- but it
2637 costs almost nothing to distinguish them and may improve portability
2638 and simplify debugging.
2639
2640 \subsection{Compilation}
2641
2642
2643 \def\is{\mbox{\it is}}
2644 \def\ts{\mbox{\it ts}}
2645 \def\as{\mbox{\it as}}
2646 \def\bs{\mbox{\it bs}}
2647 \def\cs{\mbox{\it cs}}
2648 \def\rs{\mbox{\it rs}}
2649 \def\us{\mbox{\it us}}
2650 \def\vs{\mbox{\it vs}}
2651 \def\ws{\mbox{\it ws}}
2652 \def\xs{\mbox{\it xs}}
2653
2654 \def\e{\mbox{\it e}}
2655 \def\alts{\mbox{\it alts}}
2656 \def\fail{\mbox{\it fail}}
2657 \def\panic{\mbox{\it panic}}
2658 \def\ua{\mbox{\it ua}}
2659 \def\obj{\mbox{\it obj}}
2660 \def\bco{\mbox{\it bco}}
2661 \def\tag{\mbox{\it tag}}
2662 \def\entry{\mbox{\it entry}}
2663 \def\su{\mbox{\it su}}
2664
2665 \def\Ind#1{{\mbox{\it Ind}\ {#1}}}
2666 \def\update#1{{\mbox{\it update}\ {#1}}}
2667
2668 \def\next{$\Longrightarrow$}
2669 \def\append{\mathrel{+\mkern-6mu+}}
2670 \def\reverse{\mbox{\it reverse}}
2671 \def\size#1{{\vert {#1} \vert}}
2672 \def\arity#1{{\mbox{\it arity}{#1}}}
2673
2674 \def\AP{\mbox{\it AP}}
2675 \def\PAP{\mbox{\it PAP}}
2676 \def\GHCRET{\mbox{\it GHCRET}}
2677 \def\GHCOBJ{\mbox{\it GHCOBJ}}
2678
2679 To make sense of the instructions, we need a sense of how they will be
2680 used.  Here is a small compiler for the STG language.
2681
2682 @
2683 > cg (f{a1, ... am}) = do
2684 >   pushAtom am; ... pushAtom a1
2685 >   pushVar f
2686 >   SLIDE (m+1) |env|
2687 >   ENTER
2688 > cg (let{x1=rhs1; ... xm=rhsm in e) = do
2689 >   ALLOC x1 |rhs1|, ... ALLOC xm |rhsm|
2690 >   build x1 rhs1,   ... build xm rhsm
2691 >   cg e
2692 > cg (case e of alts) = do
2693 >   PUSHALTS (cgAlts alts)
2694 >   cg e
2695
2696 > cgAlts { alt1; ... altm }  = cgAlt alt1 $ ... $ cgAlt altm pmFail
2697 >
2698 > cgAlt (x@C{xs} -> e) fail = do
2699 >   TEST C fail
2700 >   HEAPCHECK (heapUse e)
2701 >   UNPACK xs
2702 >   cg e
2703
2704 > build x (C{a1, ... am}) = do 
2705 >   pushUntaggedAtom am; ... pushUntaggedAtom a1
2706 >   PACK x C
2707 > build x ({v1, ... vm} \ {}. e) = do 
2708 >   pushVar vm; ... pushVar v1
2709 >   PUSHBCO (cgRhs ({v1, ... vm} \ {}. e))
2710 >   MKAP x m
2711 > build x ({v1, ... vm} \ {x1, ... xm}. e) = do 
2712 >   pushVar vm; ... pushVar v1
2713 >   PUSHBCO (cgRhs ({v1, ... vm} \ {x1, ... xm}. e))
2714 >   MKPAP x m
2715
2716 > cgRhs (vs \ xs. e) = do
2717 >   ARGCHECK   (xs ++ vs)  -- can be omitted if xs == {}
2718 >   STACKCHECK min(stackUse e,heapOverflowSlop)
2719 >   HEAPCHECK  (heapUse e)
2720 >   cg e
2721
2722 > pushAtom x  = pushVar x
2723 > pushAtom i# = PUSHINT i#
2724
2725 > pushVar x = if isGlobalVar x then PUSHGLOBAL x else PUSHLOCAL x 
2726
2727 > pushUntaggedAtom x  = pushVar x
2728 > pushUntaggedAtom i# = PUSHUNTAGGEDINT i#
2729
2730 > pushVar x = if isGlobalVar x then PUSHGLOBAL x else PUSHLOCAL x 
2731 @
2732
2733 \ToDo{Is there an easy way to add semi-tagging?  Would it be that different?}
2734
2735 \ToDo{Optimise thunks of the form @f{x1,...xm}@ so that we build an AP directly}
2736
2737 \subsection{Instructions}
2738
2739 We specify the semantics of instructions using transition rules of
2740 the form:
2741
2742 \begin{tabular}{|llrrrrr|}
2743 \hline
2744         & $\is$         & $s$   & $\su$         & $h$  & $hp$  & $\sigma$ \\
2745 \next   & $\is'$        & $s'$  & $\su'$        & $h'$ & $hp'$ & $\sigma$ \\
2746 \hline
2747 \end{tabular}
2748
2749 where $\is$ is an instruction stream, $s$ is the stack, $\su$ is the 
2750 update frame pointer and $h$ is the heap.
2751
2752
2753 \subsection{Stack manipulation}
2754
2755 \begin{description}
2756
2757 \item[ Push a global variable ].
2758
2759 \begin{tabular}{|llrrrrr|}
2760 \hline
2761         & PUSHGLOBAL $o$ : $\is$ & $s$          & $su$ & $h$ & $hp$ & $\sigma$ \\
2762 \next   & $\is$                  & $\sigma!o:s$ & $su$ & $h$ & $hp$ & $\sigma$ \\
2763 \hline
2764 \end{tabular}
2765
2766 \item[ Push a local variable ].
2767
2768 \begin{tabular}{|llrrrrr|}
2769 \hline
2770         & PUSHLOCAL $o$ : $\is$ & $s$           & $su$ & $h$ & $hp$ & $\sigma$ \\
2771 \next   & $\is$                 & $s!o : s$     & $su$ & $h$ & $hp$ & $\sigma$ \\
2772 \hline
2773 \end{tabular}
2774
2775 \item[ Push an unboxed int ].
2776
2777 \begin{tabular}{|llrrrrr|}
2778 \hline
2779         & PUSHINT $o$ : $\is$   & $s$                   & $su$ & $h$ & $hp$ & $\sigma$ \\
2780 \next   & $\is$                 & $I\# : \sigma!o : s$  & $su$ & $h$ & $hp$ & $\sigma$ \\
2781 \hline
2782 \end{tabular}
2783
2784 The $I\#$ is a tag included for the benefit of the garbage collector.
2785 Similar rules exist for floats, doubles, chars, etc.
2786
2787 \item[ Push an unboxed int ].
2788
2789 \begin{tabular}{|llrrrrr|}
2790 \hline
2791         & PUSHUNTAGGEDINT $o$ : $\is$   & $s$                   & $su$ & $h$ & $hp$ & $\sigma$ \\
2792 \next   & $\is$                 & $\sigma!o : s$        & $su$ & $h$ & $hp$ & $\sigma$ \\
2793 \hline
2794 \end{tabular}
2795
2796 Similar rules exist for floats, doubles, chars, etc.
2797
2798 \item[ Delete environment from stack --- ready for tail call ].
2799
2800 \begin{tabular}{|llrrrrr|}
2801 \hline
2802         & SLIDE $m$ $n$ : $\is$ & $\as \append \bs \append \cs$         & $su$ & $h$ & $hp$ & $\sigma$ \\
2803 \next   & $\is$                 & $\as \append \cs$                     & $su$ & $h$ & $hp$ & $\sigma$ \\
2804 \hline
2805 \end{tabular}
2806 \\
2807 where $\size{\as} = m$ and $\size{\bs} = n$.
2808
2809
2810 \item[ Push a return address ].
2811
2812 \begin{tabular}{|llrrrrr|}
2813 \hline
2814         & PUSHALTS $o$:$\is$    & $s$                   & $su$ & $h$ & $hp$ & $\sigma$ \\
2815 \next   & $\is$                 & $@HUGS_RET@:\sigma!o:s$       & $su$ & $h$ & $hp$ & $\sigma$ \\
2816 \hline
2817 \end{tabular}
2818
2819 \item[ Push a BCO ].
2820
2821 \begin{tabular}{|llrrrrr|}
2822 \hline
2823         & PUSHBCO $o$ : $\is$   & $s$                   & $su$ & $h$ & $hp$ & $\sigma$ \\
2824 \next   & $\is$                 & $\sigma!o : s$        & $su$ & $h$ & $hp$ & $\sigma$ \\
2825 \hline
2826 \end{tabular}
2827
2828 \end{description}
2829
2830 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2831 \subsection{Heap manipulation}
2832 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2833
2834 \begin{description}
2835
2836 \item[ Allocate a heap object ].
2837
2838 \begin{tabular}{|llrrrrr|}
2839 \hline
2840         & ALLOC $m$ : $\is$     & $s$    & $su$ & $h$ & $hp$   & $\sigma$ \\
2841 \next   & $\is$                 & $hp:s$ & $su$ & $h$ & $hp+m$ & $\sigma$ \\
2842 \hline
2843 \end{tabular}
2844
2845 \item[ Build a constructor ].
2846
2847 \begin{tabular}{|llrrrrr|}
2848 \hline
2849         & PACK $o$ $o'$ : $\is$ & $\ws \append s$       & $su$ & $h$                            & $hp$ & $\sigma$ \\
2850 \next   & $\is$                 & $s$                   & $su$ & $h[s!o \mapsto Pack C\{\ws\}]$ & $hp$ & $\sigma$ \\
2851 \hline
2852 \end{tabular}
2853 \\
2854 where $C = \sigma!o'$ and $\size{\ws} = \arity{C}$.
2855
2856 \item[ Build an AP or  PAP ].
2857
2858 \begin{tabular}{|llrrrrr|}
2859 \hline
2860         & MKAP $o$ $m$:$\is$    & $f : \ws \append s$   & $su$ & $h$                            & $hp$ & $\sigma$ \\
2861 \next   & $\is$                 & $s$                   & $su$ & $h[s!o \mapsto \AP(f,\ws)]$    & $hp$ & $\sigma$ \\
2862 \hline
2863 \end{tabular}
2864 \\
2865 where $\size{\ws} = m$.
2866
2867 \begin{tabular}{|llrrrrr|}
2868 \hline
2869         & MKPAP $o$ $m$:$\is$   & $f : \ws \append s$   & $su$ & $h$                            & $hp$ & $\sigma$ \\
2870 \next   & $\is$                 & $s$                   & $su$ & $h[s!o \mapsto \PAP(f,\ws)]$   & $hp$ & $\sigma$ \\
2871 \hline
2872 \end{tabular}
2873 \\
2874 where $\size{\ws} = m$.
2875
2876 \item[ Unpacking a constructor ].
2877
2878 \begin{tabular}{|llrrrrr|}
2879 \hline
2880         & UNPACK : $is$         & $a : s$                               & $su$ & $h[a \mapsto C\ \ws]$          & $hp$ & $\sigma$ \\
2881 \next   & $is'$                 & $(\reverse\ \ws) \append a : s$       & $su$ & $h$                            & $hp$ & $\sigma$ \\
2882 \hline
2883 \end{tabular}
2884
2885 The $\reverse\ \ws$ looks expensive but, since the stack grows down
2886 and the heap grows up, that's actually the cheap way of copying from
2887 heap to stack.  Looking at the compilation rules, you'll see that we
2888 always push the args in reverse order.
2889
2890 \end{description}
2891
2892
2893 \subsection{Entering a closure}
2894
2895 \begin{description}
2896
2897 \item[ Enter a BCO ].
2898
2899 \begin{tabular}{|llrrrrr|}
2900 \hline
2901         & [ENTER]       & $a : s$       & $su$ & $h[a \mapsto BCO\{\is\} ]$     & $hp$ & $\sigma$ \\
2902 \next   & $\is$         & $a : s$       & $su$ & $h$                            & $hp$ & $a$ \\
2903 \hline
2904 \end{tabular}
2905
2906 \item[ Enter a PAP closure ].
2907
2908 \begin{tabular}{|llrrrrr|}
2909 \hline
2910         & [ENTER]       & $a : s$               & $su$ & $h[a \mapsto \PAP(f,\ws)]$     & $hp$ & $\sigma$ \\
2911 \next   & [ENTER]       & $f : \ws \append s$   & $su$ & $h$                            & $hp$ & $???$ \\
2912 \hline
2913 \end{tabular}
2914
2915 \item[ Entering an AP closure ].
2916
2917 \begin{tabular}{|llrrrrr|}
2918 \hline
2919         & [ENTER]       & $a : s$                               & $su$  & $h[a \mapsto \AP(f,ws)]$      & $hp$ & $\sigma$ \\
2920 \next   & [ENTER]       & $f : \ws \append @UPD_RET@:\su:a:s$   & $su'$ & $h$                           & $hp$ & $???$ \\
2921 \hline
2922 \end{tabular}
2923
2924 Optimisations:
2925 \begin{itemize}
2926 \item Instead of blindly pushing an update frame for $a$, we can first test whether there's already
2927  an update frame there.  If so, overwrite the existing updatee with an indirection to $a$ and
2928  overwrite the updatee field with $a$.  (Overwriting $a$ with an indirection to the updatee also
2929  works.)  This results in update chains of maximum length 2. 
2930 \end{itemize}
2931
2932
2933 \item[ Returning a constructor ].
2934
2935 \begin{tabular}{|llrrrrr|}
2936 \hline
2937         & [ENTER]               & $a : @HUGS_RET@ : \alts : s$  & $su$ & $h[a \mapsto C\{\ws\}]$        & $hp$ & $\sigma$ \\
2938 \next   & $\alts.\entry$        & $a:s$                         & $su$ & $h$                            & $hp$ & $\sigma$ \\
2939 \hline
2940 \end{tabular}
2941
2942
2943 \item[ Entering an indirection node ].
2944
2945 \begin{tabular}{|llrrrrr|}
2946 \hline
2947         & [ENTER]       & $a  : s$      & $su$ & $h[a \mapsto \Ind{a'}]$        & $hp$ & $\sigma$ \\
2948 \next   & [ENTER]       & $a' : s$      & $su$ & $h$                            & $hp$ & $\sigma$ \\
2949 \hline
2950 \end{tabular}
2951
2952 \item[Entering GHC closure].
2953
2954 \begin{tabular}{|llrrrrr|}
2955 \hline
2956         & [ENTER]       & $a : s$       & $su$ & $h[a \mapsto \GHCOBJ]$         & $hp$ & $\sigma$ \\
2957 \next   & [ENTERGHC]    & $a : s$       & $su$ & $h$                            & $hp$ & $\sigma$ \\
2958 \hline
2959 \end{tabular}
2960
2961 \item[Returning a constructor to GHC].
2962
2963 \begin{tabular}{|llrrrrr|}
2964 \hline
2965         & [ENTER]       & $a : \GHCRET : s$     & $su$ & $h[a \mapsto C \ws]$   & $hp$ & $\sigma$ \\
2966 \next   & [ENTERGHC]    & $a : \GHCRET : s$     & $su$ & $h$                    & $hp$ & $\sigma$ \\
2967 \hline
2968 \end{tabular}
2969
2970 \end{description}
2971
2972
2973 \subsection{Updates}
2974
2975 \begin{description}
2976
2977 \item[ Updating with a constructor].
2978
2979 \begin{tabular}{|llrrrrr|}
2980 \hline
2981         & [ENTER]       & $a : @UPD_RET@ : ua : s$      & $su$ & $h[a \mapsto C\{\ws\}]$  & $hp$ & $\sigma$ \\
2982 \next   & [ENTER]       & $a \append s$                 & $su$ & $h[au \mapsto \Ind{a}$   & $hp$ & $\sigma$ \\
2983 \hline
2984 \end{tabular}
2985
2986 \item[ Argument checks].
2987
2988 \begin{tabular}{|llrrrrr|}
2989 \hline
2990         & ARGCHECK $m$:$\is$    & $a : \as \append s$   & $su$ & $h$    & $hp$ & $\sigma$ \\
2991 \next   & $\is$                 & $a : \as \append s$   & $su$ & $h'$   & $hp$ & $\sigma$ \\
2992 \hline
2993 \end{tabular}
2994 \\
2995 where $m \ge (su - sp)$
2996
2997 \begin{tabular}{|llrrrrr|}
2998 \hline
2999         & ARGCHECK $m$:$\is$    & $a : \as \append @UPD_RET@:su:ua:s$   & $su$ & $h$    & $hp$ & $\sigma$ \\
3000 \next   & $\is$                 & $a : \as \append s$                   & $su$ & $h'$   & $hp$ & $\sigma$ \\
3001 \hline
3002 \end{tabular}
3003 \\
3004 where $m < (su - sp)$ and
3005       $h' = h[ua \mapsto \Ind{a'}, a' \mapsto \PAP(a,\reverse\ \as) ]$
3006
3007 Again, we reverse the list of values as we transfer them from the
3008 stack to the heap --- reflecting the fact that the stack and heap grow
3009 in different directions.
3010
3011 \end{description}
3012
3013 \subsection{Branches}
3014
3015 \begin{description}
3016
3017 \item[ Testing a constructor ].
3018
3019 \begin{tabular}{|llrrrrr|}
3020 \hline
3021         & TEST $tag$ $is'$ : $is$       & $a : s$       & $su$ & $h[a \mapsto C\ \ws]$  & $hp$ & $\sigma$ \\
3022 \next   & $is$                          & $a : s$       & $su$ & $h$                    & $hp$ & $\sigma$ \\
3023 \hline
3024 \end{tabular}
3025 \\
3026 where $C.\tag = tag$
3027
3028 \begin{tabular}{|llrrrrr|}
3029 \hline
3030         & TEST $tag$ $is'$ : $is$       & $a : s$       & $su$ & $h[a \mapsto C\ \ws]$  & $hp$ & $\sigma$ \\
3031 \next   & $is'$                         & $a : s$       & $su$ & $h$                    & $hp$ & $\sigma$ \\
3032 \hline
3033 \end{tabular}
3034 \\
3035 where $C.\tag \neq tag$
3036
3037 \end{description}
3038
3039 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3040 \subsection{Heap and stack checks}
3041 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3042
3043 \begin{tabular}{|llrrrrr|}
3044 \hline
3045         & STACKCHECK $stk$:$\is$        & $s$   & $su$ & $h$    & $hp$ & $\sigma$ \\
3046 \next   & $\is$                         & $s$   & $su$ & $h$    & $hp$ & $\sigma$ \\
3047 \hline
3048 \end{tabular}
3049 \\
3050 if $s$ has $stk$ free slots.
3051
3052 \begin{tabular}{|llrrrrr|}
3053 \hline
3054         & HEAPCHECK $hp$:$\is$          & $s$   & $su$ & $h$    & $hp$ & $\sigma$ \\
3055 \next   & $\is$                         & $s$   & $su$ & $h$    & $hp$ & $\sigma$ \\
3056 \hline
3057 \end{tabular}
3058 \\
3059 if $h$ has $hp$ free slots.
3060
3061 If either check fails, we push the current bco ($\sigma$) onto the
3062 stack and return to the scheduler.  When the scheduler has fixed the
3063 problem, it pops the top object off the stack and reenters it.
3064
3065
3066 Optimisations:
3067 \begin{itemize}
3068 \item The bytecode CHECK1000 conservatively checks for 1000 words of heap space and 1000 words of stack space.
3069       We use it to reduce code space and instruction decoding time.
3070 \item The bytecode HEAPCHECK1000 conservatively checks for 1000 words of heap space.
3071       It is used in case alternatives.
3072 \end{itemize}
3073
3074
3075 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3076 \subsection{Primops}
3077 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3078
3079 \ToDo{primops take m words and return n words. The expect boxed arguments on the stack.}
3080
3081
3082 \section{The Machine Code Evaluator}
3083
3084 This section describes the framework in which compiled code evaluates
3085 expressions.  Only at certain points will compiled code need to be
3086 able to talk to the interpreted world; these are discussed in Section
3087 \ref{sect:switching-worlds}.
3088
3089 \subsection{Calling conventions}
3090
3091 \subsubsection{The call/return registers}
3092
3093 One of the problems in designing a virtual machine is that we want it
3094 abstract away from tedious machine details but still reveal enough of
3095 the underlying hardware that we can make sensible decisions about code
3096 generation.  A major problem area is the use of registers in
3097 call/return conventions.  On a machine with lots of registers, it's
3098 cheaper to pass arguments and results in registers than to pass them
3099 on the stack.  On a machine with very few registers, it's cheaper to
3100 pass arguments and results on the stack than to use ``virtual
3101 registers'' in memory.  We therefore use a hybrid system: the first
3102 $n$ arguments or results are passed in registers; and the remaining
3103 arguments or results are passed on the stack.  For register-poor
3104 architectures, it is important that we allow $n=0$.
3105
3106 We'll label the arguments and results \Arg{1} \ldots \Arg{m} --- with
3107 the understanding that \Arg{1} \ldots \Arg{n} are in registers and
3108 \Arg{n+1} \ldots \Arg{m} are on top of the stack.
3109
3110 Note that the mapping of arguments \Arg{1} \ldots \Arg{n} to machine
3111 registers depends on the {\em kinds} of the arguments.  For example,
3112 if the first argument is a Float, we might pass it in a different
3113 register from if it is an Int.  In fact, we might find that a given
3114 architecture lets us pass varying numbers of arguments according to
3115 their types.  For example, if a CPU has 2 Int registers and 2 Float
3116 registers then we could pass between 2 and 4 arguments in machine
3117 registers --- depending on whether they all have the same kind or they
3118 have different kinds.
3119
3120 \subsubsection{Entering closures}
3121 \label{sect:entering-closures}
3122
3123 To evaluate a closure we jump to the entry code for the closure
3124 passing a pointer to the closure in \Arg{1} so that the entry code can
3125 access its environment.
3126
3127 \subsubsection{Function call}
3128
3129 The function-call mechanism is obviously crucial.  There are five different
3130 cases to consider:
3131 \begin{enumerate}
3132
3133 \item {\em Known combinator (function with no free variables) and enough arguments.}  
3134
3135 A fast call can be made: push excess arguments onto stack and jump to
3136 function's {\em fast entry point} passing arguments in \Arg{1} \ldots
3137 \Arg{m}.  
3138
3139 The {\em fast entry point} is only called with exactly the right
3140 number of arguments (in \Arg{1} \ldots \Arg{m}) so it can instantly
3141 start doing useful work without first testing whether it has enough
3142 registers or having to pop them off the stack first.
3143
3144 \item {\em Known combinator and insufficient arguments.}
3145
3146 A slow call can be made: push all arguments onto stack and jump to
3147 function's {\em slow entry point}.
3148
3149 Any unpointed arguments which are pushed on the stack must be tagged.
3150 This means pushing an extra word on the stack below the unpointed
3151 words, containing the number of unpointed words above it.
3152
3153 %Todo: forward ref about tagging?
3154 %Todo: picture?
3155
3156 The {\em slow entry point} might be called with insufficient arguments
3157 and so it must test whether there are enough arguments on the stack.
3158 This {\em argument satisfaction check} consists of checking that
3159 @Su-Sp@ is big enough to hold all the arguments (including any tags).
3160
3161 \begin{itemize} 
3162
3163 \item If the argument satisfaction check fails, it is because there is
3164 one or more update frames on the stack before the rest of the
3165 arguments that the function needs.  In this case, we construct a PAP
3166 (partial application, section~\ref{sect:PAP}) containing the arguments
3167 which are on the stack.  The PAP construction code will return to the
3168 update frame with the address of the PAP in \Arg{1}.
3169
3170 \item If the argument satisfaction check succeeds, we jump to the fast
3171 entry point with the arguments in \Arg{1} \ldots \Arg{arity}.
3172
3173 If the fast entry point expects to receive some of \Arg{i} on the
3174 stack, we can reduce the amount of movement required by making the
3175 stack layout for the fast entry point look like the stack layout for
3176 the slow entry point.  Since the slow entry point is entered with the
3177 first argument on the top of the stack and with tags in front of any
3178 unpointed arguments, this means that if \Arg{i} is unpointed, there
3179 should be space below it for a tag and that the highest numbered
3180 argument should be passed on the top of the stack.
3181
3182 We usually arrange that the fast entry point is placed immediately
3183 after the slow entry point --- so we can just ``fall through'' to the
3184 fast entry point without performing a jump.
3185
3186 \end{itemize}
3187
3188
3189 \item {\em Known function closure (function with free variables) and enough arguments.}
3190
3191 A fast call can be made: push excess arguments onto stack and jump to
3192 function's {\em fast entry point} passing a pointer to closure in
3193 \Arg{1} and arguments in \Arg{2} \ldots \Arg{m+1}.
3194
3195 Like the fast entry point for a combinator, the fast entry point for a
3196 closure is only called with appropriate values in \Arg{1} \ldots
3197 \Arg{m+1} so we can start work straight away.  The pointer to the
3198 closure is used to access the free variables of the closure.
3199
3200
3201 \item {\em Known function closure and insufficient arguments.}
3202
3203 A slow call can be made: push all arguments onto stack and jump to the
3204 closure's slow entry point passing a pointer to the closure in \Arg{1}.
3205
3206 Again, the slow entry point performs an argument satisfaction check
3207 and either builds a PAP or pops the arguments off the stack into
3208 \Arg{2} \ldots \Arg{m+1} and jumps to the fast entry point.
3209
3210
3211 \item {\em Unknown function closure, thunk or constructor.}
3212
3213 Sometimes, the function being called is not statically identifiable.
3214 Consider, for example, the @compose@ function:
3215 @
3216   compose f g x = f (g x)
3217 @
3218 Since @f@ and @g@ are passed as arguments to @compose@, the latter has
3219 to make a heap call.  In a heap call the arguments are pushed onto the
3220 stack, and the closure bound to the function is entered.  In the
3221 example, a thunk for @(g x)@ will be allocated, (a pointer to it)
3222 pushed on the stack, and the closure bound to @f@ will be
3223 entered. That is, we will jump to @f@s entry point passing @f@ in
3224 \Arg{1}.  If \Arg{1} is passed on the stack, it is pushed on top of
3225 the thunk for @(g x)@.
3226
3227 The {\em entry code} for an updateable thunk (which must have arity 0)
3228 pushes an update frame on the stack and starts executing the body of
3229 the closure --- using \Arg{1} to access any free variables.  This is
3230 described in more detail in section~\ref{sect:data-updates}.
3231
3232 The {\em entry code} for a non-updateable closure is just the
3233 closure's slow entry point.
3234
3235 \end{enumerate}
3236
3237 In addition to the above considerations, if there are \emph{too many}
3238 arguments then the extra arguments are simply pushed on the stack with
3239 appropriate tags.
3240
3241 To summarise, a closure's standard (slow) entry point performs the following:
3242 \begin{description}
3243 \item[Argument satisfaction check.] (function closure only)
3244 \item[Stack overflow check.]
3245 \item[Heap overflow check.]
3246 \item[Copy free variables out of closure.] %Todo: why?
3247 \item[Eager black holing.] (updateable thunk only) %Todo: forward ref.
3248 \item[Push update frame.]
3249 \item[Evaluate body of closure.]
3250 \end{description}
3251
3252
3253 \subsection{Case expressions and return conventions}
3254 \label{sect:return-conventions}
3255
3256 The {\em evaluation} of a thunk is always initiated by
3257 a @case@ expression.  For example:
3258 @
3259   case x of (a,b) -> E
3260 @
3261
3262 The code for a @case@ expression looks like this:
3263
3264 \begin{itemize}
3265 \item Push the free variables of the branches on the stack (fv(@E@) in
3266 this case).
3267 \item  Push a \emph{return address} on the stack.
3268 \item  Evaluate the scrutinee (@x@ in this case).
3269 \end{itemize}
3270
3271 Once evaluation of the scrutinee is complete, execution resumes at the
3272 return address, which points to the code for the expression @E@.
3273
3274 When execution resumes at the return point, there must be some {\em
3275 return convention} that defines where the components of the pair, @a@
3276 and @b@, can be found.  The return convention varies according to the
3277 type of the scrutinee @x@:
3278
3279 \begin{itemize}
3280
3281 \item 
3282
3283 (A space for) the return address is left on the top of the stack.
3284 Leaving the return address on the stack ensures that the top of the
3285 stack contains a valid activation record
3286 (section~\ref{sect:activation-records}) --- should a garbage collection
3287 be required.
3288
3289 \item If @x@ has a boxed type (e.g.~a data constructor or a function),
3290 a pointer to @x@ is returned in \Arg{1}.
3291
3292 \ToDo{Warn that components of E should be extracted as soon as
3293 possible to avoid a space leak.}
3294
3295 \item If @x@ is an unboxed type (e.g.~@Int#@ or @Float#@), @x@ is
3296 returned in \Arg{1}
3297
3298 \item If @x@ is an unboxed tuple constructor, the components of @x@
3299 are returned in \Arg{1} \ldots \Arg{n} but no object is constructed in
3300 the heap.  
3301
3302 When passing an unboxed tuple to a function, the components are
3303 flattened out and passed in \Arg{1} \ldots \Arg{n} as usual.
3304
3305 \end{itemize}
3306
3307 \subsection{Vectored Returns}
3308
3309 Many algebraic data types have more than one constructor.  For
3310 example, the @Maybe@ type is defined like this:
3311 @
3312   data Maybe a = Nothing | Just a
3313 @
3314 How does the return convention encode which of the two constructors is
3315 being returned?  A @case@ expression scrutinising a value of @Maybe@
3316 type would look like this: 
3317 @
3318   case E of 
3319     Nothing -> ...
3320     Just a  -> ...
3321 @
3322 Rather than pushing a return address before evaluating the scrutinee,
3323 @E@, the @case@ expression pushes (a pointer to) a {\em return
3324 vector}, a static table consisting of two code pointers: one for the
3325 @Just@ alternative, and one for the @Nothing@ alternative.  
3326
3327 \begin{itemize}
3328
3329 \item
3330
3331 The constructor @Nothing@ returns by jumping to the first item in the
3332 return vector with a pointer to a (statically built) Nothing closure
3333 in \Arg{1}.  
3334
3335 It might seem that we could avoid loading \Arg{1} in this case since the
3336 first item in the return vector will know that @Nothing@ was returned
3337 (and can easily access the Nothing closure in the (unlikely) event
3338 that it needs it.  The only reason we load \Arg{1} is in case we have to
3339 perform an update (section~\ref{sect:data-updates}).
3340
3341 \item 
3342
3343 The constructor @Just@ returns by jumping to the second element of the
3344 return vector with a pointer to the closure in \Arg{1}.  
3345
3346 \end{itemize}
3347
3348 In this way no test need be made to see which constructor returns;
3349 instead, execution resumes immediately in the appropriate branch of
3350 the @case@.
3351
3352 \subsection{Direct Returns}
3353
3354 When a datatype has a large number of constructors, it may be
3355 inappropriate to use vectored returns.  The vector tables may be
3356 large and sparse, and it may be better to identify the constructor
3357 using a test-and-branch sequence on the tag.  For this reason, we
3358 provide an alternative return convention, called a \emph{direct
3359 return}.
3360
3361 In a direct return, the return address pushed on the stack really is a
3362 code pointer.  The returning code loads a pointer to the closure being
3363 returned in \Arg{1} as usual, and also loads the tag into \Arg{2}.
3364 The code at the return address will test the tag and jump to the
3365 appropriate code for the case branch.
3366
3367 The choice of whether to use a vectored return or a direct return is
3368 made on a type-by-type basis --- up to a certain maximum number of
3369 constructors imposed by the update mechanism
3370 (section~\ref{sect:data-updates}).
3371
3372 Single-constructor data types also use direct returns, although in
3373 that case there is no need to return a tag in \Arg{2}.
3374
3375 \ToDo{Say whether we pop the return address before returning}
3376
3377 \ToDo{Stack stubbing?}
3378
3379 \subsection{Updates}
3380 \label{sect:data-updates}
3381
3382 The entry code for an updatable thunk (which must be of arity 0):
3383
3384 \begin{itemize}
3385 \item copies the free variables out of the thunk into registers or
3386   onto the stack.
3387 \item pushes an {\em update frame} onto the stack.
3388
3389 An update frame is a small activation record consisting of
3390 \begin{center}
3391 \begin{tabular}{|l|l|l|}
3392 \hline
3393 {\em Fixed header} & {\em Update Frame link} & {\em Updatee} \\
3394 \hline
3395 \end{tabular}
3396 \end{center}
3397
3398 \note{In the semantics part of the STG paper (section 5.6), an update
3399 frame consists of everything down to the last update frame on the
3400 stack.  This would make sense too --- and would fit in nicely with
3401 what we're going to do when we add support for speculative
3402 evaluation.}
3403 \ToDo{I think update frames contain cost centres sometimes}
3404
3405 \item 
3406 If we are doing ``eager blackholing,'' we then overwrite the thunk
3407 with a black hole.  Otherwise, we leave it to the garbage collector to
3408 black hole the thunk.
3409
3410 \item 
3411 Start evaluating the body of the expression.
3412
3413 \end{itemize}
3414
3415 When the expression finishes evaluation, it will enter the update
3416 frame on the top of the stack.  Since the returner doesn't know
3417 whether it is entering a normal return address/vector or an update
3418 frame, we follow exactly the same conventions as return addresses and
3419 return vectors.  That is, on entering the update frame:
3420
3421 \begin{itemize} 
3422 \item The value of the thunk is in \Arg{1}.  (Recall that only thunks
3423 are updateable and that thunks return just one value.)
3424
3425 \item If the data type is a direct-return type rather than a
3426 vectored-return type, then the tag is in \Arg{2}.
3427
3428 \item The update frame is still on the stack.
3429 \end{itemize}
3430
3431 We can safely share a single statically-compiled update function
3432 between all types.  However, the code must be able to handle both
3433 vectored and direct-return datatypes.  This is done by arranging that
3434 the update code looks like this:
3435
3436 @
3437                 |       ^       |
3438                 | return vector |
3439                 |---------------|
3440                 |  fixed-size   |
3441                 |  info table   |
3442                 |---------------|  <- update code pointer
3443                 |  update code  |
3444                 |       v       |
3445 @
3446
3447 Each entry in the return vector (which is large enough to cover the
3448 largest vectored-return type) points to the update code.
3449
3450 The update code:
3451 \begin{itemize}
3452 \item overwrites the {\em updatee} with an indirection to \Arg{1};
3453 \item loads @Su@ from the Update Frame link;
3454 \item removes the update frame from the stack; and 
3455 \item enters \Arg{1}.
3456 \end{itemize}
3457
3458 We enter \Arg{1} again, having probably just come from there, because
3459 it knows whether to perform a direct or vectored return.  This could
3460 be optimised by compiling special update code for each slot in the
3461 return vector, which performs the correct return.
3462
3463 \subsection{Semi-tagging}
3464 \label{sect:semi-tagging}
3465
3466 When a @case@ expression evaluates a variable that might be bound
3467 to a thunk it is often the case that the scrutinee is already evaluated.
3468 In this case we have paid the penalty of (a) pushing the return address (or
3469 return vector address) on the stack, (b) jumping through the info pointer
3470 of the scrutinee, and (c) returning by an indirect jump through the
3471 return address on the stack.
3472
3473 If we knew that the scrutinee was already evaluated we could generate
3474 (better) code which simply jumps to the appropriate branch of the
3475 @case@ with a pointer to the scrutinee in \Arg{1}.  (For direct
3476 returns to multiconstructor datatypes, we might also load the tag into
3477 \Arg{2}).
3478
3479 An obvious idea, therefore, is to test dynamically whether the heap
3480 closure is a value (using the tag in the info table).  If not, we
3481 enter the closure as usual; if so, we jump straight to the appropriate
3482 alternative.  Here, for example, is pseudo-code for the expression
3483 @(case x of { (a,_,c) -> E }@:
3484 @
3485       \Arg{1} = <pointer to x>;
3486       tag = \Arg{1}->entry->tag;
3487       if (isWHNF(tag)) {
3488           Sp--;  \\ insert space for return address
3489           goto ret;
3490       }
3491       push(ret);           
3492       goto \Arg{1}->entry;
3493       
3494       <info table for return address goes here>
3495 ret:  a = \Arg{1}->data1; \\ suck out a and c to avoid space leak
3496       c = \Arg{1}->data3;
3497       <code for E2>
3498 @
3499 and here is the code for the expression @(case x of { [] -> E1; x:xs -> E2 }@:
3500 @
3501       \Arg{1} = <pointer to x>;
3502       tag = \Arg{1}->entry->tag;
3503       if (isWHNF(tag)) {
3504           Sp--;  \\ insert space for return address
3505           goto retvec[tag];
3506       }
3507       push(retinfo);          
3508       goto \Arg{1}->entry;
3509       
3510       .addr ret2
3511       .addr ret1
3512 retvec:           \\ reversed return vector
3513       <return info table for case goes here>
3514 retinfo:
3515       panic("Direct return into vectored case");
3516       
3517 ret1: <code for E1>
3518
3519 ret2: x  = \Arg{1}->head;
3520       xs = \Arg{1}->tail;
3521       <code for E2>
3522 @
3523 There is an obvious cost in compiled code size (but none in the size
3524 of the bytecodes).  There is also a cost in execution time if we enter
3525 more thunks than data constructors.
3526
3527 Both the direct and vectored returns are easily modified to chase chains
3528 of indirections too.  In the vectored case, this is most easily done by
3529 making sure that @IND = TAG_1 - 1@, and adding an extra field to every
3530 return vector.  In the above example, the indirection code would be
3531 @
3532 ind:  \Arg{1} = \Arg{1}->next;
3533       goto ind_loop;
3534 @
3535 where @ind_loop@ is the second line of code.
3536
3537 Note that we have to leave space for a return address since the return
3538 address expects to find one.  If the body of the expression requires a
3539 heap check, we will actually have to write the return address before
3540 entering the garbage collector.
3541
3542
3543 \subsection{Heap and Stack Checks}
3544 \label{sect:heap-and-stack-checks}
3545
3546 The storage manager detects that it needs to garbage collect the old
3547 generation when the evaluator requests a garbage collection without
3548 having moved the heap pointer since the last garbage collection.  It
3549 is therefore important that the GC routines {\em not} move the heap
3550 pointer unless the heap check fails.  This is different from what
3551 happens in the current STG implementation.
3552
3553 Assuming that the stack can never shrink, we perform a stack check
3554 when we enter a closure but not when we return to a return
3555 continuation.  This doesn't work for heap checks because we cannot
3556 predict what will happen to the heap if we call a function.
3557
3558 If we wish to allow the stack to shrink, we need to perform a stack
3559 check whenever we enter a return continuation.  Most of these checks
3560 could be eliminated if the storage manager guaranteed that a stack
3561 would always have 1000 words (say) of space after it was shrunk.  Then
3562 we can omit stack checks for less than 1000 words in return
3563 continuations.
3564
3565 When an argument satisfaction check fails, we need to push the closure
3566 (in R1) onto the stack - so we need to perform a stack check.  The
3567 problem is that the argument satisfaction check occurs \emph{before}
3568 the stack check.  The solution is that the caller of a slow entry
3569 point or closure will guarantee that there is at least one word free
3570 on the stack for the callee to use.  
3571
3572 Similarily, if a heap or stack check fails, we need to push the arguments
3573 and closure onto the stack.  If we just came from the slow entry point, 
3574 there's certainly enough space and it is the responsibility of anyone
3575 using the fast entry point to guarantee that there is enough space.
3576
3577 \ToDo{Be more precise about how much space is required - document it
3578 in the calling convention section.}
3579
3580 \subsection{Handling interrupts/signals}
3581
3582 @
3583 May have to keep C stack pointer in register to placate OS?
3584 May have to revert black holes - ouch!
3585 @
3586
3587
3588
3589 \section{The Loader}
3590 \section{The Compilers}
3591
3592 \iffalse
3593 \part{Old stuff - needs to be mined for useful info}
3594
3595 \section{The Scheduler}
3596
3597 The Scheduler is the heart of the run-time system.  A running program
3598 consists of a single running thread, and a list of runnable and
3599 blocked threads.  The running thread returns to the scheduler when any
3600 of the following conditions arises:
3601
3602 \begin{itemize}
3603 \item A heap check fails, and a garbage collection is required
3604 \item Compiled code needs to switch to interpreted code, and vice
3605 versa.
3606 \item The thread becomes blocked.
3607 \item The thread is preempted.
3608 \end{itemize}
3609
3610 A running system has a global state, consisting of
3611
3612 \begin{itemize}
3613 \item @Hp@, the current heap pointer, which points to the next
3614 available address in the Heap.
3615 \item @HpLim@, the heap limit pointer, which points to the end of the
3616 heap.
3617 \item The Thread Preemption Flag, which is set whenever the currently
3618 running thread should be preempted at the next opportunity.
3619 \item A list of runnable threads. 
3620 \item A list of blocked threads.
3621 \end{itemize}
3622
3623 Each thread is represented by a Thread State Object (TSO), which is
3624 described in detail in Section \ref{sect:TSO}.
3625
3626 The following is pseudo-code for the inner loop of the scheduler
3627 itself.
3628
3629 @
3630 while (threads_exist) {
3631   // handle global problems: GC, parallelism, etc
3632   if (need_gc) gc();  
3633   if (external_message) service_message();
3634   // deal with other urgent stuff
3635
3636   pick a runnable thread;
3637   do {
3638     // enter object on top of stack
3639     // if the top object is a BCO, we must enter it
3640     // otherwise appply any heuristic we wish.
3641     if (thread->stack[thread->sp]->info.type == BCO) {
3642         status = runHugs(thread,&smInfo);
3643     } else {
3644         status = runGHC(thread,&smInfo);
3645     }
3646     switch (status) {  // handle local problems
3647       case (StackOverflow): enlargeStack; break;
3648       case (Error e)      : error(thread,e); break;
3649       case (ExitWith e)   : exit(e); break;
3650       case (Yield)        : break;
3651     }
3652   } while (thread_runnable);
3653 }
3654 @
3655
3656 \subsection{Invoking the garbage collector}
3657 \subsection{Putting the thread to sleep}
3658
3659 \subsection{Calling C from Haskell}
3660
3661 We distinguish between "safe calls" where the programmer guarantees
3662 that the C function will not call a Haskell function or, in a
3663 multithreaded system, block for a long period of time and "unsafe
3664 calls" where the programmer cannot make that guarantee.  
3665
3666 Safe calls are performed without returning to the scheduler and are
3667 discussed elsewhere (\ToDo{discuss elsewhere}).
3668
3669 Unsafe calls are performed by returning an array (outside the Haskell
3670 heap) of arguments and a C function pointer to the scheduler.  The
3671 scheduler allocates a new thread from the operating system
3672 (multithreaded system only), spawns a call to the function and
3673 continues executing another thread.  When the ccall completes, the
3674 thread informs the scheduler and the scheduler adds the thread to the
3675 runnable threads list.  
3676
3677 \ToDo{Describe this in more detail.}
3678
3679
3680 \subsection{Calling Haskell from C}
3681
3682 When C calls a Haskell closure, it sends a message to the scheduler
3683 thread.  On receiving the message, the scheduler creates a new Haskell
3684 thread, pushes the arguments to the C function onto the thread's stack
3685 (with tags for unboxed arguments) pushes the Haskell closure and adds
3686 the thread to the runnable list so that it can be entered in the
3687 normal way.
3688
3689 When the closure returns, the scheduler sends back a message which
3690 awakens the (C) thread.  
3691
3692 \ToDo{Do we need to worry about the garbage collector deallocating the
3693 thread if it gets blocked?}
3694
3695 \subsection{Switching Worlds}
3696 \label{sect:switching-worlds}
3697
3698 \ToDo{This has all changed: we always leave a closure on top of the
3699 stack if we mean to continue executing it.  The scheduler examines the
3700 top of the stack and tries to guess which world we want to be in.  If
3701 it finds a @BCO@, it certainly enters Hugs, if it finds a @GHC@
3702 closure, it certainly enters GHC and if it finds a standard closure,
3703 it is free to choose either one but it's probably best to enter GHC
3704 for everything except @BCO@s and perhaps @AP@s.}
3705
3706 Because this is a combined compiled/interpreted system, the
3707 interpreter will sometimes encounter compiled code, and vice-versa.
3708
3709 All world-switches go via the scheduler, ensuring that the world is in
3710 a known state ready to enter either compiled code or the interpreter.
3711 When a thread is run from the scheduler, the @whatNext@ field in the
3712 TSO (Section \ref{sect:TSO}) is checked to find out how to execute the
3713 thread.
3714
3715 \begin{itemize}
3716 \item If @whatNext@ is set to @ReturnGHC@, we load up the required
3717 registers from the TSO and jump to the address at the top of the user
3718 stack.
3719 \item If @whatNext@ is set to @EnterGHC@, we load up the required
3720 registers from the TSO and enter the closure pointed to by the top
3721 word of the stack.
3722 \item If @whatNext@ is set to @EnterHugs@, we enter the top thing on
3723 the stack, using the interpreter.
3724 \end{itemize}
3725
3726 There are four cases we need to consider:
3727
3728 \begin{enumerate}
3729 \item A GHC thread enters a Hugs-built closure.
3730 \item A GHC thread returns to a Hugs-compiled return address.
3731 \item A Hugs thread enters a GHC-built closure.
3732 \item A Hugs thread returns to a Hugs-compiled return address.
3733 \end{enumerate}
3734
3735 GHC-compiled modules cannot call functions in a Hugs-compiled module
3736 directly, because the compiler has no information about arities in the
3737 external module.  Therefore it must assume any top-level objects are
3738 CAFs, and enter their closures.
3739
3740 \ToDo{Hugs-built constructors?}
3741
3742 We now examine the various cases one by one and describe how the
3743 switch happens in each situation.
3744
3745 \subsection{A GHC thread enters a Hugs-built closure}
3746 \label{sect:ghc-to-hugs-switch}
3747
3748 There is three possibilities: GHC has entered a @PAP@, or it has
3749 entered a @AP@, or it has entered the BCO directly (for a top-level
3750 function closure).  @AP@s and @PAP@s are ``standard closures'' and
3751 so do not require us to enter the bytecode interpreter.
3752
3753 The entry code for a BCO does the following:
3754
3755 \begin{itemize}
3756 \item Push the address of the object entered on the stack.
3757 \item Save the current state of the thread in its TSO.
3758 \item Return to the scheduler, setting @whatNext@ to @EnterHugs@.
3759 \end{itemize}
3760
3761 BCO's for thunks and functions have the same entry conventions as
3762 slow entry points: they expect to find their arguments on the stac
3763 with unboxed arguments preceded by appropriate tags.
3764
3765 \subsection{A GHC thread returns to a Hugs-compiled return address}
3766 \label{sect:ghc-to-hugs-switch}
3767
3768 Hugs return addresses are laid out as in Figure
3769 \ref{fig:hugs-return-stack}.  If GHC is returning, it will return to
3770 the address at the top of the stack, namely @HUGS_RET@.  The code at
3771 @HUGS_RET@ performs the following:
3772
3773 \begin{itemize}
3774 \item pushes \Arg{1} (the return value) on the stack.
3775 \item saves the thread state in the TSO
3776 \item returns to the scheduler with @whatNext@ set to @EnterHugs@.
3777 \end{itemize}
3778
3779 \noindent When Hugs runs, it will enter the return value, which will
3780 return using the correct Hugs convention (Section
3781 \ref{sect:hugs-return-convention}) to the return address underneath it
3782 on the stack.
3783
3784 \subsection{A Hugs thread enters a GHC-compiled closure}
3785 \label{sect:hugs-to-ghc-switch}
3786
3787 Hugs can recognise a GHC-built closure as not being one of the
3788 following types of object:
3789
3790 \begin{itemize}
3791 \item A @BCO@,
3792 \item A @AP@,
3793 \item A @PAP@,
3794 \item An indirection, or
3795 \item A constructor.
3796 \end{itemize}
3797
3798 When Hugs is called on to enter a GHC closure, it executes the
3799 following sequence of instructions:
3800
3801 \begin{itemize}
3802 \item Push the address of the closure on the stack.
3803 \item Save the current state of the thread in the TSO.
3804 \item Return to the scheduler, with the @whatNext@ field set to
3805 @EnterGHC@.
3806 \end{itemize}
3807
3808 \subsection{A Hugs thread returns to a GHC-compiled return address}
3809 \label{sect:hugs-to-ghc-switch}
3810
3811 When Hugs encounters a return address on the stack that is not
3812 @HUGS_RET@, it knows that a world-switch is required.  At this point
3813 the stack contains a pointer to the return value, followed by the GHC
3814 return address.  The following sequence is then performed:
3815
3816 \begin{itemize}
3817 \item save the state of the thread in the TSO.
3818 \item return to the scheduler, setting @whatNext@ to @EnterGHC@.
3819 \end{itemize}
3820
3821 The first thing that GHC will do is enter the object on the top of the
3822 stack, which is a pointer to the return value.  This value will then
3823 return itself to the return address using the GHC return convention.
3824
3825
3826 \fi
3827
3828 \part{Implementation}
3829
3830 \section{Overview}
3831
3832 This part describes the inner workings of the major components of the system.
3833 Their external interfaces are described in the previous part.
3834
3835 The major components of the system are:
3836 \begin{itemize}
3837 \item The scheduler
3838 \item The loader
3839 \item The storage manager
3840 \item The machine code evaluator (compiled code)
3841 \item The bytecode evaluator (interpreted code)
3842 \end{itemize}
3843
3844 \iffalse
3845
3846 \section{Heap objects}
3847 \label{sect:heap-objects}
3848 \label{sect:fixed-header}
3849
3850 \ToDo{Fix this picture}
3851
3852 \begin{figure}
3853 \begin{center}
3854 \input{closure}
3855 \end{center}
3856 \caption{A closure}
3857 \label{fig:closure}
3858 \end{figure}
3859
3860 Every {\em heap object} is a contiguous block
3861 of memory, consisting of a fixed-format {\em header} followed
3862 by zero or more {\em data words}.
3863
3864 \ToDo{I absolutely do not believe that every heap object has a header
3865 like this - ADR.  I believe that they all have an info pointer but I
3866 see no readon why stack objects and unpointed heap objects would have
3867 an entry count since this will always be zero.}
3868
3869 The header consists of the following fields:
3870 \begin{itemize}
3871 \item A one-word {\em info pointer}, which points to
3872 the object's static {\em info table}.
3873 \item Zero or more {\em admin words} that support
3874 \begin{itemize}
3875 \item Profiling (notably a {\em cost centre} word).
3876   \note{We could possibly omit the cost centre word from some 
3877   administrative objects.}
3878 \item Parallelism (e.g. GranSim keeps the object's global address here,
3879 though GUM keeps a separate hash table).
3880 \item Statistics (e.g. a word to track how many times a thunk is entered.).
3881
3882 We add a Ticky word to the fixed-header part of closures.  This is
3883 used to indicate if a closure has been updated but not yet entered. It
3884 is set when the closure is updated and cleared when subsequently
3885 entered.
3886
3887 NB: It is {\em not} an ``entry count'', it is an
3888 ``entries-after-update count.''  The commoning up of @CONST@,
3889 @CHARLIKE@ and @INTLIKE@ closures is turned off(?) if this is
3890 required. This has only been done for 2s collection.
3891
3892 \end{itemize}
3893 \end{itemize}
3894
3895 Most of the RTS is completely insensitive to the number of admin words.
3896 The total size of the fixed header is @FIXED_HS@.
3897
3898 Many heap objects contain fields allowing them to be inserted onto lists
3899 during evaluation or during garbage collection. The lists required by
3900 the evaluator and storage manager are as follows.
3901
3902 \begin{itemize}
3903 \item 2 lists of threads: runnable threads and sleeping threads.
3904
3905 \item The {\em static object list} is a list of all statically
3906 allocated objects which might contain pointers into the heap.
3907 (Section~\ref{sect:static-objects}.)
3908
3909 \item The {\em updated thunk list} is a list of all thunks in the old
3910 generation which have been updated with an indirection.  
3911 (Section~\ref{sect:IND_OLDGEN}.)
3912
3913 \item The {\em mutables list} is a list of all other objects in the
3914 old generation which might contain pointers into the new generation.
3915 Most of the object on this list are ``mutable.''
3916 (Section~\ref{sect:mutables}.)
3917
3918 \item The {\em Foreign Object list} is a list of all foreign objects
3919  which have not yet been deallocated. (Section~\ref{sect:FOREIGN}.)
3920
3921 \item The {\em Spark pool} is a doubly(?) linked list of Spark objects
3922 maintained by the parallel system.  (Section~\ref{sect:SPARK}.)
3923
3924 \item The {\em Blocked Fetch list} (or
3925 lists?). (Section~\ref{sect:BLOCKED_FETCH}.)
3926
3927 \item For each thread, there is a list of all update frames on the
3928 stack.  (Section~\ref{sect:data-updates}.)
3929
3930
3931 \end{itemize}
3932
3933 \ToDo{The links for these fields are usually inserted immediately
3934 after the fixed header except ...}
3935
3936 \subsection{Info Tables}
3937
3938 An {\em info table} is a contiguous block of memory, {\em laid out
3939 backwards}.  That is, the first field in the list that follows
3940 occupies the highest memory address, and the successive fields occupy
3941 successive decreasing memory addresses.
3942
3943 \begin{center}
3944 \begin{tabular}{|c|}
3945    \hline Parallelism Info 
3946 \\ \hline Profile Info 
3947 \\ \hline Debug Info 
3948 \\ \hline Tag / Static reference table
3949 \\ \hline Storage manager layout info
3950 \\ \hline Closure type 
3951 \\ \hline entry code
3952 \\       \vdots
3953 \end{tabular}
3954 \end{center}
3955 An info table has the following contents (working backwards in memory
3956 addresses):
3957 \begin{itemize}
3958 \item The {\em entry code} for the closure.
3959 This code appears literally as the (large) last entry in the
3960 info table, immediately preceded by the rest of the info table.
3961 An {\em info pointer} always points to the first byte of the entry code.
3962
3963 \item A one-word {\em closure type field}, @INFO_TYPE@, identifies what kind
3964 of closure the object is.  The various types of closure are described
3965 in Section~\ref{sect:closures}.
3966 In some configurations, some useful properties of 
3967 closures (is it a HNF?  can it be sparked?)
3968 are represented as high-order bits so they can be tested quickly.
3969
3970 \item A single pointer or word --- the {\em storage manager info field},
3971 @INFO_SM@, contains auxiliary information describing the closure's
3972 precise layout, for the benefit of the garbage collector and the code
3973 that stuffs graph into packets for transmission over the network.
3974
3975 \item A one-word {\em Tag/Static Reference Table} field, @INFO_SRT@.
3976 For data constructors, this field contains the constructor tag, in the
3977 range $0..n-1$ where $n$ is the number of constructors.  For all other
3978 objects it contains a pointer to a table which enables the garbage
3979 collector to identify all accessible code and CAFs.  They are fully
3980 described in Section~\ref{sect:srt}.
3981
3982 \item {\em Profiling info\/}
3983
3984 Closure category records are attached to the info table of the
3985 closure. They are declared with the info table. We put pointers to
3986 these ClCat things in info tables.  We need these ClCat things because
3987 they are mutable, whereas info tables are immutable.  Hashing will map
3988 similar categories to the same hash value allowing statistics to be
3989 grouped by closure category.
3990
3991 Cost Centres and Closure Categories are hashed to provide indexes
3992 against which arbitrary information can be stored. These indexes are
3993 memoised in the appropriate cost centre or category record and
3994 subsequent hashes avoided by the index routine (it simply returns the
3995 memoised index).
3996
3997 There are different features which can be hashed allowing information
3998 to be stored for different groupings. Cost centres have the cost
3999 centre recorded (using the pointer), module and group. Closure
4000 categories have the closure description and the type
4001 description. Records with the same feature will be hashed to the same
4002 index value.
4003
4004 The initialisation routines, @init_index_<feature>@, allocate a hash
4005 table in which the cost centre / category records are stored. The
4006 lower bound for the table size is taken from @max_<feature>_no@. They
4007 return the actual table size used (the next power of 2). Unused
4008 locations in the hash table are indicated by a 0 entry. Successive
4009 @init_index_<feature>@ calls just return the actual table size.
4010
4011 Calls to @index_<feature>@ will insert the cost centre / category
4012 record in the @<feature>@ hash table, if not already inserted. The hash
4013 index is memoised in the record and returned. 
4014
4015 CURRENTLY ONLY ONE MEMOISATION SLOT IS AVILABLE IN EACH RECORD SO
4016 HASHING CAN ONLY BE DONE ON ONE FEATURE FOR EACH RECORD. This can be
4017 easily relaxed at the expense of extra memoisation space or continued
4018 rehashing.
4019
4020 The initialisation routines must be called before initialisation of
4021 the stacks and heap as they require to allocate storage. It is also
4022 expected that the caller may want to allocate additional storage in
4023 which to store profiling information based on the return table size
4024 value(s).
4025
4026 \begin{center}
4027 \begin{tabular}{|l|}
4028    \hline Hash Index
4029 \\ \hline Selected
4030 \\ \hline Kind
4031 \\ \hline Description String
4032 \\ \hline Type String
4033 \\ \hline
4034 \end{tabular}
4035 \end{center}
4036
4037 \begin{description}
4038 \item[Hash Index] Memoised copy
4039 \item[Selected] 
4040   Is this category selected (-1 == not memoised, selected? 0 or 1)
4041 \item[Kind]
4042 One of the following values (defined in CostCentre.lh):
4043
4044 \begin{description}
4045 \item[@CON_K@]
4046 A constructor.
4047 \item[@FN_K@]
4048 A literal function.
4049 \item[@PAP_K@]
4050 A partial application.
4051 \item[@THK_K@]
4052 A thunk, or suspension.
4053 \item[@BH_K@]
4054 A black hole.
4055 \item[@ARR_K@]
4056 An array.
4057 \item[@ForeignObj_K@]
4058 A Foreign object (non-Haskell heap resident).
4059 \item[@SPT_K@]
4060 The Stable Pointer table.  (There should only be one of these but it
4061 represents a form of weak space leak since it can't shrink to meet
4062 non-demand so it may be worth watching separately? ADR)
4063 \item[@INTERNAL_KIND@]
4064 Something internal to the runtime system.
4065 \end{description}
4066
4067
4068 \item[Description] Source derived string detailing closure description.
4069 \item[Type] Source derived string detailing closure type.
4070 \end{description}
4071
4072 \item {\em Parallelism info\/}
4073 \ToDo{}
4074
4075 \item {\em Debugging info\/}
4076 \ToDo{}
4077
4078 \end{itemize}
4079
4080
4081 %-----------------------------------------------------------------------------
4082 \subsection{Kinds of Heap Object}
4083 \label{sect:closures}
4084
4085 Heap objects can be classified in several ways, but one useful one is
4086 this:
4087 \begin{itemize}
4088 \item 
4089 {\em Static closures} occupy fixed, statically-allocated memory
4090 locations, with globally known addresses.
4091
4092 \item 
4093 {\em Dynamic closures} are individually allocated in the heap.
4094
4095 \item 
4096 {\em Stack closures} are closures allocated within a thread's stack
4097 (which is itself a heap object).  Unlike other closures, there are
4098 never any pointers to stack closures.  Stack closures are discussed in
4099 Section~\ref{sect:stacks}.
4100
4101 \end{itemize}
4102 A second useful classification is this:
4103 \begin{itemize}
4104 \item 
4105 {\em Executive objects}, such as thunks and data constructors,
4106 participate directly in a program's execution.  They can be subdivided into
4107 three kinds of objects according to their type:
4108 \begin{itemize}
4109 \item 
4110 {\em Pointed objects}, represent values of a {\em pointed} type
4111 (<.pointed types launchbury.>) --i.e.~a type that includes $\bottom$ such as @Int@ or @Int# -> Int#@.
4112
4113 \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#@.
4114
4115 \item {\em Activation frames}, represent ``continuations''.  They are
4116 always stored on the stack and are never pointed to by heap objects or
4117 passed as arguments.  \note{It's not clear if this will still be true
4118 once we support speculative evaluation.}
4119
4120 \end{itemize}
4121
4122 \item {\em Administrative objects}, such as stack objects and thread
4123 state objects, do not represent values in the original program.
4124 \end{itemize}
4125
4126 Only pointed objects can be entered.  All pointed objects share a
4127 common header format: the ``pointed header''; while all unpointed
4128 objects share a common header format: the ``unpointed header''.
4129 \ToDo{Describe the difference and update the diagrams to mention
4130 an appropriate header type.}
4131
4132 This section enumerates all the kinds of heap objects in the system.
4133 Each is identified by a distinct @INFO_TYPE@ tag in its info table.
4134
4135 \ToDo{Check this table very carefully}
4136
4137 \begin{tabular}{|l|l|l|l|l|l|l|l|l|l|l|}
4138 \hline
4139
4140 closure kind          & HNF & UPD & NS & STA & THU & MUT & UPT & BH & IND & Section \\
4141
4142 \hline                                                              
4143 {\em Pointed} \\ 
4144 \hline 
4145
4146 @CONSTR@              & 1 &   & 1 &   &   &   &   &   &   & \ref{sect:CONSTR}    \\
4147 @CONSTR_STATIC@       & 1 &   & 1 & 1 &   &   &   &   &   & \ref{sect:CONSTR}    \\
4148 @CONSTR_STATIC_NOCAF@ & 1 &   & 1 & 1 &   &   &   &   &   & \ref{sect:CONSTR}    \\
4149
4150 @FUN@                 & 1 &   & ? &   &   &   &   &   &   & \ref{sect:FUN}       \\
4151 @FUN_STATIC@          & 1 &   & ? & 1 &   &   &   &   &   & \ref{sect:FUN}       \\
4152
4153 @THUNK@               &   & 1 &   &   & 1 &   &   &   &   & \ref{sect:THUNK}     \\
4154 @THUNK_STATIC@        &   & 1 &   & 1 & 1 &   &   &   &   & \ref{sect:THUNK}     \\
4155 @THUNK_SELECTOR@      &   & 1 & 1 &   & 1 &   &   &   &   & \ref{sect:THUNK_SEL} \\
4156
4157 @BCO@                 & 1 &   & 1 &   &   &   &   &   &   & \ref{sect:BCO}       \\
4158 @BCO_CAF@             &   & 1 &   &   & 1 &   &   &   &   & \ref{sect:BCO}       \\
4159
4160 @AP@                  &   & 1 &   &   & 1 &   &   &   &   & \ref{sect:AP}        \\
4161 @PAP@                 & 1 &   & 1 &   &   &   &   &   &   & \ref{sect:PAP}       \\
4162
4163 @IND@                 & ? &   & ? &   & ? &   &   &   & 1 & \ref{sect:IND}       \\
4164 @IND_OLDGEN@          & ? &   & ? &   & ? &   &   &   & 1 & \ref{sect:IND}       \\
4165 @IND_PERM@            & ? &   & ? &   & ? &   &   &   & 1 & \ref{sect:IND}       \\
4166 @IND_OLDGEN_PERM@     & ? &   & ? &   & ? &   &   &   & 1 & \ref{sect:IND}       \\
4167 @IND_STATIC@          & ? &   & ? & 1 & ? &   &   &   & 1 & \ref{sect:IND}       \\
4168                                                          
4169 \hline                                                   
4170 {\em Unpointed} \\                                       
4171 \hline                                                   
4172                                                          
4173                                                          
4174 @ARR_WORDS@           & 1 &   & 1 &   &   &   & 1 &   &   & \ref{sect:ARR_WORDS1},\ref{sect:ARR_WORDS2} \\
4175 @ARR_PTRS@            & 1 &   & 1 &   &   &   & 1 &   &   & \ref{sect:ARR_PTRS}  \\
4176 @MUTVAR@              & 1 &   & 1 &   &   & 1 & 1 &   &   & \ref{sect:MUTVAR}    \\
4177 @MUTARR_PTRS@         & 1 &   & 1 &   &   & 1 & 1 &   &   & \ref{sect:MUTARR_PTRS} \\
4178 @MUTARR_PTRS_FROZEN@  & 1 &   & 1 &   &   & 1 & 1 &   &   & \ref{sect:MUTARR_PTRS_FROZEN} \\
4179                                                          
4180 @FOREIGN@             & 1 &   & 1 &   &   &   & 1 &   &   & \ref{sect:FOREIGN}   \\
4181                                                          
4182 @BH@                  &   & 1 & 1 &   & ? & ? &   & 1 & ? & \ref{sect:BH}        \\
4183 @MVAR@                & 1 &   & 1 &   &   &   &   &   &   & \ref{sect:MVAR}      \\
4184 @IVAR@                & 1 &   & 1 &   &   &   &   &   &   & \ref{sect:IVAR}      \\
4185 @FETCHME@             & 1 &   & 1 &   &   &   &   &   &   & \ref{sect:FETCHME}   \\
4186 \hline
4187 \end{tabular}
4188
4189 Activation frames do not live (directly) on the heap --- but they have
4190 a similar organisation.  The classification bits are all zero in
4191 activation frames.
4192
4193 \begin{tabular}{|l|l|}\hline
4194 closure kind            & Section                       \\ \hline
4195 @RET_SMALL@             & \ref{sect:activation-records} \\
4196 @RET_VEC_SMALL@         & \ref{sect:activation-records} \\
4197 @RET_BIG@               & \ref{sect:activation-records} \\
4198 @RET_VEC_BIG@           & \ref{sect:activation-records} \\
4199 @UPDATE_FRAME@          & \ref{sect:activation-records} \\
4200 \hline
4201 \end{tabular}
4202
4203 There are also a number of administrative objects.  The classification bits are
4204 all zero in administrative objects.
4205
4206 \begin{tabular}{|l|l|}\hline
4207 closure kind            & Section                       \\ \hline
4208 @TSO@                   & \ref{sect:TSO}                \\
4209 @STACK_OBJECT@          & \ref{sect:STACK_OBJECT}       \\
4210 @STABLEPTR_TABLE@       & \ref{sect:STABLEPTR_TABLE}    \\
4211 @SPARK_OBJECT@          & \ref{sect:SPARK}              \\
4212 @BLOCKED_FETCH@         & \ref{sect:BLOCKED_FETCH}      \\
4213 \hline
4214 \end{tabular}
4215
4216 \ToDo{I guess the parallel system has something like a stable ptr
4217 table.  Is there any opportunity for sharing code/data structures
4218 here?}
4219
4220
4221 \subsection{Classification bits}
4222
4223 The top bits of the @INFO_TYPE@ tag tells what sort of animal the
4224 closure is.
4225
4226 \begin{tabular}{|l|l|l|}                                                        \hline
4227 Abbrev & Bit & Interpretation                                                   \\ \hline
4228 HNF    & 0   & 1 $\Rightarrow$ Head normal form                                 \\
4229 UPD    & 4   & 1 $\Rightarrow$ May be updated (inconsistent with being a HNF)   \\ 
4230 NS     & 1   & 1 $\Rightarrow$ Don't spark me  (Any HNF will have this set to 1)\\
4231 STA    & 2   & 1 $\Rightarrow$ This is a static closure                         \\
4232 THU    & 8   & 1 $\Rightarrow$ Is a thunk                                       \\
4233 MUT    & 3   & 1 $\Rightarrow$ Has mutable pointer fields                       \\ 
4234 UPT    & 5   & 1 $\Rightarrow$ Has an unpointed type (eg a primitive array)     \\
4235 BH     & 6   & 1 $\Rightarrow$ Is a black hole                                  \\
4236 IND    & 7   & 1 $\Rightarrow$ Is an indirection                                \\
4237 \hline
4238 \end{tabular}
4239
4240 Updatable structures (@_UP@) are thunks that may be shared.  Primitive
4241 arrays (@_BM@ -- Big Mothers) are structures that are always held
4242 in-memory (basically extensions of a closure).  Because there may be
4243 offsets into these arrays, a primitive array cannot be handled as a
4244 FetchMe in the parallel system, but must be shipped in its entirety if
4245 its parent closure is shipped.
4246
4247 The other bits in the info-type field simply give a unique bit-pattern
4248 to identify the closure type.
4249
4250 \iffalse
4251 @
4252 #define _NF                     0x0001  /* Normal form  */
4253 #define _NS                     0x0002  /* Don't spark  */
4254 #define _ST                     0x0004  /* Is static    */
4255 #define _MU                     0x0008  /* Is mutable   */
4256 #define _UP                     0x0010  /* Is updatable (but not mutable) */
4257 #define _BM                     0x0020  /* Is a "primitive" array */
4258 #define _BH                     0x0040  /* Is a black hole */
4259 #define _IN                     0x0080  /* Is an indirection */
4260 #define _TH                     0x0100  /* Is a thunk */
4261
4262
4263
4264 SPEC    
4265 SPEC_N          SPEC | _NF | _NS
4266 SPEC_S          SPEC | _TH
4267 SPEC_U          SPEC | _UP | _TH
4268                 
4269 GEN     
4270 GEN_N           GEN | _NF | _NS
4271 GEN_S           GEN | _TH
4272 GEN_U           GEN | _UP | _TH
4273                 
4274 DYN             _NF | _NS
4275 TUPLE           _NF | _NS | _BM
4276 DATA            _NF | _NS | _BM
4277 MUTUPLE         _NF | _NS | _MU | _BM
4278 IMMUTUPLE       _NF | _NS | _BM
4279 STATIC          _NS | _ST
4280 CONST           _NF | _NS
4281 CHARLIKE        _NF | _NS
4282 INTLIKE         _NF | _NS
4283
4284 BH              _NS | _BH
4285 BH_N            BH
4286 BH_U            BH | _UP
4287                 
4288 BQ              _NS | _MU | _BH
4289 IND             _NS | _IN
4290 CAF             _NF | _NS | _ST | _IN
4291
4292 FM              
4293 FETCHME         FM | _MU
4294 FMBQ            FM | _MU | _BH
4295
4296 TSO             _MU
4297
4298 STKO    
4299 STKO_DYNAMIC    STKO | _MU
4300 STKO_STATIC     STKO | _ST
4301                 
4302 SPEC_RBH        _NS | _MU | _BH
4303 GEN_RBH         _NS | _MU | _BH
4304 BF              _NS | _MU | _BH
4305 INTERNAL        
4306
4307 @
4308 \fi
4309
4310 Notes:
4311
4312 An indirection either points to HNF (post update); or is result of
4313 overwriting a FetchMe, in which case the thing fetched is either
4314 under evaluation (BH), or by now an HNF.  Thus, indirections get NoSpark flag.
4315
4316
4317
4318 \subsection{Hugs Objects}
4319
4320 \subsubsection{Byte-Code Objects}
4321 \label{sect:BCO}
4322
4323 A Byte-Code Object (BCO) is a container for a a chunk of byte-code,
4324 which can be executed by Hugs.  The byte-code represents a
4325 supercombinator in the program: when hugs compiles a module, it
4326 performs lambda lifting and each resulting supercombinator becomes a
4327 byte-code object in the heap.
4328
4329 There are two kinds of BCO: a standard @BCO@ which has an arity of one
4330 or more, and a @BCO_CAF@ which takes no arguments and can be updated.
4331 When a @BCO_CAF@ is updated, the code is thrown away!
4332
4333 The semantics of BCOs are described in Section
4334 \ref{sect:hugs-heap-objects}.  A BCO has the following structure:
4335
4336 \begin{center}
4337 \begin{tabular}{|l|l|l|l|l|l|}
4338 \hline 
4339 \emph{Fixed Header} & \emph{Layout} & \emph{Offset} & \emph{Size} &
4340 \emph{Literals} & \emph{Byte code} \\
4341 \hline
4342 \end{tabular}
4343 \end{center}
4344
4345 \noindent where:
4346 \begin{itemize}
4347 \item The entry code is a static code fragment/info table that
4348 returns to the scheduler to invoke Hugs (Section
4349 \ref{sect:ghc-to-hugs-switch}).
4350 \item \emph{Layout} contains the number of pointer literals in the
4351 \emph{Literals} field.
4352 \item \emph{Offset} is the offset to the byte code from the start of
4353 the object.
4354 \item \emph{Size} is the number of words of byte code in the object.
4355 \item \emph{Literals} contains any pointer and non-pointer literals used in
4356 the byte-codes (including jump addresses), pointers first.
4357 \item \emph{Byte code} contains \emph{Size} words of non-pointer byte
4358 code.
4359 \end{itemize}
4360
4361 \subsection{Pointed Objects}
4362
4363 All pointed objects can be entered.
4364
4365 \subsubsection{Function closures}\label{sect:FUN}
4366
4367 Function closures represent lambda abstractions.  For example,
4368 consider the top-level declaration:
4369 @
4370   f = \x -> let g = \y -> x+y
4371             in g x
4372 @
4373 Both @f@ and @g@ are represented by function closures.  The closure
4374 for @f@ is {\em static} while that for @g@ is {\em dynamic}.
4375
4376 The layout of a function closure is as follows:
4377 \begin{center}
4378 \begin{tabular}{|l|l|l|l|}\hline
4379 {\em Fixed header}  & {\em Pointers} & {\em Non-pointers} \\ \hline
4380 \end{tabular}
4381 \end{center}
4382 The data words (pointers and non-pointers) are the free variables of
4383 the function closure.  
4384 The number of pointers
4385 and number of non-pointers are stored in the @INFO_SM@ word, in the least significant
4386 and most significant half-word respectively.
4387
4388 There are several different sorts of function closure, distinguished
4389 by their @INFO_TYPE@ field:
4390 \begin{itemize}
4391 \item @FUN@: a vanilla, dynamically allocated on the heap. 
4392
4393 \item $@FUN_@p@_@np$: to speed up garbage collection a number of
4394 specialised forms of @FUN@ are provided, for particular $(p,np)$ pairs,
4395 where $p$ is the number of pointers and $np$ the number of non-pointers.
4396
4397 \item @FUN_STATIC@.  Top-level, static, function closures (such as
4398 @f@ above) have a different
4399 layout than dynamic ones:
4400 \begin{center}
4401 \begin{tabular}{|l|l|l|}\hline
4402 {\em Fixed header}  & {\em Static object link} \\ \hline
4403 \end{tabular}
4404 \end{center}
4405 Static function closures have no free variables.  (However they may refer to other 
4406 static closures; these references are recorded in the function closure's SRT.)
4407 They have one field that is not present in dynamic closures, the {\em static object
4408 link} field.  This is used by the garbage collector in the same way that to-space
4409 is, to gather closures that have been determined to be live but that have not yet
4410 been scavenged.
4411 \note{Static function closures that have no static references, and hence
4412 a null SRT pointer, don't need the static object link field.  Is it worth
4413 taking advantage of this?  See @CONSTR_STATIC_NOCAF@.}
4414 \end{itemize}
4415
4416 Each lambda abstraction, $f$, in the STG program has its own private info table.
4417 The following labels are relevant:
4418 \begin{itemize}
4419 \item $f$@_info@  is $f$'s info table.
4420 \item $f$@_entry@ is $f$'s slow entry point (i.e. the entry code of its
4421 info table; so it will label the same byte as $f$@_info@).
4422 \item $f@_fast_@k$ is $f$'s fast entry point.  $k$ is the number of arguments
4423 $f$ takes; encoding this number in the fast-entry label occasionally catches some nasty
4424 code-generation errors.
4425 \end{itemize}
4426
4427 \subsubsection{Data Constructors}\label{sect:CONSTR}
4428
4429 Data-constructor closures represent values constructed with
4430 algebraic data type constructors.
4431 The general layout of data constructors is the same as that for function
4432 closures.  That is
4433 \begin{center}
4434 \begin{tabular}{|l|l|l|l|}\hline
4435 {\em Fixed header}  & {\em Pointers} & {\em Non-pointers} \\ \hline
4436 \end{tabular}
4437 \end{center}
4438
4439 The SRT pointer in a data constructor's info table is used for the
4440 constructor tag, since a constructor never has any static references.
4441
4442 There are several different sorts of constructor:
4443 \begin{itemize}
4444 \item @CONSTR@: a vanilla, dynamically allocated constructor.
4445 \item @CONSTR_@$p$@_@$np$: just like $@FUN_@p@_@np$.
4446 \item @CONSTR_INTLIKE@.
4447 A dynamically-allocated heap object that looks just like an @Int@.  The 
4448 garbage collector checks to see if it can common it up with one of a fixed
4449 set of static int-like closures, thus getting it out of the dynamic heap
4450 altogether.
4451
4452 \item @CONSTR_CHARLIKE@:  same deal, but for @Char@.
4453
4454 \item @CONSTR_STATIC@ is similar to @FUN_STATIC@, with the complication that
4455 the layout of the constructor must mimic that of a dynamic constructor,
4456 because a static constructor might be returned to some code that unpacks it.
4457 So its layout is like this:
4458 \begin{center}
4459 \begin{tabular}{|l|l|l|l|l|}\hline
4460 {\em Fixed header}  & {\em Pointers} & {\em Non-pointers} & {\em Static object link}\\ \hline
4461 \end{tabular}
4462 \end{center}
4463 The static object link, at the end of the closure, serves the same purpose
4464 as that for @FUN_STATIC@.  The pointers in the static constructor can point
4465 only to other static closures.
4466
4467 The static object link occurs last in the closure so that static
4468 constructors can store their data fields in exactly the same place as
4469 dynamic constructors.
4470
4471 \item @CONSTR_STATIC_NOCAF@.  A statically allocated data constructor
4472 that guarantees not to point (directly or indirectly) to any CAF
4473 (section~\ref{sect:CAF}).  This means it does not need a static object
4474 link field.  Since we expect that there might be quite a lot of static
4475 constructors this optimisation makes sense.  Furthermore, the @NOCAF@
4476 tag allows the compiler to indicate that no CAFs can be reached
4477 anywhere {\em even indirectly}.
4478
4479
4480 \end{itemize}
4481
4482 For each data constructor $Con$, two
4483 info tables are generated:
4484 \begin{itemize}
4485 \item $Con$@_info@ labels $Con$'s dynamic info table, 
4486 shared by all dynamic instances of the constructor.
4487 \item $Con$@_static@ labels $Con$'s static info table, 
4488 shared by all static instances of the constructor.
4489 \end{itemize}
4490
4491 \subsubsection{Thunks}
4492 \label{sect:THUNK}
4493 \label{sect:THUNK_SEL}
4494
4495 A thunk represents an expression that is not obviously in head normal 
4496 form.  For example, consider the following top-level definitions:
4497 @
4498   range = between 1 10
4499   f = \x -> let ys = take x range
4500             in sum ys
4501 @
4502 Here the right-hand sides of @range@ and @ys@ are both thunks; the former
4503 is static while the latter is dynamic.
4504
4505 The layout of a thunk is the same as that for a function closure,
4506 except that it may have some words of ``slop'' at the end to make sure
4507 that it has 
4508 at least @MIN_UPD_PAYLOAD@ words in addition to its
4509 fixed header.
4510 \begin{center}
4511 \begin{tabular}{|l|l|l|l|l|}\hline
4512 {\em Fixed header}  & {\em Pointers} & {\em Non-pointers} & {\em Slop} \\ \hline
4513 \end{tabular}
4514 \end{center}
4515 The @INFO_SM@ word contains the same information as for function
4516 closures; that is, number of pointers and number of non-pointers (excluding slop).
4517
4518 A thunk differs from a function closure in that it can be updated.
4519
4520 There are several forms of thunk:
4521 \begin{itemize}
4522 \item @THUNK@: a vanilla, dynamically allocated thunk.
4523 The garbage collection code for thunks whose
4524 pointer + non-pointer words is less than @MIN_UPD_PAYLOAD@ differs from
4525 that for function closures and data constructors, because the GC code
4526 has to account for the slop.
4527 \item $@THUNK_@p@_@np$.  Similar comments apply.
4528 \item @THUNK_STATIC@.  A static thunk is also known as 
4529 a {\em constant applicative form}, or {\em CAF}.
4530
4531 \begin{center}
4532 \begin{tabular}{|l|l|l|l|l|}\hline
4533 {\em Fixed header}  & {\em Pointers} & {\em Non-pointers} & {\em Slop} & {\em Static object link}\\ \hline
4534 \end{tabular}
4535 \end{center}
4536
4537 \item @THUNK_SELECTOR@ is a (dynamically allocated) thunk
4538 whose entry code performs a simple selection operation from
4539 a data constructor drawn from a single-constructor type.  For example,
4540 the thunk
4541 @
4542         x = case y of (a,b) -> a
4543 @
4544 is a selector thunk.  A selector thunk is laid out like this:
4545 \begin{center}
4546 \begin{tabular}{|l|l|l|l|}\hline
4547 {\em Fixed header}  & {\em Selectee pointer} \\ \hline
4548 \end{tabular}
4549 \end{center}
4550 The @INFO_SM@ word contains the byte offset of the desired word in
4551 the selectee.  Note that this is different from all other thunks.
4552
4553 The garbage collector ``peeks'' at the selectee's
4554 tag (in its info table).  If it is evaluated, then it goes ahead and do
4555 the selection, and then behaves just as if the selector thunk was an
4556 indirection to the selected field.
4557 If it is not
4558 evaluated, it treats the selector thunk like any other thunk of that
4559 shape.  [Implementation notes.  
4560 Copying: only the evacuate routine needs to be special.
4561 Compacting: only the PRStart (marking) routine needs to be special.]
4562 \end{itemize}
4563
4564
4565 The only label associated with a thunk is its info table:
4566 \begin{description}
4567 \item[$f$@_info@] is $f$'s info table.
4568 \end{description}
4569
4570
4571 \subsubsection{Partial applications (PAPs)}\label{sect:PAP}
4572
4573 A partial application (PAP) represents a function applied to too few arguments.
4574 It is only built as a result of updating after an argument-satisfaction
4575 check failure.  A PAP has the following shape:
4576 \begin{center}
4577 \begin{tabular}{|l|l|l|l|}\hline
4578 {\em Fixed header}  & {\em No of arg words} & {\em Function closure} & {\em Arg stack} \\ \hline
4579 \end{tabular}
4580 \end{center}
4581 The ``arg stack'' is a copy of the chunk of stack above the update
4582 frame; ``no of arg words'' tells how many words it consists of.  The
4583 function closure is (a pointer to) the closure for the function whose
4584 argument-satisfaction check failed.
4585
4586 There is just one standard form of PAP with @INFO_TYPE@ = @PAP@.
4587 There is just one info table too, called @PAP_info@.
4588 Its entry code simply copies the arg stack chunk back on top of the
4589 stack and enters the function closure.  (It has to do a stack overflow test first.)
4590
4591 PAPs are also used to implement Hugs functions (where the arguments are free variables).
4592 PAPs generated by Hugs can be static.
4593
4594 \subsubsection{@AP@ objects}
4595 \label{sect:AP}
4596
4597 @AP@ objects are used to represent thunks built by Hugs.  The only distintion between
4598 an @AP@ and a @PAP@ is that an @AP@ is updateable.
4599
4600 \begin{center}
4601 \begin{tabular}{|l|l|l|l|}
4602 \hline
4603 \emph{Fixed Header} & {\em No of arg words} & {\em Function closure} & {\em Arg stack} \\
4604 \hline
4605 \end{tabular}
4606 \end{center}
4607
4608 The entry code pushes an update frame, copies the arg stack chunk on
4609 top of the stack, and enters the function closure.  (It has to do a
4610 stack overflow test first.)
4611
4612 The ``arg stack'' is a block of (tagged) arguments representing the
4613 free variables of the thunk; ``no of arg words'' tells how many words
4614 it consists of.  The function closure is (a pointer to) the closure
4615 for the thunk.  The argument stack may be empty if the thunk has no
4616 free variables.
4617
4618
4619 \subsubsection{Indirections}
4620 \label{sect:IND}
4621 \label{sect:IND_OLDGEN}
4622
4623 Indirection closures just point to other closures. They are introduced
4624 when a thunk is updated to point to its value. 
4625 The entry code for all indirections simply enters the closure it points to.
4626
4627 There are several forms of indirection:
4628 \begin{description}
4629 \item[@IND@] is the vanilla, dynamically-allocated indirection.
4630 It is removed by the garbage collector. It has the following
4631 shape:
4632 \begin{center}
4633 \begin{tabular}{|l|l|l|}\hline
4634 {\em Fixed header} & {\em Target closure} \\ \hline
4635 \end{tabular}
4636 \end{center}
4637
4638 \item[@IND_OLDGEN@] is the indirection used to update an old-generation
4639 thunk. Its shape is like this:
4640 \begin{center}
4641 \begin{tabular}{|l|l|l|}\hline
4642 {\em Fixed header} & {\em Mutable link field} & {\em Target closure} \\ \hline
4643 \end{tabular}
4644 \end{center}
4645 It contains a {\em mutable link field} that is used to string together
4646 all old-generation indirections that might have a pointer into
4647 the new generation.
4648
4649
4650 \item[@IND_PERMANENT@ and @IND_OLDGEN_PERMANENT@.]
4651 for lexical profiling, it is necessary to maintain cost centre
4652 information in an indirection, so ``permanent indirections'' are
4653 retained forever.  Otherwise they are just like vanilla indirections.
4654 \note{If a permanent indirection points to another permanent
4655 indirection or a @CONST@ closure, it is possible to elide the indirection
4656 since it will have no effect on the profiler.}
4657 \note{Do we still need @IND@ and @IND_OLDGEN@
4658 in the profiling build, or can we just make
4659 do with one pair whose behaviour changes when profiling is built?}
4660
4661 \item[@IND_STATIC@] is used for overwriting CAFs when they have been
4662 evaluated.  Static indirections are not removed by the garbage
4663 collector; and are statically allocated outside the heap (and should
4664 stay there).  Their static object link field is used just as for
4665 @FUN_STATIC@ closures.
4666
4667 \begin{center}
4668 \begin{tabular}{|l|l|l|}
4669 \hline
4670 {\em Fixed header} & {\em Target closure} & {\em Static object link} \\
4671 \hline
4672 \end{tabular}
4673 \end{center}
4674
4675 \end{description}
4676
4677 \subsubsection{Activation Records}
4678
4679 Activation records are parts of the stack described by return address
4680 info tables (closures with @INFO_TYPE@ values of @RET_SMALL@,
4681 @RET_VEC_SMALL@, @RET_BIG@ and @RET_VEC_BIG@). They are described in
4682 section~\ref{sect:activation-records}.
4683
4684
4685 \subsubsection{Black holes, MVars and IVars}
4686 \label{sect:BH}
4687 \label{sect:MVAR}
4688 \label{sect:IVAR}
4689
4690 Black hole closures are used to overwrite closures currently being
4691 evaluated. They inform the garbage collector that there are no live
4692 roots in the closure, thus removing a potential space leak.  
4693
4694 Black holes also become synchronization points in the threaded world.
4695 They contain a pointer to a list of blocked threads to be awakened
4696 when the black hole is updated (or @NULL@ if the list is empty).
4697 \begin{center}
4698 \begin{tabular}{|l|l|l|}
4699 \hline 
4700 {\em Fixed header} & {\em Mutable link} & {\em Blocked thread link} \\
4701 \hline
4702 \end{tabular}
4703 \end{center}
4704 The {\em Blocked thread link} points to the TSO of the first thread
4705 waiting for the value of this thunk.  All subsequent TSOs in the list
4706 are linked together using their @TSO_LINK@ field.
4707
4708 When the blocking queue is non-@NULL@, the black hole must be added to
4709 the mutables list since the TSOs on the list may contain pointers into
4710 the new generation.  There is no need to clutter up the mutables list
4711 with black holes with empty blocking queues.
4712
4713 \ToDo{MVars}
4714
4715
4716 \subsubsection{FetchMes}\label{sect:FETCHME}
4717
4718 In the parallel systems, FetchMes are used to represent pointers into
4719 the global heap.  When evaluated, the value they point to is read from
4720 the global heap.
4721
4722 \ToDo{Describe layout}
4723
4724
4725 \subsection{Unpointed Objects}
4726
4727 A variable of unpointed type is always bound to a {\em value}, never to a {\em thunk}.
4728 For this reason, unpointed objects cannot be entered.
4729
4730 A {\em value} may be:
4731 \begin{itemize}
4732 \item {\em Boxed}, i.e.~represented indirectly by a pointer to a heap object (e.g.~foreign objects, arrays); or
4733 \item {\em Unboxed}, i.e.~represented directly by a bit-pattern in one or more registers (e.g.~@Int#@ and @Float#@).
4734 \end{itemize}
4735 All {\em pointed} values are {\em boxed}.  
4736
4737 \subsubsection{Immutable Objects}
4738 \label{sect:ARR_WORDS1}
4739 \label{sect:ARR_PTRS}
4740
4741 \begin{description}
4742 \item[@ARR_WORDS@] is a variable-sized object consisting solely of
4743 non-pointers.  It is used for arrays of all
4744 sorts of things (bytes, words, floats, doubles... it doesn't matter).
4745 \begin{center}
4746 \begin{tabular}{|c|c|c|c|}
4747 \hline
4748 {\em Fixed Hdr} & {\em No of non-pointers} & {\em Non-pointers\ldots}   \\ \hline
4749 \end{tabular}
4750 \end{center}
4751
4752 \item[@ARR_PTRS@] is an immutable, variable sized array of pointers.
4753 \begin{center}
4754 \begin{tabular}{|c|c|c|c|}
4755 \hline
4756 {\em Fixed Hdr} & {\em Mutable link} & {\em No of pointers} & {\em Pointers\ldots}      \\ \hline
4757 \end{tabular}
4758 \end{center}
4759 The mutable link is present so that we can easily freeze and thaw an
4760 array (by changing the header and adding/removing the array to the
4761 mutables list).
4762
4763 \end{description}
4764
4765 \subsubsection{Mutable Objects}
4766 \label{sect:mutables}
4767 \label{sect:ARR_WORDS2}
4768 \label{sect:MUTVAR}
4769 \label{sect:MUTARR_PTRS}
4770 \label{sect:MUTARR_PTRS_FROZEN}
4771
4772 Some of these objects are {\em mutable}; they represent objects which
4773 are explicitly mutated by Haskell code through the @ST@ monad.
4774 They're not used for thunks which are updated precisely once.
4775 Depending on the garbage collector, mutable closures may contain extra
4776 header information which allows a generational collector to implement
4777 the ``write barrier.''
4778
4779 \begin{description}
4780
4781 \item[@ARR_WORDS@] is also used to represent {\em mutable} arrays of
4782 bytes, words, floats, doubles, etc.  It's possible to use the same
4783 object type because even generational collectors don't need to
4784 distinguish them.
4785
4786 \item[@MUTVAR@] is a mutable variable.
4787 \begin{center}
4788 \begin{tabular}{|c|c|c|}
4789 \hline
4790 {\em Fixed Hdr} & {\em Mutable link} & {\em Pointer} \\ \hline
4791 \end{tabular}
4792 \end{center}
4793
4794 \item[@MUTARR_PTRS@] is a mutable array of pointers.
4795 Such an array may be {\em frozen}, becoming an @SM_MUTARR_PTRS_FROZEN@, with a
4796 different info-table.
4797 \begin{center}
4798 \begin{tabular}{|c|c|c|c|}
4799 \hline
4800 {\em Fixed Hdr} & {\em Mutable link} & {\em No of ptrs} & {\em Pointers\ldots} \\ \hline
4801 \end{tabular}
4802 \end{center}
4803
4804 \item[@MUTARR_PTRS_FROZEN@] is a frozen @MUTARR_PTRS@ closure.
4805 The garbage collector converts @MUTARR_PTRS_FROZEN@ to @ARR_PTRS@ as it removes them from
4806 the mutables list.
4807
4808 \end{description}
4809
4810
4811 \subsubsection{Foreign Objects}\label{sect:FOREIGN}
4812
4813 Here's what a ForeignObj looks like:
4814
4815 \begin{center}
4816 \begin{tabular}{|l|l|l|l|}
4817 \hline 
4818 {\em Fixed header} & {\em Data} & {\em Free Routine} & {\em Foreign object link} \\
4819 \hline
4820 \end{tabular}
4821 \end{center}
4822
4823 The @FreeRoutine@ is a reference to the finalisation routine to call
4824 when the @ForeignObj@ becomes garbage.  If @freeForeignObject@ is
4825 called on a Foreign Object, the @FreeRoutine@ is set to zero and the
4826 garbage collector will not attempt to call @FreeRoutine@ when the 
4827 object becomes garbage.
4828
4829 The Foreign object link is a link to the next foreign object in the
4830 list.  This list is traversed at the end of garbage collection: if an
4831 object is about to be deallocated (e.g.~it was not marked or
4832 evacuated), the free routine is called and the object is deleted from
4833 the list.  
4834
4835
4836 The remaining objects types are all administrative --- none of them may be entered.
4837
4838 \subsection{Thread State Objects (TSOs)}\label{sect:TSO}
4839
4840 In the multi-threaded system, the state of a suspended thread is
4841 packed up into a Thread State Object (TSO) which contains all the
4842 information needed to restart the thread and for the garbage collector
4843 to find all reachable objects.  When a thread is running, it may be
4844 ``unpacked'' into machine registers and various other memory locations
4845 to provide faster access.
4846
4847 Single-threaded systems don't really {\em need\/} TSOs --- but they do
4848 need some way to tell the storage manager about live roots so it is
4849 convenient to use a single TSO to store the mutator state even in
4850 single-threaded systems.
4851
4852 Rather than manage TSOs' alloc/dealloc, etc., in some {\em ad hoc}
4853 way, we instead alloc/dealloc/etc them in the heap; then we can use
4854 all the standard garbage-collection/fetching/flushing/etc machinery on
4855 them.  So that's why TSOs are ``heap objects,'' albeit very special
4856 ones.
4857 \begin{center}
4858 \begin{tabular}{|l|l|}
4859    \hline {\em Fixed header}
4860 \\ \hline @TSO_LINK@
4861 \\ \hline @TSO_WHATNEXT@
4862 \\ \hline @TSO_WHATNEXT_INFO@ 
4863 \\ \hline @TSO_STACK@ 
4864 \\ \hline {\em Exception Handlers}
4865 \\ \hline {\em Ticky Info}
4866 \\ \hline {\em Profiling Info}
4867 \\ \hline {\em Parallel Info}
4868 \\ \hline {\em GranSim Info}
4869 \\ \hline
4870 \end{tabular}
4871 \end{center}
4872 The contents of a TSO are:
4873 \begin{itemize}
4874
4875 \item A pointer (@TSO_LINK@) used to maintain a list of threads with a similar
4876   state (e.g.~all runnable, all sleeping, all blocked on the same black
4877   hole, all blocked on the same MVar, etc.)
4878
4879 \item A word (@TSO_WHATNEXT@) which is in suspended threads to record
4880  how to awaken it.  This typically requires a program counter which is stored
4881  in the pointer @TSO_WHATNEXT_INFO@
4882
4883 \item A pointer (@TSO_STACK@) to the top stack block.
4884
4885 \item Optional information for ``Ticky Ticky'' statistics: @TSO_STK_HWM@ is
4886   the maximum number of words allocated to this thread.
4887
4888 \item Optional information for profiling: 
4889   @TSO_CCC@ is the current cost centre.
4890
4891 \item Optional information for parallel execution:
4892 \begin{itemize}
4893
4894 \item The types of threads (@TSO_TYPE@):
4895 \begin{description}
4896 \item[@T_MAIN@]     Must be executed locally.
4897 \item[@T_REQUIRED@] A required thread  -- may be exported.
4898 \item[@T_ADVISORY@] An advisory thread -- may be exported.
4899 \item[@T_FAIL@]     A failure thread   -- may be exported.
4900 \end{description}
4901
4902 \item I've no idea what else
4903
4904 \end{itemize}
4905
4906 \item Optional information for GranSim execution:
4907 \begin{itemize}
4908 \item locked         
4909 \item sparkname  
4910 \item started at         
4911 \item exported   
4912 \item basic blocks       
4913 \item allocs     
4914 \item exectime   
4915 \item fetchtime  
4916 \item fetchcount         
4917 \item blocktime  
4918 \item blockcount         
4919 \item global sparks      
4920 \item local sparks       
4921 \item queue              
4922 \item priority   
4923 \item clock          (gransim light only)
4924 \end{itemize}
4925
4926
4927 Here are the various queues for GrAnSim-type events.
4928 @
4929 Q_RUNNING   
4930 Q_RUNNABLE  
4931 Q_BLOCKED   
4932 Q_FETCHING  
4933 Q_MIGRATING 
4934 @
4935
4936 \end{itemize}
4937
4938 \subsection{Other weird objects}
4939 \label{sect:SPARK}
4940 \label{sect:BLOCKED_FETCH}
4941
4942 \begin{description}
4943 \item[@BlockedFetch@ heap objects (`closures')] (parallel only)
4944
4945 @BlockedFetch@s are inbound fetch messages blocked on local closures.
4946 They arise as entries in a local blocking queue when a fetch has been
4947 received for a local black hole.  When awakened, we look at their
4948 contents to figure out where to send a resume.
4949
4950 A @BlockedFetch@ closure has the form:
4951 \begin{center}
4952 \begin{tabular}{|l|l|l|l|l|l|}\hline
4953 {\em Fixed header} & link & node & gtid & slot & weight \\ \hline
4954 \end{tabular}
4955 \end{center}
4956
4957 \item[Spark Closures] (parallel only)
4958
4959 Spark closures are used to link together all closures in the spark pool.  When
4960 the current processor is idle, it may choose to speculatively evaluate some of
4961 the closures in the pool.  It may also choose to delete sparks from the pool.
4962 \begin{center}
4963 \begin{tabular}{|l|l|l|l|l|l|}\hline
4964 {\em Fixed header} & {\em Spark pool link} & {\em Sparked closure} \\ \hline
4965 \end{tabular}
4966 \end{center}
4967
4968
4969 \end{description}
4970
4971
4972 \subsection{Stack Objects}
4973 \label{sect:STACK_OBJECT}
4974 \label{sect:stacks}
4975
4976 These are ``stack objects,'' which are used in the threaded world as
4977 the stack for each thread is allocated from the heap in smallish
4978 chunks.  (The stack in the sequential world is allocated outside of
4979 the heap.)
4980
4981 Each reduction thread has to have its own stack space.  As there may
4982 be many such threads, and as any given one may need quite a big stack,
4983 a naive give-'em-a-big-stack-and-let-'em-run approach will cost a {\em
4984 lot} of memory.
4985
4986 Our approach is to give a thread a small stack space, and then link
4987 on/off extra ``chunks'' as the need arises.  Again, this is a
4988 storage-management problem, and, yet again, we choose to graft the
4989 whole business onto the existing heap-management machinery.  So stack
4990 objects will live in the heap, be garbage collected, etc., etc..
4991
4992 A stack object is laid out like this:
4993
4994 \begin{center}
4995 \begin{tabular}{|l|}
4996 \hline
4997 {\em Fixed header} 
4998 \\ \hline
4999 {\em Link to next stack object (0 for last)}
5000 \\ \hline
5001 {\em N, the payload size in words}
5002 \\ \hline
5003 {\em @Sp@ (byte offset from head of object)}
5004 \\ \hline
5005 {\em @Su@ (byte offset from head of object)}
5006 \\ \hline
5007 {\em Payload (N words)}
5008 \\ \hline
5009 \end{tabular}
5010 \end{center}
5011
5012 \ToDo{Are stack objects on the mutable list?}
5013
5014 The stack grows downwards, towards decreasing
5015 addresses.  This makes it easier to print out the stack
5016 when debugging, and it means that a return address is
5017 at the lowest address of the chunk of stack it ``knows about''
5018 just like an info pointer on a closure.
5019
5020 The garbage collector needs to be able to find all the
5021 pointers in a stack.  How does it do this?
5022
5023 \begin{itemize}
5024
5025 \item Within the stack there are return addresses, pushed
5026 by @case@ expressions.  Below a return address (i.e. at higher
5027 memory addresses, since the stack grows downwards) is a chunk
5028 of stack that the return address ``knows about'', namely the
5029 activation record of the currently running function.
5030
5031 \item Below each such activation record is a {\em pending-argument
5032 section}, a chunk of
5033 zero or more words that are the arguments to which the result
5034 of the function should be applied.  The return address does not
5035 statically
5036 ``know'' how many pending arguments there are, or their types.
5037 (For example, the function might return a result of type $\alpha$.)
5038
5039 \item Below each pending-argument section is another return address,
5040 and so on.  Actually, there might be an update frame instead, but we
5041 can consider update frames as a special case of a return address with
5042 a well-defined activation record.
5043
5044 \ToDo{Doesn't it {\em have} to be an update frame?  After all, the arg
5045 satisfaction check is @Su - Sp >= ...@.}
5046
5047 \end{itemize}
5048
5049 The game plan is this.  The garbage collector
5050 walks the stack from the top, traversing pending-argument sections and
5051 activation records alternately.  Next we discuss how it finds
5052 the pointers in each of these two stack regions.
5053
5054
5055 \subsubsection{Activation records}\label{sect:activation-records}
5056
5057 An {\em activation record} is a contiguous chunk of stack,
5058 with a return address as its first word, followed by as many
5059 data words as the return address ``knows about''.  The return
5060 address is actually a fully-fledged info pointer.  It points
5061 to an info table, replete with:
5062
5063 \begin{itemize}
5064 \item entry code (i.e. the code to return to).
5065 \item @INFO_TYPE@ is either @RET_SMALL/RET_VEC_SMALL@ or @RET_BIG/RET_VEC_BIG@, depending
5066 on whether the activation record has more than 32 data words (\note{64 for 8-byte-word architectures}) and on whether 
5067 to use a direct or a vectored return.
5068 \item @INFO_SM@ for @RET_SMALL@ is a bitmap telling the layout
5069 of the activation record, one bit per word.  The least-significant bit
5070 describes the first data word of the record (adjacent to the fixed
5071 header) and so on.  A ``@1@'' indicates a non-pointer, a ``@0@''
5072 indicates
5073 a pointer.  We don't need to indicate exactly how many words there
5074 are,
5075 because when we get to all zeros we can treat the rest of the 
5076 activation record as part of the next pending-argument region.
5077
5078 For @RET_BIG@ the @INFO_SM@ field points to a block of bitmap
5079 words, starting with a word that tells how many words are in
5080 the block.
5081
5082 \item @INFO_SRT@ is the Static Reference Table for the return
5083 address (Section~\ref{sect:srt}).
5084 \end{itemize}
5085
5086 The activation record is a fully fledged closure too.
5087 As well as an info pointer, it has all the other attributes of
5088 a fixed header (Section~\ref{sect:fixed-header}) including a saved cost
5089 centre which is reloaded when the return address is entered.
5090
5091 In other words, all the attributes of closures are needed for
5092 activation records, so it's very convenient to make them look alike.
5093
5094
5095 \subsubsection{Pending arguments}
5096
5097 So that the garbage collector can correctly identify pointers
5098 in pending-argument sections we explicitly tag all non-pointers.
5099 Every non-pointer in a pending-argument section is preceded
5100 (at the next lower memory word) by a one-word byte count that
5101 says how many bytes to skip over (excluding the tag word).
5102
5103 The garbage collector traverses a pending argument section from 
5104 the top (i.e. lowest memory address).  It looks at each word in turn:
5105
5106 \begin{itemize}
5107 \item If it is less than or equal to a small constant @MAX_STACK_TAG@
5108 then
5109 it treats it as a tag heralding zero or more words of non-pointers,
5110 so it just skips over them.
5111
5112 \item If it points to the code segment, it must be a return
5113 address, so we have come to the end of the pending-argument section.
5114
5115 \item Otherwise it must be a bona fide heap pointer.
5116 \end{itemize}
5117
5118
5119 \subsection{The Stable Pointer Table}\label{sect:STABLEPTR_TABLE}
5120
5121 A stable pointer is a name for a Haskell object which can be passed to
5122 the external world.  It is ``stable'' in the sense that the name does
5123 not change when the Haskell garbage collector runs---in contrast to
5124 the address of the object which may well change.
5125
5126 A stable pointer is represented by an index into the
5127 @StablePointerTable@.  The Haskell garbage collector treats the
5128 @StablePointerTable@ as a source of roots for GC.
5129
5130 In order to provide efficient access to stable pointers and to be able
5131 to cope with any number of stable pointers (eg $0 \ldots 100000$), the
5132 table of stable pointers is an array stored on the heap and can grow
5133 when it overflows.  (Since we cannot compact the table by moving
5134 stable pointers about, it seems unlikely that a half-empty table can
5135 be reduced in size---this could be fixed if necessary by using a
5136 hash table of some sort.)
5137
5138 In general a stable pointer table closure looks like this:
5139
5140 \begin{center}
5141 \begin{tabular}{|l|l|l|l|l|l|l|l|l|l|l|}
5142 \hline
5143 {\em Fixed header} & {\em No of pointers} & {\em Free} & $SP_0$ & \ldots & $SP_{n-1}$ 
5144 \\\hline
5145 \end{tabular}
5146 \end{center}
5147
5148 The fields are:
5149 \begin{description}
5150
5151 \item[@NPtrs@:] number of (stable) pointers.
5152
5153 \item[@Free@:] the byte offset (from the first byte of the object) of the first free stable pointer.
5154
5155 \item[$SP_i$:] A stable pointer slot.  If this entry is in use, it is
5156 an ``unstable'' pointer to a closure.  If this entry is not in use, it
5157 is a byte offset of the next free stable pointer slot.
5158
5159 \end{description}
5160
5161 When a stable pointer table is evacuated
5162 \begin{enumerate}
5163 \item the free list entries are all set to @NULL@ so that the evacuation
5164   code knows they're not pointers;
5165
5166 \item The stable pointer slots are scanned linearly: non-@NULL@ slots
5167 are evacuated and @NULL@-values are chained together to form a new free list.
5168 \end{enumerate}
5169
5170 There's no need to link the stable pointer table onto the mutable
5171 list because we always treat it as a root.
5172
5173 \fi
5174
5175 \section{The Storage Manager}
5176
5177 The generational collector remembers the depth of the last generation
5178 collected and the value of the heap pointer at the end of the last GC.
5179 If the mutator has not moved the heap pointer, that means that the
5180 amount of space recovered is insufficient to satisfy even one request
5181 and it is time to collect an older generation or report a heap overflow.
5182
5183 A deeper collection is also triggered when a minor collection fails to
5184 recover at least @...@ bytes of space.
5185
5186 When can a GC happen?
5187
5188 @
5189 - During updates (ie during returns)
5190 - When a heap check fails
5191 - When a stack check fails (concurrent system only)
5192 - When a context switch happens (concurrent system only)
5193
5194 When do heap checks occur?
5195 - Immediately after entering a thunk
5196 - Immediately after entering a case alternative
5197
5198 When do stack checks occur?
5199 - We calculate the worst-case stack usage of an entire
5200   thunk so there's no need to put a check inside each alternative.
5201 - Immediately after entering a thunk
5202   We can't make a similar worst-case calculation for heap usage
5203   because the heap isn't used in a stacklike manner so any
5204   evaluation inside a case might steal some of the heap we've
5205   checked for.
5206
5207 Concurrency
5208 - Threads can be blocked
5209 - Threads can be put to sleep
5210   - Heap may move while we sleep
5211   - Black holing may happen while we sleep (ie during GC)
5212 @
5213
5214 \subsection{The SM state}
5215
5216 Contains @Hp@, @HpLim@, @StablePtrTable@ plus version-specific info.
5217
5218 \begin{itemize}
5219
5220 \item Static Object list 
5221 \item Foreign Object list
5222 \item Stable Pointer Table
5223
5224 \end{itemize}
5225
5226 In addition, the generational collector requires:
5227
5228 \begin{itemize}
5229
5230 \item Old Generation Indirection list
5231 \item Mutables list --- list of mutable objects in the old generation.
5232 \item @OldLim@ --- the boundary between the generations
5233 \item Old Foreign Object list --- foreign objects in the old generation
5234
5235 \end{itemize}
5236
5237 It is passed a table of {\em roots\/} containing
5238
5239 \begin{itemize}
5240
5241 \item All runnable TSOs
5242
5243 \end{itemize}
5244
5245
5246 In the parallel system, there must be some extra magic associated with
5247 global GC.
5248
5249 \subsection{The SM interface}
5250
5251 @initSM@ finalizes any runtime parameters of the storage manager.
5252
5253 @exitSM@ does any cleaning up required by the storage manager before
5254 the program is executed. Its main purpose is to print any summary
5255 statistics.
5256
5257 @initHeap@ allocates the heap. It initialises the @hp@ and @hplim@
5258 fields of @sm@ to represent an empty heap for the compiled-in garbage
5259 collector.  It also initialises @CAFlist@ to be the empty list. If we
5260 are using Appel's collector it also initialises the @OldLim@ field.
5261 It also initialises the stable pointer table and the @ForeignObjList@
5262 (and @OldForeignObjList@) fields.
5263
5264 @collectHeap@ invokes the garbage collector.  @collectHeap@ requires
5265 all the fields of @sm@ to be initialised appropriately (from the
5266 STG-machine registers).  The following are identified as heap roots:
5267 \begin{itemize}
5268 \item The updated CAFs recorded in @CAFlist@.
5269 \item Any pointers found on the stack.
5270 \item All runnable and sleeping TSOs.
5271 \item The stable pointer table.
5272 \end{itemize}
5273
5274 There are two possible results from a garbage collection:
5275 \begin{description} 
5276 \item[@GC_FAIL@] 
5277 The garbage collector is unable to free up any more space.
5278
5279 \item[@GC_SUCCESS@]
5280 The garbage collector managed to free up more space.
5281
5282 \begin{itemize} 
5283 \item @hp@ and @hplim@ will indicate the new space available for
5284 allocation.
5285
5286 \item The elements of @CAFlist@ and the stable pointers will be
5287 updated to point to the new locations of the closures they reference.
5288
5289 \item Any members of @ForeignObjList@ which became garbage should have
5290 been reported (by calling their finalising routines; and the
5291 @(Old)ForeignObjList@ updated to contain only those Foreign objects
5292 which are still live.  
5293
5294 \end{itemize}
5295
5296 \end{description}
5297
5298 %************************************************************************
5299 %*                                                                      *
5300 \subsection{``What really happens in a garbage collection?''}
5301 %*                                                                      *
5302 %************************************************************************
5303
5304 \ToDo{I commented out this long, out of date section - ADR}
5305
5306 \iffalse
5307
5308 This is a brief tutorial on ``what really happens'' going to/from the
5309 storage manager in a garbage collection.
5310
5311 \begin{description}
5312 %------------------------------------------------------------------------
5313 \item[The heap check:]
5314
5315 [OLD-ISH: WDP]
5316
5317 If you gaze into the C output of GHC, you see many macros calls like:
5318 \begin{verbatim}
5319 HEAP_CHK_2PtrsLive((_FHS+2));
5320 \end{verbatim}
5321
5322 This expands into the C (roughly speaking...):
5323 @
5324 Hp = Hp + (_FHS+2);     /* optimistically move heap pointer forward */
5325
5326 GC_WHILE_OR_IF (HEAP_OVERFLOW_OP(Hp, HpLim) OR_INTERVAL_EXPIRED) {
5327         STGCALL2_GC(PerformGC, <liveness-bits>, (_FHS+2));
5328 }
5329 @
5330
5331 In the parallel world, where we will need to re-try the heap check,
5332 @GC_WHILE_OR_IF@ will be a ``while''; in the sequential world, it will
5333 be an ``if''.
5334
5335 The ``heap lookahead'' checks, which are similar and used for
5336 multi-precision @Integer@ ops, have some further complications.  See
5337 the commentary there (@StgMacros.lh@).
5338
5339 %------------------------------------------------------------------------
5340 \item[Into @callWrapper_GC@...:]
5341
5342 When we failed the heap check (above), we were inside the
5343 GCC-registerised ``threaded world.''  @callWrapper_GC@ is all about
5344 getting in and out of the threaded world.  On SPARCs, with register
5345 windows, the name of the game is not shifting windows until we have
5346 what we want out of the old one.  In tricky cases like this, it's best
5347 written in assembly language.
5348
5349 Performing a GC (potentially) means giving up the thread of control.
5350 So we must fill in the thread-state-object (TSO) [and its associated
5351 stk object] with enough information for later resumption:
5352 \begin{enumerate}
5353 \item
5354 Save the return address in the TSO's PC field.
5355 \item
5356 Save the machine registers used in the STG threaded world in their
5357 corresponding TSO fields.  We also save the pointer-liveness
5358 information in the TSO.
5359 \item
5360 The registers that are not thread-specific, notably @Hp@ and
5361 @HpLim@, are saved in the @StorageMgrInfo@ structure.
5362 \item
5363 Call the routine it was asked to call; in this example, call
5364 @PerformGC@ with arguments @<liveness>@ and @_FHS+2@ (some constant)...
5365
5366 \end{enumerate}
5367
5368 %------------------------------------------------------------------------
5369 \item[Into the heap overflow wrapper, @PerformGC@ [parallel]:]
5370
5371 Most information has already been saved in the TSO.
5372
5373 \begin{enumerate}
5374 \item
5375 The first argument (@<liveness>@, in our example) say what registers
5376 are live, i.e., are ``roots'' the storage manager needs to know.
5377 \begin{verbatim}
5378 StorageMgrInfo.rootno   = 2;
5379 StorageMgrInfo.roots[0] = (P_) Ret1_SAVE;
5380 StorageMgrInfo.roots[1] = (P_) Ret2_SAVE;
5381 \end{verbatim}
5382
5383 \item
5384 We move the heap-pointer back [we had optimistically
5385 advanced it, in the initial heap check]
5386
5387 \item 
5388 We load up the @smInfo@ data from the STG registers' @*_SAVE@ locations.
5389
5390 \item
5391 We mark on the scheduler's big ``blackboard'' that a GC is
5392 required.
5393
5394 \item
5395 We reschedule, i.e., this thread gives up control.  (The scheduler
5396 will presumably initiate a garbage-collection, but it may have to do
5397 any number of other things---flushing, for example---before ``normal
5398 execution'' resumes; and it most certainly may not be this thread that
5399 resumes at that point!)
5400 \end{enumerate}
5401
5402 IT IS AT THIS POINT THAT THE WORLD IS COMPLETELY TIDY.
5403
5404 %------------------------------------------------------------------------
5405 \item[Out of @callWrapper_GC@ [parallel]:]
5406
5407 When this thread is finally resumed after GC (and who knows what
5408 else), it will restart by the normal enter-TSO/enter-stack-object
5409 sequence, which has the effect of re-loading the registers, etc.,
5410 (i.e., restoring the state).
5411
5412 Because the address we saved in the TSO's PC field was that at the end
5413 of the heap check, and because the check is a while-loop in the
5414 parallel system, we will now loop back around, and make sure there is
5415 enough space before continuing.
5416 \end{description}
5417
5418 \fi % end of commented out part
5419
5420 \subsection{Static Reference Tables (SRTs)}
5421 \label{sect:srt}
5422 \label{sect:CAF}
5423 \label{sect:static-objects}
5424
5425 In the above, we assumed that objects always contained pointers to all
5426 their free variables.  In fact, this isn't quite true: GHC omits
5427 pointers to top-level objects and allocates their closures in static
5428 memory.  This optimisation reduces the number of free variables in
5429 heap objects - reducing memory usage and the effort needed to put them
5430 into heap objects.  However, this optimisation comes at a cost: we
5431 need to complicate the garbage collector with machinery for tracing
5432 these static references.
5433
5434 Early versions of GHC used a very simple algorithm: it treated all
5435 static objects as roots.  This is safe in the sense that no object is
5436 ever deallocated if there's a chance that it might be required later
5437 but can lead to some terrible space leaks.  For example, this program
5438 ought to be able to run in constant space but, because @xs@ is never
5439 deallocated, it runs in linear space.
5440
5441 @
5442 main = print xs
5443 xs = [1..]
5444 @
5445
5446 The correct behaviour is for the garbage collector to keep a static
5447 object alive iff it might be required later in execution.  That is, if
5448 it is reachable from any live heap objects {\em or\/} from any return
5449 addresses found on the stack or from the current program counter.
5450 Since it is obviously infeasible for the garbage collector to scan
5451 machine code looking for static references, the code generator must
5452 generate a table of all static references in any piece of code (and we
5453 must place a pointer to this table next to any piece of code we
5454 generate).
5455
5456 Here's what the SRT has to contain:
5457
5458 @
5459 ...
5460 @
5461
5462 Here's how we represent it:
5463
5464 @
5465 ...
5466 must be able to handle 0 references well
5467 @
5468
5469 @
5470 Other trickery:
5471 o The CAF list
5472 o The scavenge list
5473 o Generational GC trickery
5474 @
5475
5476 \subsection{Space leaks and black holes}
5477 \label{sect:black-hole}
5478
5479 \iffalse
5480
5481 \ToDo{Insert text stolen from update paper}
5482
5483 \else
5484
5485 A program exhibits a {\em space leak} if it retains storage that is
5486 sure not to be used again.  Space leaks are becoming increasingly
5487 common in imperative programs that @malloc@ storage and fail
5488 subsequently to @free@ it.  They are, however, also common in
5489 garbage-collected systems, especially where lazy evaluation is
5490 used.[.wadler leak, runciman heap profiling jfp.]
5491
5492 Quite a bit of experience has now accumulated suggesting that
5493 implementors must be very conscientious about avoiding gratuitous
5494 space leaks --- that is, ones which are an accidental artefact of some
5495 implementation technique.[.appel book.]  The update mechanism is
5496 a case in point, as <.jones jfp leak.> points out.  Consider a thunk for
5497 the expression
5498 @
5499   let xs = [1..1000] in last xs
5500 @
5501 where @last@ is a function that returns the last element of its
5502 argument list.  When the thunk is entered it will call @last@, which
5503 will consume @xs@ until it finds the last element.  Since the list
5504 @[1..1000]@ is produced lazily one might reasonably expect the
5505 expression to evaluate in constant space.  But {\em until the moment
5506 of update, the thunk itself still retains a pointer to the beginning
5507 of the list @xs@}.  So, until the update takes place the whole list
5508 will be retained!
5509
5510 Of course, this is completely gratuitous.  The pointer to @xs@ in the
5511 thunk will never be used again.  In <.peyton stock hardware.> the solution to
5512 this problem that we advocated was to overwrite a thunk's info with a
5513 fixed ``black hole'' info pointer, {\em at the moment of entry}.  The
5514 storage management information attached to a black-hole info pointer
5515 tells the garbage collector that the closure contains no pointers,
5516 thereby plugging the space leak.
5517
5518 \subsubsection{Lazy black-holing}
5519 \label{sect:lazy-black-holing}
5520
5521 \Note{We currently plan to implement eager black holing because the
5522 lazy blackholing scheme leavs "slop" in the heap.}
5523
5524 Black-holing is a well-known idea.  The trouble is that it is
5525 gallingly expensive.  To avoid the occasional space leak, for every
5526 single thunk entry we have to load a full-word literal constant into a
5527 register (often two instructions) and then store that register into a
5528 memory location.  
5529
5530 Fortunately, this cost can easily be avoided.  The
5531 idea is simple: {\em instead of black-holing every thunk on entry,
5532 wait until the garbage collector is called, and then black-hole all
5533 (and only) the thunks whose evaluation is in progress at that moment}.
5534 There is no benefit in black-holing a thunk that is updated before
5535 garbage collection strikes!  In effect, the idea is to perform the
5536 black-holing operation lazily, only when it is needed.  This
5537 dramatically cuts down the number of black-holing operations, as our
5538 results show {\em forward ref}.
5539
5540 How can we find all the thunks whose evaluation is in progress?  They
5541 are precisely the ones for which update frames are on the stack.  So
5542 all we need do is find all the update frames (via the @Su@ chain) and
5543 black-hole their thunks right at the start of garbage collection.
5544 Notice that it is not enough to refrain from treating update frames as
5545 roots: firstly because the thunks to which they point may need to be
5546 moved in a copying collector, but more importantly because the thunk
5547 might be accessible via some other route.
5548
5549 \subsubsection{Detecting loops}
5550
5551 Black-holing has a second minor advantage: evaluation of a thunk whose
5552 value depends on itself will cause a black hole closure to be entered,
5553 which can cause a suitable error message to be displayed. For example,
5554 consider the definition
5555 @
5556   x = 1+x
5557 @
5558 The code to evaluate @x@'s right hand side will evaluate @x@.  In the
5559 absence of black-holing, the result will be a stack overflow, as the
5560 evaluator repeatedly pushes a return address and enters @x@.  If
5561 thunks are black-holed on entry, then this infinite loop can be caught
5562 almost instantly.
5563
5564 With our new method of lazy black-holing, a self-referential program
5565 might cause either stack overflow or a black-hole error message,
5566 depending on exactly when garbage collection strikes.  It is quite
5567 easy to conceal these differences, however.  If stack overflow occurs,
5568 all we need do is examine the update frames on the stack to see if
5569 more than one refers to the same thunk.  If so, there is a loop that
5570 would have been detected by eager black-holing.
5571
5572 \subsubsection{Lazy locking}
5573 \label{sect:lock}
5574
5575 In a parallel implementation, it is necessary somehow to ``lock'' a
5576 thunk that is under evaluation, so that other parallel evaluators
5577 cannot simultaneously evaluate it and thereby duplicate work.
5578 Instead, an evaluator that enters a locked thunk should be blocked,
5579 and made runnable again when the thunk is updated.
5580
5581 This locking is readily arranged in the same way as black-holing, by
5582 overwriting the thunk's info pointer with a special ``locked'' info
5583 pointer, at the moment of entry.  If another evaluator enters the
5584 thunk before it has been updated, it will land in the entry code for
5585 the ``locked'' info pointer, which blocks the evaluator and queues it
5586 on the locked thunk.
5587
5588 The details are given by <.portable parallel trinder.>.  However, the close similarity
5589 between locking and black holing suggests the following question: can
5590 locking be done lazily too?  The answer is that it can, except that
5591 locking can be postponed only until the next {\em context switch},
5592 rather than the next {\em garbage collection}.  We are assuming here
5593 that the parallel implementation does not use shared memory to allow
5594 two processors to access the same closure.  If such access is
5595 permitted then every thunk entry requires a hardware lock, and becomes
5596 much too expensive.
5597
5598 Is lazy locking worth while, given that it requires extra work every
5599 context switch?  We believe it is, because contexts switches are
5600 relatively infrequent, and thousands of thunk-entries typically take
5601 place between each.
5602
5603 {\em Measurements elsewhere.  Omit this section? If so, fix cross refs to here.}
5604
5605 \fi
5606
5607
5608 \subsection{Squeezing identical updates}
5609
5610 \Note{This can also be done by testing whether @Sp == Su@ when we push
5611 an update frame.  If so, we can overwrite the updatee with an
5612 indirection to the existing updatee (and some slop objects) and avoid
5613 pushing an update frame.}
5614
5615 \iffalse
5616
5617 \ToDo{Insert text stolen from update paper}
5618
5619 \else
5620
5621 Consider the following Haskell definition of the standard
5622 function @partition@ that divides a list into two, those elements
5623 that satisfy a predicate @p@ and those that do not:
5624 @
5625   partition :: (a->Bool) -> [a] -> ([a],[a])
5626   partition p [] = ([],[])
5627   partition p (x:xs) = if p x then (x:ys, zs)
5628                               else (ys, x:zs)
5629                      where
5630                        (ys,zs) = partition p xs
5631 @
5632 By the time this definition has been desugared, it looks like this:
5633 @
5634   partition p xs
5635     = case xs of
5636         [] -> ([],[])
5637         (x:xs) -> let
5638                     t = partition p xs
5639                     ys = fst t
5640                     zs = snd t
5641                   in
5642                   if p x then (x:ys,zs)
5643                          else (ys,x:zs)
5644 @
5645 Lazy evaluation demands that the recursive call is bound to an
5646 intermediate variable, @t@, from which @ys@ and @zs@ are lazily
5647 selected. (The functions @fst@ and @snd@ select the first and second
5648 elements of a pair, respectively.)
5649
5650 Now, suppose that @partition@ is applied to a list @[x1,x2]@,
5651 all of whose
5652 elements satisfy @p@.  We can get a good idea of what will happen
5653 at runtime by unrolling the recursion a few times in our heads.
5654 Unrolling once, and remembering that @(p x1)@ is @True@, we get this:
5655 @
5656   partition p [x1,x2]
5657 =
5658   let t1 = partition [x2]
5659       ys1 = fst t1
5660       zs1 = snd t1
5661   in (x1:ys1, zs1)
5662 @
5663 Unrolling the rest of the way gives this:
5664 @
5665   partition p [x1,x2]
5666 =
5667   let t2  = ([],[])
5668       ys2 = fst t2
5669       zs2 = snd t2
5670       t1  = (x2:ys2,zs2)
5671       ys1 = fst t1
5672       zs1 = snd t1
5673    in (x1:ys1,zs1)
5674 @
5675 Now consider what happens if @zs1@ is evaluated.  It is bound to a
5676 thunk, which will push an update frame before evaluating the
5677 expression @snd t1@.  This expression in turn forces evaluation of
5678 @zs2@, which pushes an update frame before evaluating @snd t2@.
5679 Indeed the stack of update frames will grow as deep as the list is
5680 long when @zs1@ is evaluated.  This is rather galling, since all the
5681 thunks @zs1@, @zs2@, and so on, have the same value.
5682
5683 \ToDo{Describe the state-transformer case in which we get a space leak from
5684 pending update frames.}
5685
5686 The solution is simple.  The garbage collector, which is going to traverse the
5687 update stack in any case, can easily identify two update frames that are directly
5688 on top of each other.  The second of these will update its target with the same
5689 value as the first.  Therefore, the garbage collector can perform the update 
5690 right away, by overwriting one update target with an indirection to the second,
5691 and eliminate the corresponding update frame.  In this way ever-growing stacks of
5692 update frames are reduced to a single representative at garbage collection time.
5693 If this is done at the start of garbage collection then, if it turns out that
5694 some of these update targets are garbage they will be collected right away.
5695
5696 \fi
5697
5698 \subsection{Space leaks and selectors}\label{sect:space-leaks-and-selectors}
5699
5700 \iffalse
5701
5702 \ToDo{Insert text stolen from update paper}
5703
5704 \else
5705
5706 In 1987, Wadler identified an important source of space leaks in
5707 lazy functional programs.  Consider the Haskell function definition:
5708 @
5709   f p = (g1 a, g2 b) where (a,b) = p
5710 @
5711 The pattern-matching in the @where@ clause is known as
5712 {\em lazy pattern-matching}, because it is performed only if @a@
5713 or @b@ is actually evaluated.  The desugarer translates lazy pattern matching
5714 to the use of selectors, @fst@ and @snd@ in this case:
5715 @
5716   f p = let a = fst p
5717             b = snd p
5718         in
5719         (b, a)
5720 @
5721 Now suppose that the second component of the pair @(f p)@, namely @a@,
5722 is evaluated and discarded, but the first is not although it remains
5723 reachable.  The garbage collector will find that the thunk for @b@ refers
5724 to @p@ and hence to @a@.  Thus, although @a@ cannot ever be used again, its
5725 space is retained.  It turns out that this space leak can have a very bad effect
5726 indeed on a program's space behaviour (Section~\ref{sect:selector-results}).
5727
5728 Wadler's paper also proposed a solution: if the garbage collector
5729 encounters a thunk of the form @snd p@, where @p@ is evaluated, then
5730 the garbage collector should perform the selection and overwrite the
5731 thunk with a pointer to the second component of the pair.  In effect, the
5732 garbage collector thereby performs a bounded amount of as-yet-undemanded evaluation
5733 in the hope of improving space behaviour.
5734 We implement this idea directly, by making the garbage collector
5735 eagerly execute all selector thunks\footnote{A word of caution: it is rather easy 
5736 to make a mistake in the implementation, especially if the garbage collector
5737 uses pointer reversal to traverse the reachable graph.},
5738 with results 
5739 reported in Section~\ref{sect:THUNK_SEL}.
5740
5741 One could easily imagine generalisations of this idea, with the garbage 
5742 collector performing bounded amounts of space-saving work.  One example is
5743 this:
5744 @
5745   f x []     = (x,x)
5746   f x (y:ys) = f (x+1) ys
5747 @
5748 Most lazy evaluators will build up a chain of thunks for the accumulating
5749 parameter, @x@, each of which increments @x@.  It is not safe to evaluate
5750 any of these thunks eagerly, since @f@ is not strict in @x@, and we know nothing
5751 about the value of @x@ passed in the initial call to @f@.
5752 On the other hand, if the garbage collector found a thunk @(x+1)@ where
5753 @x@ happened to be evaluated, then it could ``execute'' it eagerly.
5754 If done carefully, the entire chain could be eliminated in a single
5755 garbage collection.   We have not (yet) implemented this idea.
5756 A very similar idea, dubbed ``stingy evaluation'', is described 
5757 by <.stingy.>.
5758
5759 \ToDo{Simple generalisation: handle all the ``standard closures'' this way.}
5760
5761 <.sparud lazy pattern matching.> describes another solution to the
5762 lazy-pattern-matching
5763 problem.  His solution involves adding code to the two thunks for
5764 @a@ and @b@ so that if either is evaluated it arranges to update the
5765 other as well as itself.  The garbage-collector solution is a little
5766 more general, since it applies whether or not the selectors were
5767 generated by lazy pattern matching, and in our setting it was easier
5768 to implement than Sparud's.
5769
5770 \fi
5771
5772
5773 \subsection{Internal workings of the Compacting Collector}
5774
5775 \subsection{Internal workings of the Copying Collector}
5776
5777 \subsection{Internal workings of the Generational Collector}
5778
5779
5780 \section{Profiling}
5781
5782 Registering costs centres looks awkward - can we tidy it up?
5783
5784 \section{Parallelism}
5785
5786 Something about global GC, inter-process messages and fetchmes.
5787
5788 \section{Debugging}
5789
5790 \section{Ticky Ticky profiling}
5791
5792 Measure what proportion of ...:
5793 \begin{itemize}
5794 \item
5795 ... Enters are to data values, function values, thunks.
5796 \item
5797 ... allocations are for data values, functions values, thunks.
5798 \item
5799 ... updates are for data values, function values.
5800 \item
5801 ... updates ``fit''
5802 \item
5803 ... return-in-heap (dynamic)
5804 \item
5805 ... vectored return (dynamic)
5806 \item
5807 ... updates are wasted (never re-entered).
5808 \item
5809 ... constructor returns get away without hitting an update.
5810 \end{itemize}
5811
5812 %************************************************************************
5813 %*                                                                      *
5814 \subsection[ticky-stk-heap-use]{Stack and heap usage}
5815 %*                                                                      *
5816 %************************************************************************
5817
5818 Things we are interested in here:
5819 \begin{itemize}
5820 \item
5821 How many times we do a heap check and move @Hp@; comparing this with
5822 the allocations gives an indication of how many things we get per trip
5823 to the well:
5824
5825 If we do a ``heap lookahead,'' we haven't really allocated any
5826 heap, so we need to undo the effects of an @ALLOC_HEAP@:
5827
5828 \item
5829 The stack high-water mark.
5830
5831 \item
5832 Re-use of stack slots, and stubbing of stack slots:
5833
5834 \end{itemize}
5835
5836 %************************************************************************
5837 %*                                                                      *
5838 \subsection[ticky-allocs]{Allocations}
5839 %*                                                                      *
5840 %************************************************************************
5841
5842 We count things every time we allocate something in the dynamic heap.
5843 For each, we count the number of words of (1)~``admin'' (header),
5844 (2)~good stuff (useful pointers and data), and (3)~``slop'' (extra
5845 space, in hopes it will allow an in-place update).
5846
5847 The first five macros are inserted when the compiler generates code
5848 to allocate something; the categories correspond to the @ClosureClass@
5849 datatype (manifest functions, thunks, constructors, big tuples, and
5850 partial applications).
5851
5852 We may also allocate space when we do an update, and there isn't
5853 enough space.  These macros suffice (for: updating with a partial
5854 application and a constructor):
5855
5856 In the threaded world, we allocate space for the spark pool, stack objects,
5857 and thread state objects.
5858
5859 The histogrammy bit is fairly straightforward; the @-2@ is: one for
5860 0-origin C arrays; the other one because we do {\em no} one-word
5861 allocations, so we would never inc that histogram slot; so we shift
5862 everything over by one.
5863
5864 Some hard-to-account-for words are allocated by/for primitives,
5865 includes Integer support.  @ALLOC_PRIM2@ tells us about these.  We
5866 count everything as ``goods'', which is not strictly correct.
5867 (@ALLOC_PRIM@ is the same sort of stuff, but we know the
5868 admin/goods/slop breakdown.)
5869
5870 %************************************************************************
5871 %*                                                                      *
5872 \subsection[ticky-enters]{Enters}
5873 %*                                                                      *
5874 %************************************************************************
5875
5876 We do more magical things with @ENT_FUN_DIRECT@.  Besides simply knowing
5877 how many ``fast-entry-point'' enters there were, we'd like {\em simple}
5878 information about where those enters were, and the properties thereof.
5879 @
5880 struct ent_counter {
5881     unsigned    registeredp:16, /* 0 == no, 1 == yes */
5882                 arity:16,       /* arity (static info) */
5883                 Astk_args:16,   /* # of args off A stack */
5884                 Bstk_args:16;   /* # of args off B stack */
5885                                 /* (rest of args are in registers) */
5886     StgChar     *f_str;         /* name of the thing */
5887     StgChar     *f_arg_kinds;   /* info about the args types */
5888     StgChar     *wrap_str;      /* name of its wrapper (if any) */
5889     StgChar     *wrap_arg_kinds;/* info about the orig wrapper's arg types */
5890     I_          ctr;            /* the actual counter */
5891     struct ent_counter *link;   /* link to chain them all together */
5892 };
5893 @
5894
5895 %************************************************************************
5896 %*                                                                      *
5897 \subsection[ticky-returns]{Returns}
5898 %*                                                                      *
5899 %************************************************************************
5900
5901 Whenever a ``return'' occurs, it is returning the constituent parts of
5902 a data constructor.  The parts can be returned either in registers, or
5903 by allocating some heap to put it in (the @ALLOC_*@ macros account for
5904 the allocation).  The constructor can either be an existing one
5905 (@*OLD*@) or we could have {\em just} figured out this stuff
5906 (@*NEW*@).
5907
5908 Here's some special magic that Simon wants [edited to match names
5909 actually used]:
5910
5911 @
5912 From: Simon L Peyton Jones <simonpj>
5913 To: partain, simonpj
5914 Subject: counting updates
5915 Date: Wed, 25 Mar 92 08:39:48 +0000
5916
5917 I'd like to count how many times we update in place when actually Node
5918 points to the thing.  Here's how:
5919
5920 @RET_OLD_IN_REGS@ sets the variable @ReturnInRegsNodeValid@ to @True@;
5921 @RET_NEW_IN_REGS@ sets it to @False@.
5922
5923 @RET_SEMI_???@ sets it to??? ToDo [WDP]
5924
5925 @UPD_CON_IN_PLACE@ tests the variable, and increments @UPD_IN_PLACE_COPY_ctr@
5926 if it is true.
5927
5928 Then we need to report it along with the update-in-place info.
5929 @
5930
5931
5932 Of all the returns (sum of four categories above), how many were
5933 vectored?  (The rest were obviously unvectored).
5934
5935 %************************************************************************
5936 %*                                                                      *
5937 \subsection[ticky-update-frames]{Update frames}
5938 %*                                                                      *
5939 %************************************************************************
5940
5941 These macros count up the following update information.
5942
5943 \begin{tabular}{|l|l|} \hline
5944 Macro                   &       Counts                                  \\ \hline
5945                         &                                               \\
5946 @UPDF_STD_PUSHED@       &       Update frame pushed                     \\
5947 @UPDF_CON_PUSHED@       &       Constructor update frame pushed         \\
5948 @UPDF_HOLE_PUSHED@      &       An update frame to update a black hole  \\
5949 @UPDF_OMITTED@          &       A thunk decided not to push an update frame \\
5950                         &       (all subsets of @ENT_THK@)              \\
5951 @UPDF_RCC_PUSHED@       &       Cost Centre restore frame pushed        \\
5952 @UPDF_RCC_OMITTED@      &       Cost Centres not required -- not pushed \\\hline
5953 \end{tabular}
5954
5955 %************************************************************************
5956 %*                                                                      *
5957 \subsection[ticky-updates]{Updates}
5958 %*                                                                      *
5959 %************************************************************************
5960
5961 These macros record information when we do an update.  We always
5962 update either with a data constructor (CON) or a partial application
5963 (PAP).
5964
5965 \begin{tabular}{|l|l|}\hline
5966 Macro                   &       Where                                           \\ \hline
5967                         &                                                       \\
5968 @UPD_EXISTING@          &       Updating with an indirection to something       \\
5969                         &       already in the heap                             \\
5970 @UPD_SQUEEZED@          &       Same as @UPD_EXISTING@ but because              \\
5971                         &       of stack-squeezing                              \\
5972 @UPD_CON_W_NODE@        &       Updating with a CON: by indirecting to Node     \\
5973 @UPD_CON_IN_PLACE@      &       Ditto, but in place                             \\
5974 @UPD_CON_IN_NEW@        &       Ditto, but allocating the object                \\
5975 @UPD_PAP_IN_PLACE@      &       Same, but updating w/ a PAP                     \\
5976 @UPD_PAP_IN_NEW@        &                                                       \\\hline
5977 \end{tabular}
5978
5979 %************************************************************************
5980 %*                                                                      *
5981 \subsection[ticky-selectors]{Doing selectors at GC time}
5982 %*                                                                      *
5983 %************************************************************************
5984
5985 @GC_SEL_ABANDONED@: we could've done the selection, but we gave up
5986 (e.g., to avoid overflowing the C stack); @GC_SEL_MINOR@: did a
5987 selection in a minor GC; @GC_SEL_MAJOR@: ditto, but major GC.
5988
5989
5990
5991 \section{History}
5992
5993 We're nuking the following:
5994
5995 \begin{itemize}
5996 \item
5997   Two stacks
5998
5999 \item
6000   Return in registers.
6001   This lets us remove update code pointers from info tables,
6002   removes the need for phantom info tables, simplifies 
6003   semi-tagging, etc.
6004
6005 \item
6006   Threaded GC.
6007   Careful analysis suggests that it doesn't buy us very much
6008   and it is hard to work with.
6009
6010   Eliminating threaded GCs eliminates the desire to share SMReps
6011   so they are (once more) part of the Info table.
6012
6013 \item
6014   RetReg.
6015   Doesn't buy us anything on a register-poor architecture and
6016   isn't so important if we have semi-tagging.
6017
6018 @
6019     - Probably bad on register poor architecture 
6020     - Can avoid need to write return address to stack on reg rich arch.
6021       - when a function does a small amount of work, doesn't 
6022         enter any other thunks and then returns.
6023         eg entering a known constructor (but semitagging will catch this)
6024     - Adds complications
6025 @
6026
6027 \item
6028   Update in place
6029
6030   This lets us drop CONST closures and CHARLIKE closures (assuming we
6031   don't support Unicode).  The only point of these closures was to 
6032   avoid updating with an indirection.
6033
6034   We also drop @MIN_UPD_SIZE@ --- all we need is space to insert an
6035   indirection or a black hole.
6036
6037 \item
6038   STATIC SMReps are now called CONST
6039
6040 \item
6041   @SM_MUTVAR@ is new
6042
6043 \item The profiling ``kind'' field is now encoded in the @INFO_TYPE@ field.
6044 This identifies the general sort of the closure for profiling purposes.
6045
6046 \item Various papers describe deleting update frames for unreachable objects.
6047   This has never been implemented and we don't plan to anytime soon.
6048
6049 \end{itemize}
6050
6051 \section{Old tricks}
6052
6053 @CAF@ indirections:
6054
6055 These are statically defined closures which have been updated with a
6056 heap-allocated result.  Initially these are exactly the same as a
6057 @STATIC@ closure but with special entry code. On entering the closure
6058 the entry code must:
6059
6060 \begin{itemize}
6061 \item Allocate a black hole in the heap which will be updated with
6062       the result.
6063 \item Overwrite the static closure with a special @CAF@ indirection.
6064
6065 \item Link the static indirection onto the list of updated @CAF@s.
6066 \end{itemize}
6067
6068 The indirection and the link field require the initial @STATIC@
6069 closure to be of at least size @MIN_UPD_SIZE@ (excluding the fixed
6070 header).
6071
6072 @CAF@s are treated as special garbage collection roots.  These roots
6073 are explicitly collected by the garbage collector, since they may
6074 appear in code even if they are not linked with the main heap.  They
6075 consequently represent potentially enormous space-leaks.  A @CAF@
6076 closure retains a fixed location in statically allocated data space.
6077 When updated, the contents of the @CAF@ indirection are changed to
6078 reflect the new closure. @CAF@ indirections require special garbage
6079 collection code.
6080
6081 \section{Old stuff about SRTs}
6082
6083 \ToDo{Commented out}
6084
6085 \iffalse
6086
6087 Garbage collection of @CAF@s is tricky.  We have to cope with explicit
6088 collection from the @CAFlist@ as well as potential references from the
6089 stack and heap which will cause the @CAF@ evacuation code to be
6090 called.  They are treated like indirections which are shorted out.
6091 However they must also be updated to point to the new location of the
6092 new closure as the @CAF@ may still be used by references which
6093 reside in the code.
6094
6095 {\bf Copying Collection}
6096
6097 A first scheme might use evacuation code which evacuates the reference
6098 and updates the indirection. This is no good as subsequent evacuations
6099 will result in an already evacuated closure being evacuated. This will
6100 leave a forward reference in to-space!
6101
6102 An alternative scheme evacuates the @CAFlist@ first. The closures
6103 referenced are evacuated and the @CAF@ indirection updated to point to
6104 the evacuated closure. The @CAF@ evacuation code simply returns the
6105 updated indirection pointer --- the pointer to the evacuated closure.
6106 Unfortunately the closure the @CAF@ references may be a static
6107 closure, in fact, it may be another @CAF@. This will cause the second
6108 @CAF@'s evacuation code to be called before the @CAF@ has been
6109 evacuated, returning an unevacuated pointer.
6110
6111 Another scheme leaves updating the @CAF@ indirections to the end of
6112 the garbage collection.  All the references are evacuated and
6113 scavenged as usual (including the @CAFlist@). Once collection is
6114 complete the @CAFlist@ is traversed updating the @CAF@ references with
6115 the result of evacuating the referenced closure again. This will
6116 immediately return as it must be a forward reference, a static
6117 closure, or a @CAF@ which will indirect by evacuating its reference.
6118
6119 The crux of the problem is that the @CAF@ evacuation code needs to
6120 know if its reference has already been evacuated and updated. If not,
6121 then the reference can be evacuated, updated and returned safely
6122 (possibly evacuating another @CAF@). If it has, then the updated
6123 reference can be returned. This can be done using two @CAF@
6124 info-tables. At the start of a collection the @CAFlist@ is traversed
6125 and set to an internal {\em evacuate and update} info-table. During
6126 collection, evacution of such a @CAF@ also results in the info-table
6127 being reset back to the standard @CAF@ info-table. Thus subsequent
6128 evacuations will simply return the updated reference. On completion of
6129 the collection all @CAF@s will have {\em return reference} info-tables
6130 again.
6131
6132 This is the scheme we adopt. A @CAF@ indirection has evacuation code
6133 which returns the evacuated and updated reference. During garbage
6134 collection, all the @CAF@s are overwritten with an internal @CAF@ info
6135 table which has evacuation code which performs this evacuate and
6136 update and restores the original @CAF@ code. At some point during the
6137 collection we must ensure that all the @CAF@s are indeed evacuated.
6138
6139 The only potential problem with this scheme is a cyclic list of @CAF@s
6140 all directly referencing (possibly via indirections) another @CAF@!
6141 Evacuation of the first @CAF@ will fail in an infinite loop of @CAF@
6142 evacuations. This is solved by ensuring that the @CAF@ info-table is
6143 updated to a {\em return reference} info-table before performing the
6144 evacuate and update. If this {\em return reference} evacuation code is
6145 called before the actual evacuation is complete it must be because
6146 such a cycle of references exists. Returning the still unevacuated
6147 reference is OK --- all the @CAF@s will now reference the same
6148 @CAF@ which will reference itself! Construction of such a structure
6149 indicates the program must be in an infinite loop.
6150
6151 {\bf Compacting Collector}
6152
6153 When shorting out a @CAF@, its reference must be marked. A first
6154 attempt might explicitly mark the @CAF@s, updating the reference with
6155 the marked reference (possibly short circuting indirections). The
6156 actual @CAF@ marking code can indicate that they have already been
6157 marked (though this might not have actually been done yet) and return
6158 the indirection pointer so it is shorted out. Unfortunately the @CAF@
6159 reference might point to an indirection which will be subsequently
6160 shorted out. Rather than returning the @CAF@ reference we treat the
6161 @CAF@ as an indirection, calling the mark code of the reference, which
6162 will return the appropriately shorted reference.
6163
6164 Problem: Cyclic list of @CAF@s all directly referencing (possibly via
6165 indirections) another @CAF@!
6166
6167 Before compacting, the locations of the @CAF@ references are
6168 explicitly linked to the closures they reference (if they reference
6169 heap allocated closures) so that the compacting process will update
6170 them to the closure's new location. Unfortunately these locations'
6171 @CAF@ indirections are static.  This causes premature termination
6172 since the test to find the info pointer at the end of the location
6173 list will match more than one value.  This can be solved by using an
6174 auxiliary dynamic array (on the top of the A stack).  One location for
6175 each @CAF@ indirection is linked to the closure that the @CAF@
6176 references. Once collection is complete this array is traversed and
6177 the corresponding @CAF@ is then updated with the updated pointer from
6178 the auxiliary array.
6179
6180
6181 It is possible to use an alternative marking scheme, using a similar
6182 idea to the copying solution. This scheme avoids the need to update
6183 the @CAF@ references explicitly. We introduce an auxillary {\em mark
6184 and update} @CAF@ info-table which is used to update all @CAF@s at the
6185 start of a collection. The new code marks the @CAF@ reference,
6186 updating it with the returned reference.  The returned reference is
6187 itself returned so the @CAF@ is shorted out.  The code also modifies the
6188 @CAF@ info-table to be a {\em return reference}.  Subsequent attempts to
6189 mark the @CAF@ simply return the updated reference.
6190
6191 A cyclic @CAF@ reference will result in an attempt to mark the @CAF@
6192 before the marking has been completed and the reference updated. We
6193 cannot start marking the @CAF@ as it is already being marked. Nor can
6194 we return the reference as it has not yet been updated. Neither can we
6195 treat the CAF as an indirection since the @CAF@ reference has been
6196 obscured by the pointer reversal stack. All we can do is return the
6197 @CAF@ itself. This will result in some @CAF@ references not being
6198 shorted out.
6199
6200 This scheme has not been adopted but has been implemented. The code is
6201 commented out with @#if 0@.
6202
6203 \fi
6204
6205 \subsection{The virtual register set}
6206
6207 \ToDo{Commented out}
6208
6209 \iffalse
6210
6211 We refer to any (atomic) part of the virtual machine state as a ``register.''
6212 These ``registers'' may be shared between all threads in the system or may be
6213 specific to each thread.
6214
6215 Global: 
6216 @
6217   Hp
6218   HpLim
6219   Thread preemption flag
6220 @
6221
6222 Thread specific:
6223 @
6224   TSO - pointer to the TSO for when we have to pack thread away
6225   Sp
6226   SpLim
6227   Su - used to calculate number of arguments on stack
6228      - this is a more convenient representation
6229   Call/return registers (aka General purpose registers)
6230   Cost centre (and other debug/profile info)
6231   Statistic gathering (not in production system)
6232   Exception handlers 
6233     Heap overflow  - possible global?
6234     Stack overflow - possibly global?
6235     Pattern match failure
6236     maybe a failWith handler?
6237     maybe an exitWith handler?
6238     ...
6239 @
6240
6241 Some of these virtual ``registers'' are used very frequently and should
6242 be mapped onto machine registers if at all possible.  Others are used
6243 very infrequently and can be kept in memory to free up registers for
6244 other uses.
6245
6246 On register-poor architectures, we can play a few tricks to reduce the
6247 number of virtual registers which need to be accessed on a regular
6248 basis:
6249
6250 @
6251 - HpLim trick
6252 - Grow stack and heap towards each other (single-threaded system only)
6253 - We might need to keep the C stack pointer in a register if that
6254   is what the OS expects when a signal occurs.
6255 - Preemption flag trick
6256 - If any of the frequently accessed registers cannot be mapped onto
6257   machine registers we should keep the TSO in a machine register to
6258   allow faster access to all the other non-machine registers.
6259 @
6260
6261 \fi
6262
6263 \end{document}
6264
6265