[project @ 1999-08-02 13:11:02 by simonmar]
[ghc-hetmet.git] / ghc / 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 \newcommand{\note}[1]{{{\bf Note:}\sl #1}}
26 \newcommand{\ToDo}[1]{{{\bf ToDo:}\sl #1}}
27 \newcommand{\Arg}[1]{\mbox{${\tt arg}_{#1}$}}
28 \newcommand{\bottom}{\perp}
29
30 \newcommand{\secref}[1]{Section~\ref{sec:#1}}
31 \newcommand{\figref}[1]{Figure~\ref{fig:#1}}
32 \newcommand{\Section}[2]{\section{#1}\label{sec:#2}}
33 \newcommand{\Subsection}[2]{\subsection{#1}\label{sec:#2}}
34 \newcommand{\Subsubsection}[2]{\subsubsection{#1}\label{sec:#2}}
35
36 % DIMENSION OF TEXT:
37 \textheight 8.5 in
38 \textwidth 6.25 in
39
40 \topmargin 0 in
41 \headheight 0 in
42 \headsep .25 in
43
44
45 \setlength{\parskip}{0.15cm}
46 \setlength{\parsep}{0.15cm}
47 \setlength{\topsep}{0cm}        % Reduces space before and after verbatim,
48                                 % which is implemented using trivlist 
49 \setlength{\parindent}{0cm}
50
51 \renewcommand{\textfraction}{0.2}
52 \renewcommand{\floatpagefraction}{0.7}
53
54 \begin{document}
55
56 \title{The STG runtime system (revised)}
57 \author{Simon Peyton Jones \\ Microsoft Research Ltd., Cambridge \and
58 Simon Marlow \\ Microsoft Research Ltd., Cambridge \and
59 Alastair Reid \\ Yale University} 
60
61 \maketitle
62
63 \tableofcontents
64 \newpage
65
66 \part{Introduction}
67 \Section{Overview}{overview}
68
69 This document describes the GHC/Hugs run-time system.  It serves as 
70 a Glasgow/Yale/Nottingham ``contract'' about what the RTS does.
71
72 \Subsection{New features compared to GHC 3.xx}{new-features}
73
74 \begin{itemize}
75 \item The RTS supports mixed compiled/interpreted execution, so
76 that a program can consist of a mixture of GHC-compiled and Hugs-interpreted
77 code.
78
79 \item The RTS supports concurrency by default.
80 This has some costs (eg we can't do hardware stack checks) but
81 reduces the number of different configurations we need to support.
82
83 \item CAFs are only retained if they are
84 reachable.  Since they are referred to by implicit references buried
85 in code, this means that the garbage collector must traverse the whole
86 accessible code tree.  This feature eliminates a whole class of painful
87 space leaks.
88
89 \item A running thread has only one stack, which contains a mixture of
90 pointers and non-pointers.  \secref{TSO} describes how we find out
91 which is which.  (GHC has used two stacks for some while.  Using one
92 stack instead of two reduces register pressure, reduces the size of
93 update frames, and eliminates ``stack-stubbing'' instructions.)
94
95 \item The ``return in registers'' return convention has been dropped
96 because it was complicated and doesn't work well on register-poor
97 architectures.  It has been partly replaced by unboxed tuples
98 (\secref{unboxed-tuples}) which allow the programmer to
99 explicitly state where results should be returned in registers (or on
100 the stack) instead of on the heap.
101
102 \item Exceptions are supported by the RTS.
103
104 \item Weak Pointers generalise the previously available Foreign Object
105 interface.
106
107 \item The garbage collector supports a number of new features,
108 including a dynamically resizable heap and multiple generations with
109 aging within a generation.
110
111 \end{itemize}
112
113 \Subsection{Wish list}{wish-list}
114
115 Here's a list of things we'd like to support in the future.
116 \begin{itemize}
117 \item Interrupts, speculative computation.
118
119 \item
120 The SM could tune the size of the allocation arena, the number of
121 generations, etc taking into account residency, GC rate and page fault
122 rate.
123
124 \item 
125 We could trigger a GC when all threads are blocked waiting for IO if
126 the allocation arena (or some of the generations) are nearly full.
127
128 \end{itemize}
129
130 \Subsection{Configuration}{configuration}
131
132 Some of the above features are expensive or less portable, so we
133 envision building a number of different configurations supporting
134 different subsets of the above features.
135
136 You can make the following choices:
137 \begin{itemize}
138 \item
139 Support for parallelism.  There are three mutually-exclusive choices.
140
141 \begin{description}
142 \item[@SEQUENTIAL@] Support for concurrency but not for parallelism.
143 \item[@GRANSIM@]    Concurrency support and simulated parallelism.
144 \item[@PARALLEL@]   Concurrency support and real parallelism.
145 \end{description}
146
147 \item @PROFILING@ adds cost-centre profiling.
148
149 \item @TICKY@ gathers internal statistics (often known as ``ticky-ticky'' code).
150
151 \item @DEBUG@ does internal consistency checks.
152
153 \item Persistence. (well, not yet).
154
155 \item
156 Which garbage collector to use.  At the moment we
157 only anticipate one, however.
158 \end{itemize}
159
160 \Subsection{Glossary}{glossary}
161
162 \ToDo{This terminology is not used consistently within the document.
163 If you find something which disagrees with this terminology, fix the
164 usage.}
165
166 In the type system, we have boxed and unboxed types.
167
168 \begin{itemize}
169
170 \item A \emph{pointed} type is one that contains $\bot$.  Variables with
171 pointed types are the only things which can be lazily evaluated.  In
172 the STG machine, this means that they are the only things that can be 
173 \emph{entered} or \emph{updated} and it requires that they be boxed.
174
175 \item An \emph{unpointed} type is one that does not contain $\bot$.
176 Variables with unpointed types are never delayed --- they are always
177 evaluated when they are constructed.  In the STG machine, this means
178 that they cannot be \emph{entered} or \emph{updated}.  Unpointed objects
179 may be boxed (like @Array#@) or unboxed (like @Int#@).
180
181 \end{itemize}
182
183 In the implementation, we have different kinds of objects:
184
185 \begin{itemize}
186
187 \item \emph{boxed} objects are heap objects used by the evaluators
188
189 \item \emph{unboxed} objects are not heap allocated
190
191 \item \emph{stack} objects are allocated on the stack
192
193 \item \emph{closures} are objects which can be \emph{entered}. 
194 They are always boxed and always have boxed types.
195 They may be in WHNF or they may be unevaluated.  
196
197 \item A \emph{thunk} is a (representation of) a value of a \emph{pointed}
198 type which is \emph{not} in WHNF.
199
200 \item A \emph{value} is an object in WHNF.  It can be pointed or unpointed.
201
202 \end{itemize}
203
204
205
206 At the hardware level, we have \emph{word}s and \emph{pointer}s.
207
208 \begin{itemize}
209
210 \item A \emph{word} is (at least) 32 bits and can hold either a signed
211 or an unsigned int.
212
213 \item A \emph{pointer} is (at least) 32 bits and big enough to hold a
214 function pointer or a data pointer.  
215
216 \end{itemize}
217
218 Occasionally, a field of a data structure must hold either a word or a
219 pointer.  In such circumstances, it is \emph{not safe} to assume that
220 words and pointers are the same size.  \ToDo{GHC currently makes words
221 the same size as pointers to reduce complexity in the code
222 generator/RTS.  It would be useful to relax this restriction, and have
223 eg. 32-bit Ints on a 64-bit machine.}
224
225 % should define terms like SRT, CAF, PAP, etc. here?  --KSW 1999-03
226
227 \subsection{Subtle Dependencies}
228
229 Some decisions have very subtle consequences which should be written
230 down in case we want to change our minds.  
231
232 \begin{itemize}
233
234 \item
235
236 If the garbage collector is allowed to shrink the stack of a thread,
237 we cannot omit the stack check in return continuations
238 (\secref{heap-and-stack-checks}).
239
240 \item
241
242 When we return to the scheduler, the top object on the stack is a closure.
243 The scheduler restarts the thread by entering the closure.
244
245 \secref{hugs-return-convention} discusses how Hugs returns an
246 unboxed value to GHC and how GHC returns an unboxed value to Hugs.
247
248 \item 
249
250 When we return to the scheduler, we need a few empty words on the stack
251 to store a closure to reenter.  \secref{heap-and-stack-checks}
252 discusses who does the stack check and how much space they need.
253
254 \item
255
256 Heap objects never contain slop --- this is required if we want to
257 support mostly-copying garbage collection.
258
259 This is a big problem when updating since the updatee is usually
260 bigger than an indirection object.  The fix is to overwrite the end of
261 the updatee with ``slop objects'' (described in
262 \secref{slop-objects}).  This is hard to arrange if we do
263 \emph{lazy} blackholing (\secref{lazy-black-holing}) so we
264 currently plan to blackhole an object when we push the update frame.
265
266 % Idea: have specialised update code for various common sizes of
267 % updatee, the update frame hence encodes the length of the object.
268 % Specialised indirections will also encode the length of the object.  A
269 % generic version of the update code will overwrite the slop with a slop
270 % object.  We can do the same thing for blackhole objects, or just have
271 % a generic version that is the same size as an indirection and
272 % overwrite the slop with a slop object when blackholing.  So: does this
273 % avoid the need to do eager black holing?
274
275 \item
276
277 Info tables for constructors contain enough information to decide which
278 return convention they use.  This allows Hugs to use a single piece of
279 entry code for all constructors and insulates Hugs from changes in the
280 choice of return convention.
281
282 \end{itemize}
283
284 \Section{Source Language}{source-language}
285
286 \Subsection{Explicit Allocation}{explicit-allocation}
287
288 As in the original STG machine, (almost) all heap allocation is caused
289 by executing a let(rec).  Since we no longer support the return in
290 registers convention for data constructors, constructors now cause heap
291 allocation and so they should be let-bound.
292
293 For example, we now write
294 @
295 > cons = \ x xs -> let r = (:) x xs in r
296 @
297 instead of
298 @
299 > cons = \ x xs -> (:) x xs
300 @
301
302 \note{For historical reasons, GHC doesn't use this syntax --- but it should.}
303
304 \Subsection{Unboxed tuples}{unboxed-tuples}
305
306 Functions can take multiple arguments as easily as they can take one
307 argument: there's no cost for adding another argument.  But functions
308 can only return one result: the cost of adding a second ``result'' is
309 that the function must construct a tuple of ``results'' on the heap.
310 The assymetry is rather galling and can make certain programming
311 styles quite expensive.  For example, consider a simple state transformer
312 monad:
313 @
314 > type S a     = State -> (a,State)
315 > bindS m k s0 = case m s0 of { (a,s1) -> k a s1 }
316 > returnS a s  = (a,s)
317 > getS s       = (s,s)
318 > setS s _     = ((),s)
319 @
320 Here, every use of @returnS@, @getS@ or @setS@ constructs a new tuple
321 in the heap which is instantly taken apart (and becomes garbage) by
322 the case analysis in @bind@.  Even a short state-transformer program
323 will construct a lot of these temporary tuples.
324
325 Unboxed tuples provide a way for the programmer to indicate that they
326 do not expect a tuple to be shared and that they do not expect it to
327 be allocated in the heap.  Syntactically, unboxed tuples are just like
328 single constructor datatypes except for the annotation @unboxed@.
329 @
330 > data unboxed AAndState# a = AnS a State
331 > type S a = State -> AAndState# a
332 > bindS m k s0 = case m s0 of { AnS a s1 -> k a s1 }
333 > returnS a s  = AnS a s
334 > getS s       = AnS s s
335 > setS s _     = AnS () s
336 @
337 Semantically, unboxed tuples are just unlifted tuples and are subject
338 to the same restrictions as other unpointed types.
339
340 Operationally, unboxed tuples are never built on the heap.  When
341 an unboxed tuple is returned, it is returned in multiple registers
342 or multiple stack slots.  At first sight, this seems a little strange
343 but it's no different from passing double precision floats in two
344 registers.
345
346 Notes:
347 \begin{itemize}
348 \item
349 Unboxed tuples can only have one constructor and that
350 thunks never have unboxed types --- so we'll never try to update an
351 unboxed constructor.  The restriction to a single constructor is
352 largely to avoid garbage collection complications.
353
354 \item
355 The core syntax does not allow variables to be bound to
356 unboxed tuples (ie in default case alternatives or as function arguments)
357 and does not allow unboxed tuples to be fields of other constructors.
358 However, there's no harm in allowing it in the source syntax as a
359 convenient, but easily removed, syntactic sugar.
360
361 \item
362 The compiler generates a closure of the form
363 @
364 > c = \ x y z -> C x y z
365 @
366 for every constructor (whether boxed or unboxed).  
367
368 This closure is normally used during desugaring to ensure that
369 constructors are saturated and to apply any strictness annotations.
370 They are also used when returning unboxed constructors to the machine
371 code evaluator from the bytecode evaluator and when a heap check fails
372 in a return continuation for an unboxed-tuple scrutinee.
373
374 \end{itemize}
375
376 \Subsection{STG Syntax}{stg-syntax}
377
378
379 \ToDo{Insert STG syntax with appropriate changes.}
380
381
382 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
383 \part{System Overview}
384 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
385
386 This part is concerned with defining the external interfaces of the
387 major components of the system; the next part is concerned with their
388 inner workings.
389
390 The major components of the system are:
391 \begin{itemize}
392
393 \item 
394
395 The evaluators (\secref{sm-overview}) are responsible for
396 evaluating heap objects.  The system supports two evaluators: the
397 machine code evaluator; and the bytecode evaluator.
398
399 \item 
400
401 The scheduler (\secref{scheduler-overview}) acts as the
402 coordinator for the whole system.  It is responsible for switching
403 between evaluators, switching between threads, garbage collection,
404 communication between multiple processors, etc.
405
406 \item 
407
408 The storage manager (\secref{evaluators-overview}) is
409 responsible for allocating blocks of contiguous memory and for garbage
410 collection.
411
412 \item 
413
414 The loader (\secref{loader-overview}) is responsible for
415 loading machine code and bytecode files from the file system and for
416 resolving references between separately compiled modules.
417
418 \item 
419
420 The compilers (\secref{compilers-overview}) generate machine
421 code and bytecode files which can be loaded by the loader.
422
423 \end{itemize}
424
425 \ToDo{Insert diagram showing all components underneath the scheduler
426 and communicating only with the scheduler}
427
428
429 \Section{The Evaluators}{evaluators-overview}
430
431 There are two evaluators: a machine code evaluator and a bytecode
432 evaluator.  The evaluators task is to evaluate code within a thread
433 until one of the following happens:
434
435 \begin{itemize}
436 \item heap overflow
437 \item stack overflow
438 \item it is preempted
439 \item it blocks in one of the concurrency primitives
440 \item it performs a safe ccall
441 \item it needs to switch to the other evaluator.
442 \end{itemize}
443
444 The evaluators expect to find a closure on top of the thread's stack
445 and terminate with a closure on top of the thread's stack.
446
447 \Subsection{Evaluation Model}{evaluation-model}
448
449 Whilst the evaluators differ internally, they share a common
450 evaluation model and many object representations.
451
452 \Subsubsection{Heap objects}{heap-objects-overview}
453
454 The choice of heap and stack objects used by the evaluators is tightly
455 bound to the evaluation model.  This section provides an overview of
456 the most important heap and stack objects; further details are given
457 later.
458
459 All heap objects look like this:
460
461 \begin{center}
462 \begin{tabular}{|l|l|l|l|}\hline
463 \emph{Header} & \emph{Payload} \\ \hline
464 \end{tabular}
465 \end{center}
466
467 The headers vary between different kinds of object but they all start
468 with a pointer to a pair consisting of an \emph{info table} and some
469 \emph{entry code}.  The info table is used both by the evaluators and
470 by the storage manager and contains a @type@ field which identifies
471 which kind of heap object uses it and determines the interpretation of
472 the payload and of the other fields of the info table.  The entry code
473 is some machine code used by the machine code evaluator to evaluate
474 closures and raises an error for other kinds of objects.
475
476 The major kinds of heap object used are as follows.  (For simplicity,
477 this description omits certain optimisations and extra fields required
478 by the garbage collector.)
479
480 \begin{description}
481
482 \item[Constructors] are used to represent data constructors.  Their
483 payload consists of the fields of the constructor; the tag of the
484 constructor is stored in the info table.
485
486 \begin{center}
487 \begin{tabular}{|l|l|l|l|}\hline
488 @CONSTR@ & \emph{Fields} \\ \hline
489 \end{tabular}
490 \end{center}
491
492 \item[Primitive objects] are used to represent objects with unlifted
493 types which are too large to fit in a register (or stack slot) or for
494 which sharing must be preserved.  Primitive objects include large
495 objects such as multiple precision integers and immutable arrays and
496 mutable objects such as mutable arrays, mutable variables, MVar's,
497 IVar's and foreign object pointers.  Since primitive objects are not
498 lifted, they cannot be entered.  Their payload varies according to the
499 kind of object.
500
501 \item[Function closures] are used to represent functions.  Their
502 payload (if any) consists of the free variables of the function.
503
504 \begin{center}
505 \begin{tabular}{|l|l|l|l|}\hline
506 @FUN@ & \emph{Free Variables} \\ \hline
507 \end{tabular}
508 \end{center}
509
510 Function closures are only generated by the machine code compiler.
511
512 \item[Thunks] are used to represent unevaluated expressions which will
513 be updated with their result.  Their payload (if any) consists of the
514 free variables of the function.  The entry code for a thunk starts by
515 pushing an \emph{update frame} onto the stack.  When evaluation of the
516 thunk completes, the update frame will cause the thunk to be
517 overwritten again with an \emph{indirection} to the result of the
518 thunk, which is always a constructor or a partial application.
519
520 \begin{center}
521 \begin{tabular}{|l|l|l|l|}\hline
522 @THUNK@ & \emph{Free Variables} \\ \hline
523 \end{tabular}
524 \end{center}
525
526 Thunks are only generated by the machine code evaluator.
527
528 \item[Byte-code Objects (@BCO@s)] are generated by the bytecode
529 compiler.  In conjunction with \emph{updatable applications} and
530 \emph{non-updatable applications} they are used to represent
531 functions, unevaluated expressions and return addresses.
532
533 \begin{center}
534 \begin{tabular}{|l|l|l|l|}\hline
535 @BCO@ & \emph{Constant Pool} & \emph{Bytecodes} \\ \hline
536 \end{tabular}
537 \end{center}
538
539 \item[Non-updatable (Partial) Applications] are used to represent the
540 application of a function to an insufficient number of arguments.
541 Their payload consists of the function and the arguments received so far.
542
543 \begin{center}
544 \begin{tabular}{|l|l|l|l|}\hline
545 @PAP@ & \emph{Function Closure} & \emph{Arguments} \\ \hline
546 \end{tabular}
547 \end{center}
548
549 @PAP@s are used when a function is applied to too few arguments and by
550 code generated by the lambda-lifting phase of the bytecode compiler.
551
552 \item[Updatable Applications] are used to represent the application of
553 a function to a sufficient number of arguments.  Their payload
554 consists of the function and its arguments.  
555
556 Updateable applications are like thunks: on entering an updateable
557 application, the evaluators push an \emph{update frame} onto the stack
558 and overwrite the application with a \emph{black hole}; when
559 evaluation completes, the evaluators overwrite the application with an
560 \emph{indirection} to the result of the application.
561
562 \begin{center}
563 \begin{tabular}{|l|l|l|l|}\hline
564 @AP@ & \emph{Function Closure} & \emph{Arguments} \\ \hline
565 \end{tabular}
566 \end{center}
567
568 @AP@s are only generated by the bytecode compiler.
569
570 \item[Black holes] are used to mark updateable closures which are
571 currently being evaluated.  ``Black holing'' an object cures a
572 potential space leak and detects certain classes of infinite loops.
573 More imporantly, black holes act as synchronisation objects between
574 separate threads: if a second thread tries to enter an updateable
575 closure which is already being evaluated, the second thread is added
576 to a list of blocked threads and the thread is suspended.
577
578 When evaluation of the black-holed closure completes, the black hole
579 is overwritten with an indirection to the result of the closure and
580 any blocked threads are restored to the runnable queue.
581
582 Closures are overwritten by black-holes during a ``lazy black-holing''
583 phase which runs on each thread when it returns to the scheduler.
584 \ToDo{section describing lazy black-holing}.
585
586 \begin{center}
587 \begin{tabular}{|l|l|l|l|}\hline
588 @BLACKHOLE@ & \emph{Blocked threads} \\ \hline
589 \end{tabular}
590 \end{center}
591
592 \ToDo{In a single threaded system, it's trivial to detect infinite
593 loops: reentering a BLACKHOLE is always an error.  How easy is it in a
594 multi-threaded system?}
595
596 \item[Indirections] are used to update an unevaluated closure with its
597 (usually fully evaluated) result in situations where it isn't possible
598 to perform an update in place.  (In the current system, we always
599 update with an indirection to avoid duplicating the result when doing
600 an update in place.)
601
602 \begin{center}
603 \begin{tabular}{|l|l|l|l|}\hline
604 @IND@ & \emph{Closure} \\ \hline
605 \end{tabular}
606 \end{center}
607
608 Indirections needn't always point to a closure in WHNF.  They can
609 point to a chain of indirections which point to an evaluated closure.
610
611 \item[Thread State Objects (@TSO@s)] represent Haskell threads.  Their
612 payload consists of some per-thread information such as the Thread ID
613 and the status of the thread (runnable, blocked etc.), and the
614 thread's stack.  See @TSO.h@ for the full story.  @TSO@s may be
615 resized by the scheduler if its stack is too small or too large.
616
617 The thread stack grows downwards from higher to lower addresses.
618
619 \begin{center}
620 \begin{tabular}{|l|l|l|l|}\hline
621 @TSO@ & \emph{Thread info} & \emph{Stack} \\ \hline
622 \end{tabular}
623 \end{center}
624
625 \end{description}
626
627 \Subsubsection{Stack objects}{stack-objects-overview}
628
629 The stack contains a mixture of \emph{pending arguments} and 
630 \emph{stack objects}.
631
632 Pending arguments are arguments to curried functions which have not
633 yet been incorporated into an activation frame.  For example, when
634 evaluating @let { g x y = x + y; f x = g{x} } in f{3,4}@, the
635 evaluator pushes both arguments onto the stack and enters @f@.  @f@
636 only requires one argument so it leaves the second argument as a
637 \emph{pending argument}.  The pending argument remains on the stack
638 until @f@ calls @g@ which requires two arguments: the argument passed
639 to it by @f@ and the pending argument which was passed to @f@.
640
641 Unboxed pending arguments are always preceeded by a ``tag'' which says
642 how large the argument is.  This allows the garbage collector to
643 locate pointers within the stack.
644
645 There are three kinds of stack object: return addresses, update frames
646 and seq frames.  All stack objects look like this
647
648 \begin{center}
649 \begin{tabular}{|l|l|l|l|}\hline
650 \emph{Header} & \emph{Payload} \\ \hline
651 \end{tabular}
652 \end{center}
653
654 As with heap objects, the header starts with a pointer to a pair
655 consisting of an \emph{info table} and some \emph{entry code}.
656
657 \begin{description}
658
659 \item[Return addresses] are used to cause selection and execution of
660 case alternatives when a constructor is returned.  Return addresses
661 generated by the machine code compiler look like this:
662
663 \begin{center}
664 \begin{tabular}{|l|l|l|l|}\hline
665 \emph{@RET_XXX@} & \emph{Free Variables of the case alternatives} \\ \hline
666 \end{tabular}
667 \end{center}
668
669 The free variables are a mixture of pointers and non-pointers whose
670 layout is described by a bitmask in the info table.
671
672 There are several kinds of @RET_XXX@ return address - see
673 \secref{activation-records} for the details.
674
675 Return addresses generated by the bytecode compiler look like this:
676 \begin{center}
677 \begin{tabular}{|l|l|l|l|}\hline
678 \emph{@BCO_RET@} & \emph{BCO} & \emph{Free Variables of the case alternatives} \\ \hline
679 \end{tabular}
680 \end{center}
681
682 There is just one @BCO_RET@ info pointer.  We avoid needing different
683 @BCO_RET@s for each stack layout by tagging unboxed free variables as
684 though they were pending arguments.
685
686 \item[Update frames] are used to trigger updates.  When an update
687 frame is entered, it overwrites the updatee with an indirection to the
688 result, restarts any threads blocked on the @BLACKHOLE@ and returns to
689 the stack object underneath the update frame.
690
691 \begin{center}
692 \begin{tabular}{|l|l|l|l|}\hline
693 \emph{@UPDATE_FRAME@} & \emph{Next Update Frame} & \emph{Updatee} \\ \hline
694 \end{tabular}
695 \end{center}
696
697 \item[Seq frames] are used to implement the polymorphic @seq@
698 primitive.  They are a special kind of update frame, and are linked on
699 the update frame list.
700
701 \begin{center}
702 \begin{tabular}{|l|l|l|l|}\hline
703 \emph{@SEQ_FRAME@} & \emph{Next Update Frame} \\ \hline
704 \end{tabular}
705 \end{center}
706
707 \item[Stop frames] are put on the bottom of each thread's stack, and
708 act as sentinels for the update frame list (i.e. the last update frame
709 points to the stop frame).  Returning to a stop frame terminates the
710 thread.  Stop frames have no payload:
711
712 \begin{center}
713 \begin{tabular}{|l|l|l|l|}\hline
714 \emph{@SEQ_FRAME@} \\ \hline
715 \end{tabular}
716 \end{center}
717
718 \end{description}
719
720 \Subsubsection{Case expressions}{case-expr-overview}
721
722 In the STG language, all evaluation is triggered by evaluating a case
723 expression.  When evaluating a case expression @case e of alts@, the
724 evaluators pushes a return address onto the stack and evaluate the
725 expression @e@.  When @e@ eventually reduces to a constructor, the
726 return address on the stack is entered.  The details of how the
727 constructor is passed to the return address and how the appropriate
728 case alternative is selected vary between evaluators.
729
730 Case expressions for unboxed data types are essentially the same: the
731 case expression pushes a return address onto the stack before
732 evaluating the scrutinee; when a function returns an unboxed value, it
733 enters the return address on top of the stack.
734
735
736 \Subsubsection{Function applications}{fun-app-overview}
737
738 In the STG language, all function calls are tail calls.  The arguments
739 are pushed onto the stack and the function closure is entered.  If any
740 arguments are unboxed, they must be tagged as unboxed pending
741 arguments.  Entering a closure is just a special case of calling a
742 function with no arguments.
743
744
745 \Subsubsection{Let expressions}{let-expr-overview}
746
747 In the STG language, almost all heap allocation is caused by let
748 expressions.  Filling in the contents of a set of mutually recursive
749 heap objects is simple enough; the only difficulty is that once the
750 heap space has been allocated, the thread must not return to the
751 scheduler until after the objects are filled in.
752
753
754 \Subsubsection{Primitive operations}{primop-overview}
755
756 \ToDo{}
757
758 Most primops are simple, some aren't.
759
760
761
762
763
764
765 \Section{Scheduler}{scheduler-overview}
766
767 The Scheduler is the heart of the run-time system.  A running program
768 consists of a single running thread, and a list of runnable and
769 blocked threads.  A thread is represented by a \emph{Thread Status
770 Object} (TSO), which contains a few words status information and a
771 stack.  Except for the running thread, all threads have a closure on
772 top of their stack; the scheduler restarts a thread by entering an
773 evaluator which performs some reduction and returns to the scheduler.
774
775 \Subsection{The scheduler's main loop}{scheduler-main-loop}
776
777 The scheduler consists of a loop which chooses a runnable thread and
778 invokes one of the evaluators which performs some reduction and
779 returns.
780
781 The scheduler also takes care of system-wide issues such as heap
782 overflow or communication with other processors (in the parallel
783 system) and thread-specific problems such as stack overflow.
784
785 \Subsection{Creating a thread}{create-thread}
786
787 Threads are created:
788
789 \begin{itemize}
790
791 \item
792
793 When the scheduler is first invoked.
794
795 \item
796
797 When a message is received from another processor (I think). (Parallel
798 system only.)
799
800 \item
801
802 When a C program calls some Haskell code.
803
804 \item
805
806 By @forkIO@, @takeMVar@ and (maybe) other Concurrent Haskell primitives.
807
808 \end{itemize}
809
810
811 \Subsection{Restarting a thread}{thread-restart}
812
813 When the scheduler decides to run a thread, it has to decide which
814 evaluator to use.  It does this by looking at the type of the closure
815 on top of the stack.
816 \begin{itemize}
817 \item @BCO@ $\Rightarrow$ bytecode evaluator
818 \item @FUN@ or @THUNK@ $\Rightarrow$ machine code evaluator
819 \item @CONSTR@ $\Rightarrow$ machine code evaluator
820 \item other $\Rightarrow$ either evaluator.
821 \end{itemize}
822
823 The only surprise in the above is that the scheduler must enter the
824 machine code evaluator if there's a constructor on top of the stack.
825 This allows the bytecode evaluator to return a constructor to a
826 machine code return address by pushing the constructor on top of the
827 stack and returning to the scheduler.  If the return address under the
828 constructor is @HUGS_RET@, the entry code for @HUGS_RET@ will
829 rearrange the stack so that the return @BCO@ is on top of the stack
830 and return to the scheduler which will then call the bytecode
831 evaluator.  There is little point in trying to shorten this slightly
832 indirect route since it is will happen very rarely if at all.
833
834 \note{As an optimisation, we could store the choice of evaluator in
835 the TSO status whenever we leave the evaluator.  This is required for
836 any thread, no matter what state it is in (blocked, stack overflow,
837 etc).  It isn't clear whether this would accomplish anything.}
838
839 \Subsection{Returning from a thread}{thread-return}
840
841 The evaluators return to the scheduler when any of the following
842 conditions arise:
843
844 \begin{itemize}
845 \item A heap check fails, and a garbage collection is required.
846
847 \item A stack check fails, and the scheduler must either enlarge the
848 current thread's stack, or flag an out of memory condition.
849
850 \item A thread enters a closure built by the other evaluator.  That
851 is, when the bytecode interpreter enters a closure compiled by GHC or
852 when the machine code evaluator enters a BCO.
853
854 \item A thread returns to a return continuation built by the other
855 evaluator.  That is, when the machine code evaluator returns to a
856 continuation built by Hugs or when the bytecode evaluator returns to a
857 continuation built by GHC.
858
859 \item The evaluator needs to perform a ``safe'' C call
860 (\secref{c-calls}).
861
862 \item The thread becomes blocked.  This happens when a thread requires
863 the result of a computation currently being performed by another
864 thread, or it reads a synchronisation variable that is currently empty
865 (\secref{MVAR}).
866
867 \item The thread is preempted (the preemption mechanism is described
868 in \secref{thread-preemption}).
869
870 \item The thread terminates.
871 \end{itemize}
872
873 Except when the thread terminates, the thread always terminates with a
874 closure on the top of the stack.  The mechanism used to trigger the
875 world switch and the choice of closure left on top of the stack varies
876 according to which world is being left and what is being returned.
877
878 \Subsubsection{Leaving the bytecode evaluator}{hugs-to-ghc-switch}
879
880 \paragraph{Entering a machine code closure}
881
882 When it enters a closure, the bytecode evaluator performs a switch
883 based on the type of closure (@AP@, @PAP@, @Ind@, etc).  On entering a
884 machine code closure, it returns to the scheduler with the closure on
885 top of the stack.
886
887 \paragraph{Returning a constructor}
888
889 When it enters a constructor, the bytecode evaluator tests the return
890 continuation on top of the stack.  If it is a machine code
891 continuation, it returns to the scheduler with the constructor on top
892 of the stack.
893
894 \note{This is why the scheduler must enter the machine code evaluator
895 if it finds a constructor on top of the stack.}
896
897 \paragraph{Returning an unboxed value}
898
899 \note{Hugs doesn't support unboxed values in source programs but they
900 are used for a few complex primops.}
901
902 When it returns an unboxed value, the bytecode evaluator tests the
903 return continuation on top of the stack.  If it is a machine code
904 continuation, it returns to the scheduler with the tagged unboxed
905 value and a special closure on top of the stack.  When the closure is
906 entered (by the machine code evaluator), it returns the unboxed value
907 on top of the stack to the return continuation under it.
908
909 The runtime library for GHC provides one of these closures for each unboxed
910 type.  Hugs cannot generate them itself since the entry code is really
911 very tricky.
912
913 \paragraph{Heap/Stack overflow and preemption}
914
915 The bytecode evaluator tests for heap/stack overflow and preemption
916 when entering a BCO and simply returns with the BCO on top of the
917 stack.
918
919 \Subsubsection{Leaving the machine code evaluator}{ghc-to-hugs-switch}
920
921 \paragraph{Entering a BCO}
922
923 The entry code for a BCO pushes the BCO onto the stack and returns to
924 the scheduler.
925
926 \paragraph{Returning a constructor}
927
928 We avoid the need to test return addresses in the machine code
929 evaluator by pushing a special return address on top of a pointer to
930 the bytecode return continuation.  \figref{hugs-return-stack1}
931 shows the state of the stack just before evaluating the scrutinee.
932
933 \begin{figure}[ht]
934 \begin{center}
935 @
936 | stack    |
937 +----------+
938 | bco      |--> BCO
939 +----------+
940 | HUGS_RET |
941 +----------+
942 @
943 %\input{hugs_return1.pstex_t}
944 \end{center}
945 \caption{Stack layout for evaluating a scrutinee}
946 \label{fig:hugs-return-stack1}
947 \end{figure}
948
949 This return address rearranges the stack so that the bco pointer is
950 above the constructor on the stack (as shown in
951 \figref{hugs-boxed-return}) and returns to the scheduler.
952
953 \begin{figure}[ht]
954 \begin{center}
955 @
956 | stack    |
957 +----------+
958 | con      |--> Constructor
959 +----------+
960 | bco      |--> BCO
961 +----------+
962 @
963 %\input{hugs_return2.pstex_t}
964 \end{center}
965 \caption{Stack layout for entering a Hugs return address}
966 \label{fig:hugs-boxed-return}
967 \end{figure}
968
969 \paragraph{Returning an unboxed value}
970
971 We avoid the need to test return addresses in the machine code
972 evaluator by pushing a special return address on top of a pointer to
973 the bytecode return continuation.  This return address rearranges the
974 stack so that the bco pointer is above the tagged unboxed value (as
975 shown in \figref{hugs-entering-unboxed-return}) and returns to the
976 scheduler.
977
978 \begin{figure}[ht]
979 \begin{center}
980 @
981 | stack    |
982 +----------+
983 | 1#       |
984 +----------+
985 | I#       |
986 +----------+
987 | bco      |--> BCO
988 +----------+
989 @
990 %\input{hugs_return2.pstex_t}
991 \end{center}
992 \caption{Stack layout for returning an unboxed value}
993 \label{fig:hugs-entering-unboxed-return}
994 \end{figure}
995
996 \paragraph{Heap/Stack overflow and preemption}
997
998 \ToDo{}
999
1000
1001 \Subsection{Preempting a thread}{thread-preemption}
1002
1003 Strictly speaking, threads cannot be preempted --- the scheduler
1004 merely sets a preemption request flag which the thread must arrange to
1005 test on a regular basis.  When an evaluator finds that the preemption
1006 request flag is set, it pushes an appropriate closure onto the stack
1007 and returns to the scheduler.
1008
1009 In the bytecode interpreter, the flag is tested whenever we enter a
1010 closure.  If the preemption flag is set, it leaves the closure on top
1011 of the stack and returns to the scheduler.
1012
1013 In the machine code evaluator, the flag is only tested when a heap or
1014 stack check fails.  This is less expensive than testing the flag on
1015 entering every closure but runs the risk that a thread will enter an
1016 infinite loop which does not allocate any space.  If the flag is set,
1017 the evaluator returns to the scheduler exactly as if a heap check had
1018 failed.
1019
1020 \Subsection{``Safe'' and ``unsafe'' C calls}{c-calls}
1021
1022 There are two ways of calling C: 
1023
1024 \begin{description}
1025
1026 \item[``Unsafe'' C calls] are used if the programer is certain that
1027 the C function will not do anything dangerous.  Unsafe C calls are
1028 faster but must be hand-checked by the programmer.
1029
1030 Dangerous things include:
1031
1032 \begin{itemize}
1033
1034 \item 
1035
1036 Call a system function such as @getchar@ which might block
1037 indefinitely.  This is dangerous because we don't want the entire
1038 runtime system to block just because one thread blocks.
1039
1040 \item
1041
1042 Call an RTS function which will block on the RTS access semaphore.
1043 This would lead to deadlock.
1044
1045 \item
1046
1047 Call a Haskell function.  This is just a special case of calling an
1048 RTS function.
1049
1050 \end{itemize}
1051
1052 Unsafe C calls are performed by pushing the arguments onto the C stack
1053 and jumping to the C function's entry point.  On exit, the result of
1054 the function is in a register which is returned to the Haskell code as
1055 an unboxed value.
1056
1057 \item[``Safe'' C calls] are used if the programmer suspects that the
1058 thread may do something dangerous.  Safe C calls are relatively slow
1059 but are less problematic.
1060
1061 Safe C calls are performed by pushing the arguments onto the Haskell
1062 stack, pushing a return continuation and returning a \emph{C function
1063 descriptor} to the scheduler.  The scheduler suspends the Haskell thread,
1064 spawns a new operating system thread which pops the arguments off the
1065 Haskell stack onto the C stack, calls the C function, pushes the
1066 function result onto the Haskell stack and informs the scheduler that
1067 the C function has completed and the Haskell thread is now runnable.
1068
1069 \end{description}
1070
1071 The bytecode evaluator will probably treat all C calls as being safe.
1072
1073 \ToDo{It might be good for the programmer to indicate how the program
1074 is unsafe.  For example, if we distinguish between C functions which
1075 might call Haskell functions and those which might block, we could
1076 perform an unsafe call for blocking functions in a single-threaded
1077 system or, perhaps, in a multi-threaded system which only happens to
1078 have a single thread at the moment.}
1079
1080
1081
1082 \Section{The Storage Manager}{sm-overview}
1083
1084 The storage manager is responsible for managing the heap and all
1085 objects stored in it.  It provides special support for lazy evaluation
1086 and for foreign function calls.
1087
1088 \Subsection{SM support for lazy evaluation}{sm-lazy-evaluation}
1089
1090 \begin{itemize}
1091 \item
1092
1093 Indirections are shorted out.
1094
1095 \item
1096
1097 Update frames pointing to unreachable objects are squeezed out.
1098
1099 \ToDo{Part IV suggests this doesn't happen.}
1100
1101 \item
1102
1103 Adjacent update frames (for different closures) are compressed to a
1104 single update frame pointing to a single black hole.
1105
1106 \end{itemize}
1107
1108
1109 \Subsection{SM support for foreign function calls}{sm-foreign-calls}
1110
1111 \begin{itemize}
1112
1113 \item
1114
1115 Stable pointers allow other languages to access Haskell objects.
1116
1117 \item
1118
1119 Weak pointers and foreign objects provide finalisation support for
1120 Haskell references to external objects.
1121
1122 \end{itemize}
1123
1124 \Subsection{Misc}{sm-misc}
1125
1126 \begin{itemize}
1127
1128 \item
1129
1130 If the stack contains a large amount of free space, the storage
1131 manager may shrink the stack.  If it shrinks the stack, it guarantees
1132 never to leave less than @MIN_SIZE_SHRUNKEN_STACK@ empty words on the
1133 stack when it does so.
1134
1135 \item
1136
1137 For efficiency reasons, very large objects (eg large arrays and TSOs)
1138 are not moved if possible.
1139
1140 \end{itemize}
1141
1142
1143 \Section{The Compilers}{compilers-overview}
1144
1145 Need to describe interface files, format of bytecode files, symbols
1146 defined by machine code files.
1147
1148 \Subsection{Interface Files}{interface-files}
1149
1150 Here's an example - but I don't know the grammar - ADR.
1151 @
1152 _interface_ Main 1
1153 _exports_
1154 Main main ;
1155 _declarations_
1156 1 main _:_ IOBase.IO PrelBase.();;
1157 @
1158
1159 \Subsection{Bytecode files}{bytecode-files}
1160
1161 (All that matters here is what the loader sees.)
1162
1163 \Subsection{Machine code files}{asm-files}
1164
1165 (Again, all that matters is what the loader sees.)
1166
1167 \Section{The Loader}{loader-overview}
1168
1169 In a batch mode system, we can statically link all the modules
1170 together.  In an interactive system we need a loader which will
1171 explicitly load and unload individual modules (or, perhaps, blocks of
1172 mutually dependent modules) and resolve references between modules.
1173
1174 While many operating systems provide support for dynamic loading and
1175 will automatically resolve cross-module references for us, we generally
1176 cannot rely on being able to load mutually dependent modules.
1177
1178 A portable solution is to perform some of the linking ourselves.  Each module
1179 should provide three global symbols: 
1180 \begin{itemize}
1181 \item
1182 An initialisation routine.  (Might also be used for finalisation.)
1183 \item
1184 A table of symbols it exports.
1185 Entries in this table consist of the symbol name and the address of the
1186 name's value.
1187 \item
1188 A table of symbols it imports.
1189 Entries in this table consist of the symbol name and a list of references
1190 to that symbol.
1191 \end{itemize}
1192
1193 On loading a group of modules, the loader adds the contents of the
1194 export lists to a symbol table and then fills in all the references in the
1195 import lists.
1196
1197 References in import lists are of two types:
1198 \begin{description}
1199 \item[ References in machine code ]
1200
1201 The most efficient approach is to patch the machine code directly, but
1202 this will be a lot of work, very painful to port and rather fragile.
1203
1204 Alternatively, the loader could store the value of each symbol in the
1205 import table for each module and the compiled code can access all
1206 external objects through the import table.  This requires that the
1207 import table be writable but does not require that the machine code or
1208 info tables be writable.
1209
1210 \item[ References in data structures (SRTs and static data constructors) ]
1211
1212 Either we patch the SRTs and constructors directly or we somehow use
1213 indirections through the symbol table.  Patching the SRTs requires
1214 that we make them writable and prevents us from making effective use
1215 of virtual memories that use copy-on-write policies (this only makes a
1216 difference if we want to run several copies of the same program
1217 simultaneously).  Using an indirection is possible but tricky.
1218
1219 Note: We could avoid patching machine code if all references to
1220 external references went through the SRT --- then we just have one
1221 thing to patch.  But the SRT always contains a pointer to the closure
1222 rather than the fast entry point (say), so we'd take a big performance
1223 hit for doing this.
1224
1225 \end{description}
1226
1227 Using the above scheme, all accesses to ``external'' objects involve a
1228 layer of indirection.  To avoid this overhead, the machine code
1229 compiler might provide a way for the programmer to specify which
1230 modules will be statically linked and which will be dynamically linked
1231 --- the idea being that statically linked code and data will be
1232 accessed directly.
1233
1234
1235 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1236 \part{Internal details}
1237 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1238
1239 This part is concerned with the internal details of the components
1240 described in the previous part.
1241
1242 The major components of the system are:
1243 \begin{itemize}
1244 \item The scheduler (\secref{scheduler-internals})
1245 \item The storage manager (\secref{storage-manager-internals})
1246 \item The evaluators
1247 \item The loader
1248 \item The compilers
1249 \end{itemize}
1250
1251 \Section{The Scheduler}{scheduler-internals}
1252
1253 \ToDo{Detailed description of scheduler}
1254
1255 Many heap objects contain fields allowing them to be inserted onto lists
1256 during evaluation or during garbage collection. The lists required by
1257 the evaluator and storage manager are as follows.
1258
1259 \begin{itemize}
1260
1261 \item 4 lists of threads: runnable threads, sleeping threads, threads
1262 waiting for timeout and threads waiting for I/O.
1263
1264 \item The \emph{mutables list} is a list of all objects in the old
1265 generation which might contain pointers into the new generation.  Most
1266 of the objects on this list are indirections (\secref{IND})
1267 or ``mutable.''  (\secref{mutables}.)
1268
1269 \item The \emph{Foreign Object list} is a list of all foreign objects
1270  which have not yet been deallocated. (\secref{FOREIGN}.)
1271
1272 \item The \emph{Spark pool} is a doubly(?) linked list of Spark objects
1273 maintained by the parallel system.  (\secref{SPARK}.)
1274
1275 \item The \emph{Blocked Fetch list} (or
1276 lists?). (\secref{BLOCKED_FETCH}.)
1277
1278 \item For each thread, there is a list of all update frames on the
1279 stack.  (\secref{data-updates}.)
1280
1281 \item The Stable Pointer Table is a table of pointers to objects which
1282 are known to the outside world and must be retained by the garbage
1283 collector even if they are not accessible from within the heap.
1284
1285 \end{itemize}
1286
1287 \ToDo{The links for these fields are usually inserted immediately
1288 after the fixed header except ...}
1289
1290
1291
1292 \Section{The Storage Manager}{storage-manager-internals}
1293
1294 \subsection{Misc Text looking for a home}
1295
1296 A \emph{value} may be:
1297 \begin{itemize}
1298 \item \emph{Boxed}, i.e.~represented indirectly by a pointer to a heap object (e.g.~foreign objects, arrays); or
1299 \item \emph{Unboxed}, i.e.~represented directly by a bit-pattern in one or more registers (e.g.~@Int#@ and @Float#@).
1300 \end{itemize}
1301 All \emph{pointed} values are \emph{boxed}.  
1302
1303
1304 \Subsection{Heap Objects}{heap-objects}
1305 \label{sec:fixed-header}
1306
1307 \begin{figure}
1308 \begin{center}
1309 \input{closure}
1310 \end{center}
1311 \ToDo{Fix this picture}
1312 \caption{A closure}
1313 \label{fig:closure}
1314 \end{figure}
1315
1316 Every \emph{heap object} is a contiguous block of memory, consisting
1317 of a fixed-format \emph{header} followed by zero or more \emph{data
1318 words}.
1319
1320 The header consists of the following fields:
1321 \begin{itemize}
1322 \item A one-word \emph{info pointer}, which points to
1323 the object's static \emph{info table}.
1324 \item Zero or more \emph{admin words} that support
1325 \begin{itemize}
1326 \item Profiling (notably a \emph{cost centre} word).
1327   \note{We could possibly omit the cost centre word from some 
1328   administrative objects.}
1329 \item Parallelism (e.g. GranSim keeps the object's global address here,
1330 though GUM keeps a separate hash table).
1331 \item Statistics (e.g. a word to track how many times a thunk is entered.).
1332
1333 We add a Ticky word to the fixed-header part of closures.  This is
1334 used to indicate if a closure has been updated but not yet entered. It
1335 is set when the closure is updated and cleared when subsequently
1336 entered.  \footnote{% NB: It is \emph{not} an ``entry count'', it is
1337 an ``entries-after-update count.''  The commoning up of @CONST@,
1338 @CHARLIKE@ and @INTLIKE@ closures is turned off(?) if this is
1339 required. This has only been done for 2s collection.  }
1340
1341 \end{itemize}
1342 \end{itemize}
1343
1344 Most of the RTS is completely insensitive to the number of admin
1345 words.  The total size of the fixed header is given by
1346 @sizeof(StgHeader)@.
1347
1348 \Subsection{Info Tables}{info-tables}
1349
1350 An \emph{info table} is a contiguous block of memory, laid out as follows:
1351
1352 \begin{center}
1353 \begin{tabular}{|r|l|}
1354    \hline Parallelism Info      & variable
1355 \\ \hline Profile Info          & variable
1356 \\ \hline Debug Info            & variable
1357 \\ \hline Static reference table  & pointer word (optional)
1358 \\ \hline Storage manager layout info & pointer word
1359 \\ \hline Closure flags         & 8 bits
1360 \\ \hline Closure type          & 8 bits
1361 \\ \hline Constructor Tag / SRT length          & 16 bits
1362 \\ \hline entry code
1363 \\       \vdots
1364 \end{tabular}
1365 \end{center}
1366
1367 On a 64-bit machine the tag, type and flags fields will all be doubled
1368 in size, so the info table is a multiple of 64 bits.
1369
1370 An info table has the following contents (working backwards in memory
1371 addresses):
1372
1373 \begin{itemize}
1374
1375 \item The \emph{entry code} for the closure.  This code appears
1376 literally as the (large) last entry in the info table, immediately
1377 preceded by the rest of the info table.  An \emph{info pointer} always
1378 points to the first byte of the entry code.
1379
1380 \item A 16-bit constructor tag / SRT length.  For a constructor info
1381 table this field contains the tag of the constructor, in the range
1382 $0..n-1$ where $n$ is the number of constructors in the datatype.
1383 Otherwise, it contains the number of entries in this closure's Static
1384 Reference Table (\secref{srt}).
1385
1386 \item An 8-bit {\em closure type field}, which identifies what kind of
1387 closure the object is.  The various types of closure are described in
1388 \secref{closures}.
1389
1390 \item an 8-bit flags field, which holds various flags pertaining to
1391 the closure type.
1392
1393 \item A single pointer or word --- the {\em storage manager info
1394 field}, contains auxiliary information describing the closure's
1395 precise layout, for the benefit of the garbage collector and the code
1396 that stuffs graph into packets for transmission over the network.
1397 There are three kinds of layout information:
1398
1399 \begin{itemize}
1400 \item Standard layout information is for closures which place pointers
1401 before non-pointers in instances of the closure (this applies to most
1402 heap-based and static closures, but not activation records).  The
1403 layout information for standard closures is
1404
1405         \begin{itemize}
1406         \item Number of pointer fields (16 bits).
1407         \item Number of non-pointer fields (16 bits).
1408         \end{itemize}
1409
1410 \item Activation records don't have pointers before non-pointers,
1411 since stack-stubbing requires that the record has holes in it.  The
1412 layout is therefore represented by a bitmap in which each '1' bit
1413 represents a non-pointer word.  This kind of layout info is used for
1414 @RET_SMALL@ and @RET_VEC_SMALL@ closures.
1415
1416 \item If an activation record is longer than 32 words, then the layout
1417 field contains a pointer to a bitmap record, consisting of a length
1418 field followed by two or more bitmap words.  This layout information
1419 is used for @RET_BIG@ and @RET_VEC_BIG@ closures.
1420
1421 \item Selector Thunks (\secref{THUNK_SELECTOR}) use the closure
1422 layout field to hold the selector index, since the layout is always
1423 known (the closure contains a single pointer field).
1424 \end{itemize}
1425
1426 \item A one-word {\em Static Reference Table} field.  This field
1427 points to the static reference table for the closure (\secref{srt}),
1428 and is only present for the following closure types:
1429
1430         \begin{itemize}
1431         \item @FUN_*@
1432         \item @THUNK_*@
1433         \item @RET_*@
1434         \end{itemize}
1435
1436 \ToDo{Expand the following explanation.}
1437
1438 An SRT is basically a vector of pointers to static closures.  A
1439 top-level function or thunk will have an SRT (which might be empty),
1440 which points to all the static closures referenced by that function or
1441 thunk.  Every non-top-level thunk or function also has an SRT, but
1442 it'll be a sub-sequence of the top-level SRT, so we just store a
1443 pointer and a length in the info table - the pointer points into the
1444 middle of the larger SRT.
1445
1446 At GC time, the garbage collector traverses the transitive closure of
1447 all the SRTs reachable from the roots, and thereby discovers which
1448 CAFs are live.
1449   
1450 \item \emph{Profiling info\/}
1451
1452 \ToDo{The profiling info is completely bogus.  I've not deleted it
1453 from the document but I've commented it all out.}
1454
1455 % change to \iftrue to uncomment this section
1456 \iffalse
1457
1458 Closure category records are attached to the info table of the
1459 closure. They are declared with the info table. We put pointers to
1460 these ClCat things in info tables.  We need these ClCat things because
1461 they are mutable, whereas info tables are immutable.  Hashing will map
1462 similar categories to the same hash value allowing statistics to be
1463 grouped by closure category.
1464
1465 Cost Centres and Closure Categories are hashed to provide indexes
1466 against which arbitrary information can be stored. These indexes are
1467 memoised in the appropriate cost centre or category record and
1468 subsequent hashes avoided by the index routine (it simply returns the
1469 memoised index).
1470
1471 There are different features which can be hashed allowing information
1472 to be stored for different groupings. Cost centres have the cost
1473 centre recorded (using the pointer), module and group. Closure
1474 categories have the closure description and the type
1475 description. Records with the same feature will be hashed to the same
1476 index value.
1477
1478 The initialisation routines, @init_index_<feature>@, allocate a hash
1479 table in which the cost centre / category records are stored. The
1480 lower bound for the table size is taken from @max_<feature>_no@. They
1481 return the actual table size used (the next power of 2). Unused
1482 locations in the hash table are indicated by a 0 entry. Successive
1483 @init_index_<feature>@ calls just return the actual table size.
1484
1485 Calls to @index_<feature>@ will insert the cost centre / category
1486 record in the @<feature>@ hash table, if not already inserted. The hash
1487 index is memoised in the record and returned. 
1488
1489 CURRENTLY ONLY ONE MEMOISATION SLOT IS AVILABLE IN EACH RECORD SO
1490 HASHING CAN ONLY BE DONE ON ONE FEATURE FOR EACH RECORD. This can be
1491 easily relaxed at the expense of extra memoisation space or continued
1492 rehashing.
1493
1494 The initialisation routines must be called before initialisation of
1495 the stacks and heap as they require to allocate storage. It is also
1496 expected that the caller may want to allocate additional storage in
1497 which to store profiling information based on the return table size
1498 value(s).
1499
1500 \begin{center}
1501 \begin{tabular}{|l|}
1502    \hline Hash Index
1503 \\ \hline Selected
1504 \\ \hline Kind
1505 \\ \hline Description String
1506 \\ \hline Type String
1507 \\ \hline
1508 \end{tabular}
1509 \end{center}
1510
1511 \begin{description}
1512 \item[Hash Index] Memoised copy
1513 \item[Selected] 
1514   Is this category selected (-1 == not memoised, selected? 0 or 1)
1515 \item[Kind]
1516 One of the following values (defined in CostCentre.lh):
1517
1518 \begin{description}
1519 \item[@CON_K@]
1520 A constructor.
1521 \item[@FN_K@]
1522 A literal function.
1523 \item[@PAP_K@]
1524 A partial application.
1525 \item[@THK_K@]
1526 A thunk, or suspension.
1527 \item[@BH_K@]
1528 A black hole.
1529 \item[@ARR_K@]
1530 An array.
1531 \item[@ForeignObj_K@]
1532 A Foreign object (non-Haskell heap resident).
1533 \item[@SPT_K@]
1534 The Stable Pointer table.  (There should only be one of these but it
1535 represents a form of weak space leak since it can't shrink to meet
1536 non-demand so it may be worth watching separately? ADR)
1537 \item[@INTERNAL_KIND@]
1538 Something internal to the runtime system.
1539 \end{description}
1540
1541
1542 \item[Description] Source derived string detailing closure description.
1543 \item[Type] Source derived string detailing closure type.
1544 \end{description}
1545
1546 \fi % end of commented out stuff
1547
1548 \item \emph{Parallelism info\/}
1549 \ToDo{}
1550
1551 \item \emph{Debugging info\/}
1552 \ToDo{}
1553
1554 \end{itemize}
1555
1556
1557 %-----------------------------------------------------------------------------
1558 \Subsection{Kinds of Heap Object}{closures}
1559
1560 Heap objects can be classified in several ways, but one useful one is
1561 this:
1562 \begin{itemize}
1563 \item 
1564 \emph{Static closures} occupy fixed, statically-allocated memory
1565 locations, with globally known addresses.
1566
1567 \item 
1568 \emph{Dynamic closures} are individually allocated in the heap.
1569
1570 \item 
1571 \emph{Stack closures} are closures allocated within a thread's stack
1572 (which is itself a heap object).  Unlike other closures, there are
1573 never any pointers to stack closures.  Stack closures are discussed in
1574 \secref{TSO}.
1575
1576 \end{itemize}
1577 A second useful classification is this:
1578 \begin{itemize}
1579
1580 \item \emph{Executive objects}, such as thunks and data constructors,
1581 participate directly in a program's execution.  They can be subdivided
1582 into three kinds of objects according to their type: \begin{itemize}
1583
1584 \item \emph{Pointed objects}, represent values of a \emph{pointed}
1585 type (<.pointed types launchbury.>) --i.e.~a type that includes
1586 $\bottom$ such as @Int@ or @Int# -> Int#@.
1587
1588 \item \emph{Unpointed objects}, represent values of a \emph{unpointed}
1589 type --i.e.~a type that does not include $\bottom$ such as @Int#@ or
1590 @Array#@.
1591
1592 \item \emph{Activation frames}, represent ``continuations''.  They are
1593 always stored on the stack and are never pointed to by heap objects or
1594 passed as arguments.  \note{It's not clear if this will still be true
1595 once we support speculative evaluation.}
1596
1597 \end{itemize}
1598
1599 \item \emph{Administrative objects}, such as stack objects and thread
1600 state objects, do not represent values in the original program.
1601 \end{itemize}
1602
1603 Only pointed objects can be entered.  If an unpointed object is
1604 entered the program will usually terminate with a fatal error.
1605
1606 This section enumerates all the kinds of heap objects in the system.
1607 Each is identified by a distinct closure type field in its info table.
1608
1609 \begin{tabular}{|l|l|l|l|l|l|l|l|l|l|l|}
1610 \hline
1611
1612 closure type          & Section \\
1613                       
1614 \hline                          
1615 \emph{Pointed} \\      
1616 \hline                
1617                       
1618 @CONSTR@              & \ref{sec:CONSTR}    \\
1619 @CONSTR_p_n@          & \ref{sec:CONSTR}    \\
1620 @CONSTR_STATIC@       & \ref{sec:CONSTR}    \\
1621 @CONSTR_NOCAF_STATIC@ & \ref{sec:CONSTR}    \\
1622                       
1623 @FUN@                 & \ref{sec:FUN}       \\
1624 @FUN_p_n@             & \ref{sec:FUN}       \\
1625 @FUN_STATIC@          & \ref{sec:FUN}       \\
1626                       
1627 @THUNK@               & \ref{sec:THUNK}     \\
1628 @THUNK_p_n@           & \ref{sec:THUNK}     \\
1629 @THUNK_STATIC@        & \ref{sec:THUNK}     \\
1630 @THUNK_SELECTOR@      & \ref{sec:THUNK_SELECTOR} \\
1631                       
1632 @BCO@                 & \ref{sec:BCO}       \\
1633                       
1634 @AP_UPD@              & \ref{sec:AP_UPD}    \\
1635 @PAP@                 & \ref{sec:PAP}       \\
1636                       
1637 @IND@                 & \ref{sec:IND}       \\
1638 @IND_OLDGEN@          & \ref{sec:IND}       \\
1639 @IND_PERM@            & \ref{sec:IND}       \\
1640 @IND_OLDGEN_PERM@     & \ref{sec:IND}       \\
1641 @IND_STATIC@          & \ref{sec:IND}       \\
1642                       
1643 @CAF_UNENTERED@       & \ref{sec:CAF}       \\
1644 @CAF_ENTERED@         & \ref{sec:CAF}       \\
1645 @CAF_BLACKHOLE@       & \ref{sec:CAF}       \\
1646
1647 \hline                
1648 \emph{Unpointed} \\    
1649 \hline                
1650                                       
1651 @BLACKHOLE@           & \ref{sec:BLACKHOLE} \\
1652 @BLACKHOLE_BQ@        & \ref{sec:BLACKHOLE_BQ} \\
1653
1654 @MVAR@                & \ref{sec:MVAR}      \\
1655
1656 @ARR_WORDS@           & \ref{sec:ARR_WORDS} \\
1657
1658 @MUTARR_PTRS@         & \ref{sec:MUT_ARR_PTRS} \\
1659 @MUTARR_PTRS_FROZEN@  & \ref{sec:MUT_ARR_PTRS_FROZEN} \\
1660
1661 @MUT_VAR@              & \ref{sec:MUT_VAR}    \\
1662
1663 @WEAK@                & \ref{sec:WEAK}   \\
1664 @FOREIGN@             & \ref{sec:FOREIGN}   \\
1665 @STABLE_NAME@         & \ref{sec:STABLE_NAME}   \\
1666 \hline
1667 \end{tabular}
1668
1669 Activation frames do not live (directly) on the heap --- but they have
1670 a similar organisation.
1671
1672 \begin{tabular}{|l|l|}\hline
1673 closure type            & Section                       \\ \hline
1674 @RET_SMALL@             & \ref{sec:activation-records}  \\
1675 @RET_VEC_SMALL@         & \ref{sec:activation-records}  \\
1676 @RET_BIG@               & \ref{sec:activation-records}  \\
1677 @RET_VEC_BIG@           & \ref{sec:activation-records}  \\
1678 @UPDATE_FRAME@          & \ref{sec:activation-records}  \\
1679 @CATCH_FRAME@           & \ref{sec:activation-records}  \\
1680 @SEQ_FRAME@             & \ref{sec:activation-records}  \\
1681 @STOP_FRAME@            & \ref{sec:activation-records}  \\
1682 \hline
1683 \end{tabular}
1684
1685 There are also a number of administrative objects.  It is an error to
1686 enter one of these objects.
1687
1688 \begin{tabular}{|l|l|}\hline
1689 closure type            & Section                       \\ \hline
1690 @TSO@                   & \ref{sec:TSO}                 \\
1691 @SPARK_OBJECT@          & \ref{sec:SPARK}               \\
1692 @BLOCKED_FETCH@         & \ref{sec:BLOCKED_FETCH}       \\
1693 @FETCHME@               & \ref{sec:FETCHME}   \\
1694 \hline
1695 \end{tabular}
1696
1697 \Subsection{Predicates}{closure-predicates}
1698
1699 The runtime system sometimes needs to be able to distinguish objects
1700 according to their properties: is the object updateable? is it in weak
1701 head normal form? etc.  These questions can be answered by examining
1702 the closure type field of the object's info table.  
1703
1704 We define the following predicates to detect families of related
1705 info types.  They are mutually exclusive and exhaustive.
1706
1707 \begin{itemize}
1708 \item @isCONSTR@ is true for @CONSTR@s.
1709 \item @isFUN@ is true for @FUN@s.
1710 \item @isTHUNK@ is true for @THUNK@s.
1711 \item @isBCO@ is true for @BCO@s.
1712 \item @isAP@ is true for @AP@s.
1713 \item @isPAP@ is true for @PAP@s.
1714 \item @isINDIRECTION@ is true for indirection objects. 
1715 \item @isBH@ is true for black holes.
1716 \item @isFOREIGN_OBJECT@ is true for foreign objects.
1717 \item @isARRAY@ is true for array objects.
1718 \item @isMVAR@ is true for @MVAR@s.
1719 \item @isIVAR@ is true for @IVAR@s.
1720 \item @isFETCHME@ is true for @FETCHME@s.
1721 \item @isSLOP@ is true for slop objects.
1722 \item @isRET_ADDR@ is true for return addresses.
1723 \item @isUPD_ADDR@ is true for update frames.
1724 \item @isTSO@ is true for @TSO@s.
1725 \item @isSTABLE_PTR_TABLE@ is true for the stable pointer table.
1726 \item @isSPARK_OBJECT@ is true for spark objects.
1727 \item @isBLOCKED_FETCH@ is true for blocked fetch objects.
1728 \item @isINVALID_INFOTYPE@ is true for all other info types.
1729
1730 \end{itemize}
1731
1732 The following predicates detect other interesting properties:
1733
1734 \begin{itemize}
1735
1736 \item @isPOINTED@ is true if an object has a pointed type.
1737
1738 If an object is pointed, the following predicates may be true
1739 (otherwise they are false).  @isWHNF@ and @isUPDATEABLE@ are
1740 mutually exclusive.
1741
1742 \begin{itemize} 
1743 \item @isWHNF@ is true if the object is in Weak Head Normal Form.  
1744 Note that unpointed objects are (arbitrarily) not considered to be in WHNF.
1745
1746 @isWHNF@ is true for @PAP@s, @CONSTR@s, @FUN@s and all @BCO@s.
1747
1748 \ToDo{Need to distinguish between whnf BCOs and non-whnf BCOs in their
1749 closure type}
1750
1751 \item @isUPDATEABLE@ is true if the object may be overwritten with an
1752  indirection object.
1753
1754 @isUPDATEABLE@ is true for @THUNK@s, @AP@s and @BH@s.
1755
1756 \end{itemize}
1757
1758 It is possible for a pointed object to be neither updatable nor in
1759 WHNF.  For example, indirections.
1760
1761 \item @isUNPOINTED@ is true if an object has an unpointed type.
1762 All such objects are boxed since only boxed objects have info pointers.
1763
1764 It is true for @ARR_WORDS@, @ARR_PTRS@, @MUTVAR@, @MUTARR_PTRS@,
1765 @MUTARR_PTRS_FROZEN@, @FOREIGN@ objects, @MVAR@s and @IVAR@s.
1766
1767 \item @isACTIVATION_FRAME@ is true for activation frames of all sorts.
1768
1769 It is true for return addresses and update frames.
1770 \begin{itemize}
1771 \item @isVECTORED_RETADDR@ is true for vectored return addresses.
1772 \item @isDIRECT_RETADDR@ is true for direct return addresses.
1773 \end{itemize}
1774
1775 \item @isADMINISTRATIVE@ is true for administrative objects:
1776 @TSO@s, the stable pointer table, spark objects and blocked fetches.
1777
1778 \item @hasSRT@ is true if the info table for the object contains an
1779 SRT pointer.  
1780
1781 @hasSRT@ is true for @THUNK@s, @FUN@s, and @RET@s.
1782
1783 \end{itemize}
1784
1785 \begin{itemize}
1786
1787 \item @isSTATIC@ is true for any statically allocated closure.
1788
1789 \item @isMUTABLE@ is true for objects with mutable pointer fields:
1790   @MUT_ARR@s, @MUTVAR@s, @MVAR@s and @IVAR@s.
1791
1792 \item @isSparkable@ is true if the object can (and should) be sparked.
1793 It is true of updateable objects which are not in WHNF with the
1794 exception of @THUNK_SELECTOR@s and black holes.
1795
1796 \end{itemize}
1797
1798 As a minor optimisation, we might use the top bits of the @INFO_TYPE@
1799 field to ``cache'' the answers to some of these predicates.
1800
1801 An indirection either points to HNF (post update); or is result of
1802 overwriting a FetchMe, in which case the thing fetched is either under
1803 evaluation (BLACKHOLE), or by now an HNF.  Thus, indirections get
1804 NoSpark flag.
1805
1806 \subsection{Closures (aka Pointed Objects)}
1807
1808 An object can be entered iff it is a closure.
1809
1810 \Subsubsection{Function closures}{FUN}
1811
1812 Function closures represent lambda abstractions.  For example,
1813 consider the top-level declaration:
1814 @
1815   f = \x -> let g = \y -> x+y
1816             in g x
1817 @
1818 Both @f@ and @g@ are represented by function closures.  The closure
1819 for @f@ is \emph{static} while that for @g@ is \emph{dynamic}.
1820
1821 The layout of a function closure is as follows:
1822 \begin{center}
1823 \begin{tabular}{|l|l|l|l|}\hline
1824 \emph{Fixed header}  & \emph{Pointers} & \emph{Non-pointers} \\ \hline
1825 \end{tabular}
1826 \end{center}
1827
1828 The data words (pointers and non-pointers) are the free variables of
1829 the function closure.  The number of pointers and number of
1830 non-pointers are stored in @info->layout.ptrs@ and
1831 @info->layout.nptrs@ respecively.
1832
1833 There are several different sorts of function closure, distinguished
1834 by their closure type field:
1835
1836 \begin{itemize}
1837
1838 \item @FUN@: a vanilla, dynamically allocated on the heap.
1839
1840 \item $@FUN_@p@_@np$: to speed up garbage collection a number of
1841 specialised forms of @FUN@ are provided, for particular $(p,np)$
1842 pairs, where $p$ is the number of pointers and $np$ the number of
1843 non-pointers.
1844
1845 \item @FUN_STATIC@.  Top-level, static, function closures (such as @f@
1846 above) have a different layout than dynamic ones:
1847
1848 \begin{center}
1849 \begin{tabular}{|l|l|l|}\hline
1850 \emph{Fixed header}  & \emph{Static object link} \\ \hline
1851 \end{tabular}
1852 \end{center}
1853
1854 Static function closures have no free variables.  (However they may
1855 refer to other static closures; these references are recorded in the
1856 function closure's SRT.)  They have one field that is not present in
1857 dynamic closures, the \emph{static object link} field.  This is used
1858 by the garbage collector in the same way that to-space is, to gather
1859 closures that have been determined to be live but that have not yet
1860 been scavenged.
1861
1862 \note{Static function closures that have no static references, and
1863 hence a null SRT pointer, don't need the static object link field.  We
1864 don't take advantage of this at the moment, but we could.  See
1865 @CONSTR_NOCAF_STATIC@.}  
1866 \end{itemize}
1867
1868 Each lambda abstraction, $f$, in the STG program has its own private
1869 info table.  The following labels are relevant:
1870
1871 \begin{itemize}
1872
1873 \item $f$@_info@  is $f$'s info table.
1874
1875 \item $f$@_entry@ is $f$'s slow entry point (i.e. the entry code of
1876 its info table; so it will label the same byte as $f$@_info@).
1877
1878 \item $f@_fast_@k$ is $f$'s fast entry point.  $k$ is the number of
1879 arguments $f$ takes; encoding this number in the fast-entry label
1880 occasionally catches some nasty code-generation errors.
1881
1882 \end{itemize}
1883
1884 \Subsubsection{Data constructors}{CONSTR}
1885
1886 Data-constructor closures represent values constructed with algebraic
1887 data type constructors.  The general layout of data constructors is
1888 the same as that for function closures.  That is
1889
1890 \begin{center}
1891 \begin{tabular}{|l|l|l|l|}\hline
1892 \emph{Fixed header}  & \emph{Pointers} & \emph{Non-pointers} \\ \hline
1893 \end{tabular}
1894 \end{center}
1895
1896 There are several different sorts of constructor:
1897
1898 \begin{itemize}
1899
1900 \item @CONSTR@: a vanilla, dynamically allocated constructor.
1901
1902 \item @CONSTR_@$p$@_@$np$: just like $@FUN_@p@_@np$.
1903
1904 \item @CONSTR_INTLIKE@.  A dynamically-allocated heap object that
1905 looks just like an @Int@.  The garbage collector checks to see if it
1906 can common it up with one of a fixed set of static int-like closures,
1907 thus getting it out of the dynamic heap altogether.
1908
1909 \item @CONSTR_CHARLIKE@:  same deal, but for @Char@.
1910
1911 \item @CONSTR_STATIC@ is similar to @FUN_STATIC@, with the
1912 complication that the layout of the constructor must mimic that of a
1913 dynamic constructor, because a static constructor might be returned to
1914 some code that unpacks it.  So its layout is like this:
1915
1916 \begin{center}
1917 \begin{tabular}{|l|l|l|l|l|}\hline
1918 \emph{Fixed header}  & \emph{Pointers} & \emph{Non-pointers} & \emph{Static object link}\\ \hline
1919 \end{tabular}
1920 \end{center}
1921
1922 The static object link, at the end of the closure, serves the same purpose
1923 as that for @FUN_STATIC@.  The pointers in the static constructor can point
1924 only to other static closures.
1925
1926 The static object link occurs last in the closure so that static
1927 constructors can store their data fields in exactly the same place as
1928 dynamic constructors.
1929
1930 \item @CONSTR_NOCAF_STATIC@.  A statically allocated data constructor
1931 that guarantees not to point (directly or indirectly) to any CAF
1932 (\secref{CAF}).  This means it does not need a static object
1933 link field.  Since we expect that there might be quite a lot of static
1934 constructors this optimisation makes sense.  Furthermore, the @NOCAF@
1935 tag allows the compiler to indicate that no CAFs can be reached
1936 anywhere \emph{even indirectly}.
1937
1938 \end{itemize}
1939
1940 For each data constructor $Con$, two info tables are generated:
1941
1942 \begin{itemize}
1943 \item $Con$@_con_info@ labels $Con$'s dynamic info table, 
1944 shared by all dynamic instances of the constructor.
1945 \item $Con$@_static@ labels $Con$'s static info table, 
1946 shared by all static instances of the constructor.
1947 \end{itemize}
1948
1949 Each constructor also has a \emph{constructor function}, which is a
1950 curried function which builds an instance of the constructor.  The
1951 constructor function has an info table labelled as @$Con$_info@, and
1952 entry code pointed to by @$Con$_entry@.
1953
1954 Nullary constructors are represented by a single static info table,
1955 which everyone points to.  Thus for a nullary constructor we can omit
1956 the dynamic info table and the constructor function.
1957
1958 \subsubsection{Thunks}
1959 \label{sec:THUNK}
1960 \label{sec:THUNK_SELECTOR}
1961
1962 A thunk represents an expression that is not obviously in head normal 
1963 form.  For example, consider the following top-level definitions:
1964 @
1965   range = between 1 10
1966   f = \x -> let ys = take x range
1967             in sum ys
1968 @
1969 Here the right-hand sides of @range@ and @ys@ are both thunks; the former
1970 is static while the latter is dynamic.
1971
1972 The layout of a thunk is the same as that for a function closure.
1973 However, thunks must have a payload of at least @MIN_UPD_SIZE@
1974 words to allow it to be overwritten with a black hole and an
1975 indirection.  The compiler may have to add extra non-pointer fields to
1976 satisfy this constraint.
1977
1978 \begin{center}
1979 \begin{tabular}{|l|l|l|l|l|}\hline
1980 \emph{Fixed header}  & \emph{Pointers} & \emph{Non-pointers} \\ \hline
1981 \end{tabular}
1982 \end{center}
1983
1984 The layout word in the info table contains the same information as for
1985 function closures; that is, number of pointers and number of
1986 non-pointers.
1987
1988 A thunk differs from a function closure in that it can be updated.
1989
1990 There are several forms of thunk:
1991
1992 \begin{itemize}
1993
1994 \item @THUNK@ and $@THUNK_@p@_@np$: vanilla, dynamically allocated
1995 thunks.  Dynamic thunks are overwritten with normal indirections
1996 (@IND@), or old generation indirections (@IND_OLDGEN@): see
1997 \secref{IND}.
1998
1999 \item @THUNK_STATIC@.  A static thunk is also known as a
2000 \emph{constant applicative form}, or \emph{CAF}.  Static thunks are
2001 overwritten with static indirections.
2002
2003 \begin{center}
2004 \begin{tabular}{|l|l|}\hline
2005 \emph{Fixed header}  & \emph{Static object link}\\ \hline
2006 \end{tabular}
2007 \end{center}
2008
2009 \item @THUNK_SELECTOR@ is a (dynamically allocated) thunk whose entry
2010 code performs a simple selection operation from a data constructor
2011 drawn from a single-constructor type.  For example, the thunk
2012 @
2013         x = case y of (a,b) -> a
2014 @
2015 is a selector thunk.  A selector thunk is laid out like this:
2016
2017 \begin{center}
2018 \begin{tabular}{|l|l|l|l|}\hline
2019 \emph{Fixed header}  & \emph{Selectee pointer} \\ \hline
2020 \end{tabular}
2021 \end{center}
2022
2023 The layout word contains the byte offset of the desired word in the
2024 selectee.  Note that this is different from all other thunks.
2025
2026 The garbage collector ``peeks'' at the selectee's tag (in its info
2027 table).  If it is evaluated, then it goes ahead and does the
2028 selection, and then behaves just as if the selector thunk was an
2029 indirection to the selected field.  If it is not evaluated, it treats
2030 the selector thunk like any other thunk of that shape.
2031 [Implementation notes.  Copying: only the evacuate routine needs to be
2032 special.  Compacting: only the PRStart (marking) routine needs to be
2033 special.]
2034
2035 There is a fixed set of pre-compiled selector thunks built into the
2036 RTS, representing offsets from 0 to @MAX_SPEC_SELECTOR_THUNK@.  The
2037 info tables are labelled @__sel_$n$_upd_info@ where $n$ is the offset.
2038 Non-updating versions are also built in, with info tables labelled
2039 @__sel_$n$_noupd_info@.
2040
2041 \end{itemize}
2042
2043 The only label associated with a thunk is its info table:
2044
2045 \begin{description}
2046 \item[$f$@_info@] is $f$'s info table.
2047 \end{description}
2048
2049
2050 \Subsubsection{Byte-code objects}{BCO}
2051
2052 A Byte-Code Object (BCO) is a container for a a chunk of byte-code,
2053 which can be executed by Hugs.  The byte-code represents a
2054 supercombinator in the program: when Hugs compiles a module, it
2055 performs lambda lifting and each resulting supercombinator becomes a
2056 byte-code object in the heap.
2057
2058 BCOs are not updateable; the bytecode compiler represents updatable
2059 thunks using a combination of @AP@s and @BCO@s.
2060
2061 The semantics of BCOs are described in \secref{hugs-heap-objects}.  A
2062 BCO has the following structure:
2063
2064 \begin{center}
2065 \begin{tabular}{|l|l|l|l|l|l|}
2066 \hline 
2067 \emph{Fixed Header} & \emph{Layout} & \emph{Offset} & \emph{Size} &
2068 \emph{Literals} & \emph{Byte code} \\
2069 \hline
2070 \end{tabular}
2071 \end{center}
2072
2073 \noindent where:
2074 \begin{itemize}
2075 \item The entry code is a static code fragment/info table that returns
2076 to the scheduler to invoke Hugs (\secref{ghc-to-hugs-switch}).
2077 \item \emph{Layout} contains the number of pointer literals in the
2078 \emph{Literals} field.
2079 \item \emph{Offset} is the offset to the byte code from the start of
2080 the object.
2081 \item \emph{Size} is the number of words of byte code in the object.
2082 \item \emph{Literals} contains any pointer and non-pointer literals used in
2083 the byte-codes (including jump addresses), pointers first.
2084 \item \emph{Byte code} contains \emph{Size} words of non-pointer byte
2085 code.
2086 \end{itemize}
2087
2088
2089 \Subsubsection{Partial applications}{PAP}
2090
2091 A partial application (PAP) represents a function applied to too few
2092 arguments.  It is only built as a result of updating after an
2093 argument-satisfaction check failure.  A PAP has the following shape:
2094
2095 \begin{center}
2096 \begin{tabular}{|l|l|l|l|}\hline
2097 \emph{Fixed header}  & \emph{No of words of stack} & \emph{Function closure} & \emph{Stack chunk ...} \\ \hline
2098 \end{tabular}
2099 \end{center}
2100
2101 The ``Stack chunk'' is a copy of the chunk of stack above the update
2102 frame; ``No of words of stack'' tells how many words it consists of.
2103 The function closure is (a pointer to) the closure for the function
2104 whose argument-satisfaction check failed.
2105
2106 In the normal case where a PAP is built as a result of an argument
2107 satisfaction check failure, the stack chunk will just contain
2108 ``pending arguments'', ie. pointers and tagged non-pointers.  It may
2109 in fact also contain activation records, but not update frames, seq
2110 frames, or catch frames.  The reason is the garbage collector uses the
2111 same code to scavenge a stack as it does to scavenge the payload of a
2112 PAP, but an update frame contains a link to the next update frame in
2113 the chain and this link would need to be relocated during garbage
2114 collection.  Revertible black holes and asynchronous exceptions use
2115 the more general form of PAPs (see Section \ref{revertible-bh}).
2116
2117 There is just one standard form of PAP. There is just one info table
2118 too, called @PAP_info@.  Its entry code simply copies the arg stack
2119 chunk back on top of the stack and enters the function closure.  (It
2120 has to do a stack overflow test first.)
2121
2122 There is just one way to build a PAP: by calling @stg_update_PAP@ with
2123 the function closure in register @R1@ and the pending arguments on the
2124 stack.  The @stg_update_PAP@ function will build the PAP, perform the
2125 update, and return to the next activation record on the stack.  If
2126 there are \emph{no} pending arguments on the stack, then no PAP need
2127 be built: in this case @stg_update_PAP@ just overwrites the updatee
2128 with an indirection to the function closure.
2129
2130 PAPs are also used to implement Hugs functions (where the arguments
2131 are free variables).  PAPs generated by Hugs can be static so we need
2132 both @PAP@ and @PAP_STATIC@.
2133
2134 \Subsubsection{@AP_UPD@ objects}{AP_UPD}
2135
2136 @AP_UPD@ objects are used to represent thunks built by Hugs.  The only
2137 distintion between an @AP_UPD@ and a @PAP@ is that an @AP_UPD@ is
2138 updateable.
2139
2140 \begin{center}
2141 \begin{tabular}{|l|l|l|l|}
2142 \hline
2143 \emph{Fixed Header} & \emph{No of stack words} & \emph{Function closure} & \emph{Stack chunk} \\
2144 \hline
2145 \end{tabular}
2146 \end{center}
2147
2148 The entry code pushes an update frame, copies the arg stack chunk on
2149 top of the stack, and enters the function closure.  (It has to do a
2150 stack overflow test first.)
2151
2152 The ``stack chunk'' is a block of stack not containing update frames,
2153 seq frames or catch frames (just like a PAP).  In the case of Hugs,
2154 the stack chunk will contain the free variables of the thunk, and the
2155 function closure is (a pointer to) the closure for the thunk.  The
2156 argument stack may be empty if the thunk has no free variables.
2157
2158 \note{Since @AP_UPD@s are updateable, the @MIN_UPD_SIZE@ constraint
2159 applies here too.}
2160
2161 \Subsubsection{Indirections}{IND}
2162
2163 Indirection closures just point to other closures. They are introduced
2164 when a thunk is updated to point to its value.  The entry code for all
2165 indirections simply enters the closure it points to.
2166
2167 There are several forms of indirection:
2168
2169 \begin{description}
2170 \item[@IND@] is the vanilla, dynamically-allocated indirection.
2171 It is removed by the garbage collector. It has the following
2172 shape:
2173 \begin{center}
2174 \begin{tabular}{|l|l|l|}\hline
2175 \emph{Fixed header} & \emph{Target closure} \\ \hline
2176 \end{tabular}
2177 \end{center}
2178
2179 An @IND@ only exists in the youngest generation.  In older
2180 generations, we have @IND_OLDGEN@s.  The update code
2181 (@Upd_frame_$n$_entry@) checks whether the updatee is in the youngest
2182 generation before deciding which kind of indirection to use.
2183
2184 \item[@IND_OLDGEN@] is the vanilla, dynamically-allocated indirection.
2185 It is removed by the garbage collector. It has the following
2186 shape:
2187 \begin{center}
2188 \begin{tabular}{|l|l|l|}\hline
2189 \emph{Fixed header} & \emph{Target closure} & \emph{Mutable link field} \\ \hline
2190 \end{tabular}
2191 \end{center}
2192 It contains a \emph{mutable link field} that is used to string together
2193 mutable objects in each old generation.
2194
2195 \item[@IND_PERM@]
2196 For lexical profiling, it is necessary to maintain cost centre
2197 information in an indirection, so ``permanent indirections'' are
2198 retained forever.  Otherwise they are just like vanilla indirections.
2199 \note{If a permanent indirection points to another permanent
2200 indirection or a @CONST@ closure, it is possible to elide the indirection
2201 since it will have no effect on the profiler.}
2202
2203 \note{Do we still need @IND@ in the profiling build, or do we just
2204 need @IND@ but its behaviour changes when profiling is on?}
2205
2206 \item[@IND_OLDGEN_PERM@]
2207 Just like an @IND_OLDGEN@, but sticks around like an @IND_PERM@.
2208
2209 \item[@IND_STATIC@] is used for overwriting CAFs when they have been
2210 evaluated.  Static indirections are not removed by the garbage
2211 collector; and are statically allocated outside the heap (and should
2212 stay there).  Their static object link field is used just as for
2213 @FUN_STATIC@ closures.
2214
2215 \begin{center}
2216 \begin{tabular}{|l|l|l|}
2217 \hline
2218 \emph{Fixed header} & \emph{Target closure} & \emph{Static link field} \\
2219 \hline
2220 \end{tabular}
2221 \end{center}
2222
2223 \end{description}
2224
2225 \subsubsection{Black holes and blocking queues}
2226 \label{sec:BLACKHOLE}
2227 \label{sec:BLACKHOLE_BQ}
2228
2229 Black hole closures are used to overwrite closures currently being
2230 evaluated. They inform the garbage collector that there are no live
2231 roots in the closure, thus removing a potential space leak.  
2232
2233 Black holes also become synchronization points in the concurrent
2234 world.  When a thread attempts to enter a blackhole, it must wait for
2235 the result of the computation, which is presumably in progress in
2236 another thread.
2237
2238 \note{In a single-threaded system, entering a black hole indicates an
2239 infinite loop.  In a concurrent system, entering a black hole
2240 indicates an infinite loop only if the hole is being entered by the
2241 same thread that originally entered the closure.  It could also bring
2242 about a deadlock situation where several threads are waiting
2243 circularly on computations in progress.}
2244
2245 There are two types of black hole:
2246
2247 \begin{description}
2248
2249 \item[@BLACKHOLE@]
2250 A straightforward blackhole just consists of an info pointer and some
2251 padding to allow updating with an @IND_OLDGEN@ if necessary.  This
2252 type of blackhole has no waiting threads.
2253
2254 \begin{center}
2255 \begin{tabular}{|l|l|l|}
2256 \hline 
2257 \emph{Fixed header} & \emph{Padding} & \emph{Padding} \\
2258 \hline
2259 \end{tabular}
2260 \end{center}
2261
2262 If we're doing \emph{eager blackholing} then a thunk's info pointer is
2263 overwritten with @BLACKHOLE_info@ at the time of entry; hence the need
2264 for blackholes to be small, otherwise we'd be overwriting part of the
2265 thunk itself.
2266
2267 \item[@BLACKHOLE_BQ@] 
2268 When a thread enters a @BLACKHOLE@, it is turned into a @BLACKHOLE_BQ@
2269 (blocking queue), which contains a linked list of blocked threads in
2270 addition to the info pointer.
2271
2272 \begin{center}
2273 \begin{tabular}{|l|l|l|}
2274 \hline 
2275 \emph{Fixed header} & \emph{Blocked thread link} & \emph{Mutable link field} \\
2276 \hline
2277 \end{tabular}
2278 \end{center}
2279
2280 The \emph{Blocked thread link} points to the TSO of the first thread
2281 waiting for the value of this thunk.  All subsequent TSOs in the list
2282 are linked together using their @tso->link@ field, ending in
2283 @END_TSO_QUEUE_closure@.
2284
2285 Because new threads can be added to the \emph{Blocked thread link}, a
2286 blocking queue is \emph{mutable}, so we need a mutable link field in
2287 order to chain it on to a mutable list for the generational garbage
2288 collector.
2289
2290 \end{description}
2291
2292 \Subsubsection{FetchMes}{FETCHME} 
2293
2294 In the parallel systems, FetchMes are used to represent pointers into
2295 the global heap.  When evaluated, the value they point to is read from
2296 the global heap.
2297
2298 \ToDo{Describe layout}
2299
2300 Because there may be offsets into these arrays, a primitive array
2301 cannot be handled as a FetchMe in the parallel system, but must be
2302 shipped in its entirety if its parent closure is shipped.
2303
2304
2305
2306 \Subsection{Unpointed Objects}{unpointed-objects}
2307
2308 A variable of unpointed type is always bound to a \emph{value}, never
2309 to a \emph{thunk}.  For this reason, unpointed objects cannot be
2310 entered.
2311
2312 \subsubsection{Immutable objects}
2313 \label{sec:ARR_WORDS}
2314
2315 \begin{description}
2316 \item[@ARR_WORDS@] is a variable-sized object consisting solely of
2317 non-pointers.  It is used for arrays of all sorts of things (bytes,
2318 words, floats, doubles... it doesn't matter).
2319
2320 Strictly speaking, an @ARR_WORDS@ could be mutable, but because it
2321 only contains non-pointers we don't need to track this fact.
2322
2323 \begin{center}
2324 \begin{tabular}{|c|c|c|c|}
2325 \hline
2326 \emph{Fixed Hdr} & \emph{No of non-pointers} & \emph{Non-pointers\ldots}        \\ \hline
2327 \end{tabular}
2328 \end{center}
2329 \end{description}
2330
2331 \subsubsection{Mutable objects}
2332 \label{sec:mutables}
2333 \label{sec:MUT_VAR}
2334 \label{sec:MUT_ARR_PTRS}
2335 \label{sec:MUT_ARR_PTRS_FROZEN}
2336 \label{sec:MVAR}
2337
2338 Some of these objects are \emph{mutable}; they represent objects which
2339 are explicitly mutated by Haskell code through the @ST@ or @IO@
2340 monads.  They're not used for thunks which are updated precisely once.
2341 Depending on the garbage collector, mutable closures may contain extra
2342 header information which allows a generational collector to implement
2343 the ``write barrier.''
2344
2345 Notice that mutable objects all have the same general layout: there is
2346 a mutable link field as the second word after the header.  This is so
2347 that code to process old-generation mutable lists doesn't need to look
2348 at the type of the object to determine where its link field is.
2349
2350 \begin{description}
2351
2352 \item[@MUT_VAR@] is a mutable variable.
2353 \begin{center}
2354 \begin{tabular}{|c|c|c|}
2355 \hline
2356 \emph{Fixed Hdr} \emph{Pointer} & \emph{Mutable link} & \\ \hline
2357 \end{tabular}
2358 \end{center}
2359
2360 \item[@MUT_ARR_PTRS@] is a mutable array of pointers.  Such an array
2361 may be \emph{frozen}, becoming an @MUT_ARR_PTRS_FROZEN@, with a
2362 different info-table.
2363
2364 \begin{center}
2365 \begin{tabular}{|c|c|c|c|}
2366 \hline
2367 \emph{Fixed Hdr} & \emph{No of ptrs} & \emph{Mutable link} & \emph{Pointers\ldots} \\ \hline
2368 \end{tabular}
2369 \end{center}
2370
2371 \item[@MUT_ARR_PTRS_FROZEN@] This is the immutable version of
2372 @MUT_ARR_PTRS@.  It still has a mutable link field for two reasons: we
2373 need to keep it on the mutable list for an old generation at least
2374 until the next garbage collection, and it may become mutable again via
2375 @thawArray@.
2376
2377 \begin{center}
2378 \begin{tabular}{|c|c|c|c|}
2379 \hline
2380 \emph{Fixed Hdr} & \emph{No of ptrs} & \emph{Mutable link} & \emph{Pointers\ldots} \\ \hline
2381 \end{tabular}
2382 \end{center}
2383
2384 \item[@MVAR@]
2385
2386 \begin{center}
2387 \begin{tabular}{|l|l|l|l|l|}
2388 \hline 
2389 \emph{Fixed header} & \emph{Head} & \emph{Mutable link} & \emph{Tail}
2390 & \emph{Value}\\
2391 \hline
2392 \end{tabular}
2393 \end{center}
2394
2395 \ToDo{MVars}
2396
2397 \end{description}
2398
2399
2400 \Subsubsection{Foreign objects}{FOREIGN}
2401
2402 Here's what a ForeignObj looks like:
2403
2404 \begin{center}
2405 \begin{tabular}{|l|l|l|l|}
2406 \hline 
2407 \emph{Fixed header} & \emph{Data} \\
2408 \hline
2409 \end{tabular}
2410 \end{center}
2411
2412 A foreign object is simple a boxed pointer to an address outside the
2413 Haskell heap, possible to @malloc@ed data.  The only reason foreign
2414 objects exist is so that we can track the lifetime of one using weak
2415 pointers (see \secref{WEAK}) and run a finaliser when the foreign
2416 object is unreachable.
2417
2418 \subsubsection{Weak pointers}
2419 \label{sec:WEAK}
2420
2421 \begin{center}
2422 \begin{tabular}{|l|l|l|l|l|}
2423 \hline 
2424 \emph{Fixed header} & \emph{Key} & \emph{Value} & \emph{Finaliser}
2425 & \emph{Link}\\
2426 \hline
2427 \end{tabular}
2428 \end{center}
2429
2430 \ToDo{Weak poitners}
2431
2432 \subsubsection{Stable names}
2433 \label{sec:STABLE_NAME}
2434
2435 \begin{center}
2436 \begin{tabular}{|l|l|l|l|}
2437 \hline 
2438 \emph{Fixed header} & \emph{Index} \\
2439 \hline
2440 \end{tabular}
2441 \end{center}
2442
2443 \ToDo{Stable names}
2444
2445 The remaining objects types are all administrative --- none of them
2446 may be entered.
2447
2448 \subsection{Other weird objects}
2449 \label{sec:SPARK}
2450 \label{sec:BLOCKED_FETCH}
2451
2452 \begin{description}
2453 \item[@BlockedFetch@ heap objects (`closures')] (parallel only)
2454
2455 @BlockedFetch@s are inbound fetch messages blocked on local closures.
2456 They arise as entries in a local blocking queue when a fetch has been
2457 received for a local black hole.  When awakened, we look at their
2458 contents to figure out where to send a resume.
2459
2460 A @BlockedFetch@ closure has the form:
2461 \begin{center}
2462 \begin{tabular}{|l|l|l|l|l|l|}\hline
2463 \emph{Fixed header} & link & node & gtid & slot & weight \\ \hline
2464 \end{tabular}
2465 \end{center}
2466
2467 \item[Spark Closures] (parallel only)
2468
2469 Spark closures are used to link together all closures in the spark pool.  When
2470 the current processor is idle, it may choose to speculatively evaluate some of
2471 the closures in the pool.  It may also choose to delete sparks from the pool.
2472 \begin{center}
2473 \begin{tabular}{|l|l|l|l|l|l|}\hline
2474 \emph{Fixed header} & \emph{Spark pool link} & \emph{Sparked closure} \\ \hline
2475 \end{tabular}
2476 \end{center}
2477
2478 \item[Slop Objects]\label{sec:slop-objects}
2479
2480 Slop objects are used to overwrite the end of an updatee if it is
2481 larger than an indirection.  Normal slop objects consist of an info
2482 pointer a size word and a number of slop words.  
2483
2484 \begin{center}
2485 \begin{tabular}{|l|l|l|l|l|l|}\hline
2486 \emph{Info Pointer} & \emph{Size} & \emph{Slop Words} \\ \hline
2487 \end{tabular}
2488 \end{center}
2489
2490 This is too large for single word slop objects which consist of a
2491 single info table.
2492
2493 Note that slop objects only contain an info pointer, not a standard
2494 fixed header.  This doesn't cause problems because slop objects are
2495 always unreachable --- they can only be accessed by linearly scanning
2496 the heap.
2497
2498 \note{Currently we don't use slop objects because the storage manager
2499 isn't reliant on objects being adjacent, but if we move to a ``mostly
2500 copying'' style collector, this will become an issue.}
2501
2502 \end{description}
2503
2504 \Subsection{Thread State Objects (TSOs)}{TSO}
2505
2506 In the multi-threaded system, the state of a suspended thread is
2507 packed up into a Thread State Object (TSO) which contains all the
2508 information needed to restart the thread and for the garbage collector
2509 to find all reachable objects.  When a thread is running, it may be
2510 ``unpacked'' into machine registers and various other memory locations
2511 to provide faster access.
2512
2513 Single-threaded systems don't really \emph{need\/} TSOs --- but they do
2514 need some way to tell the storage manager about live roots so it is
2515 convenient to use a single TSO to store the mutator state even in
2516 single-threaded systems.
2517
2518 Rather than manage TSOs' alloc/dealloc, etc., in some \emph{ad hoc}
2519 way, we instead alloc/dealloc/etc them in the heap; then we can use
2520 all the standard garbage-collection/fetching/flushing/etc machinery on
2521 them.  So that's why TSOs are ``heap objects,'' albeit very special
2522 ones.
2523 \begin{center}
2524 \begin{tabular}{|l|l|}
2525    \hline \emph{Fixed header}
2526 \\ \hline \emph{Link field}
2527 \\ \hline \emph{Mutable link field}
2528 \\ \hline \emph{What next}
2529 \\ \hline \emph{State}
2530 \\ \hline \emph{Thread Id}
2531 \\ \hline \emph{Exception Handlers}
2532 \\ \hline \emph{Ticky Info}
2533 \\ \hline \emph{Profiling Info}
2534 \\ \hline \emph{Parallel Info}
2535 \\ \hline \emph{GranSim Info}
2536 \\ \hline \emph{Stack size}
2537 \\ \hline \emph{Max Stack size}
2538 \\ \hline \emph{Sp}
2539 \\ \hline \emph{Su}
2540 \\ \hline \emph{SpLim}
2541 \\ \hline 
2542 \\
2543           \emph{Stack}
2544 \\
2545 \\ \hline 
2546 \end{tabular}
2547 \end{center}
2548 The contents of a TSO are:
2549 \begin{description}
2550
2551 \item[\emph{Link field}] This is a pointer used to maintain a list of
2552 threads with a similar state (e.g.~all runnable, all sleeping, all
2553 blocked on the same black hole, all blocked on the same MVar,
2554 etc.)
2555
2556 \item[\emph{Mutable link field}] Because the stack is mutable by
2557 definition, the generational collector needs to track TSOs in older
2558 generations that may point into younger ones (which is just about any
2559 TSO for a thread that has run recently).  Hence the need for a mutable
2560 link field (see \secref{mutables}).
2561
2562 \item[\emph{What next}]
2563 This field has five values:  
2564 \begin{description}
2565 \item[@ThreadEnterGHC@]  The thread can be started by entering the
2566 closure pointed to by the word on the top of the stack.
2567 \item[@ThreadRunGHC@]  The thread can be started by jumping to the
2568 address on the top of the stack.
2569 \item[@ThreadEnterHugs@]  The stack has a pointer to a Hugs-built
2570 closure on top of the stack: enter the closure to run the thread.
2571 \item[@ThreadKilled@] The thread has been killed (by @killThread#@).
2572 It is probably still around because it is on some queue somewhere and
2573 hasn't been garbage collected yet.
2574 \item[@ThreadComplete@] The thread has finished.  Its @TSO@ hasn't
2575 been garbage collected yet.
2576 \end{description}
2577
2578 \item[\emph{Thread Id}]
2579 This field contains a (not necessarily unique) integer that identifies
2580 the thread.  It can be used eg. for hashing.
2581
2582 \item[\emph{Ticky Info}] Optional information for ``Ticky Ticky''
2583 statistics: @TSO_STK_HWM@ is the maximum number of words allocated to
2584 this thread.
2585
2586 \item[\emph{Profiling Info}] Optional information for profiling:
2587 @TSO_CCC@ is the current cost centre.
2588
2589 \item[\emph{Parallel Info}]
2590 Optional information for parallel execution.
2591
2592 % \begin{itemize}
2593
2594 % \item The types of threads (@TSO_TYPE@):
2595 % \begin{description}
2596 % \item[@T_MAIN@]     Must be executed locally.
2597 % \item[@T_REQUIRED@] A required thread  -- may be exported.
2598 % \item[@T_ADVISORY@] An advisory thread -- may be exported.
2599 % \item[@T_FAIL@]     A failure thread   -- may be exported.
2600 % \end{description}
2601
2602 % \item I've no idea what else
2603
2604 % \end{itemize}
2605
2606 \item[\emph{GranSim Info}]
2607 Optional information for gransim execution.
2608
2609 % \item Optional information for GranSim execution:
2610 % \begin{itemize}
2611 % \item locked         
2612 % \item sparkname        
2613 % \item started at       
2614 % \item exported         
2615 % \item basic blocks     
2616 % \item allocs   
2617 % \item exectime         
2618 % \item fetchtime        
2619 % \item fetchcount       
2620 % \item blocktime        
2621 % \item blockcount       
2622 % \item global sparks    
2623 % \item local sparks     
2624 % \item queue            
2625 % \item priority         
2626 % \item clock          (gransim light only)
2627 % \end{itemize}
2628
2629
2630 % Here are the various queues for GrAnSim-type events.
2631
2632 % Q_RUNNING   
2633 % Q_RUNNABLE  
2634 % Q_BLOCKED   
2635 % Q_FETCHING  
2636 % Q_MIGRATING 
2637
2638
2639 \item[\emph{Stack Info}] Various fields contain information on the
2640 stack: its current size, its maximum size (to avoid infinite loops
2641 overflowing the memory), the current stack pointer (\emph{Sp}), the
2642 current stack update frame pointer (\emph{Su}), and the stack limit
2643 (\emph{SpLim}).  The latter three fields are loaded into the relevant
2644 registers when the thread is run.
2645
2646 \item[\emph{Stack}] This is the actual stack for the thread,
2647 \emph{Stack size} words long.  It grows downwards from higher
2648 addresses to lower addresses.  When the stack overflows, it will
2649 generally be relocated into larger premises unless \emph{Max stack
2650 size} is reached.
2651
2652 \end{description}
2653
2654 The garbage collector needs to be able to find all the
2655 pointers in a stack.  How does it do this?
2656
2657 \begin{itemize}
2658
2659 \item Within the stack there are return addresses, pushed
2660 by @case@ expressions.  Below a return address (i.e. at higher
2661 memory addresses, since the stack grows downwards) is a chunk
2662 of stack that the return address ``knows about'', namely the
2663 activation record of the currently running function.
2664
2665 \item Below each such activation record is a \emph{pending-argument
2666 section}, a chunk of
2667 zero or more words that are the arguments to which the result
2668 of the function should be applied.  The return address does not
2669 statically
2670 ``know'' how many pending arguments there are, or their types.
2671 (For example, the function might return a result of type $\alpha$.)
2672
2673 \item Below each pending-argument section is another return address,
2674 and so on.  Actually, there might be an update frame instead, but we
2675 can consider update frames as a special case of a return address with
2676 a well-defined activation record.
2677
2678 \end{itemize}
2679
2680 The game plan is this.  The garbage collector walks the stack from the
2681 top, traversing pending-argument sections and activation records
2682 alternately.  Next we discuss how it finds the pointers in each of
2683 these two stack regions.
2684
2685
2686 \Subsubsection{Activation records}{activation-records}
2687
2688 An \emph{activation record} is a contiguous chunk of stack,
2689 with a return address as its first word, followed by as many
2690 data words as the return address ``knows about''.  The return
2691 address is actually a fully-fledged info pointer.  It points
2692 to an info table, replete with:
2693
2694 \begin{itemize}
2695 \item entry code (i.e. the code to return to).
2696
2697 \item closure type is either @RET_SMALL/RET_VEC_SMALL@ or
2698 @RET_BIG/RET_VEC_BIG@, depending on whether the activation record has
2699 more than 32 data words (\note{64 for 8-byte-word architectures}) and
2700 on whether to use a direct or a vectored return.
2701
2702 \item the layout info for @RET_SMALL@ is a bitmap telling the layout
2703 of the activation record, one bit per word.  The least-significant bit
2704 describes the first data word of the record (adjacent to the fixed
2705 header) and so on.  A ``@1@'' indicates a non-pointer, a ``@0@''
2706 indicates a pointer.  We don't need to indicate exactly how many words
2707 there are, because when we get to all zeros we can treat the rest of
2708 the activation record as part of the next pending-argument region.
2709
2710 For @RET_BIG@ the layout field points to a block of bitmap words,
2711 starting with a word that tells how many words are in the block.
2712
2713 \item the info table contains a Static Reference Table pointer for the
2714 return address (\secref{srt}).
2715 \end{itemize}
2716
2717 The activation record is a fully fledged closure too.  As well as an
2718 info pointer, it has all the other attributes of a fixed header
2719 (\secref{fixed-header}) including a saved cost centre which
2720 is reloaded when the return address is entered.
2721
2722 In other words, all the attributes of closures are needed for
2723 activation records, so it's very convenient to make them look alike.
2724
2725
2726 \Subsubsection{Pending arguments}{pending-args}
2727
2728 So that the garbage collector can correctly identify pointers in
2729 pending-argument sections we explicitly tag all non-pointers.  Every
2730 non-pointer in a pending-argument section is preceded (at the next
2731 lower memory word) by a one-word byte count that says how many bytes
2732 to skip over (excluding the tag word).
2733
2734 The garbage collector traverses a pending argument section from the
2735 top (i.e. lowest memory address).  It looks at each word in turn:
2736
2737 \begin{itemize}
2738 \item If it is less than or equal to a small constant @ARGTAG_MAX@
2739 then it treats it as a tag heralding zero or more words of
2740 non-pointers, so it just skips over them.
2741
2742 \item If it points to the code segment, it must be a return
2743 address, so we have come to the end of the pending-argument section.
2744
2745 \item Otherwise it must be a bona fide heap pointer.
2746 \end{itemize}
2747
2748
2749 \Subsection{The Stable Pointer Table}{STABLEPTR_TABLE}
2750
2751 A stable pointer is a name for a Haskell object which can be passed to
2752 the external world.  It is ``stable'' in the sense that the name does
2753 not change when the Haskell garbage collector runs---in contrast to
2754 the address of the object which may well change.
2755
2756 A stable pointer is represented by an index into the
2757 @StablePointerTable@.  The Haskell garbage collector treats the
2758 @StablePointerTable@ as a source of roots for GC.
2759
2760 In order to provide efficient access to stable pointers and to be able
2761 to cope with any number of stable pointers (eg $0 \ldots 100000$), the
2762 table of stable pointers is an array stored on the heap and can grow
2763 when it overflows.  (Since we cannot compact the table by moving
2764 stable pointers about, it seems unlikely that a half-empty table can
2765 be reduced in size---this could be fixed if necessary by using a
2766 hash table of some sort.)
2767
2768 In general a stable pointer table closure looks like this:
2769
2770 \begin{center}
2771 \begin{tabular}{|l|l|l|l|l|l|l|l|l|l|l|}
2772 \hline
2773 \emph{Fixed header} & \emph{No of pointers} & \emph{Free} & $SP_0$ & \ldots & $SP_{n-1}$ 
2774 \\\hline
2775 \end{tabular}
2776 \end{center}
2777
2778 The fields are:
2779 \begin{description}
2780
2781 \item[@NPtrs@:] number of (stable) pointers.
2782
2783 \item[@Free@:] the byte offset (from the first byte of the object) of the first free stable pointer.
2784
2785 \item[$SP_i$:] A stable pointer slot.  If this entry is in use, it is
2786 an ``unstable'' pointer to a closure.  If this entry is not in use, it
2787 is a byte offset of the next free stable pointer slot.
2788
2789 \end{description}
2790
2791 When a stable pointer table is evacuated
2792 \begin{enumerate}
2793 \item the free list entries are all set to @NULL@ so that the evacuation
2794   code knows they're not pointers;
2795
2796 \item The stable pointer slots are scanned linearly: non-@NULL@ slots
2797 are evacuated and @NULL@-values are chained together to form a new free list.
2798 \end{enumerate}
2799
2800 There's no need to link the stable pointer table onto the mutable
2801 list because we always treat it as a root.
2802
2803 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2804 \Subsection{Garbage Collecting CAFs}{CAF}
2805 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2806
2807 % begin{direct quote from current paper}
2808 A CAF (constant applicative form) is a top-level expression with no
2809 arguments.  The expression may need a large, even unbounded, amount of
2810 storage when it is fully evaluated.
2811
2812 CAFs are represented by closures in static memory that are updated
2813 with indirections to objects in the heap space once the expression is
2814 evaluated.  Previous version of GHC maintained a list of all evaluated
2815 CAFs and traversed them during GC, the result being that the storage
2816 allocated by a CAF would reside in the heap until the program ended.
2817 % end{direct quote from current paper}
2818
2819 % begin{elaboration on why CAFs are very very bad}
2820 Treating CAFs this way has two problems:
2821 \begin{itemize}
2822 \item
2823 It can cause a very large space leak.  For example, this program
2824 should run in constant space but, instead, will run out of memory.
2825 \begin{verbatim}
2826 > main :: IO ()
2827 > main = print nats
2828 >
2829 > nats :: [Int]
2830 > nats = [0..maxInt]
2831 \end{verbatim}
2832
2833 \item
2834 Expressions with no arguments have very different space behaviour
2835 depending on whether or not they occur at the top level.  For example, 
2836 if we make \verb+nats+ a local definition, the space leak goes away 
2837 and the resulting program runs in constant space, as expected.
2838 \begin{verbatim}
2839 > main :: IO ()
2840 > main = print nats
2841 >  where
2842 >   nats :: [Int]
2843 >   nats = [0..maxInt]
2844 \end{verbatim}
2845
2846 This huge change in the operational behaviour of the program 
2847 is a problem for optimising compilers and for programmers.
2848 For example, GHC will normally flatten a set of let bindings using
2849 this transformation:
2850 \begin{verbatim}
2851 let x1 = let x2 = e2 in e1   ==>   let x2 = e2 in let x1 = e1
2852 \end{verbatim}
2853 but it does not do so if this would raise \verb+x2+ to the top level
2854 since that may create a CAF.  Many Haskell programmers avoid creating
2855 large CAFs by adding a dummy argument to a CAF or by moving a CAF away
2856 from the top level.
2857
2858 \end{itemize}
2859 % end{elaboration on why CAFs are very very bad}
2860
2861 Solving the CAF problem requires different treatment in interactive
2862 systems such as Hugs than in batch-mode systems such as GHC 
2863 \begin{itemize}
2864 \item
2865 In a batch-mode the program the runtime system is terminated
2866 after every execution of the runtime system.  In such systems,
2867 the garbage collector can completely ``destroy'' a CAF when it 
2868 is no longer live --- in much the same way as it ``destroys''
2869 normal closures when they are no longer live.
2870
2871 \item
2872 In an interactive system, many expressions are evaluated without
2873 restarting the runtime system between each evaluation.  In such
2874 systems, the garbage collector cannot completely ``destroy'' a CAF
2875 when it is no longer live because, whilst it might not be required in
2876 the evaluation of the current expression, it might be required in the
2877 next evaluation.
2878
2879 There are two possible behaviours we might want:
2880 \begin{enumerate}
2881 \item
2882 When a CAF is no longer required for the current evaluation, the CAF
2883 should be reverted to its original form.  This behaviour ensures that
2884 the operational behaviour of the interactive system is a reasonable
2885 predictor of the operational behaviour of the batch-mode system.  This
2886 allows us to use Hugs for performance debugging (in particular, trying
2887 to understand and reduce the heap usage of a program) --- an area of
2888 increasing importance as Haskell is used more and more to solve ``real
2889 problems'' in ``real problem domains''.
2890
2891 \item
2892 Even if a CAF is no longer required for the current evaluation, we might
2893 choose to hang onto it by collecting it in the normal way.  This keeps
2894 the space leak but might be useful in a teaching environment when
2895 trying to teach the difference between call by name evaluation (which
2896 doesn't share work) and lazy evaluation (which does share work).
2897
2898 \end{enumerate}
2899
2900 It turns out that it is easy to support both styles of use, so the
2901 runtime system provides a switch which lets us turn this on and off
2902 during execution.  \ToDo{What is this switch called?}  It would also
2903 be easy to provide a function \verb+RevertCAF+ to let the interpreter
2904 revert any CAF it wanted between (but not during) executions, if we so
2905 desired.  Running \verb+RevertCAF+ during execution would lose some sharing
2906 but is otherwise harmless.
2907
2908 \end{itemize}
2909
2910 % % begin{even more pointless observation?}
2911 % The simplest fix would be to remove the special treatment of 
2912 % top level variables.  This works but is very inefficient.
2913 % ToDo: say why.
2914 % (Note: delete this paragraph from final version.)
2915 % % end{even more pointless observation?}
2916
2917 % begin{pointless observation?}
2918 An easy but inefficient fix to the CAF problem would be to make a
2919 complete copy of the heap before every evaluation and discard the copy
2920 after evaluation.  This works but is inefficient.
2921 % end{pointless observation?}
2922
2923 An efficient way to achieve a similar effect is to revert all
2924 updatable thunks to their original form as they become unnecessary for
2925 the current evaluation.  To do this, we modify the compiler to ensure
2926 that the only updatable thunks generated by the compiler are CAFs and
2927 we modify the garbage collector to revert entered CAFs to unentered
2928 CAFs as their value becomes unnecessary.
2929
2930
2931 \subsubsection{New Heap Objects}
2932
2933 We add three new kinds of heap object: unentered CAF closures, entered
2934 CAF objects and CAF blackholes.  We first describe how they are
2935 evaluated and then how they are garbage collected.
2936 \begin{itemize}
2937 \item
2938 Unentered CAF closures contain a pointer to closure representing the
2939 body of the CAF.  The ``body closure'' is not updatable.
2940
2941 Unentered CAF closures contain two unused fields to make them the same
2942 size as entered CAF closures --- which allows us to perform an inplace
2943 update.  \ToDo{Do we have to add another kind of inplace update operation
2944 to the storage manager interface or do we consider this to be internal
2945 to the SM?}
2946 \begin{center}
2947 \begin{tabular}{|l|l|l|l|}\hline
2948 \verb+CAF_unentered+ & \emph{body closure} & \emph{unused} & \emph{unused} \\ \hline
2949 \end{tabular}
2950 \end{center}
2951 When an unentered CAF is entered, we do the following:
2952 \begin{itemize}
2953 \item
2954 allocate a CAF black hole;
2955
2956 \item
2957 push an update frame (to update the CAF black hole) onto the stack;
2958
2959 \item
2960 overwrite the CAF with an entered CAF object (see below) with the same
2961 body and whose value field points to the black hole;
2962
2963 \item
2964 add the CAF to a list of all entered CAFs (called ``the CAF list'');
2965 and
2966
2967 \item
2968 the closure representing the value of the CAF is entered.
2969
2970 \end{itemize}
2971
2972 When evaluation of the CAF body returns a value, the update frame
2973 causes the CAF black hole to be updated with the value in the normal
2974 way.
2975
2976 \ToDo{Add a picture}
2977
2978 \item
2979 Entered CAF closures contain two pointers: a pointer to the CAF body
2980 (the same as for unentered CAF closures); a pointer to the CAF value
2981 (this is initialised with a CAF blackhole, as previously described);
2982 and a link to the next CAF in the CAF list 
2983
2984 \ToDo{How is the end of the list marked?  Null pointer or sentinel value?}.
2985
2986 \begin{center}
2987 \begin{tabular}{|l|l|l|l|}\hline
2988 \verb+CAF_entered+ & \emph{body closure} & \emph{value} & \emph{link} \\ \hline
2989 \end{tabular}
2990 \end{center}
2991 When an entered CAF is entered, it enters its value closure.
2992
2993 \item
2994 CAF blackholes are identical to normal blackholes except that they
2995 have a different infotable.  The only reason for having CAF blackholes
2996 is to allow an optimisation of lazy blackholing where we stop scanning
2997 the stack when we see the first {\em normal blackhole} but not
2998 when we see a {\em CAF blackhole.}
2999 \ToDo{The optimisation we want to allow should be described elsewhere
3000 so that all we have to do here is describe the difference.}
3001
3002 Instead of allocating a blackhole to update with the value of the CAF,
3003 it might seem simpler to update the CAF directly.  This would require
3004 a new kind of update frame which would update the value field of the
3005 CAF with a pointer to the value and wouldn't catch blackholes caused
3006 by CAFs that depend on themselves so we chose not to do so.
3007
3008 \end{itemize}
3009
3010 \subsubsection{Garbage Collection}
3011
3012 To avoid the space leak, each run of the garbage collector must revert
3013 the entered CAFs which are not required to complete the current
3014 evaluation (that is all the closures reachable from the set of
3015 runnable threads and the stable pointer table).
3016
3017 It does this by performing garbage collection in three phases:
3018 \begin{enumerate}
3019 \item
3020 During the first phase, we ``mark'' all closures reachable from the
3021 scheduler state.  
3022
3023 How we ``mark'' closures depends on the garbage collector.  For
3024 example, in a 2-space collector, closures are ``marked'' by copying
3025 them into ``to-space'', overwriting them with a forwarding node and
3026 ``marking'' all the closures reachable from the copy.  The only
3027 requirements are that we can test whether a closure is marked and if a
3028 closure is marked then so are all closures reachable from it.
3029
3030 \ToDo{At present we say that the scheduler state includes any state
3031 that Hugs may have.  This is not true anymore.}
3032
3033 Performing this phase first provides us with a cheap test for
3034 execution closures: at this stage in execution, the execution closures
3035 are precisely the marked closures.
3036
3037 \item
3038 During the second phase, we revert all unmarked CAFs on the CAF list
3039 and remove them from the CAF list.
3040
3041 Since the CAF list is exactly the set of all entered CAFs, this reverts
3042 all entered CAFs which are not execution closures.
3043
3044 \item
3045 During the third phase, we mark all top level objects (including CAFs)
3046 by calling \verb+MarkHugsRoots+ which will call \verb+MarkRoot+ for
3047 each top level object known to Hugs.
3048
3049 \end{enumerate}
3050
3051 To implement the second style of interactive behaviour (where we
3052 deliberately keep the CAF-related space leak), we simply omit the
3053 second phase.  Omitting the second phase causes the third phase to
3054 mark any unmarked CAF value closures.
3055
3056 So far, we have been describing a pure Hugs system which contains no
3057 machine generated code.  The main difference in a hybrid system is
3058 that GHC-generated code is statically allocated in memory instead of
3059 being dynamically allocated on the heap.  We split both
3060 \verb+CAF_unentered+ and \verb+CAF_entered+ into two versions: a
3061 static and a dynamic version.  The static and dynamic versions of each
3062 CAF differ only in whether they are moved during garbage collection.
3063 When reverting CAFs, we revert dynamic entered CAFs to dynamic
3064 unentered CAFs and static entered CAFs to static unentered CAFs.
3065
3066
3067
3068
3069 \Section{The Bytecode Evaluator}{bytecode-evaluator}
3070
3071 This section describes how the Hugs interpreter interprets code in the
3072 same environment as compiled code executes.  Both evaluation models
3073 use a common garbage collector, so they must agree on the form of
3074 objects in the heap.
3075
3076 Hugs interprets code by converting it to byte-code and applying a
3077 byte-code interpreter to it.  Wherever possible, we try to ensure that
3078 the byte-code is all that is required to interpret a section of code.
3079 This means not dynamically generating info tables, and hence we can
3080 only have a small number of possible heap objects each with a statically
3081 compiled info table.  Similarly for stack objects: in fact we only
3082 have one Hugs stack object, in which all information is tagged for the
3083 garbage collector.
3084
3085 There is, however, one exception to this rule.  Hugs must generate
3086 info tables for any constructors it is asked to compile, since the
3087 alternative is to force a context-switch each time compiled code
3088 enters a Hugs-built constructor, which would be prohibitively
3089 expensive.
3090
3091 We achieve this simplicity by forgoing some of the optimisations used
3092 by compiled code:
3093 \begin{itemize}
3094 \item
3095
3096 Whereas compiled code has five different ways of entering a closure
3097 (\secref{ghc-fun-call}), interpreted code has only one.
3098 The entry point for interpreted code behaves like slow entry points for
3099 compiled code.
3100
3101 \item
3102
3103 We use just one info table for \emph{all\/} direct returns.  
3104 This introduces two problems:
3105 \begin{enumerate}
3106 \item How does the interpreter know what code to execute?
3107
3108 Instead of pushing just a return address, we push a return BCO and a 
3109 trivial return address which just enters the return BCO.
3110
3111 (In a purely interpreted system, we could avoid pushing the trivial
3112 return address.)
3113
3114 \item How can the garbage collector follow pointers within the
3115 activation record?
3116
3117 We could push a third word ---a bitmask describing the location of any
3118 pointers within the record--- but, since we're already tagging unboxed
3119 function arguments on the stack, we use the same mechanism for unboxed
3120 values within the activation record.
3121
3122 \ToDo{Do we have to stub out dead variables in the activation frame?}
3123
3124 \end{enumerate}
3125
3126 \item
3127
3128 We trivially support vectored returns by pushing a return vector whose
3129 entries are all the same.
3130
3131 \item
3132
3133 We avoid the need to build SRTs by putting bytecode objects on the
3134 heap and restricting BCOs to a single basic block.
3135
3136 \end{itemize}
3137
3138 \Subsection{Hugs Info Tables}{hugs-info-tables}
3139
3140 Hugs requires the following info tables and closures:
3141 \begin{description}
3142 \item [@HUGS_RET@].
3143
3144 Contains both a vectored return table and a direct entry point.  All
3145 entry points are the same: they rearrange the stack to match the Hugs
3146 return convention (\secref{hugs-return-convention}) and return to the
3147 scheduler.  When the scheduler restarts the thread, it will find a BCO
3148 on top of the stack and will enter the Hugs interpreter.
3149
3150 \item [@UPD_RET@].
3151
3152 This is just the standard info table for an update frame.
3153
3154 \item [Constructors].
3155
3156 The entry code for a constructor jumps to a generic entry point in the
3157 runtime system which decides whether to do a vectored or unvectored
3158 return depending on the shape of the constructor/type.  This implies that
3159 info tables must have enough info to make that decision.
3160
3161 \item [@AP@ and @PAP@].
3162
3163 \item [Indirections].
3164
3165 \item [Selectors].
3166
3167 Hugs doesn't generate them itself but it ought to recognise them
3168
3169 \item [Complex primops].
3170
3171 Some of the primops are too complex for GHC to generate inline.
3172 Instead, these primops are hand-written and called as normal functions.
3173 Hugs only needs to know their names and types but doesn't care whether
3174 they are generated by GHC or by hand.  Two things to watch:
3175
3176 \begin{enumerate}
3177 \item
3178 Hugs must be able to enter these primops even if it is working on a
3179 standalone system that does not support genuine GHC generated code.
3180
3181 \item The complex primops often involve unboxed tuple types (which
3182 Hugs does not support at the source level) so we cannot specify their
3183 types in a Haskell source file.
3184
3185 \end{enumerate}
3186
3187 \end{description}
3188
3189 \Subsection{Hugs Heap Objects}{hugs-heap-objects}
3190
3191 \subsubsection{Byte-code objects}
3192
3193 Compiled byte code lives on the global heap, in objects called
3194 Byte-Code Objects (or BCOs).  The layout of BCOs is described in
3195 detail in \secref{BCO}, in this section we will describe
3196 their semantics.
3197
3198 Since byte-code lives on the heap, it can be garbage collected just
3199 like any other heap-resident data.  Hugs arranges that any BCO's
3200 referred to by the Hugs symbol tables are treated as live objects by
3201 the garbage collector.  When a module is unloaded, the pointers to its
3202 BCOs are removed from the symbol table, and the code will be garbage
3203 collected some time later.
3204
3205 A BCO represents a basic block of code --- the (only) entry points is
3206 at the beginning of a BCO, and it is impossible to jump into the
3207 middle of one.  A BCO represents not only the code for a function, but
3208 also its closure; a BCO can be entered just like any other closure.
3209 Hugs performs lambda-lifting during compilation to byte-code, and each
3210 top-level combinator becomes a BCO in the heap.
3211
3212
3213 \subsubsection{Thunks and partial applications}
3214
3215 A thunk consists of a code pointer, and values for the free variables
3216 of that code.  Since Hugs byte-code is lambda-lifted, free variables
3217 become arguments and are expected to be on the stack by the called
3218 function.
3219
3220 Hugs represents updateable thunks with @AP_UPD@ objects applying a closure
3221 to a list of arguments.  (As for @PAP@s, unboxed arguments should be
3222 preceded by a tag.)  When it is entered, it pushes an update frame
3223 followed by its payload on the stack, and enters the first word (which
3224 will be a pointer to a BCO).  The layout of @AP_UPD@ objects is described
3225 in more detail in \secref{AP_UPD}.
3226
3227 Partial applications are represented by @PAP@ objects, which are
3228 non-updatable.
3229
3230 \ToDo{Hugs Constructors}.
3231
3232 \Subsection{Calling conventions}{hugs-calling-conventions}
3233
3234 The calling convention for any byte-code function is straightforward:
3235 \begin{itemize}
3236 \item Push any arguments on the stack.
3237 \item Push a pointer to the BCO.
3238 \item Begin interpreting the byte code.
3239 \end{itemize}
3240
3241 In a system containing both GHC and Hugs, the bytecode interpreter
3242 only has to be able to enter BCOs: everything else can be handled by
3243 returning to the compiled world (as described in
3244 \secref{hugs-to-ghc-switch}) and entering the closure
3245 there.
3246
3247 This would work but it would obviously be very inefficient if we
3248 entered a @AP@ by switching worlds, entering the @AP@, pushing the
3249 arguments and function onto the stack, and entering the function
3250 which, likely as not, will be a byte-code object which we will enter
3251 by \emph{returning} to the byte-code interpreter.  To avoid such
3252 gratuitious world switching, we choose to recognise certain closure
3253 types as being ``standard'' --- and duplicate the entry code for the
3254 ``standard closures'' in the bytecode interpreter.
3255
3256 A closure is said to be ``standard'' if its entry code is entirely
3257 determined by its info table.  \emph{Standard Closures} have the
3258 desirable property that the byte-code interpreter can enter the
3259 closure by simply ``interpreting'' the info table instead of switching
3260 to the compiled world.  The standard closures include:
3261
3262 \begin{description}
3263 \item[Constructor] To enter a constructor, we simply return (see
3264 \secref{hugs-return-convention}).
3265
3266 \item[Indirection]
3267 To enter an indirection, we simply enter the object it points to
3268 after possibly adjusting the current cost centre.
3269
3270 \item[@AP@] 
3271
3272 To enter an @AP@, we push an update frame, push the
3273 arguments, push the function and enter the function.
3274 (Not forgetting a stack check at the start.)
3275
3276 \item[@PAP@]
3277
3278 To enter a @PAP@, we push the arguments, push the function and enter
3279 the function.  (Not forgetting a stack check at the start.)
3280
3281 \item[Selector]
3282
3283 To enter a selector (\secref{THUNK_SELECTOR}), we test whether the
3284 selectee is a value.  If so, we simply select the appropriate
3285 component; if not, it's simplest to treat it as a GHC-built closure
3286 --- though we could interpret it if we wanted.
3287
3288 \end{description}
3289
3290 The most obvious omissions from the above list are @BCO@s (which we
3291 dealt with above) and GHC-built closures (which are covered in
3292 \secref{hugs-to-ghc-switch}).
3293
3294
3295 \Subsection{Return convention}{hugs-return-convention}
3296
3297 When Hugs pushes a return address, it pushes both a pointer to the BCO
3298 to return to, and a pointer to a static code fragment @HUGS_RET@ (this
3299 is described in \secref{ghc-to-hugs-switch}).  The
3300 stack layout is shown in \figref{hugs-return-stack}.
3301
3302 \begin{figure}[ht]
3303 \begin{center}
3304 @
3305 | stack    |
3306 +----------+
3307 | bco      |--> BCO
3308 +----------+
3309 | HUGS_RET |
3310 +----------+
3311 @
3312 %\input{hugs_ret.pstex_t}
3313 \end{center}
3314 \caption{Stack layout for a Hugs return address}
3315 \label{fig:hugs-return-stack}
3316 % this figure apparently duplicates {fig:hugs-return-stack1} earlier.
3317 \end{figure}
3318
3319 \begin{figure}[ht]
3320 \begin{center}
3321 @
3322 | stack    |
3323 +----------+
3324 | con      |--> CON
3325 +----------+
3326 @
3327 %\input{hugs_ret2.pstex_t}
3328 \end{center}
3329 \caption{Stack layout on enterings a Hugs return address}
3330 \label{fig:hugs-return2}
3331 \end{figure}
3332
3333 \begin{figure}[ht]
3334 \begin{center}
3335 @
3336 | stack    |
3337 +----------+
3338 | 3#       |
3339 +----------+
3340 | I#       |
3341 +----------+
3342 @
3343 %\input{hugs_ret2.pstex_t}
3344 \end{center}
3345 \caption{Stack layout on entering a Hugs return address with an unboxed value}
3346 \label{fig:hugs-return-int1}
3347 \end{figure}
3348
3349 \begin{figure}[ht]
3350 \begin{center}
3351 @
3352 | stack    |
3353 +----------+
3354 | ghc_ret  |
3355 +----------+
3356 | con      |--> CON
3357 +----------+
3358 @
3359 %\input{hugs_ret3.pstex_t}
3360 \end{center}
3361 \caption{Stack layout on enterings a GHC return address}
3362 \label{fig:hugs-return3}
3363 \end{figure}
3364
3365 \begin{figure}[ht]
3366 \begin{center}
3367 @
3368 | stack    |
3369 +----------+
3370 | ghc_ret  |
3371 +----------+
3372 | 3#       |
3373 +----------+
3374 | I#       |
3375 +----------+
3376 | restart  |--> id_Int#_closure
3377 +----------+
3378 @
3379 %\input{hugs_ret2.pstex_t}
3380 \end{center}
3381 \caption{Stack layout on enterings a GHC return address with an unboxed value}
3382 \label{fig:hugs-return-int}
3383 \end{figure}
3384
3385 When a Hugs byte-code sequence enters a closure, it examines the 
3386 return address on top of the stack.
3387
3388 \begin{itemize}
3389
3390 \item If the return address is @HUGS_RET@, pop the @HUGS_RET@ and the
3391 bco for the continuation off the stack, push a pointer to the constructor onto
3392 the stack and enter the BCO with the current object pointer set to the BCO
3393 (\figref{hugs-return2}).
3394
3395 \item If the top of the stack is not @HUGS_RET@, we need to do a world
3396 switch as described in \secref{hugs-to-ghc-switch}.
3397
3398 \end{itemize}
3399
3400 \ToDo{This duplicates what we say about switching worlds
3401 (\secref{switching-worlds}) - kill one or t'other.}
3402
3403
3404 \ToDo{This was in the evaluation model part but it really belongs in
3405 this part which is about the internal details of each of the major
3406 sections.}
3407
3408 \Subsection{Addressing Modes}{hugs-addressing-modes}
3409
3410 To avoid potential alignment problems and simplify garbage collection,
3411 all literal constants are stored in two tables (one boxed, the other
3412 unboxed) within each BCO and are referred to by offsets into the tables.
3413 Slots in the constant tables are word aligned.
3414
3415 \ToDo{How big can the offsets be?  Is the offset specified in the
3416 address field or in the instruction?}
3417
3418 Literals can have the following types: char, int, nat, float, double,
3419 and pointer to boxed object.  There is no real difference between
3420 char, int, nat and float since they all occupy 32 bits --- but it
3421 costs almost nothing to distinguish them and may improve portability
3422 and simplify debugging.
3423
3424 \Subsection{Compilation}{hugs-compilation}
3425
3426
3427 \def\is{\mbox{\it is}}
3428 \def\ts{\mbox{\it ts}}
3429 \def\as{\mbox{\it as}}
3430 \def\bs{\mbox{\it bs}}
3431 \def\cs{\mbox{\it cs}}
3432 \def\rs{\mbox{\it rs}}
3433 \def\us{\mbox{\it us}}
3434 \def\vs{\mbox{\it vs}}
3435 \def\ws{\mbox{\it ws}}
3436 \def\xs{\mbox{\it xs}}
3437
3438 \def\e{\mbox{\it e}}
3439 \def\alts{\mbox{\it alts}}
3440 \def\fail{\mbox{\it fail}}
3441 \def\panic{\mbox{\it panic}}
3442 \def\ua{\mbox{\it ua}}
3443 \def\obj{\mbox{\it obj}}
3444 \def\bco{\mbox{\it bco}}
3445 \def\tag{\mbox{\it tag}}
3446 \def\entry{\mbox{\it entry}}
3447 \def\su{\mbox{\it su}}
3448
3449 \def\Ind#1{{\mbox{\it Ind}\ {#1}}}
3450 \def\update#1{{\mbox{\it update}\ {#1}}}
3451
3452 \def\next{$\Longrightarrow$}
3453 \def\append{\mathrel{+\mkern-6mu+}}
3454 \def\reverse{\mbox{\it reverse}}
3455 \def\size#1{{\vert {#1} \vert}}
3456 \def\arity#1{{\mbox{\it arity}{#1}}}
3457
3458 \def\AP{\mbox{\it AP}}
3459 \def\PAP{\mbox{\it PAP}}
3460 \def\GHCRET{\mbox{\it GHCRET}}
3461 \def\GHCOBJ{\mbox{\it GHCOBJ}}
3462
3463 To make sense of the instructions, we need a sense of how they will be
3464 used.  Here is a small compiler for the STG language.
3465
3466 @
3467 > cg (f{a1, ... am}) = do
3468 >   pushAtom am; ... pushAtom a1
3469 >   pushVar f
3470 >   SLIDE (m+1) |env|
3471 >   ENTER
3472 > cg (let {x1=rhs1; ... xm=rhsm} in e) = do
3473 >   ALLOC x1 |rhs1|, ... ALLOC xm |rhsm|
3474 >   build x1 rhs1,   ... build xm rhsm
3475 >   cg e
3476 > cg (case e of alts) = do
3477 >   PUSHALTS (cgAlts alts)
3478 >   cg e
3479
3480 > cgAlts { alt1; ... altm }  = cgAlt alt1 $ ... $ cgAlt altm pmFail
3481 >
3482 > cgAlt (x@C{xs} -> e) fail = do
3483 >   TEST C fail
3484 >   HEAPCHECK (heapUse e)
3485 >   UNPACK xs
3486 >   cg e
3487
3488 > build x (C{a1, ... am}) = do 
3489 >   pushUntaggedAtom am; ... pushUntaggedAtom a1
3490 >   PACK x C
3491 > -- A useful optimisation
3492 > build x ({v1, ... vm} \ {}. f{a1, ... am}) = do 
3493 >   pushVar am; ... pushVar a1
3494 >   pushVar f
3495 >   MKAP x m
3496 > build x ({v1, ... vm} \ {}. e) = do 
3497 >   pushVar vm; ... pushVar v1
3498 >   PUSHBCO (cgRhs ({v1, ... vm} \ {}. e))
3499 >   MKAP x m
3500 > build x ({v1, ... vm} \ {x1, ... xm}. e) = do 
3501 >   pushVar vm; ... pushVar v1
3502 >   PUSHBCO (cgRhs ({v1, ... vm} \ {x1, ... xm}. e))
3503 >   MKPAP x m
3504
3505 > cgRhs (vs \ xs. e) = do
3506 >   ARGCHECK   (xs ++ vs)  -- can be omitted if xs == {}
3507 >   STACKCHECK min(stackUse e,heapOverflowSlop)
3508 >   HEAPCHECK  (heapUse e)
3509 >   cg e
3510
3511 > pushAtom x  = pushVar x
3512 > pushAtom i# = PUSHINT i#
3513
3514 > pushVar x = if isGlobalVar x then PUSHGLOBAL x else PUSHLOCAL x 
3515
3516 > pushUntaggedAtom x  = pushVar x
3517 > pushUntaggedAtom i# = PUSHUNTAGGEDINT i#
3518
3519 > pushVar x = if isGlobalVar x then PUSHGLOBAL x else PUSHLOCAL x 
3520 @
3521
3522 \ToDo{Is there an easy way to add semi-tagging?  Would it be that different?}
3523
3524 \ToDo{Optimise thunks of the form @f{x1,...xm}@ so that we build an AP directly}
3525
3526 \Subsection{Instructions}{hugs-instructions}
3527
3528 We specify the semantics of instructions using transition rules of
3529 the form:
3530
3531 \begin{tabular}{|llrrrrr|}
3532 \hline
3533         & $\is$         & $s$   & $\su$         & $h$  & $hp$  & $\sigma$ \\
3534 \next   & $\is'$        & $s'$  & $\su'$        & $h'$ & $hp'$ & $\sigma$ \\
3535 \hline
3536 \end{tabular}
3537
3538 where $\is$ is an instruction stream, $s$ is the stack, $\su$ is the 
3539 update frame pointer and $h$ is the heap.
3540
3541
3542 \Subsection{Stack manipulation}{hugs-stack-manipulation}
3543
3544 \begin{description}
3545
3546 \item[ Push a global variable ].
3547
3548 \begin{tabular}{|llrrrrr|}
3549 \hline
3550         & PUSHGLOBAL $o$ : $\is$ & $s$          & $su$ & $h$ & $hp$ & $\sigma$ \\
3551 \next   & $\is$                  & $\sigma!o:s$ & $su$ & $h$ & $hp$ & $\sigma$ \\
3552 \hline
3553 \end{tabular}
3554
3555 \item[ Push a local variable ].
3556
3557 \begin{tabular}{|llrrrrr|}
3558 \hline
3559         & PUSHLOCAL $o$ : $\is$ & $s$           & $su$ & $h$ & $hp$ & $\sigma$ \\
3560 \next   & $\is$                 & $s!o : s$     & $su$ & $h$ & $hp$ & $\sigma$ \\
3561 \hline
3562 \end{tabular}
3563
3564 \item[ Push an unboxed int ].
3565
3566 \begin{tabular}{|llrrrrr|}
3567 \hline
3568         & PUSHINT $o$ : $\is$   & $s$                   & $su$ & $h$ & $hp$ & $\sigma$ \\
3569 \next   & $\is$                 & $I\# : \sigma!o : s$  & $su$ & $h$ & $hp$ & $\sigma$ \\
3570 \hline
3571 \end{tabular}
3572
3573 The $I\#$ is a tag included for the benefit of the garbage collector.
3574 Similar rules exist for floats, doubles, chars, etc.
3575
3576 \item[ Push an unboxed int ].
3577
3578 \begin{tabular}{|llrrrrr|}
3579 \hline
3580         & PUSHUNTAGGEDINT $o$ : $\is$   & $s$                   & $su$ & $h$ & $hp$ & $\sigma$ \\
3581 \next   & $\is$                 & $\sigma!o : s$        & $su$ & $h$ & $hp$ & $\sigma$ \\
3582 \hline
3583 \end{tabular}
3584
3585 Similar rules exist for floats, doubles, chars, etc.
3586
3587 \item[ Delete environment from stack --- ready for tail call ].
3588
3589 \begin{tabular}{|llrrrrr|}
3590 \hline
3591         & SLIDE $m$ $n$ : $\is$ & $\as \append \bs \append \cs$         & $su$ & $h$ & $hp$ & $\sigma$ \\
3592 \next   & $\is$                 & $\as \append \cs$                     & $su$ & $h$ & $hp$ & $\sigma$ \\
3593 \hline
3594 \end{tabular}
3595 \\
3596 where $\size{\as} = m$ and $\size{\bs} = n$.
3597
3598
3599 \item[ Push a return address ].
3600
3601 \begin{tabular}{|llrrrrr|}
3602 \hline
3603         & PUSHALTS $o$:$\is$    & $s$                   & $su$ & $h$ & $hp$ & $\sigma$ \\
3604 \next   & $\is$                 & $@HUGS_RET@:\sigma!o:s$       & $su$ & $h$ & $hp$ & $\sigma$ \\
3605 \hline
3606 \end{tabular}
3607
3608 \item[ Push a BCO ].
3609
3610 \begin{tabular}{|llrrrrr|}
3611 \hline
3612         & PUSHBCO $o$ : $\is$   & $s$                   & $su$ & $h$ & $hp$ & $\sigma$ \\
3613 \next   & $\is$                 & $\sigma!o : s$        & $su$ & $h$ & $hp$ & $\sigma$ \\
3614 \hline
3615 \end{tabular}
3616
3617 \end{description}
3618
3619 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3620 \Subsection{Heap manipulation}{hugs-heap-manipulation}
3621 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3622
3623 \begin{description}
3624
3625 \item[ Allocate a heap object ].
3626
3627 \begin{tabular}{|llrrrrr|}
3628 \hline
3629         & ALLOC $m$ : $\is$     & $s$    & $su$ & $h$ & $hp$   & $\sigma$ \\
3630 \next   & $\is$                 & $hp:s$ & $su$ & $h$ & $hp+m$ & $\sigma$ \\
3631 \hline
3632 \end{tabular}
3633
3634 \item[ Build a constructor ].
3635
3636 \begin{tabular}{|llrrrrr|}
3637 \hline
3638         & PACK $o$ $o'$ : $\is$ & $\ws \append s$       & $su$ & $h$                            & $hp$ & $\sigma$ \\
3639 \next   & $\is$                 & $s$                   & $su$ & $h[s!o \mapsto Pack C\{\ws\}]$ & $hp$ & $\sigma$ \\
3640 \hline
3641 \end{tabular}
3642 \\
3643 where $C = \sigma!o'$ and $\size{\ws} = \arity{C}$.
3644
3645 \item[ Build an AP or  PAP ].
3646
3647 \begin{tabular}{|llrrrrr|}
3648 \hline
3649         & MKAP $o$ $m$:$\is$    & $f : \ws \append s$   & $su$ & $h$                            & $hp$ & $\sigma$ \\
3650 \next   & $\is$                 & $s$                   & $su$ & $h[s!o \mapsto \AP(f,\ws)]$    & $hp$ & $\sigma$ \\
3651 \hline
3652 \end{tabular}
3653 \\
3654 where $\size{\ws} = m$.
3655
3656 \begin{tabular}{|llrrrrr|}
3657 \hline
3658         & MKPAP $o$ $m$:$\is$   & $f : \ws \append s$   & $su$ & $h$                            & $hp$ & $\sigma$ \\
3659 \next   & $\is$                 & $s$                   & $su$ & $h[s!o \mapsto \PAP(f,\ws)]$   & $hp$ & $\sigma$ \\
3660 \hline
3661 \end{tabular}
3662 \\
3663 where $\size{\ws} = m$.
3664
3665 \item[ Unpacking a constructor ].
3666
3667 \begin{tabular}{|llrrrrr|}
3668 \hline
3669         & UNPACK : $is$         & $a : s$                               & $su$ & $h[a \mapsto C\ \ws]$          & $hp$ & $\sigma$ \\
3670 \next   & $is'$                 & $(\reverse\ \ws) \append a : s$       & $su$ & $h$                            & $hp$ & $\sigma$ \\
3671 \hline
3672 \end{tabular}
3673
3674 The $\reverse\ \ws$ looks expensive but, since the stack grows down
3675 and the heap grows up, that's actually the cheap way of copying from
3676 heap to stack.  Looking at the compilation rules, you'll see that we
3677 always push the args in reverse order.
3678
3679 \end{description}
3680
3681
3682 \Subsection{Entering a closure}{hugs-entering}
3683
3684 \begin{description}
3685
3686 \item[ Enter a BCO ].
3687
3688 \begin{tabular}{|llrrrrr|}
3689 \hline
3690         & [ENTER]       & $a : s$       & $su$ & $h[a \mapsto BCO\{\is\} ]$     & $hp$ & $\sigma$ \\
3691 \next   & $\is$         & $a : s$       & $su$ & $h$                            & $hp$ & $a$ \\
3692 \hline
3693 \end{tabular}
3694
3695 \item[ Enter a PAP closure ].
3696
3697 \begin{tabular}{|llrrrrr|}
3698 \hline
3699         & [ENTER]       & $a : s$               & $su$ & $h[a \mapsto \PAP(f,\ws)]$     & $hp$ & $\sigma$ \\
3700 \next   & [ENTER]       & $f : \ws \append s$   & $su$ & $h$                            & $hp$ & $???$ \\
3701 \hline
3702 \end{tabular}
3703
3704 \item[ Entering an AP closure ].
3705
3706 \begin{tabular}{|llrrrrr|}
3707 \hline
3708         & [ENTER]       & $a : s$                               & $su$  & $h[a \mapsto \AP(f,ws)]$      & $hp$ & $\sigma$ \\
3709 \next   & [ENTER]       & $f : \ws \append @UPD_RET@:\su:a:s$   & $su'$ & $h$                           & $hp$ & $???$ \\
3710 \hline
3711 \end{tabular}
3712
3713 Optimisations:
3714 \begin{itemize}
3715 \item Instead of blindly pushing an update frame for $a$, we can first test whether there's already
3716  an update frame there.  If so, overwrite the existing updatee with an indirection to $a$ and
3717  overwrite the updatee field with $a$.  (Overwriting $a$ with an indirection to the updatee also
3718  works.)  This results in update chains of maximum length 2. 
3719 \end{itemize}
3720
3721
3722 \item[ Returning a constructor ].
3723
3724 \begin{tabular}{|llrrrrr|}
3725 \hline
3726         & [ENTER]               & $a : @HUGS_RET@ : \alts : s$  & $su$ & $h[a \mapsto C\{\ws\}]$        & $hp$ & $\sigma$ \\
3727 \next   & $\alts.\entry$        & $a:s$                         & $su$ & $h$                            & $hp$ & $\sigma$ \\
3728 \hline
3729 \end{tabular}
3730
3731
3732 \item[ Entering an indirection node ].
3733
3734 \begin{tabular}{|llrrrrr|}
3735 \hline
3736         & [ENTER]       & $a  : s$      & $su$ & $h[a \mapsto \Ind{a'}]$        & $hp$ & $\sigma$ \\
3737 \next   & [ENTER]       & $a' : s$      & $su$ & $h$                            & $hp$ & $\sigma$ \\
3738 \hline
3739 \end{tabular}
3740
3741 \item[Entering GHC closure].
3742
3743 \begin{tabular}{|llrrrrr|}
3744 \hline
3745         & [ENTER]       & $a : s$       & $su$ & $h[a \mapsto \GHCOBJ]$         & $hp$ & $\sigma$ \\
3746 \next   & [ENTERGHC]    & $a : s$       & $su$ & $h$                            & $hp$ & $\sigma$ \\
3747 \hline
3748 \end{tabular}
3749
3750 \item[Returning a constructor to GHC].
3751
3752 \begin{tabular}{|llrrrrr|}
3753 \hline
3754         & [ENTER]       & $a : \GHCRET : s$     & $su$ & $h[a \mapsto C \ws]$   & $hp$ & $\sigma$ \\
3755 \next   & [ENTERGHC]    & $a : \GHCRET : s$     & $su$ & $h$                    & $hp$ & $\sigma$ \\
3756 \hline
3757 \end{tabular}
3758
3759 \end{description}
3760
3761
3762 \Subsection{Updates}{hugs-updates}
3763
3764 \begin{description}
3765
3766 \item[ Updating with a constructor].
3767
3768 \begin{tabular}{|llrrrrr|}
3769 \hline
3770         & [ENTER]       & $a : @UPD_RET@ : ua : s$      & $su$ & $h[a \mapsto C\{\ws\}]$  & $hp$ & $\sigma$ \\
3771 \next   & [ENTER]       & $a \append s$                 & $su$ & $h[au \mapsto \Ind{a}$   & $hp$ & $\sigma$ \\
3772 \hline
3773 \end{tabular}
3774
3775 \item[ Argument checks].
3776
3777 \begin{tabular}{|llrrrrr|}
3778 \hline
3779         & ARGCHECK $m$:$\is$    & $a : \as \append s$   & $su$ & $h$    & $hp$ & $\sigma$ \\
3780 \next   & $\is$                 & $a : \as \append s$   & $su$ & $h'$   & $hp$ & $\sigma$ \\
3781 \hline
3782 \end{tabular}
3783 \\
3784 where $m \ge (su - sp)$
3785
3786 \begin{tabular}{|llrrrrr|}
3787 \hline
3788         & ARGCHECK $m$:$\is$    & $a : \as \append @UPD_RET@:su:ua:s$   & $su$ & $h$    & $hp$ & $\sigma$ \\
3789 \next   & $\is$                 & $a : \as \append s$                   & $su$ & $h'$   & $hp$ & $\sigma$ \\
3790 \hline
3791 \end{tabular}
3792 \\
3793 where $m < (su - sp)$ and
3794       $h' = h[ua \mapsto \Ind{a'}, a' \mapsto \PAP(a,\reverse\ \as) ]$
3795
3796 Again, we reverse the list of values as we transfer them from the
3797 stack to the heap --- reflecting the fact that the stack and heap grow
3798 in different directions.
3799
3800 \end{description}
3801
3802 \Subsection{Branches}{hugs-branches}
3803
3804 \begin{description}
3805
3806 \item[ Testing a constructor ].
3807
3808 \begin{tabular}{|llrrrrr|}
3809 \hline
3810         & TEST $tag$ $is'$ : $is$       & $a : s$       & $su$ & $h[a \mapsto C\ \ws]$  & $hp$ & $\sigma$ \\
3811 \next   & $is$                          & $a : s$       & $su$ & $h$                    & $hp$ & $\sigma$ \\
3812 \hline
3813 \end{tabular}
3814 \\
3815 where $C.\tag = tag$
3816
3817 \begin{tabular}{|llrrrrr|}
3818 \hline
3819         & TEST $tag$ $is'$ : $is$       & $a : s$       & $su$ & $h[a \mapsto C\ \ws]$  & $hp$ & $\sigma$ \\
3820 \next   & $is'$                         & $a : s$       & $su$ & $h$                    & $hp$ & $\sigma$ \\
3821 \hline
3822 \end{tabular}
3823 \\
3824 where $C.\tag \neq tag$
3825
3826 \end{description}
3827
3828 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3829 \Subsection{Heap and stack checks}{hugs-heap-stack-checks}
3830 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3831
3832 \begin{tabular}{|llrrrrr|}
3833 \hline
3834         & STACKCHECK $stk$:$\is$        & $s$   & $su$ & $h$    & $hp$ & $\sigma$ \\
3835 \next   & $\is$                         & $s$   & $su$ & $h$    & $hp$ & $\sigma$ \\
3836 \hline
3837 \end{tabular}
3838 \\
3839 if $s$ has $stk$ free slots.
3840
3841 \begin{tabular}{|llrrrrr|}
3842 \hline
3843         & HEAPCHECK $hp$:$\is$          & $s$   & $su$ & $h$    & $hp$ & $\sigma$ \\
3844 \next   & $\is$                         & $s$   & $su$ & $h$    & $hp$ & $\sigma$ \\
3845 \hline
3846 \end{tabular}
3847 \\
3848 if $h$ has $hp$ free slots.
3849
3850 If either check fails, we push the current bco ($\sigma$) onto the
3851 stack and return to the scheduler.  When the scheduler has fixed the
3852 problem, it pops the top object off the stack and reenters it.
3853
3854
3855 Optimisations:
3856 \begin{itemize}
3857 \item The bytecode CHECK1000 conservatively checks for 1000 words of heap space and 1000 words of stack space.
3858       We use it to reduce code space and instruction decoding time.
3859 \item The bytecode HEAPCHECK1000 conservatively checks for 1000 words of heap space.
3860       It is used in case alternatives.
3861 \end{itemize}
3862
3863
3864 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3865 \Subsection{Primops}{hugs-primops}
3866 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3867
3868 \ToDo{primops take m words and return n words. The expect boxed arguments on the stack.}
3869
3870
3871 \Section{The Machine Code Evaluator}{asm-evaluator}
3872
3873 This section describes the framework in which compiled code evaluates
3874 expressions.  Only at certain points will compiled code need to be
3875 able to talk to the interpreted world; these are discussed in
3876 \secref{switching-worlds}.
3877
3878 \Subsection{Calling conventions}{ghc-calling-conventions}
3879
3880 \Subsubsection{The call/return registers}{ghc-regs}
3881
3882 One of the problems in designing a virtual machine is that we want it
3883 abstract away from tedious machine details but still reveal enough of
3884 the underlying hardware that we can make sensible decisions about code
3885 generation.  A major problem area is the use of registers in
3886 call/return conventions.  On a machine with lots of registers, it's
3887 cheaper to pass arguments and results in registers than to pass them
3888 on the stack.  On a machine with very few registers, it's cheaper to
3889 pass arguments and results on the stack than to use ``virtual
3890 registers'' in memory.  We therefore use a hybrid system: the first
3891 $n$ arguments or results are passed in registers; and the remaining
3892 arguments or results are passed on the stack.  For register-poor
3893 architectures, it is important that we allow $n=0$.
3894
3895 We'll label the arguments and results \Arg{1} \ldots \Arg{m} --- with
3896 the understanding that \Arg{1} \ldots \Arg{n} are in registers and
3897 \Arg{n+1} \ldots \Arg{m} are on top of the stack.
3898
3899 Note that the mapping of arguments \Arg{1} \ldots \Arg{n} to machine
3900 registers depends on the \emph{kinds} of the arguments.  For example,
3901 if the first argument is a Float, we might pass it in a different
3902 register from if it is an Int.  In fact, we might find that a given
3903 architecture lets us pass varying numbers of arguments according to
3904 their types.  For example, if a CPU has 2 Int registers and 2 Float
3905 registers then we could pass between 2 and 4 arguments in machine
3906 registers --- depending on whether they all have the same kind or they
3907 have different kinds.
3908
3909 \Subsubsection{Entering closures}{entering-closures}
3910
3911 To evaluate a closure we jump to the entry code for the closure
3912 passing a pointer to the closure in \Arg{1} so that the entry code can
3913 access its environment.
3914
3915 \Subsubsection{Function call}{ghc-fun-call}
3916
3917 The function-call mechanism is obviously crucial.  There are five different
3918 cases to consider:
3919 \begin{enumerate}
3920
3921 \item \emph{Known combinator (function with no free variables) and
3922 enough arguments.}
3923
3924 A fast call can be made: push excess arguments onto stack and jump to
3925 function's \emph{fast entry point} passing arguments in \Arg{1} \ldots
3926 \Arg{m}.
3927
3928 The \emph{fast entry point} is only called with exactly the right
3929 number of arguments (in \Arg{1} \ldots \Arg{m}) so it can instantly
3930 start doing useful work without first testing whether it has enough
3931 registers or having to pop them off the stack first.
3932
3933 \item \emph{Known combinator and insufficient arguments.}
3934
3935 A slow call can be made: push all arguments onto stack and jump to
3936 function's \emph{slow entry point}.
3937
3938 Any unpointed arguments which are pushed on the stack must be tagged.
3939 This means pushing an extra word on the stack below the unpointed
3940 words, containing the number of unpointed words above it.
3941
3942 %Todo: forward ref about tagging?
3943 %Todo: picture?
3944
3945 The \emph{slow entry point} might be called with insufficient arguments
3946 and so it must test whether there are enough arguments on the stack.
3947 This \emph{argument satisfaction check} consists of checking that
3948 @Su-Sp@ is big enough to hold all the arguments (including any tags).
3949
3950 \begin{itemize} 
3951
3952 \item If the argument satisfaction check fails, it is because there is
3953 one or more update frames on the stack before the rest of the
3954 arguments that the function needs.  In this case, we construct a PAP
3955 (partial application, \secref{PAP}) containing the arguments
3956 which are on the stack.  The PAP construction code will return to the
3957 update frame with the address of the PAP in \Arg{1}.
3958
3959 \item If the argument satisfaction check succeeds, we jump to the fast
3960 entry point with the arguments in \Arg{1} \ldots \Arg{arity}.
3961
3962 If the fast entry point expects to receive some of \Arg{i} on the
3963 stack, we can reduce the amount of movement required by making the
3964 stack layout for the fast entry point look like the stack layout for
3965 the slow entry point.  Since the slow entry point is entered with the
3966 first argument on the top of the stack and with tags in front of any
3967 unpointed arguments, this means that if \Arg{i} is unpointed, there
3968 should be space below it for a tag and that the highest numbered
3969 argument should be passed on the top of the stack.
3970
3971 We usually arrange that the fast entry point is placed immediately
3972 after the slow entry point --- so we can just ``fall through'' to the
3973 fast entry point without performing a jump.
3974
3975 \end{itemize}
3976
3977
3978 \item \emph{Known function closure (function with free variables) and
3979 enough arguments.}
3980
3981 A fast call can be made: push excess arguments onto stack and jump to
3982 function's \emph{fast entry point} passing a pointer to closure in
3983 \Arg{1} and arguments in \Arg{2} \ldots \Arg{m+1}.
3984
3985 Like the fast entry point for a combinator, the fast entry point for a
3986 closure is only called with appropriate values in \Arg{1} \ldots
3987 \Arg{m+1} so we can start work straight away.  The pointer to the
3988 closure is used to access the free variables of the closure.
3989
3990
3991 \item \emph{Known function closure and insufficient arguments.}
3992
3993 A slow call can be made: push all arguments onto stack and jump to the
3994 closure's slow entry point passing a pointer to the closure in \Arg{1}.
3995
3996 Again, the slow entry point performs an argument satisfaction check
3997 and either builds a PAP or pops the arguments off the stack into
3998 \Arg{2} \ldots \Arg{m+1} and jumps to the fast entry point.
3999
4000
4001 \item \emph{Unknown function closure, thunk or constructor.}
4002
4003 Sometimes, the function being called is not statically identifiable.
4004 Consider, for example, the @compose@ function:
4005 @
4006   compose f g x = f (g x)
4007 @
4008 Since @f@ and @g@ are passed as arguments to @compose@, the latter has
4009 to make a heap call.  In a heap call the arguments are pushed onto the
4010 stack, and the closure bound to the function is entered.  In the
4011 example, a thunk for @(g x)@ will be allocated, (a pointer to it)
4012 pushed on the stack, and the closure bound to @f@ will be
4013 entered. That is, we will jump to @f@s entry point passing @f@ in
4014 \Arg{1}.  If \Arg{1} is passed on the stack, it is pushed on top of
4015 the thunk for @(g x)@.
4016
4017 The \emph{entry code} for an updateable thunk (which must have arity 0)
4018 pushes an update frame on the stack and starts executing the body of
4019 the closure --- using \Arg{1} to access any free variables.  This is
4020 described in more detail in \secref{data-updates}.
4021
4022 The \emph{entry code} for a non-updateable closure is just the
4023 closure's slow entry point.
4024
4025 \end{enumerate}
4026
4027 In addition to the above considerations, if there are \emph{too many}
4028 arguments then the extra arguments are simply pushed on the stack with
4029 appropriate tags.
4030
4031 To summarise, a closure's standard (slow) entry point performs the
4032 following:
4033
4034 \begin{description}
4035 \item[Argument satisfaction check.] (function closure only)
4036 \item[Stack overflow check.]
4037 \item[Heap overflow check.]
4038 \item[Copy free variables out of closure.] %Todo: why?
4039 \item[Eager black holing.] (updateable thunk only) %Todo: forward ref.
4040 \item[Push update frame.]
4041 \item[Evaluate body of closure.]
4042 \end{description}
4043
4044
4045 \Subsection{Case expressions and return conventions}{return-conventions}
4046
4047 The \emph{evaluation} of a thunk is always initiated by
4048 a @case@ expression.  For example:
4049 @
4050   case x of (a,b) -> E
4051 @
4052
4053 The code for a @case@ expression looks like this:
4054
4055 \begin{itemize}
4056 \item Push the free variables of the branches on the stack (fv(@E@) in
4057 this case).
4058 \item  Push a \emph{return address} on the stack.
4059 \item  Evaluate the scrutinee (@x@ in this case).
4060 \end{itemize}
4061
4062 Once evaluation of the scrutinee is complete, execution resumes at the
4063 return address, which points to the code for the expression @E@.
4064
4065 When execution resumes at the return point, there must be some {\em
4066 return convention} that defines where the components of the pair, @a@
4067 and @b@, can be found.  The return convention varies according to the
4068 type of the scrutinee @x@:
4069
4070 \begin{itemize}
4071
4072 \item 
4073
4074 (A space for) the return address is left on the top of the stack.
4075 Leaving the return address on the stack ensures that the top of the
4076 stack contains a valid activation record
4077 (\secref{activation-records}) --- should a garbage
4078 collection be required.
4079
4080 \item If @x@ has a boxed type (e.g.~a data constructor or a function),
4081 a pointer to @x@ is returned in \Arg{1}.
4082
4083 \ToDo{Warn that components of E should be extracted as soon as
4084 possible to avoid a space leak.}
4085
4086 \item If @x@ is an unboxed type (e.g.~@Int#@ or @Float#@), @x@ is
4087 returned in \Arg{1}
4088
4089 \item If @x@ is an unboxed tuple constructor, the components of @x@
4090 are returned in \Arg{1} \ldots \Arg{n} but no object is constructed in
4091 the heap.  
4092
4093 When passing an unboxed tuple to a function, the components are
4094 flattened out and passed in \Arg{1} \ldots \Arg{n} as usual.
4095
4096 \end{itemize}
4097
4098 \Subsection{Vectored Returns}{vectored-returns}
4099
4100 Many algebraic data types have more than one constructor.  For
4101 example, the @Maybe@ type is defined like this:
4102 @
4103   data Maybe a = Nothing | Just a
4104 @
4105 How does the return convention encode which of the two constructors is
4106 being returned?  A @case@ expression scrutinising a value of @Maybe@
4107 type would look like this: 
4108 @
4109   case E of 
4110     Nothing -> ...
4111     Just a  -> ...
4112 @
4113 Rather than pushing a return address before evaluating the scrutinee,
4114 @E@, the @case@ expression pushes (a pointer to) a \emph{return
4115 vector}, a static table consisting of two code pointers: one for the
4116 @Just@ alternative, and one for the @Nothing@ alternative.  
4117
4118 \begin{itemize}
4119
4120 \item
4121
4122 The constructor @Nothing@ returns by jumping to the first item in the
4123 return vector with a pointer to a (statically built) Nothing closure
4124 in \Arg{1}.  
4125
4126 It might seem that we could avoid loading \Arg{1} in this case since the
4127 first item in the return vector will know that @Nothing@ was returned
4128 (and can easily access the Nothing closure in the (unlikely) event
4129 that it needs it.  The only reason we load \Arg{1} is in case we have to
4130 perform an update (\secref{data-updates}).
4131
4132 \item 
4133
4134 The constructor @Just@ returns by jumping to the second element of the
4135 return vector with a pointer to the closure in \Arg{1}.  
4136
4137 \end{itemize}
4138
4139 In this way no test need be made to see which constructor returns;
4140 instead, execution resumes immediately in the appropriate branch of
4141 the @case@.
4142
4143 \Subsection{Direct Returns}{direct-returns}
4144
4145 When a datatype has a large number of constructors, it may be
4146 inappropriate to use vectored returns.  The vector tables may be
4147 large and sparse, and it may be better to identify the constructor
4148 using a test-and-branch sequence on the tag.  For this reason, we
4149 provide an alternative return convention, called a \emph{direct
4150 return}.
4151
4152 In a direct return, the return address pushed on the stack really is a
4153 code pointer.  The returning code loads a pointer to the closure being
4154 returned in \Arg{1} as usual, and also loads the tag into \Arg{2}.
4155 The code at the return address will test the tag and jump to the
4156 appropriate code for the case branch.  If \Arg{2} isn't mapped to a
4157 real machine register on this architecture, then we don't load it on a
4158 return, instead using the tag directly from the info table.
4159
4160 The choice of whether to use a vectored return or a direct return is
4161 made on a type-by-type basis --- up to a certain maximum number of
4162 constructors imposed by the update mechanism
4163 (\secref{data-updates}).
4164
4165 Single-constructor data types also use direct returns, although in
4166 that case there is no need to return a tag in \Arg{2}.
4167
4168 \ToDo{for a nullary constructor we needn't return a pointer to the
4169 constructor in \Arg{1}.}
4170
4171 \Subsection{Updates}{data-updates}
4172
4173 The entry code for an updatable thunk (which must be of arity 0):
4174
4175 \begin{itemize}
4176 \item copies the free variables out of the thunk into registers or
4177   onto the stack.
4178 \item pushes an \emph{update frame} onto the stack.
4179
4180 An update frame is a small activation record consisting of
4181 \begin{center}
4182 \begin{tabular}{|l|l|l|}
4183 \hline
4184 \emph{Fixed header} & \emph{Update Frame link} & \emph{Updatee} \\
4185 \hline
4186 \end{tabular}
4187 \end{center}
4188
4189 \note{In the semantics part of the STG paper (section 5.6), an update
4190 frame consists of everything down to the last update frame on the
4191 stack.  This would make sense too --- and would fit in nicely with
4192 what we're going to do when we add support for speculative
4193 evaluation.}
4194 \ToDo{I think update frames contain cost centres sometimes}
4195
4196 \item If we are doing ``eager blackholing,'' we then overwrite the
4197 thunk with a black hole (\secref{BLACKHOLE}).  Otherwise, we leave it
4198 to the garbage collector to black hole the thunk.
4199
4200 \item 
4201 Start evaluating the body of the expression.
4202
4203 \end{itemize}
4204
4205 When the expression finishes evaluation, it will enter the update
4206 frame on the top of the stack.  Since the returner doesn't know
4207 whether it is entering a normal return address/vector or an update
4208 frame, we follow exactly the same conventions as return addresses and
4209 return vectors.  That is, on entering the update frame:
4210
4211 \begin{itemize} 
4212 \item The value of the thunk is in \Arg{1}.  (Recall that only thunks
4213 are updateable and that thunks return just one value.)
4214
4215 \item If the data type is a direct-return type rather than a
4216 vectored-return type, then the tag is in \Arg{2}.
4217
4218 \item The update frame is still on the stack.
4219 \end{itemize}
4220
4221 We can safely share a single statically-compiled update function
4222 between all types.  However, the code must be able to handle both
4223 vectored and direct-return datatypes.  This is done by arranging that
4224 the update code looks like this:
4225
4226 @
4227                 |       ^       |
4228                 | return vector |
4229                 |---------------|
4230                 |  fixed-size   |
4231                 |  info table   |
4232                 |---------------|  <- update code pointer
4233                 |  update code  |
4234                 |       v       |
4235 @
4236
4237 Each entry in the return vector (which is large enough to cover the
4238 largest vectored-return type) points to the update code.
4239
4240 The update code:
4241 \begin{itemize}
4242 \item overwrites the \emph{updatee} with an indirection to \Arg{1};
4243 \item loads @Su@ from the Update Frame link;
4244 \item removes the update frame from the stack; and 
4245 \item enters \Arg{1}.
4246 \end{itemize}
4247
4248 We enter \Arg{1} again, having probably just come from there, because
4249 it knows whether to perform a direct or vectored return.  This could
4250 be optimised by compiling special update code for each slot in the
4251 return vector, which performs the correct return.
4252
4253 \Subsection{Semi-tagging}{semi-tagging}
4254
4255 When a @case@ expression evaluates a variable that might be bound
4256 to a thunk it is often the case that the scrutinee is already evaluated.
4257 In this case we have paid the penalty of (a) pushing the return address (or
4258 return vector address) on the stack, (b) jumping through the info pointer
4259 of the scrutinee, and (c) returning by an indirect jump through the
4260 return address on the stack.
4261
4262 If we knew that the scrutinee was already evaluated we could generate
4263 (better) code which simply jumps to the appropriate branch of the
4264 @case@ with a pointer to the scrutinee in \Arg{1}.  (For direct
4265 returns to multiconstructor datatypes, we might also load the tag into
4266 \Arg{2}).
4267
4268 An obvious idea, therefore, is to test dynamically whether the heap
4269 closure is a value (using the tag in the info table).  If not, we
4270 enter the closure as usual; if so, we jump straight to the appropriate
4271 alternative.  Here, for example, is pseudo-code for the expression
4272 @(case x of { (a,_,c) -> E }@:
4273 @
4274       \Arg{1} = <pointer to x>;
4275       tag = \Arg{1}->entry->tag;
4276       if (isWHNF(tag)) {
4277           Sp--;  \\ insert space for return address
4278           goto ret;
4279       }
4280       push(ret);           
4281       goto \Arg{1}->entry;
4282       
4283       <info table for return address goes here>
4284 ret:  a = \Arg{1}->data1; \\ suck out a and c to avoid space leak
4285       c = \Arg{1}->data3;
4286       <code for E2>
4287 @
4288 and here is the code for the expression @(case x of { [] -> E1; x:xs -> E2 }@:
4289 @
4290       \Arg{1} = <pointer to x>;
4291       tag = \Arg{1}->entry->tag;
4292       if (isWHNF(tag)) {
4293           Sp--;  \\ insert space for return address
4294           goto retvec[tag];
4295       }
4296       push(retinfo);          
4297       goto \Arg{1}->entry;
4298       
4299       .addr ret2
4300       .addr ret1
4301 retvec:           \\ reversed return vector
4302       <return info table for case goes here>
4303 retinfo:
4304       panic("Direct return into vectored case");
4305       
4306 ret1: <code for E1>
4307
4308 ret2: x  = \Arg{1}->head;
4309       xs = \Arg{1}->tail;
4310       <code for E2>
4311 @
4312 There is an obvious cost in compiled code size (but none in the size
4313 of the bytecodes).  There is also a cost in execution time if we enter
4314 more thunks than data constructors.
4315
4316 Both the direct and vectored returns are easily modified to chase chains
4317 of indirections too.  In the vectored case, this is most easily done by
4318 making sure that @IND = TAG_1 - 1@, and adding an extra field to every
4319 return vector.  In the above example, the indirection code would be
4320 @
4321 ind:  \Arg{1} = \Arg{1}->next;
4322       goto ind_loop;
4323 @
4324 where @ind_loop@ is the second line of code.
4325
4326 Note that we have to leave space for a return address since the return
4327 address expects to find one.  If the body of the expression requires a
4328 heap check, we will actually have to write the return address before
4329 entering the garbage collector.
4330
4331
4332 \Subsection{Heap and Stack Checks}{heap-and-stack-checks}
4333
4334 The storage manager detects that it needs to garbage collect the old
4335 generation when the evaluator requests a garbage collection without
4336 having moved the heap pointer since the last garbage collection.  It
4337 is therefore important that the GC routines \emph{not} move the heap
4338 pointer unless the heap check fails.  This is different from what
4339 happens in the current STG implementation.
4340
4341 Assuming that the stack can never shrink, we perform a stack check
4342 when we enter a closure but not when we return to a return
4343 continuation.  This doesn't work for heap checks because we cannot
4344 predict what will happen to the heap if we call a function.
4345
4346 If we wish to allow the stack to shrink, we need to perform a stack
4347 check whenever we enter a return continuation.  Most of these checks
4348 could be eliminated if the storage manager guaranteed that a stack
4349 would always have 1000 words (say) of space after it was shrunk.  Then
4350 we can omit stack checks for less than 1000 words in return
4351 continuations.
4352
4353 When an argument satisfaction check fails, we need to push the closure
4354 (in R1) onto the stack - so we need to perform a stack check.  The
4355 problem is that the argument satisfaction check occurs \emph{before}
4356 the stack check.  The solution is that the caller of a slow entry
4357 point or closure will guarantee that there is at least one word free
4358 on the stack for the callee to use.  
4359
4360 Similarily, if a heap or stack check fails, we need to push the arguments
4361 and closure onto the stack.  If we just came from the slow entry point, 
4362 there's certainly enough space and it is the responsibility of anyone
4363 using the fast entry point to guarantee that there is enough space.
4364
4365 \ToDo{Be more precise about how much space is required - document it
4366 in the calling convention section.}
4367
4368 \Subsection{Handling interrupts/signals}{signals}
4369
4370 @
4371 May have to keep C stack pointer in register to placate OS?
4372 May have to revert black holes - ouch!
4373 @
4374
4375
4376
4377 \section{The Loader}
4378 \section{The Compilers}
4379
4380 \iffalse
4381 \part{Old stuff - needs to be mined for useful info}
4382
4383 \section{The Scheduler}
4384
4385 The Scheduler is the heart of the run-time system.  A running program
4386 consists of a single running thread, and a list of runnable and
4387 blocked threads.  The running thread returns to the scheduler when any
4388 of the following conditions arises:
4389
4390 \begin{itemize}
4391 \item A heap check fails, and a garbage collection is required
4392 \item Compiled code needs to switch to interpreted code, and vice
4393 versa.
4394 \item The thread becomes blocked.
4395 \item The thread is preempted.
4396 \end{itemize}
4397
4398 A running system has a global state, consisting of
4399
4400 \begin{itemize}
4401 \item @Hp@, the current heap pointer, which points to the next
4402 available address in the Heap.
4403 \item @HpLim@, the heap limit pointer, which points to the end of the
4404 heap.
4405 \item The Thread Preemption Flag, which is set whenever the currently
4406 running thread should be preempted at the next opportunity.
4407 \item A list of runnable threads. 
4408 \item A list of blocked threads.
4409 \end{itemize}
4410
4411 Each thread is represented by a Thread State Object (TSO), which is
4412 described in detail in \secref{TSO}.
4413
4414 The following is pseudo-code for the inner loop of the scheduler
4415 itself.
4416
4417 @
4418 while (threads_exist) {
4419   // handle global problems: GC, parallelism, etc
4420   if (need_gc) gc();  
4421   if (external_message) service_message();
4422   // deal with other urgent stuff
4423
4424   pick a runnable thread;
4425   do {
4426     // enter object on top of stack
4427     // if the top object is a BCO, we must enter it
4428     // otherwise appply any heuristic we wish.
4429     if (thread->stack[thread->sp]->info.type == BCO) {
4430         status = runHugs(thread,&smInfo);
4431     } else {
4432         status = runGHC(thread,&smInfo);
4433     }
4434     switch (status) {  // handle local problems
4435       case (StackOverflow): enlargeStack; break;
4436       case (Error e)      : error(thread,e); break;
4437       case (ExitWith e)   : exit(e); break;
4438       case (Yield)        : break;
4439     }
4440   } while (thread_runnable);
4441 }
4442 @
4443
4444 \Subsection{Invoking the garbage collector}{ghc-invoking-gc}
4445
4446 \Subsection{Putting the thread to sleep}{ghc-thread-sleeps}
4447
4448 \Subsection{Calling C from Haskell}{ghc-ccall}
4449
4450 We distinguish between "safe calls" where the programmer guarantees
4451 that the C function will not call a Haskell function or, in a
4452 multithreaded system, block for a long period of time and "unsafe
4453 calls" where the programmer cannot make that guarantee.  
4454
4455 Safe calls are performed without returning to the scheduler and are
4456 discussed elsewhere (\ToDo{discuss elsewhere}).
4457
4458 Unsafe calls are performed by returning an array (outside the Haskell
4459 heap) of arguments and a C function pointer to the scheduler.  The
4460 scheduler allocates a new thread from the operating system
4461 (multithreaded system only), spawns a call to the function and
4462 continues executing another thread.  When the ccall completes, the
4463 thread informs the scheduler and the scheduler adds the thread to the
4464 runnable threads list.  
4465
4466 \ToDo{Describe this in more detail.}
4467
4468
4469 \Subsection{Calling Haskell from C}{ghc-c-calls-haskell}
4470
4471 When C calls a Haskell closure, it sends a message to the scheduler
4472 thread.  On receiving the message, the scheduler creates a new Haskell
4473 thread, pushes the arguments to the C function onto the thread's stack
4474 (with tags for unboxed arguments) pushes the Haskell closure and adds
4475 the thread to the runnable list so that it can be entered in the
4476 normal way.
4477
4478 When the closure returns, the scheduler sends back a message which
4479 awakens the (C) thread.  
4480
4481 \ToDo{Do we need to worry about the garbage collector deallocating the
4482 thread if it gets blocked?}
4483
4484 \Subsection{Switching Worlds}{switching-worlds}
4485
4486 \ToDo{This has all changed: we always leave a closure on top of the
4487 stack if we mean to continue executing it.  The scheduler examines the
4488 top of the stack and tries to guess which world we want to be in.  If
4489 it finds a @BCO@, it certainly enters Hugs, if it finds a @GHC@
4490 closure, it certainly enters GHC and if it finds a standard closure,
4491 it is free to choose either one but it's probably best to enter GHC
4492 for everything except @BCO@s and perhaps @AP@s.}
4493
4494 Because this is a combined compiled/interpreted system, the
4495 interpreter will sometimes encounter compiled code, and vice-versa.
4496
4497 All world-switches go via the scheduler, ensuring that the world is in
4498 a known state ready to enter either compiled code or the interpreter.
4499 When a thread is run from the scheduler, the @whatNext@ field in the
4500 TSO (\secref{TSO}) is checked to find out how to execute the
4501 thread.
4502
4503 \begin{itemize}
4504 \item If @whatNext@ is set to @ReturnGHC@, we load up the required
4505 registers from the TSO and jump to the address at the top of the user
4506 stack.
4507 \item If @whatNext@ is set to @EnterGHC@, we load up the required
4508 registers from the TSO and enter the closure pointed to by the top
4509 word of the stack.
4510 \item If @whatNext@ is set to @EnterHugs@, we enter the top thing on
4511 the stack, using the interpreter.
4512 \end{itemize}
4513
4514 There are four cases we need to consider:
4515
4516 \begin{enumerate}
4517 \item A GHC thread enters a Hugs-built closure.
4518 \item A GHC thread returns to a Hugs-compiled return address.
4519 \item A Hugs thread enters a GHC-built closure.
4520 \item A Hugs thread returns to a Hugs-compiled return address.
4521 \end{enumerate}
4522
4523 GHC-compiled modules cannot call functions in a Hugs-compiled module
4524 directly, because the compiler has no information about arities in the
4525 external module.  Therefore it must assume any top-level objects are
4526 CAFs, and enter their closures.
4527
4528 \ToDo{Hugs-built constructors?}
4529
4530 We now examine the various cases one by one and describe how the
4531 switch happens in each situation.
4532
4533 \subsection{A GHC thread enters a Hugs-built closure}
4534 \label{sec:ghc-to-hugs-switch}
4535
4536 There is three possibilities: GHC has entered a @PAP@, or it has
4537 entered a @AP@, or it has entered the BCO directly (for a top-level
4538 function closure).  @AP@s and @PAP@s are ``standard closures'' and
4539 so do not require us to enter the bytecode interpreter.
4540
4541 The entry code for a BCO does the following:
4542
4543 \begin{itemize}
4544 \item Push the address of the object entered on the stack.
4545 \item Save the current state of the thread in its TSO.
4546 \item Return to the scheduler, setting @whatNext@ to @EnterHugs@.
4547 \end{itemize}
4548
4549 BCO's for thunks and functions have the same entry conventions as
4550 slow entry points: they expect to find their arguments on the stac
4551 with unboxed arguments preceded by appropriate tags.
4552
4553 \subsection{A GHC thread returns to a Hugs-compiled return address}
4554 \label{sec:ghc-to-hugs-switch}
4555
4556 Hugs return addresses are laid out as in \figref{hugs-return-stack}.
4557 If GHC is returning, it will return to the address at the top of the
4558 stack, namely @HUGS_RET@.  The code at @HUGS_RET@ performs the
4559 following:
4560
4561 \begin{itemize}
4562 \item pushes \Arg{1} (the return value) on the stack.
4563 \item saves the thread state in the TSO
4564 \item returns to the scheduler with @whatNext@ set to @EnterHugs@.
4565 \end{itemize}
4566
4567 \noindent When Hugs runs, it will enter the return value, which will
4568 return using the correct Hugs convention
4569 (\secref{hugs-return-convention}) to the return address underneath it
4570 on the stack.
4571
4572 \subsection{A Hugs thread enters a GHC-compiled closure}
4573 \label{sec:hugs-to-ghc-switch}
4574
4575 Hugs can recognise a GHC-built closure as not being one of the
4576 following types of object:
4577
4578 \begin{itemize}
4579 \item A @BCO@,
4580 \item A @AP@,
4581 \item A @PAP@,
4582 \item An indirection, or
4583 \item A constructor.
4584 \end{itemize}
4585
4586 When Hugs is called on to enter a GHC closure, it executes the
4587 following sequence of instructions:
4588
4589 \begin{itemize}
4590 \item Push the address of the closure on the stack.
4591 \item Save the current state of the thread in the TSO.
4592 \item Return to the scheduler, with the @whatNext@ field set to
4593 @EnterGHC@.
4594 \end{itemize}
4595
4596 \subsection{A Hugs thread returns to a GHC-compiled return address}
4597 \label{sec:hugs-to-ghc-switch}
4598
4599 When Hugs encounters a return address on the stack that is not
4600 @HUGS_RET@, it knows that a world-switch is required.  At this point
4601 the stack contains a pointer to the return value, followed by the GHC
4602 return address.  The following sequence is then performed:
4603
4604 \begin{itemize}
4605 \item save the state of the thread in the TSO.
4606 \item return to the scheduler, setting @whatNext@ to @EnterGHC@.
4607 \end{itemize}
4608
4609 The first thing that GHC will do is enter the object on the top of the
4610 stack, which is a pointer to the return value.  This value will then
4611 return itself to the return address using the GHC return convention.
4612
4613
4614 \fi
4615
4616
4617 \part{History}
4618
4619 We're nuking the following:
4620
4621 \begin{itemize}
4622 \item
4623   Two stacks
4624
4625 \item
4626   Return in registers.
4627   This lets us remove update code pointers from info tables,
4628   removes the need for phantom info tables, simplifies 
4629   semi-tagging, etc.
4630
4631 \item
4632   Threaded GC.
4633   Careful analysis suggests that it doesn't buy us very much
4634   and it is hard to work with.
4635
4636   Eliminating threaded GCs eliminates the desire to share SMReps
4637   so they are (once more) part of the Info table.
4638
4639 \item
4640   RetReg.
4641   Doesn't buy us anything on a register-poor architecture and
4642   isn't so important if we have semi-tagging.
4643
4644 @
4645     - Probably bad on register poor architecture 
4646     - Can avoid need to write return address to stack on reg rich arch.
4647       - when a function does a small amount of work, doesn't 
4648         enter any other thunks and then returns.
4649         eg entering a known constructor (but semitagging will catch this)
4650     - Adds complications
4651 @
4652
4653 \item
4654   Update in place
4655
4656   This lets us drop CONST closures and CHARLIKE closures (assuming we
4657   don't support Unicode).  The only point of these closures was to 
4658   avoid updating with an indirection.
4659
4660   We also drop @MIN_UPD_SIZE@ --- all we need is space to insert an
4661   indirection or a black hole.
4662
4663 \item
4664   STATIC SMReps are now called CONST
4665
4666 \item
4667   @MUTVAR@ is new
4668
4669 \item The profiling ``kind'' field is now encoded in the @INFO_TYPE@ field.
4670 This identifies the general sort of the closure for profiling purposes.
4671
4672 \item Various papers describe deleting update frames for unreachable objects.
4673   This has never been implemented and we don't plan to anytime soon.
4674
4675 \end{itemize}
4676
4677
4678 \end{document}
4679
4680