Dave Hanold CS 536 Notes April 26, 1999 =============================================================================== ** Final Exam : Tues. May 11 12:25 - 2:25 6104 Social Science ** READ 11.1-11.2, 12.1-12.2 ------------------------------------------------------------------------------- TOPIC: WRITING THE CODE GENERATOR **DISCLAIMER** The following code was copied off the board during class so some parts may abridged/wrong. This code can be found in the CSX CODE GENERATION ROUTINES handout for Program 5 boolean codeGen(printStream ASMFile) // avoids need to pass parameters by making the output file global // contained in the root node (because the code generation only occurs after a successful type checking, NO ERRORS WILL MOST LIKELY BE ENCOUNTERED DURING CODE GENERATION -- just in case though, return value of false if an error occurs) void cg() //for all other AST nodes contained in ast.java ---------------- ADR field: int value where you can find a given value can be: global --> string label local --> int varIndex (index into activation record) on stack literal --> int intVal or String strVal none ---------------- EXAMPLE OF CODE GENERATING SUBROUTINES void loadI(int val) { //generates ldc val ASMFile.println("\tldc " + val); } cg() { //intLitNode/charLitNode/bool nodes loadI(intVal); adr = literal; } cg() { //nameNode if (subscriptVal.isNull()) { if ((varName.idinfo.kind.val == Kinds.Var) || (varName.idinfo.kind.val == Kinds.Value)) { if (varName.idinfo.adr == Global) { label = varName.idinfo.label; loadGlobalInt(label); } else { varIndex = varName.idinfo.varIndex; LOADLOCALINDEXVARINDEX); } } adr = stack; } } cg() { //binaryOpNode leftOperand.cg(); //push operands onto stack rightOperand.cg(); binOp(selectOpCode(operatorCode)); //and perform operation adr = stack; } EXAMPLE OF BINOPNODE: b + 1 b = Global; label = b$ (add $ to the end of the label to ensure that the label doesn't conflict with java commands) would become: getstatic C/b$ I ==> "getStatic" -> get a static value ldc 1 C -> class name iadd b$ -> label name I -> type (I)nteger -------------------- ASSIGNMENT STATEMENTS (A = B;) 1. Compute A's address 2. Compute B onto the stack 3. Store top of stack at A's address to Compute an address: void static computeAdr(nameNode name) { if (name.subscriptVal.isNull()) { if (name.varName.idinfo.kind.val == Kinds.Var) { if (name.varName.idinfo.adr == global) { name.adr = global; name.label = name.varName.idinfo.label; } cg() { //ASG NODE computeAdr(target); source.cg(); storeName(target); } EXAMPLE: a = b + 1; b: adr = global label = b$ a: adr = local index = 0 resulting code generated: getStatic c/b$ I ldc 1 iadd istore 0