|
|
|
c This is part of the GNU Guile Reference Manual. |
|
|
|
c Free Software Foundation, Inc. |
|
|
|
|
|
node Compiling to the Virtual Machine |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
xref{Read/Load/Eval/Compile}, if you're lost and you just wanted to |
|
know how to compile your |
|
|
|
menu |
|
* Compiler Tower:: |
|
* The Scheme Compiler:: |
|
* Tree-IL:: |
|
* Continuation-Passing Style:: |
|
* Bytecode:: |
|
* Writing New High-Level Languages:: |
|
* Extending the Compiler:: |
|
|
|
|
|
node Compiler Tower |
|
|
|
|
|
emph{compilers}, to put it more |
|
accurately. Guile defines a tower of languages, starting at Scheme and |
|
progressively simplifying down to languages that resemble the VM |
|
instruction set ( |
|
|
|
|
|
|
|
|
|
|
|
|
|
code{(system base language)}: |
|
|
|
|
|
|
|
end example |
|
|
|
They are registered with the |
|
|
|
deffn {Scheme Syntax} define-language |
|
|
|
[#:parser=#f] [#:compilers='()] |
|
|
|
[#:joiner=#f] [#:for-humans?=#t] |
|
|
|
[#:lowerer=#f] [#:analyzer=#f] [#:compiler-chooser=#f] |
|
Define a language. |
|
|
|
This syntax defines a var{name} in |
|
the current environment. In addition, the language will be added to the |
|
global language set. For example, this is the language definition for |
|
Scheme: |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
end example |
|
|
|
|
|
|
|
|
|
|
|
|
|
example |
|
scheme(guile-user)> ,language tree-il |
|
Happy hacking with Tree Intermediate Language! To switch back, type `,L scheme'. |
|
tree-il(guile-user)> ,L scheme |
|
Happy hacking with Scheme! To switch back, type `,L tree-il'. |
|
scheme(guile-user)> |
|
|
|
|
|
|
|
|
|
deffn {Scheme Procedure} lookup-language name |
|
Looks up a language named |
|
|
|
var{name} in |
|
a module named var{name} spec)}. |
|
|
|
The language object will be returned, or |
|
|
|
end deffn |
|
|
|
When Guile goes to compile Scheme to bytecode, it will ask the Scheme |
|
language to choose a compiler from Scheme to the next language on the |
|
path from Scheme to bytecode. Performing this computation recursively |
|
builds transformations from a flexible chain of compilers. The next |
|
link will be obtained by invoking the language's compiler chooser, or if |
|
not present, from the language's compilers field. |
|
|
|
A language can specify an analyzer, which is run before a term of that |
|
language is lowered and compiled. This is where compiler warnings are |
|
issued. |
|
|
|
If a language specifies a lowerer, that procedure is called on |
|
expressions before compilation. This is where optimizations and |
|
canonicalizations go. |
|
|
|
Finally a language's compiler translates a lowered term from one |
|
language to the next one in the chain. |
|
|
|
There is a notion of a ``current language'', which is maintained in the |
|
code{(guile)} |
|
module. This language is normally Scheme, and may be rebound by the |
|
user. The run-time compilation interfaces |
|
( |
|
|
|
|
|
|
|
|
|
itemize |
|
|
|
item Tree Intermediate Language (Tree-IL) |
|
|
|
item Bytecode |
|
|
|
|
|
pxref{Object File Format}), bytecode is in ELF |
|
format, ready to be serialized to disk. But when compiling Scheme at |
|
run time, you want a Scheme value: for example, a compiled procedure. |
|
For this reason, so as not to break the abstraction, Guile defines a |
|
fake language at the bottom of the tower: |
|
|
|
|
|
item Value |
|
|
|
|
|
code{value} loads the bytecode into a procedure, turning |
|
cold bytes into warm code. |
|
|
|
Perhaps this strangeness can be explained by example: |
|
|
|
|
|
code{compile} defaults to compiling to |
|
|
|
|
|
c FIXME: This doesn't work anymore :( Should we add some kind of |
|
|
|
|
|
|
|
|
|
|
|
example |
|
((lambda (x) ((compile x) x)) '(lambda (x) ((compile x) x))) |
|
|
|
|
|
node The Scheme Compiler |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
code{compile} procedure: |
|
|
|
|
|
|
|
result{} |
|
#<tree-il (call (toplevel +) (const 1) (const 2))> |
|
|
|
|
|
code{(compile |
|
code{(macroexpand |
|
xref{Macro Expansion}. |
|
code{compile} to |
|
code{macroexpand}, to make |
|
it conform to the general form of compiler procedures in Guile's |
|
language tower. |
|
|
|
Compiler procedures take three arguments: an expression, an |
|
environment, and a keyword list of options. They return three values: |
|
the compiled expression, the corresponding environment for the target |
|
language, and a ``continuation environment''. The compiled expression |
|
and environment will serve as input to the next language's compiler. |
|
The ``continuation environment'' can be used to compile another |
|
expression from the same source language within the same module. |
|
|
|
For example, you might compile the expression, |
|
|
|
|
|
|
|
code{(foo)} module. That is the purpose of the |
|
``continuation environment''; you would pass it as the environment when |
|
compiling the subsequent expression. |
|
|
|
For Scheme, an environment is a module. By default, the |
|
code{compile-file} procedures compile in a fresh module, such |
|
that bindings and macros introduced by the expression being compiled |
|
are isolated: |
|
|
|
|
|
|
|
result{} #f |
|
|
|
(compile '(define hello 'world)) |
|
(defined? 'hello) |
|
|
|
|
|
|
|
|
|
result{} #f |
|
|
|
|
|
code{current-reader} fluid ( |
|
code{current-reader}}) are isolated: |
|
|
|
|
|
|
|
|
|
result{} #f |
|
|
|
|
|
dfn{compilee} share the same name |
|
space can be achieved by explicitly passing |
|
|
|
|
|
example |
|
(define hello 'world) |
|
(compile 'hello #:env (current-module)) |
|
|
|
end example |
|
|
|
|
|
subsection Tree-IL |
|
|
|
Tree Intermediate Language (Tree-IL) is a structured intermediate |
|
language that is close in expressive power to Scheme. It is an |
|
expanded, pre-analyzed Scheme. |
|
|
|
Tree-IL is ``structured'' in the sense that its representation is |
|
based on records, not S-expressions. This gives a rigidity to the |
|
language that ensures that compiling to a lower-level language only |
|
requires a limited set of transformations. For example, the Tree-IL |
|
type code{src} and |
|
code{make-const}. |
|
Fields of this type are accessed via the |
|
code{const-exp} procedures. There is also a predicate, |
|
xref{Records}, for more information on records. |
|
|
|
|
|
|
|
code{src} slot, which holds source location |
|
information for the expression. This information, if present, will be |
|
residualized into the compiled object code, allowing backtraces to |
|
show source information. The format of |
|
code{source-properties} function. |
|
|
|
|
|
|
|
|
|
|
|
code{#<const src: #f exp: 3>} expression would be: |
|
|
|
|
|
|
|
end example |
|
|
|
Users may program with this format directly at the REPL: |
|
|
|
|
|
|
|
|
|
|
|
result{} 42 |
|
|
|
|
|
code{src} fields are left out of the external representation. |
|
|
|
One may create Tree-IL objects from their external representations via |
|
calling |
|
|
|
|
|
|
|
code{parse-tree-il} |
|
take care of the rest. |
|
|
|
|
|
deftpx {External Representation} (void) |
|
An empty expression. In practice, equivalent to Scheme's |
|
|
|
end deftp |
|
|
|
|
|
deftpx {External Representation} (const |
|
|
|
end deftp |
|
|
|
|
|
deftpx {External Representation} (primitive |
|
|
|
code{cons} is usually |
|
recognized as a primitive, so that it compiles down to a single |
|
instruction. |
|
|
|
Compilation of Tree-IL usually begins with a pass that resolves some |
|
code{<toplevel-ref>} expressions to |
|
|
|
code{apply} or |
|
|
|
end deftp |
|
|
|
|
|
deftpx {External Representation} (lexical var{gensym}) |
|
A reference to a lexically-bound variable. The |
|
var{gensym} is a |
|
unique identifier for this variable. |
|
|
|
|
|
deftp {Scheme Variable} <lexical-set> src name gensym exp |
|
var{name} var{exp}) |
|
Sets a lexically-bound variable. |
|
|
|
|
|
deftp {Scheme Variable} <module-ref> src mod name public? |
|
var{mod} |
|
deftpx {External Representation} ( var{name}) |
|
A reference to a variable in a specific module. |
|
: |
|
|
|
var{public?} is true, the variable named |
|
var{mod}'s public interface, and serialized with |
|
|
|
code{}. |
|
|
|
|
|
deftp {Scheme Variable} <module-set> src mod name public? exp |
|
var{mod} var{exp}) |
|
var{mod} var{exp}) |
|
Sets a variable in a specific module. |
|
|
|
|
|
deftp {Scheme Variable} <toplevel-ref> src name |
|
var{name}) |
|
References a variable from the current procedure's module. |
|
|
|
|
|
deftp {Scheme Variable} <toplevel-set> src name exp |
|
var{name}) |
|
|
|
end deftp |
|
|
|
|
|
deftpx {External Representation} (define var{exp}) |
|
Defines a new top-level variable in the current procedure's module. |
|
|
|
|
|
deftp {Scheme Variable} <conditional> src test then else |
|
var{test} var{else}) |
|
A conditional. Note that |
|
end deftp |
|
|
|
|
|
deftpx {External Representation} (call var{args}) |
|
A procedure call. |
|
|
|
|
|
deftp {Scheme Variable} <primcall> src name args |
|
var{name} . |
|
code{(call (primitive |
|
var{args})}. This construct is often more convenient to generate and |
|
analyze than |
|
|
|
code{(call (primitive |
|
var{args})} are transformed into primcalls. |
|
|
|
|
|
deftp {Scheme Variable} <seq> src head tail |
|
var{head} |
|
var{head} is evaluated first, and |
|
any resulting values are ignored. Then |
|
|
|
end deftp |
|
|
|
|
|
deftpx {External Representation} (lambda var{body}) |
|
A closure. |
|
var{body} is a single Tree-IL expression of type |
|
code{<lambda-case>} clause can chain to |
|
an alternate clause, this makes Tree-IL's |
|
code{case-lambda}. |
|
|
|
|
|
deftp {Scheme Variable} <lambda-case> req opt rest kw inits gensyms body alternate |
|
|
|
(lambda-case ((var{opt} var{kw} var{gensyms}) |
|
var{body}) |
|
var{alternate}]) |
|
One clause of a code{lambda} expression in |
|
Scheme is treated as a |
|
|
|
var{req} is a list of the procedure's required arguments, as symbols. |
|
code{#f} if there |
|
are no optional arguments. |
|
code{#f}. |
|
|
|
code{( |
|
var{keyword} var{var}) ...)}, where |
|
var{name}, and whose |
|
corresponding gensym is code{#f} if there are no keyword |
|
arguments. |
|
|
|
var{init} |
|
expression is evaluated in the lexical context of previously bound |
|
variables, from left to right. |
|
|
|
|
|
|
|
|
|
|
|
var{body} is the body of the clause. If the procedure is called with |
|
an appropriate number of arguments, |
|
var{alternate}, it should be a |
|
|
|
var{alternate}, a wrong-number-of-arguments error is |
|
signaled. |
|
|
|
|
|
deftp {Scheme Variable} <let> src names gensyms vals exp |
|
var{names} var{vals} |
|
code{let}. |
|
var{gensyms} are gensyms corresponding to the |
|
var{vals} are Tree-IL expressions for the values. |
|
|
|
end deftp |
|
|
|
|
|
deftpx {External Representation} (letrec var{gensyms} var{exp}) |
|
var{names} var{vals} |
|
code{<let>} that creates recursive bindings, like |
|
Scheme's code{letrec*} if |
|
end deftp |
|
|
|
|
|
deftpx {External Representation} (prompt var{tag} var{handler}) |
|
A dynamic prompt. Instates a prompt named |
|
var{body}, also an |
|
expression. If an abort occurs to this prompt, control will be passed |
|
to |
|
|
|
|
|
var{escape-only?} is true, the handler should be a |
|
code{<lambda-case>} body expression with no optional or |
|
keyword arguments, and no alternate, and whose first argument is |
|
unreferenced. |
|
end deftp |
|
|
|
|
|
deftpx {External Representation} (abort var{args} |
|
var{tag}, an expression. |
|
|
|
var{tail} should be an expression that will evaluate to |
|
a list of additional arguments. An abort will save the partial |
|
continuation, which may later be reinstated, resulting in the |
|
|
|
end deftp |
|
|
|
There are two Tree-IL constructs that are not normally produced by |
|
higher-level compilers, but instead are generated during the |
|
source-to-source optimization and analysis passes that the Tree-IL |
|
compiler does. Users should not generate these expressions directly, |
|
unless they feel very clever, as the default analysis pass will generate |
|
them as necessary. |
|
|
|
|
|
deftpx {External Representation} (let-values var{gensyms} var{body}) |
|
Like Scheme's |
|
code{exp} to the |
|
var{gensyms}. That is to say, |
|
|
|
code{<let-values>} is an optimization of a |
|
code{call-with-values}. |
|
|
|
|
|
deftp {Scheme Variable} <fix> src names gensyms vals body |
|
var{names} var{vals} |
|
code{<letrec>}, but only for |
|
code{lambda} expressions. |
|
|
|
code{letrec} (and |
|
end deftp |
|
|
|
Tree-IL is a convenient compilation target from source languages. It |
|
can be convenient as a medium for optimization, though CPS is usually |
|
better. The strength of Tree-IL is that it does not fix order of |
|
evaluation, so it makes some code motion a bit easier. |
|
|
|
Optimization passes performed on Tree-IL currently include: |
|
|
|
|
|
item Open-coding (turning toplevel-refs into primitive-refs, |
|
and calls to primitives to primcalls) |
|
|
|
|
|
end itemize |
|
|
|
|
|
subsection Continuation-Passing Style |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
menu |
|
* An Introduction to CPS:: |
|
* CPS in Guile:: |
|
* Building CPS:: |
|
* CPS Soup:: |
|
* Compiling CPS:: |
|
|
|
|
|
node An Introduction to CPS |
|
|
|
|
|
|
|
|
|
lisp |
|
(begin |
|
(display "The sum of 32 and 10 is: ") |
|
(display 42) |
|
(newline)) |
|
|
|
|
|
|
|
|
|
|
|
lisp |
|
(begin |
|
(display "The sum of 32 and 10 is: ") |
|
|k1 k2 |
|
k0 |
|
(display 42) |
|
|k4 k5 |
|
k3 |
|
(newline)) |
|
|k7 |
|
k6 |
|
|
|
|
|
|
|
|
|
code{k7} is |
|
code{newline}, performed by the expression labelled |
|
code{k6}. |
|
|
|
Which expression has |
|
code{k1} or the expression labelled |
|
|
|
|
|
|
|
|
|
|
|
|
|
code{k1} is |
|
code{k2} is |
|
|
|
|
|
|
|
|
|
smalllisp |
|
(lambda (ktail) |
|
(let ((k1 (lambda () |
|
(let ((k2 (lambda (proc) |
|
(let ((k0 (lambda (arg0) |
|
(proc k4 arg0)))) |
|
(k0 "The sum of 32 and 10 is: "))))) |
|
(k2 display)))) |
|
(k4 (lambda _ |
|
(let ((k5 (lambda (proc) |
|
(let ((k3 (lambda (arg0) |
|
(proc k7 arg0)))) |
|
(k3 42))))) |
|
(k5 display)))) |
|
(k7 (lambda _ |
|
(let ((k6 (lambda (proc) |
|
(proc ktail)))) |
|
(k6 newline))))) |
|
(k1)) |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
code{k0} is in effect |
|
context. Any values it returns are ignored. In Scheme, this fact is |
|
implicit. In CPS, we can see it explicitly by noting that its |
|
continuation, |
|
code{k2}, which takes a single value; in this way we |
|
can say that code{k6} is |
|
in tail context with respect to the expression as a whole, because its |
|
continuation is the tail continuation, |
|
|
|
|
|
node CPS in Guile |
|
|
|
|
|
cindex continuation, CPS |
|
Guile's CPS language is composed of |
|
|
|
|
|
|
|
|
|
|
|
cindex term, CPS |
|
|
|
|
|
|
|
|
|
dfn{term}. A term contains an |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
code{match} form from |
|
|
|
|
|
smallexample |
|
(match cont |
|
(($ $kargs (x-name y-name) (x-var y-var) |
|
($ $continue k src ($ $primcall '+ #f (x-var y-var)))) |
|
(format #t "Add ~a and ~a and pass the result to label ~a" |
|
x-var y-var k))) |
|
|
|
|
|
code{$kargs}, which |
|
binds some number of values to variables and then evaluates a term. |
|
|
|
|
|
var{vars}, with original |
|
names var{term}. |
|
|
|
|
|
var{names} of a |
|
|
|
|
|
var{term} in a code{$continue}, which |
|
evaluates an expression and continues to a continuation. |
|
|
|
|
|
var{exp} and pass the resulting values (if any) |
|
to the continuation labelled |
|
var{src}, which is either an alist |
|
as in code{#f} if there is no associated |
|
source. |
|
|
|
|
|
|
|
code{$primcall}. |
|
|
|
|
|
code{name}, a well-known |
|
symbol, passing it the arguments |
|
|
|
|
|
var{param} is a constant parameter whose interpretation is up to the |
|
primcall in question. Usually it's |
|
|
|
code{add/immediate}, which adds a constant number to a value -- the |
|
parameter holds this information. |
|
|
|
The set of available primitives includes many primitives known to |
|
Tree-IL and then some more; see the source code for details. Note that |
|
some Tree-IL primcalls need to be converted to a sequence of lower-level |
|
CPS primcalls. Again, see |
|
|
|
end deftp |
|
|
|
|
|
code{$primcall}, or indeed by any |
|
expression, must be defined before the expression is evaluated. An |
|
equivalent way of saying this is that predecessor |
|
|
|
dfn{dominate} the continuation that uses the expression: definitions |
|
dominate uses. This condition is trivially satisfied in our example |
|
above, but in general to determine the set of variables that are in |
|
``scope'' for a given term, you need to do a flow analysis to see what |
|
continuations dominate a term. The variables that are in scope are |
|
those variables defined by the continuations that dominate a term. |
|
|
|
Here is an inventory of the kinds of expressions in Guile's CPS |
|
language, besides |
|
code{$continue} term which |
|
specifies their continuation. |
|
|
|
|
|
var{val}. |
|
|
|
|
|
deftp {CPS Expression} $prim name |
|
Continue with the procedure that implements the primitive operation |
|
named by |
|
end deftp |
|
|
|
|
|
var{proc} with the arguments |
|
var{proc} and the elements of the |
|
|
|
var{k} should be a code{$ktail} instance. |
|
|
|
|
|
deftp {CPS Expression} $values args |
|
Pass the values named by the list |
|
end deftp |
|
|
|
|
|
end deftp |
|
|
|
|
|
cindex CPS, higher-order |
|
|
|
cindex CPS, first-order |
|
There are two sub-languages of CPS, |
|
dfn{first-order CPS}. The difference is that in higher-order CPS, |
|
there are code{$rec} expressions that bind functions or |
|
mutually-recursive functions in the implicit scope of their use sites. |
|
Guile transforms higher-order CPS into first-order CPS by |
|
|
|
|
|
|
|
|
|
deftp {CPS Expression} $fun body |
|
Continue with a procedure. |
|
code{$kfun}. This expression kind is only |
|
valid in higher-order CPS, which is the CPS language before closure |
|
conversion. |
|
|
|
|
|
deftp {CPS Expression} $rec names vars funs |
|
Continue with a set of mutually recursive procedures denoted by |
|
var{vars}, and var{names} is a list of |
|
symbols, |
|
var{funs} is a list of code{$kargs} |
|
continuation should also define var{vars} bindings. |
|
|
|
|
|
|
|
code{$rec} into local continuations. Any remaining |
|
|
|
|
|
|
|
deftp {CPS Expression} $const-fun label |
|
A constant which is a function whose entry point is |
|
code{$const-fun} with the same |
|
|
|
|
|
|
|
code{$const-fun} expressions are reified by CPS-conversion |
|
for functions whose call sites are not all visible within the |
|
compilation unit and which have no free variables. This expression kind |
|
is part of first-order CPS. |
|
|
|
|
|
|
|
code{allocate-words} primcall and its free |
|
variables initialized there. The code pointer in the closure is |
|
initialized from a |
|
|
|
deftp {CPS Expression} $code label |
|
Continue with the value of |
|
code{$kfun} continuation in the program. Used when initializing the |
|
code pointer of closure objects. |
|
|
|
|
|
|
|
|
|
|
|
code{$call} to |
|
|
|
deftp {CPS Expression} $callk label proc args |
|
Like |
|
var{label} should denote some |
|
var{proc} |
|
is simply an additional argument, since it is not used to determine the |
|
call target at run-time. |
|
|
|
|
|
code{$continue} is a CPS term that continues to a |
|
single label. But there are other kinds of CPS terms that can continue |
|
to a different number of labels: code{$switch}, |
|
code{$prompt}. |
|
|
|
|
|
var{op}, with arguments |
|
var{param}, and continue to |
|
var{kf}. |
|
|
|
The code{$continue} term with a |
|
|
|
|
|
|
|
|
|
var{op} values) that are valid |
|
in a |
|
code{$branch} on a |
|
|
|
|
|
end deftp |
|
|
|
|
|
var{k*} according to the index argument |
|
var{kf} if |
|
var{k*}. The index variable |
|
|
|
|
|
code{$switch} term is like C's |
|
code{$switch} term directly, if the |
|
source language has such a concept, or it can rely on the CPS optimizer |
|
to turn appropriate chains of |
|
code{$switch} instances, which is what the Scheme compiler does. |
|
|
|
|
|
deftp {CPS Term} $throw src op param args |
|
Throw a non-resumable exception. Throw terms do not continue at all. |
|
The usual value of code{throw}, with two arguments |
|
var{args}. There are also some specific primcalls that |
|
compile to the VM code{throw/value+data} |
|
instructions; see the code for full details. |
|
|
|
The advantage of having |
|
|
|
code{char?} and the |
|
var{kt} |
|
is larger than if the throw notationally continued to some label that |
|
would never be reached by the throw. |
|
|
|
|
|
deftp {CPS Term} $prompt k kh src escape? tag |
|
Push a prompt on the stack identified by the variable name |
|
var{escape?} is true, and continue to |
|
|
|
var{kh}, which should be a |
|
|
|
code{pop-prompt} primcalls. |
|
|
|
|
|
|
|
code{$kargs}. |
|
|
|
code{$kargs} |
|
continuation var{v}, and the compiler decides |
|
to allocate var{k} should put |
|
the value for var{k}. One |
|
situation in which this isn't possible is receiving values from function |
|
calls. Guile has a calling convention for functions which currently |
|
places return values on the stack. A continuation of a call must check |
|
that the number of values returned from a function matches the expected |
|
number of values, and then must shuffle or collect those values to named |
|
variables. |
|
|
|
deftp {CPS Continuation} $kreceive arity k |
|
Receive values on the stack. Parse them according to |
|
code{$kargs} continuation |
|
labelled code{$kreceive}, |
|
|
|
end deftp |
|
|
|
code{$kreceive} and |
|
also by |
|
|
|
deftp {CPS Data} $arity req opt rest kw allow-other-keys? |
|
A data type declaring an arity. var{opt} are lists of |
|
source names of required and optional arguments, respectively. |
|
code{#f} |
|
if this arity does not accept additional values. |
|
code{((var{name} |
|
var{allow-other-keys?} is true if other keyword |
|
arguments are allowed and false otherwise. |
|
|
|
Note that all of these names with the exception of the |
|
var{kw} list are source names, not unique variable names. |
|
|
|
|
|
|
|
|
|
|
|
deftp {CPS Continuation} $kfun src meta self tail clause |
|
Declare a function entry. |
|
var{meta} is the metadata alist as described |
|
above in Tree-IL's var{self} is a variable bound to |
|
the procedure being called, and which may be used for self-references. |
|
code{$ktail} for this function, |
|
corresponding to the function's tail continuation. |
|
code{$kclause} for the first |
|
code{#f}. |
|
|
|
|
|
deftp {CPS Continuation} $ktail |
|
A tail continuation. |
|
|
|
|
|
deftp {CPS Continuation} $kclause arity cont alternate |
|
A clause of a function with a given arity. Applications of a function |
|
with a compatible set of actual arguments will continue to the |
|
continuation labelled code{$kargs} instance representing |
|
the clause body. If the arguments are incompatible, control proceeds to |
|
code{$kclause} for the next clause, or |
|
|
|
end deftp |
|
|
|
|
|
subsubsection Building CPS |
|
|
|
Unlike Tree-IL, the CPS language is built to be constructed and |
|
deconstructed with abstract macros instead of via procedural |
|
constructors or accessors, or instead of S-expression matching. |
|
|
|
Deconstruction and matching is handled adequately by the |
|
code{(ice-9 match)}. |
|
|
|
code{build-term}, code{build-exp}. |
|
|
|
In the following interface definitions, consider |
|
code{exp} to be built by code{build-exp}, |
|
respectively. Consider any other name to be evaluated as a Scheme |
|
expression. Many of these forms recognize |
|
|
|
|
|
|
|
deffn {Scheme Syntax} build-term ,val |
|
|
|
deffnx {Scheme Syntax} build-exp ,val |
|
|
|
deffnx {Scheme Syntax} build-exp ($prim name) |
|
|
|
deffnx {Scheme Syntax} build-exp ($const-fun kentry) |
|
|
|
deffnx {Scheme Syntax} build-exp ($rec names syms funs) |
|
|
|
deffnx {Scheme Syntax} build-exp ($call proc args) |
|
|
|
deffnx {Scheme Syntax} build-exp ($callk k proc args) |
|
|
|
deffnx {Scheme Syntax} build-exp ($primcall name param args) |
|
|
|
deffnx {Scheme Syntax} build-exp ($values args) |
|
|
|
deffnx {Scheme Syntax} build-term ($branch kf kt src op param (arg ...)) |
|
|
|
deffnx {Scheme Syntax} build-term ($switch kf kt* src arg) |
|
|
|
deffnx {Scheme Syntax} build-term ($throw src op param args) |
|
|
|
deffnx {Scheme Syntax} build-cont ,val |
|
|
|
deffnx {Scheme Syntax} build-cont ($kargs names syms term) |
|
|
|
deffnx {Scheme Syntax} build-cont ($kfun src meta self ktail kclause) |
|
|
|
deffnx {Scheme Syntax} build-cont ($kclause (req opt rest kw aok?) kbody) |
|
Construct a CPS term, expression, or continuation. |
|
|
|
|
|
|
|
|
|
deffn {Scheme Procedure} make-arity req opt rest kw allow-other-keywords? |
|
A procedural constructor for |
|
end deffn |
|
|
|
|
|
deffnx {Scheme Syntax} rewrite-exp val (pat exp) ... |
|
|
|
var{val} against the series of patterns |
|
code{match}. The body of the matching clause should be a template in |
|
the syntax of code{build-exp}, or |
|
|
|
end deffn |
|
|
|
|
|
subsubsection CPS Soup |
|
|
|
We describe programs in Guile's CPS language as being a kind of ``soup'' |
|
because all continuations in the program are mixed into the same |
|
``pot'', so to speak, without explicit markers as to what function or |
|
scope a continuation is in. A program in CPS is a map from continuation |
|
labels to continuation values. As discussed in the introduction, a |
|
continuation label is an integer. No label may be negative. |
|
|
|
As a matter of convention, label 0 should map to the |
|
|
|
|
|
|
|
code{$fun} and |
|
code{$const-fun}, |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
cindex intmap |
|
The ``soup'' itself is implemented as an |
|
|
|
|
|
|
|
code{(language cps intmap)} module: |
|
|
|
|
|
|
|
end example |
|
|
|
Intmaps are functional data structures, so there is no constructor as |
|
such: one can simply start with the empty intmap and add entries to it. |
|
|
|
|
|
result{} #t |
|
(define x (intmap-add empty-intmap 42 "hi")) |
|
(intmap? x) |
|
result{} "hi" |
|
(intmap-ref x 43) i{error: 43 not present} |
|
(intmap-ref x 43 (lambda (k) "yo!")) |
|
result{} |
|
end example |
|
|
|
code{intmap-add} are the core of the intmap |
|
interface. There is also |
|
|
|
code{intmap-remove}, which removes a key from an intmap. |
|
|
|
Intmaps have a tree-like structure that is well-suited to set operations |
|
such as union and intersection, so there are also the binary |
|
code{intmap-intersect} procedures. If the |
|
result is equivalent to either argument, that argument is returned |
|
as-is; in that way, one can detect whether the set operation produced a |
|
new result simply by checking with |
|
|
|
|
|
|
|
code{eq?}, the resulting value is determined |
|
by a ``meet'' procedure, which is the optional last argument to |
|
code{intmap-intersect}, and also to |
|
code{intmap-replace}, and similar functions. The |
|
meet procedure will be called with the two values and should return the |
|
intersected or unioned value in some domain-specific way. If no meet |
|
procedure is given, the default meet procedure will raise an error. |
|
|
|
To traverse over the set of values in an intmap, there are the |
|
code{intmap-prev} procedures. For example, if |
|
intmap |
|
|
|
example |
|
(intmap-next x) |
|
result{} 42 |
|
(intmap-next x 42) |
|
result{} #f |
|
(intmap-prev x) |
|
result{} 42 |
|
(intmap-prev x 41) |
|
end example |
|
|
|
There is also the |
|
|
|
code{intmap-fold-right} which does so in the opposite direction. These |
|
procedures may take up to 3 seed values. The number of values that the |
|
fold procedure returns is the number of seed values. |
|
|
|
|
|
|
|
result{} ((3 . 4) (1 . 2)) |
|
(intmap-fold-right acons q '()) |
|
end example |
|
|
|
When an entry in an intmap is updated (removed, added, or changed), a |
|
new intmap is created that shares structure with the original intmap. |
|
This operation ensures that the result of existing computations is not |
|
affected by future computations: no mutation is ever visible to user |
|
code. This is a great property in a compiler data structure, as it lets |
|
us hold a copy of a program before a transformation and use it while we |
|
build a post-transformation program. Updating an intmap is O(log |
|
|
|
|
|
var{n}) allocation costs are sometimes too much, |
|
especially in cases when we know that we can just update the intmap in |
|
place. As an example, say we have an intmap mapping the integers 1 to |
|
100 to the integers 42 to 141. Let's say that we want to transform this |
|
map by adding 1 to each value. There is already an efficient |
|
code{(language cps utils)} module, |
|
but if we didn't know about that we might do: |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
end example |
|
|
|
|
|
cindex transient intmaps |
|
Observe that the intermediate values created by |
|
|
|
code{intmap-replace} value is needed. The rest might as well share |
|
state with the last one, and we could update in place. Guile allows |
|
this kind of interface via |
|
uref{http://clojure.org/transients}). |
|
|
|
The in-place code{intmap-replace!} procedures |
|
return transient intmaps. If one of these in-place procedures is called |
|
on a normal persistent intmap, a new transient intmap is created. This |
|
is an O(1) operation. In all other respects the interface is like their |
|
persistent counterparts, code{intmap-replace}. |
|
If an in-place procedure is called on a transient intmap, the intmap is |
|
mutated in-place and the same value is returned. |
|
|
|
If a persistent operation like |
|
|
|
code{intmap-add} then runs on a new persistent intmap |
|
sharing structure but not state with the original transient. Mutating a |
|
transient will cause enough copying to ensure that it can make its |
|
change, but if part of its substructure is already ``owned'' by it, no |
|
more copying is needed. |
|
|
|
We can use transients to make |
|
strong{like this}. |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
strong{intmap-replace!} map k (1+ v)))) |
|
( |
|
end example |
|
|
|
Be sure to tag the result as persistent using the |
|
|
|
|
|
code{persistent-intmap} on the incoming map, to ensure that if it |
|
were already transient, that the mutations in the body of |
|
|
|
|
|
|
|
code{(language cps utils)} for a number of |
|
useful facilities for working with CPS values. |
|
|
|
|
|
subsubsection Compiling CPS |
|
|
|
Compiling CPS in Guile has three phases: conversion, optimization, and |
|
code generation. |
|
|
|
CPS conversion is the process of taking a higher-level language and |
|
compiling it to CPS. Source languages can do this directly, or they can |
|
convert to Tree-IL (which is probably easier) and let Tree-IL convert to |
|
CPS later. Going through Tree-IL has the advantage of running Tree-IL |
|
optimization passes, like partial evaluation. Also, the compiler from |
|
Tree-IL to CPS handles assignment conversion, in which assigned local |
|
variables (in Tree-IL, locals that are |
|
xref{Variables and the |
|
VM}. |
|
|
|
After CPS conversion, Guile runs some optimization passes over the CPS. |
|
Most optimization in Guile is done on the CPS language. The one major |
|
exception is partial evaluation, which for historic reasons is done on |
|
Tree-IL. |
|
|
|
The major optimization performed on CPS is contification, in which |
|
functions that are always called with the same continuation are |
|
incorporated directly into a function's body. This opens up space for |
|
more optimizations, and turns procedure calls into |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
node Bytecode |
|
|
|
|
|
|
|
xref{Object File Format}, for |
|
more on Guile's use of ELF. |
|
|
|
To produce a bytecode image, Guile provides an assembler and a linker. |
|
|
|
The assembler, defined in the |
|
|
|
code{make-assembler} function to instantiate an assembler and a set of |
|
var{inst}} procedures to emit instructions of each kind. |
|
|
|
The var{inst}} procedures are actually generated at |
|
compile-time from a machine-readable description of the VM. With a few |
|
exceptions for certain operand types, each operand of an emit procedure |
|
corresponds to an operand of the corresponding instruction. |
|
|
|
Consider pxref{Memory Access Instructions}. |
|
It is documented as: |
|
|
|
var{dst} s12: |
|
end deftypefn |
|
|
|
Therefore the emit procedure has the form: |
|
|
|
|
|
end deffn |
|
|
|
All emit procedure take the assembler as their first argument, and |
|
return no useful values. |
|
|
|
The argument types depend on the operand types. |
|
|
|
|
|
|
|
|
|
|
|
deffn {Scheme Procedure} emit-label asm label |
|
Define a label at the current program point. |
|
|
|
|
|
deffn {Scheme Procedure} emit-source asm source |
|
Associate |
|
end deffn |
|
|
|
|
|
deffnx {Scheme Procedure} emit-cache-set! asm key val |
|
Macro-instructions to implement compilation-unit caches. A single cache |
|
cell corresponding to |
|
|
|
end deffn |
|
|
|
|
|
var{constant} into |
|
end deffn |
|
|
|
|
|
deffnx {Scheme Procedure} emit-end-program asm |
|
Delimit the bounds of a procedure, with the given |
|
var{properties}. |
|
|
|
|
|
deffn {Scheme Procedure} emit-load-static-procedure asm dst label |
|
Load a procedure with the given var{dst}. This |
|
macro-instruction should only be used with procedures without free |
|
variables -- procedures that are not closures. |
|
|
|
|
|
deffn {Scheme Procedure} emit-begin-standard-arity asm req nlocals alternate |
|
|
|
deffnx {Scheme Procedure} emit-begin-kw-arity asm req opt rest kw-indices allow-other-keys? nlocals alternate |
|
|
|
|
|
end deffn |
|
|
|
The linker is a complicated beast. Hackers interested in how it works |
|
would do well do read Ian Lance Taylor's series of articles on linkers. |
|
Searching the internet should find them easily. From the user's |
|
perspective, there is only one knob to control: whether the resulting |
|
image will be written out to a file or not. If the user passes |
|
pxref{The Scheme |
|
Compiler}), the linker will align the resulting segments on page |
|
boundaries, and otherwise not. |
|
|
|
|
|
var{page-aligned?} is |
|
true, Guile will align the segments with different permissions on |
|
page-sized boundaries, in order to maximize code sharing between |
|
different processes. Otherwise, padding is minimized, to minimize |
|
address space consumption. |
|
|
|
|
|
code{put-bytevector} from |
|
|
|
|
|
code{value}, is performed |
|
via loading objcode into a program, then executing that thunk with |
|
respect to the compilation environment. Normally the environment |
|
propagates through the compiler transparently, but users may specify the |
|
compilation environment manually as well, as a module. Procedures to |
|
load images can be found in the |
|
|
|
lisp |
|
(use-modules (system vm loader)) |
|
|
|
|
|
deffn {Scheme Variable} load-thunk-from-file file |
|
|
|
var{file}. The file will be mapped |
|
into memory via |
|
end deffn |
|
|
|
|
|
deffnx {C Function} scm_load_thunk_from_memory (bv) |
|
Load object code from a bytevector. The data will be copied out of the |
|
bytevector in order to ensure proper alignment of embedded Scheme |
|
values. |
|
|
|
|
|
|
|
|
|
|
|
deffn {Scheme Variable} find-mapped-elf-image ptr |
|
Given the integer value |
|
|
|
code{#f}. This routine is mostly used by debuggers and other |
|
introspective tools. |
|
|
|
|
|
deffn {Scheme Variable} all-mapped-elf-images |
|
Return all mapped ELF images, as a list of bytevectors. |
|
|
|
|
|
|
|
node Writing New High-Level Languages |
|
|
|
|
|
var{lang} into Guile's compiler |
|
system, one has to create the module var{lang} spec)} |
|
containing the language definition and referencing the parser, |
|
compiler and other routines processing it. The module hierarchy in |
|
|
|
|
|
url{http://en.wikipedia.org/wiki/Brainfuck} |
|
for more information about the Brainfuck language itself. |
|
|
|
|
|
|
|
subsection Extending the Compiler |
|
|
|
At this point we take a detour from the impersonal tone of the rest of |
|
the manual. Admit it: if you've read this far into the compiler |
|
internals manual, you are a junkie. Perhaps a course at your university |
|
left you unsated, or perhaps you've always harbored a desire to hack the |
|
holy of computer science holies: a compiler. Well you're in good |
|
company, and in a good position. Guile's compiler needs your help. |
|
|
|
There are many possible avenues for improving Guile's compiler. |
|
Probably the most important improvement, speed-wise, will be some form |
|
of optimized ahead-of-time native compilation with global register |
|
allocation. A first pass could simply extend the compiler to also emit |
|
machine code in addition to bytecode, pre-filling the corresponding JIT |
|
data structures referenced by the |
|
xref{Instrumentation Instructions}. |
|
|
|
The compiler also needs help at the top end, adding new high-level |
|
compilers. We have JavaScript and Emacs Lisp mostly complete, but they |
|
could use some love; Lua would be nice as well, but whatever language it |
|
is that strikes your fancy would be welcome too. |
|
|
|
Compilers are for hacking, not for admiring or for complaining about. |
|
Get to it! |
|
|