How to do code generation The main program is "gen21.txt". It accepts a N-obj (a.obj) file produced by "nut32" compiler and outputs a S-obj file to stdout (the screen). S-obj file is a machine code for a processor (we use another virtual machine Som-v2 for this purpose), called "som.exe". (to read further about som-v2 goto this link) First we compile the code generator itself, "gen21.txt" and rename the object file to "gen21.obj". c:> nut32 < gen21.txt c:> ren a.obj gen21.obj Now "gen21.obj" will be our executable code generator. We try it out on the previous example "ex-ch2.txt". c:> nut32 < ex-ch2.txt Compile the source and now we have "a.obj" as a N-obj file. Here is what N-obj looks like: 30 30 2 1 14 1 0 4 1 20 1 2 6 0 0 4 0 8 1 19 257 6 10 1 14 1 0 12 1 14 1 10 14 1 8 0 12 16 0 0 14 0 18 1 19 257 16 20 1 16 20 0 22 1 13 18 20 24 0 0 22 0 26 1 13 8 24 28 0 0 26 0 30 1 19 1 28 0 3 18 print 3 8 1 1 20 sq 3 18 1 1 22 main 3 30 0 1 Generate S-code from it using our code generator "gen21.obj". Keep the output in "ex-ch2.s". c:> nsim32 gen21.obj < a.obj > ex-ch2.s Here is "ex-ch2.s" ---------------- 5678920 1 16 3104 23 294 280 292 532 294 280 280 3 532 550 5151 1824 800 532 2000 1999 3 print 3 3 1 1 sq 3 7 1 1 main 3 12 0 1 ---------------- The first line "5678920" denotes Som-v2 object file. The next line "1 16" is the starting address and length of the machine code. The whole next block is the machine code (S-code). Each S-code has the format arg:24 op:8, for example "3104" is: arg = 3104 >> 8 = 12 op = 3104 & 255 = 32 So this instruction is "call 12". Here is the encoding table of S-code (from my textbook chapter 4). Encoding 0 -- 1 add 2 sub 3 mul 4 div 5 band 6 bor 7 bxor 8 not 9 eq 10 ne 11 lt 12 le 13 ge 14 gt 15 shl 16 shr 17 mod 18 ldx 19 stx 20 ret 21 -- 22 array 23 24 get 25 put 26 ld 27 st 28 jmp 29 jt 30 jf 31 lit 32 call 33 -- 34 inc 35 dec 36 sys 37 case 38 fun The next block "2000 1999" is the data block, it contains start and end address follows by the data. This numbers say there is no data. The last block is the symbol table. To "run" the S-obj, use Som-v2 virtual machine ("som.exe") like this: c:> som -x < ex-ch2.s It should give out the correct result (400) on the screen. Your home work is to try this procedure with the example program from the class: (def isnull a () (< a 0)) (def tail a () (vec a 1)) (def len (a) () (if (isnull a) 0 (+ 1 (len (tail a))))) Produce the S-obj from this input source and then proceed to "disassemble" the S-obj by hand into a human readable S-code. (Don't try to run this piece of S-obj as the program is not complete, it requires the input of len to be a list). You can try to compile and generate code and run some other program that use simple input. I have include "ex-ch2.lst" in the directory "codegen" so that you can see what to be expected as a listing of a S-code listing file. last update 11 Aug 2009