After toying with the algorithm to write the assembly code, I've decided to take a step back and write a precompiler into C# instead. The reason for this is that writing the assembly code involves a lot of work I am not interested in for this project, and I believe I can accomplish the majority of what I am looking for with a precompiler. As a later phase, if I am still interested, I'll use the precompiler as a basis for a program to write assembly code.
My next step is going to be to write a pseudo-compiler. This will build the C# code in memory and compile it into an executable using standard libraries.
Maybe instead of calling it a "pseudo-compiler" I should call it a "higher-order compiler". Makes me sound smarter.
Friday, April 5, 2013
Tuesday, March 26, 2013
General Approach to Writing Assembly Code
Based on my previous plan for three layers of laziness, I've come up with the following general approach to writing the instructions for a function body.
First, by the time we are ready to write the function body code, we should have parsed the expression returned by the function into an expression tree, the nodes of which are function calls of some kind, and the branches of which are parameters to those function calls.
We will process the branches first in such a way that, once processing is finished, the result of each parameter's evaluation sits on the stack in order. When all of the branches are finished, we'll write the function call itself.
Prior to beginning to write the assembly code, we'll check the tree for duplicate function calls--calls where all of the same parameters are passed to the same function. Usually these will be unevaluated expressions passed in as parameters, or known to the function as environment variables. For each duplicate we will allocate two local variables, one to store the result of the function evaluation, and the second to store a flag indicating whether the function has already been evaluated.
If we think that the result of the function is to be used later, we'll set the corresponding flag, pop it off of the stack after evaluation, store it as a local variable, then push it back onto the stack. Later, rather than reevaluating the function call, we'll simply push the local variable onto the stack.
At the end, of course, well write a ret (return) operation.
Down the road, it might be worthwhile to consider including function calls inline, since there is essentially no overhead except for the larger size of the executable.
First, by the time we are ready to write the function body code, we should have parsed the expression returned by the function into an expression tree, the nodes of which are function calls of some kind, and the branches of which are parameters to those function calls.
We will process the branches first in such a way that, once processing is finished, the result of each parameter's evaluation sits on the stack in order. When all of the branches are finished, we'll write the function call itself.
Prior to beginning to write the assembly code, we'll check the tree for duplicate function calls--calls where all of the same parameters are passed to the same function. Usually these will be unevaluated expressions passed in as parameters, or known to the function as environment variables. For each duplicate we will allocate two local variables, one to store the result of the function evaluation, and the second to store a flag indicating whether the function has already been evaluated.
If we think that the result of the function is to be used later, we'll set the corresponding flag, pop it off of the stack after evaluation, store it as a local variable, then push it back onto the stack. Later, rather than reevaluating the function call, we'll simply push the local variable onto the stack.
At the end, of course, well write a ret (return) operation.
Down the road, it might be worthwhile to consider including function calls inline, since there is essentially no overhead except for the larger size of the executable.
Saturday, March 23, 2013
Three Layers of Laziness
In the last post I walked through the CIL disassembly for a simple function. I discovered that one of my mechanisms intended to implement laziness was really causing more work than was necessary.
As a brief recap, the problem is this: In a standard programming language, expressions that are parameters to functions are evaluated before being passed to the function, regardless of whether they are ultimately needed within the function.
I was hoping to get around this by passing in a reference to the expression, and only evaluate it if necessary. However, in my sample function I used one of my parameters three times, and the C# compiler ended up evaluating the expression three times.
This makes perfect sense in the standard programming world, because the function might not return the same value each time. However, if the function is pure, the expression only needs to be evaluated once.
In the end, I hope I can implement three layers of laziness: 1) Within a function, let each expression be evaluated only if it is needed; 2) If an expression is evaluated, let is only be evaluated once, and let its value be stored in a local variable if it is needed more than once; 3) Let a thunk remember its last evaluated value, and return it directly rather than reevaluating.
Having said that, here is a rough sketch of what the CIL for the AddAndMultiply function should have looked like. (I'm not 100% certain how to calculate the maxstack value yet...working on that).
As a brief recap, the problem is this: In a standard programming language, expressions that are parameters to functions are evaluated before being passed to the function, regardless of whether they are ultimately needed within the function.
I was hoping to get around this by passing in a reference to the expression, and only evaluate it if necessary. However, in my sample function I used one of my parameters three times, and the C# compiler ended up evaluating the expression three times.
This makes perfect sense in the standard programming world, because the function might not return the same value each time. However, if the function is pure, the expression only needs to be evaluated once.
In the end, I hope I can implement three layers of laziness: 1) Within a function, let each expression be evaluated only if it is needed; 2) If an expression is evaluated, let is only be evaluated once, and let its value be stored in a local variable if it is needed more than once; 3) Let a thunk remember its last evaluated value, and return it directly rather than reevaluating.
Having said that, here is a rough sketch of what the CIL for the AddAndMultiply function should have looked like. (I'm not 100% certain how to calculate the maxstack value yet...working on that).
.maxstack 7
.locals init (
int32 V_0,
int32 V_1)
// Get the value of x
IL_0000: ldarg.1
IL_0001: callvirt instance !0 class ToylModel20130322.ISignature`1<int32>::Value()
// Store x in a local variable
IL_0006: stloc.0
// If x >= 0 then goto IL_0019
IL_0007: ldloc.0
IL_0008: ldc.i4.0
IL_0009: bge IL_0019
// Throw exception
IL_000e: ldstr "x must not be less than zero"
IL_0013: newobj instance void class [mscorlib]System.Exception::'.ctor'(string)
IL_0018: throw
// Get the value of y
IL_0019: ldarg.2
IL_001a: callvirt instance !0 class ToylModel20130322.ISignature`1<int32>::Value()
// y is still on the stack, push x back on and add the two together
IL_0021: ldloc.0
IL_0022: add
// Push x on the stack again and multiply
IL_0023: ldloc.0
IL_0024: mul
// Return the result
IL_0025: ret
Fig. 12.1: Ideal CIL code
One geeky observation that not many people would make: The syntax of assembly language is very much like the syntax of Altaic languages--the verb always comes last.
First Leisurely Walk through CIL Code
For this project I have been alternating between Microsoft Visual Studio 2010 on a Windows 7 PC and Xamarin Studio on a Mac. The CIL code I'm looking at in this project was compiled on the Mac using mono and disassembled using monodis, so it may be a little different from what the Microsoft csc and ildasm would produce.
Right now, I'm just going to look at the AddAndMultiply function, and see how lazy evaluation was handled. Here is the CIL code:
.maxstack 11
IL_0000: ldarg.1
IL_0001: callvirt instance !0 class ToylModel20130322.ISignature`1<int32>::Value()
IL_0006: ldc.i4.0
IL_0007: bge IL_0017
IL_000c: ldstr "x must not be less than zero"
IL_0011: newobj instance void class [mscorlib]System.Exception::'.ctor'(string)
IL_0016: throw
IL_0017: ldarg.2
IL_0018: callvirt instance !0 class ToylModel20130322.ISignature`1<int32>::Value()
IL_001d: ldarg.1
IL_001e: callvirt instance !0 class ToylModel20130322.ISignature`1<int32>::Value()
IL_0023: add
IL_0024: ldarg.1
IL_0025: callvirt instance !0 class ToylModel20130322.ISignature`1<int32>::Value()
IL_002a: mul
IL_002b: ret
Fig. 11.1: CIL code for AddAndMultiply
Let's just walk through this.
ldarg.1
This loads the function's first argument (ISignature<int> x) onto the stack.
Stack now has: [x]
callvirt instance !0 class ToylModel20130322.ISignature`1<int32>::Value()
This calls the Value() method of the ISignature<int32> interface. This will pop the x off of the stack and push the result of the evaluation back on the stack. This is how we implemented lazy evaluation.
Stack now has: [x.Value]
ldc.i4.0
This pushes the constant value 0 onto the stack.
Stack now has: [x.Value, 0]
bge IL_0017
This takes the last two values from the stack. If the next-to-top value is greater than or equal to the top value (i.e. if 13 >= 0) then it will branch to the operation at IL_0017. This pops both values off the stack.
Stack now has: []
The next few steps would be followed if we had passed in an x that evaluated to a negative value.
ldstr "x must not be less than zero"
This loads the exception message string onto the stack.
Stack now has: ["x must not be less than zero"]
newobj instance void class [mscorlib]System.Exception::'.ctor'(string)
This creates a new instance of the Exception class. The constructor takes one parameter, so it pops the string off the stack. The new exception is pushed back onto the stack.
Stack now has: [Exception]
throw
This pops the exception off the stack and throws it. Execution ends here.
The following steps would be executed for non-negative values of x.
ldarg.2
callvirt instance !0 class ToylModel20130322.ISignature`1<int32>::Value()
This loads the function's second argument (ISignature<int> y) onto the stack and calls the Value() method.
Stack now has: [y.Value]
ldarg.1
callvirt instance !0 class ToylModel20130322.ISignature`1<int32>::Value()
This again loads the function's first argument (ISignature<int> x) onto the stack and calls the Value() method.
Stack now has: [y.Value, x.Value]
add
This adds the top two values on the stack and pushes the result back on.
Stack now has: [(y.Value + x.Value)]
ldarg.1
callvirt instance !0 class ToylModel20130322.ISignature`1<int32>::Value()
For the third time, this loads the function's first argument (ISignature<int> x) onto the stack and calls the Value() method.
Stack now has: [(y.Value + x.Value), x.Value]
mul
This multiplies the top two values on the stack and pushes the result back on.
Stack now has: [(y.Value + x.Value) * x.Value]
ret
This returns the value on the top of the stack.
The main lesson I learned from looking at this is that I ended up calling the Value() method four times, when I only really needed it twice. It probably would have been better if the C# code looked like this:
int _x = x.Value ();
if (_x < 0) {
throw new Exception("x must not be less than zero");
} else {
int _y = y.Value();
return (_y + _x) * _x;
}
Fig. 11.2: More efficient C# code
This code only calls Value() once and stores the result locally.
Friday, March 22, 2013
Lessons Learned
A preliminary C# expression for the Toyl model in Fig. 10.1 is now posted on github.
I rewrote this sucker about five times before I landed on the revision currently posted. What did I learn?
First, I found ways to use delegates to represent lambda expressions instead of creating separate classes for each one. That made the code a lot smaller and a lot tidier.
Second, in the case of currying and creating higher order functions, I found a way to define "delegate factories" that would generate the delegates I needed.
I'm actually pretty happy with the resulting code. In the next post, I will disassemble it and see what it looks like in CIL.
I rewrote this sucker about five times before I landed on the revision currently posted. What did I learn?
First, I found ways to use delegates to represent lambda expressions instead of creating separate classes for each one. That made the code a lot smaller and a lot tidier.
Second, in the case of currying and creating higher order functions, I found a way to define "delegate factories" that would generate the delegates I needed.
I'm actually pretty happy with the resulting code. In the next post, I will disassemble it and see what it looks like in CIL.
Walking through Compilation
I have to admit, now that I am at this point, I am a little uncomfortable with the idea that every lambda expression will be turned into a class. It seems like I will end up with a lot of tiny classes, and that seems wasteful somehow.
However, until I see real evidence that it is a problem, I'm not going to worry about it. I can think of a couple of different ways that I might reduce the number of classes.
I'm going to try my current model out by creating a model Toyl program, then working out how it would be expressed in C#. Then, I'll compile the C# program and look at how it is expressed in CIL.
So here's the model program. It includes a curried function, a higher order function, and lazy evaluation. This would compile into a DLL, because there is no impure code here to interact with the sullied world.
namespace ToylModel20130322 {
AddAndMultiply = int function(int x, int y) {
x < 0: Exception("x must not be less than zero");
otherwise: (y + x) * x;
};
C13 = 13;
AddCAndMultiplyByC = AddAndMultiply(C13);
ApplyTwice = <T> function(<T>function(<T>) f, <T> v) {
f(f(v))
};
TestFunction = int function() {
ApplyTwice(AddCAndMultiplyByC, 72)
};
}
Fig. 10.1: A model Toyl program
There is something going on here that I haven't explicitly mentioned. I am using the colon (:) and semicolon (;) as a ternary operator meaning "if...then...else". It makes the "case" blocks within function bodies look nice, but it might come back to haunt me since I am also using the semicolon as the declaration delimiter. Right now I think the two operators should exist in different domains within the code, but we'll see if I run into trouble as the process goes on.
The full C# code will probably be pretty long, so I'll work on it throughout the day and post it on github, and the next post will have my lessons learned.
Thursday, March 21, 2013
Syntax Outline
The basic unit of a Toyl program will be an expression, which may be a constant value, lambda expression, or else involve function calls and operators. The full description of expression syntax covers almost everything else I currently envision in Toyl:
expression ::= { reference | constant | evaluable | lambda }
reference ::= identifier
evaluable ::= { function-call | operator-expression } [where-phrase]
function-call ::= function-name "(" parameters ")"
function-name ::= identifier
parameters ::= expression ["," parameters]
operator-expression ::= { unary-operation | binary-operation | trinary-operation }
unary-operation ::= operator expression
binary-operation ::= expression operator expression
ternary-operation ::= expression operator expression operator expression
where-phrase ::= "where" "{" declarations "}"
declarations ::= declaration [";" declarations]
declaration ::= identifier "=" expression
lambda ::= return-type function-type "(" parameter-declarations ")" "{" expression "}"
function-type ::= "function" | "process"
parameter-declarations ::= parameter-declaration ["," parameter-declarations]
parameter-declaration ::= type identifier
Fig. 9.1: Expression syntax
Identifiers may be organized in namespaces, which (like the where-phrase above) are just collections of identifiers:
namespace ::= "namespace" "{" declarations "}"
Fig. 9.2: Namespace syntax
This looks like a good start. In the next post, I'll try to walk through the process of translating Toyl expressions into the underlying object structures and see where my ideas break.
Subscribe to:
Posts (Atom)