Java Reference
In-Depth Information
6.1.3 Scope of Our Work
We translate a sucient subset of the JVM to SPIM code to give the student a taste of
native code generation, some of the possibilities for optimization, and register allocation.
More precisely, we translate enough JVM code to SPIM code to handle the following j--
program 1 . The class spim.SPIM is a class that we have defined for accessing special SPIM
system routines for doing simple IO.
importspim.SPIM;
//Printsfactorialofanumbercomputedusingrecursiveanditerative
//algorithms.
publicclassFactorial{
//Returnthefactorialofthegivennumbercomputedrecursively.
publicstaticintcomputeRec(intn){
if(n<=0){
return1;
}else{
returnn*computeRec(n-1);
}
}
//Returnthefactorialofthegivennumbercomputediteratively.
publicstaticintcomputeIter(intn){
intresult=1;
while(n>0){
result=result*n--;
}
returnresult;
}
//Entrypoint;printfactorialofanumbercomputedusing
//recursiveanditerativealgorithms.
publicstaticvoidmain(String[]args){
intn=7;
SPIM.printInt(Factorial.computeRec(n));
SPIM.printChar('\n');
SPIM.printInt(Factorial.computeIter(n));
SPIM.printChar('\n');
}
}
We handle static methods, conditional statements, while loops, recursive method invoca-
tions, and enough arithmetic to do a few computations. We must deal with some objects,
for example, constant strings. Although the program above refers to an array, it does not
really do anything with it so we do not implement array objects. Our run-time support is
minimal.
In order to determine just what JVM instructions must be handled, it is worth looking
at the output from running javap on the class file produced for this program.
publicclassFactorialextendsjava.lang.Object
minorversion:0
majorversion:49
Constantpool:
...<theconstantpooliselidedhere>...
{
publicFactorial();
Code:
1 We also compile a few more programs, which are included in the code tree but are not discussed further
here: Fibonacci , GCD , Formals , and HelloWorld .
 
Search WWH ::




Custom Search