3.14 Translating Program Expressions 91
0 alloc 2 3 rewrite 2 3 mkbasic 2 pushloc 1
2 pushloc 0 2 loadc 7 3 rewrite 1 3 eval
3 slide 2
Executing this sequence should produce the basic value 7. The reader may check,
however, that execution leads to a call of the instruction eval for a dummy closure
— and therefore to a memory error.
The reason is that, in this example, the variable a is initialized by overwritting its
associated dummy closure again with a dummy closure, namely the closure that was
produced by the variable access to b. Even though the dummy closure for b is later
overwritten by the B-object
(B,7), the variable a still refers to the dummy closure.
We conclude that our optimization no longer always generates correct code.
The problem with our optmized code generation for variable accesses only arises
with recursive definitions of variables by variables where a variable y is used as the
right side before the dummy closure corresponding to y has been overwritten.
Luckily, we can avoid this problem first, by disallowing at translation time cyclic
variable definitions such as y
= y and, second, by organizing definitions y
i
= y
j
such that the dummy closure for y
j
is always overwritten before the dummy closure
for y
i
.
The code generation function code
C
can also be improved for functions e: func-
tions are already valuesthat need not be evaluated further. Instead of generating code
that constructs the F-object only on request, we construct this object directly:
code
C
(fun x
0
...x
k−1
→ e)
ρ
sl = code
V
(fun x
0
...x
k−1
→ e)
ρ
sl
We leave it as an exercise to compare this code with the corresponding unoptimized
instruction sequence.
After these considerations, we finish our presentation of code generation for
functional programs by explaining how to generate code for the entire program.
3.14 Translating Program Expressions
The execution of a program e starts with
PC
= 0 SP = FP = GP = −1
The expression e must not contain free variables. The code generated for e should
determine the value of e and then execute the instruction halt:
code e
= code
V
e ∅ 0
halt
It should be mentioned that the code schemes as defined so far produce spaghetti
code.Anecdotally, it issaid that an obfuscated C contest wasoncewonby translating
a functional program into C.