better stack overflow checking
[org.ibex.classgen.git] / src / org / ibex / classgen / JSSA.java
1 package org.ibex.classgen;
2 import java.io.*;
3 import java.util.*;
4
5 /**
6  *  a highly streamlined SSA-form intermediate representation of a
7  *  sequence of JVM instructions; all stack manipulation is factored
8  *  out.
9  */
10 public class JSSA extends MethodGen implements CGConst {
11
12     // Constructor //////////////////////////////////////////////////////////////////////////////
13     
14     public JSSA(Type.Class c, DataInput in, ConstantPool cp) throws IOException {
15         super(c, in, cp);
16         local = new Expr[maxLocals];
17         stack = new Expr[maxStack];
18         for(int i=0; i<this.method.getNumArgs(); i++)
19             local[i] = new Argument("arg"+i, this.method.getArgType(i));
20         for(int i=0; i<size(); i++) {
21             int    op  = get(i);
22             Object arg = getArg(i);
23             Object o = addOp(op, arg);
24             if (o != null) {
25                 ops[numOps] = o;
26                 ofs[numOps++] = i;
27             }
28         }
29     }
30
31     public void debugBodyToString(StringBuffer sb) {
32         StringBuffer sb0 = new StringBuffer();
33         super.debugBodyToString(sb0);
34         StringTokenizer st = new StringTokenizer(sb0.toString(), "\n");
35         String[] lines = new String[st.countTokens()];
36         for(int i=0; i<lines.length; i++) lines[i] = st.nextToken();
37         for(int j=0; j<ofs[0]; j++) {
38             String s = "    /* " + lines[j].trim();
39             while(s.length() < 50) s += " ";
40             s += " */";
41             sb.append(s);
42             sb.append("\n");
43         }
44         for(int i=0; i<numOps; i++) {
45             String s = "    /* " + lines[ofs[i]].trim();
46             while(s.length() < 50) s += " ";
47             s += " */  ";
48             s += ops[i].toString();
49             sb.append(s);
50             sb.append(";\n");
51             for(int j=ofs[i]+1; j<(i==numOps-1?size():ofs[i+1]); j++) {
52                 s = "    /* " + lines[j].trim();
53                 while(s.length() < 50) s += " ";
54                 s += " */";
55                 sb.append(s);
56                 sb.append("\n");
57             }
58         }
59     }
60     
61     private Object[] ops = new Object[65535];
62     private int[] ofs = new int[65535];
63     private int numOps = 0;
64
65     // Instance Data; used ONLY during constructor; then thrown away /////////////////////////////////////////////////
66
67     /** this models the JVM locals; it is only used for unwinding stack-ops into an SSA-tree, then thrown away */
68     private final Expr[] local;
69     
70     /** this models the JVM stack; it is only used for unwinding stack-ops into an SSA-tree, then thrown away */
71     private final Expr[] stack;
72
73     /** JVM stack pointer */
74     private int sp = 0;
75     
76     private Expr push(Expr e) {
77         if(sp == stack.length) {
78             for(int i=0;i<stack.length;i++) System.err.println("Stack " + i + ": " + stack[i]);
79             throw new IllegalStateException("stack overflow (" + stack.length + ")");
80         }
81         if(e.getType() == Type.VOID) throw new IllegalArgumentException("can't push a void");
82         return stack[sp++] = e;
83     }
84     private Expr pop() {
85         if(sp == 0) throw new IllegalStateException("stack underflow");
86         return stack[--sp];
87     }
88
89
90     // SSA-node classes /////////////////////////////////////////////////////////////////////////////////////////
91
92     public final Expr VOID_EXPR = new Expr() {
93         public Type getType() { return Type.VOID; }
94     };
95     
96     /** an purely imperative operation which does not generate data */
97     public abstract class Op {
98         //public abstract Op[] predecessors();  // not implemented yet
99         //public abstract Op[] successors();    // not implemented yet
100         public String toString() { return name(); }
101         String name() {
102             String name = this.getClass().getName();
103             if (name.indexOf('$') != -1) name = name.substring(name.lastIndexOf('$')+1);
104             if (name.indexOf('.') != -1) name = name.substring(name.lastIndexOf('.')+1);
105             return name;
106         }
107     }
108
109     /** an operation which generates data */
110     public abstract class Expr extends Op {
111         //public abstract Expr[] contributors();  // not implemented yet
112         //public abstract Expr[] dependents();    // not implemented yet
113
114         /** every JSSA.Expr either remembers its type _OR_ knows how to figure it out (the latter is preferred to eliminate
115          *  redundant information that could possibly "disagree" with itself -- this happened a LOT in Soot) */
116         public abstract Type getType();
117     }
118
119     /**
120      *  A "nondeterministic merge" -- for example when the first instruction in a loop reads from a local which could have been
121      *  written to either by some instruction at the end of the previous iteration of the loop or by some instruction before
122      *  the loop (on the first iteration).
123      */
124     public class Phi extends Expr {
125         private final Expr[] inputs;
126         public Phi(Expr[] inputs) {
127             this.inputs = new Expr[inputs.length];
128             System.arraycopy(inputs, 0, this.inputs, 0, inputs.length);
129         }
130         public Type getType() {
131             // sanity check
132             Type t = inputs[0].getType();
133
134             // FIXME: actually this should check type-unifiability... fe, the "type of null" unifies with any Type.Ref
135             for(int i=1; i<inputs.length; i++)
136                 if (inputs[i].getType() != t)
137                     throw new Error("Phi node with disagreeing types!  Crisis!");
138             return t;
139         }
140     }
141
142     public class Argument extends Expr {
143         public final String name;
144         public final Type t;
145         public Argument(String name, Type t) { this.name = name; this.t = t; }
146         public String toString() { return name; }
147         public Type getType() { return t; }
148     }
149     
150     // Unary Operations
151     public class Not extends Expr {
152         public final Expr e;
153         public Not(Expr e) {
154             if(e.getType() != Type.BOOLEAN) throw new IllegalArgumentException("not needs a boolean expression");
155             this.e = e;
156         }
157         public Type getType() { return Type.BOOLEAN; }
158         public String toString() { return "!(" + e + ")"; }
159     }
160     
161     public class Neg extends Expr {
162         public final Expr e;
163         public Neg(Expr e) {
164             if(!e.getType().isPrimitive()) throw new IllegalArgumentException("can only negate a primitive");
165             this.e = e;
166         }
167         public Type getType() { return e.getType(); }
168         public String toString() { return "- (" + e + ")"; }
169     }
170     
171     // Binary Operations //////////////////////////////////////////////////////////////////////////////
172
173     public abstract class BinExpr extends Expr {
174         public final Expr e1;
175         public final Expr e2;
176         private final String show;
177         public BinExpr(Expr e1, Expr e2, String show) { this.e1 = e1; this.e2 = e2; this.show = show; }
178         public String toString() {
179             // FEATURE: should we be doing some precedence stuff here? probably no worth it for debugging output
180             return "(" + e1 + show + e2 + ")";
181         }
182     }
183
184     public class Comparison extends BinExpr {
185         public Comparison(Expr e1, Expr e2, String show) { super(e1, e2, show); }
186         public Type getType() { return Type.BOOLEAN; }
187     }
188
189     public class Eq extends Comparison {
190         public Eq(Expr e1, Expr e2) {
191             super(e1, e2, "=="); 
192             if(e1.getType().isPrimitive() != e2.getType().isPrimitive())
193                 throw new IllegalArgumentException("type mismatch");
194             if(e1.getType().isPrimitive() && e1.getType() != e2.getType())
195                 throw new IllegalArgumentException("type mismatch");            
196             // FEATURE: Check if we can compare these classes
197         }
198     }
199     
200
201     public class PrimitiveComparison extends Comparison {
202         public PrimitiveComparison(Expr e1, Expr e2, String show) {
203             super(e1, e2, show);
204             if(!e1.getType().isPrimitive() || e1.getType() != e2.getType()) throw new IllegalArgumentException("type mismatch");
205         }
206     }
207     
208     public class Gt extends PrimitiveComparison { public Gt(Expr e1, Expr e2) { super(e1, e2, ">"); } }
209     public class Lt extends PrimitiveComparison { public Lt(Expr e1, Expr e2) { super(e1, e2, "<"); } }
210     public class Ge extends PrimitiveComparison { public Ge(Expr e1, Expr e2) { super(e1, e2, ">="); } }
211     public class Le extends PrimitiveComparison { public Le(Expr e1, Expr e2) { super(e1, e2, "<="); } }
212     
213     // Math Operations //////////////////////////////////////////////////////////////////////////////
214
215     public class BinMath extends BinExpr {
216         public BinMath(Expr e1, Expr e2, String show) {
217             super(e2, e1, show); 
218             if(e1.getType() != e2.getType()) throw new IllegalArgumentException("types disagree");
219         }
220         public Type getType() { return e1.getType(); }
221     }
222     
223     public class Add  extends BinMath { public  Add(Expr e, Expr e2) { super(e, e2, "+"); } }
224     public class Sub  extends BinMath { public  Sub(Expr e, Expr e2) { super(e, e2, "-"); } }
225     public class Mul  extends BinMath { public  Mul(Expr e, Expr e2) { super(e, e2, "*"); } }
226     public class Rem  extends BinMath { public  Rem(Expr e, Expr e2) { super(e, e2, "%"); } }
227     public class Div  extends BinMath { public  Div(Expr e, Expr e2) { super(e, e2, "/"); } }
228     public class And  extends BinMath { public  And(Expr e, Expr e2) { super(e, e2, "&"); } }
229     public class Or   extends BinMath { public   Or(Expr e, Expr e2) { super(e, e2, "|"); } }
230     public class Xor  extends BinMath { public  Xor(Expr e, Expr e2) { super(e, e2, "^"); } }
231     
232     public class BitShiftExpr extends BinExpr {
233         public BitShiftExpr(Expr e1, Expr e2, String show) {
234             super(e1,e2,show);
235             Type t = e1.getType();
236             if(t != Type.INT && t != Type.LONG) throw new IllegalArgumentException("type mismatch");
237             if(e2.getType() != Type.INT) throw new IllegalArgumentException("type mismatch");
238         }
239         public Type getType() { return e1.getType(); }
240     }
241     public class Shl  extends BitShiftExpr { public  Shl(Expr e, Expr e2) { super(e, e2, "<<"); } }
242     public class Shr  extends BitShiftExpr { public  Shr(Expr e, Expr e2) { super(e, e2, ">>"); } }
243     public class Ushr extends BitShiftExpr { public Ushr(Expr e, Expr e2) { super(e, e2, ">>>"); } }
244
245     // Other operations //////////////////////////////////////////////////////////////////////////////
246
247     public class Cast extends Expr {
248         final Expr e;
249         final Type t;
250         public Cast(Expr e, Type t) {
251             if(e.getType().isRef() != t.isRef()) throw new IllegalArgumentException("invalid cast");
252             // FEATURE: Check that one is a subclass of the other if it is a ref
253             this.e = e;
254             this.t = t; 
255         }
256         public Type getType() { return t; }
257     }
258
259     public class InstanceOf extends Expr {
260         final Expr e;
261         final Type.Ref t;
262         public InstanceOf(Expr e, Type.Ref t) {
263             if(!e.getType().isRef()) throw new IllegalArgumentException("can't do an instanceof check on a non-ref");
264             this.e = e; 
265             this.t = t; 
266         }
267         public Type getType() { return Type.BOOLEAN; }
268     }
269
270     public class Throw extends Op {
271         public final Expr e;
272         public Throw(Expr e) {
273             if(!e.getType().isRef()) throw new IllegalArgumentException("can't throw a non ref");
274             // FEATURE: CHeck that it is a subclass of Throwable
275             this.e = e; 
276         }
277     }
278
279     public class Branch extends Op {
280         public Branch(Expr condition, Object destination) { }
281         public Branch(Label destination) { }
282         public Branch(MethodGen.Switch s) { }
283         public Branch() { }
284     }
285     public class Goto extends Branch { }
286     public class RET extends Branch { }
287     public class JSR extends Branch { public JSR(Label l) { super(l); } }
288     public class If extends Branch { }
289
290     /** represents a "returnaddr" pushed onto the stack */
291     public class Label extends Expr {
292         public final Op op;
293         public Type getType() { throw new Error("attempted to call getType() on a Label"); }
294         public Label(Op op) { this.op = op; }
295         public Label(int i) { this.op = null; /* FIXME */ }
296     }
297
298     public class New extends Expr {
299         public final Type.Class t;
300         public Type getType() { return t; }
301         public New(Type.Class t) { this.t = t; }
302     }
303     
304     public class NewArray extends Expr {
305         public final Type.Array t;
306         public final Expr[] dims;
307         public NewArray(Type.Array t, Expr[] dims) { this.t = t; this.dims = dims; }
308         public NewArray(Type.Array t, Expr dim) { this(t,new Expr[]{dim}); }
309         public Type getType() { return t; }
310     }
311     
312     public class Return extends Op {
313         final Expr e;
314         public Return() { this(VOID_EXPR); }
315         public Return(Expr e) { this.e = e; }
316         public String toString() { return e.getType() == Type.VOID ? "return" : ("return "+e.toString()); }
317     }
318
319     /** GETFIELD and GETSTATIC */
320     public class Get extends Expr {
321         final Type.Class.Field f;
322         final Expr e;
323         public Type getType() { return f.getType(); }
324         public Get(Type.Class.Field f) { this(f, null); }
325         public Get(Type.Class.Field f, Expr e) { this.f = f; this.e = e; }
326         public String toString() {
327             return
328                 (e!=null
329                  ? e+"."+f.name
330                  : f.getDeclaringClass() == JSSA.this.method.getDeclaringClass()
331                  ? f.name
332                  : f.toString());
333         }
334     }
335
336     /** PUTFIELD and PUTSTATIC */
337     public class Put extends Op {
338         final Type.Class.Field f;
339         final Expr v;
340         final Expr e;
341         public Put(Type.Class.Field f, Expr v) { this(f, v, null); }
342         public Put(Type.Class.Field f, Expr v, Expr e) { this.f = f; this.v = v; this.e = e; }
343         public String toString() {
344             return
345                 (e!=null
346                  ? e+"."+f.name
347                  : f.getDeclaringClass() == JSSA.this.method.getDeclaringClass()
348                  ? f.name
349                  : f.toString()) + " = " + v;
350         }
351     }
352
353     public class ArrayPut extends Op {
354         final Expr e, i, v;
355         public ArrayPut(Expr e, Expr i, Expr v) { this.e = e; this.i = i; this.v = v; }
356     }
357
358     public class ArrayGet extends Expr {
359         final Expr e, i;
360         public ArrayGet(Expr e, Expr i) { this.e = e; this.i = i; }
361         public Type getType() { return e.getType().asArray().getElementType(); }
362     }
363
364     public class ArrayLength extends Expr {
365         final Expr e;
366         public ArrayLength(Expr e) { this.e = e; }
367         public Type getType() { return Type.INT; }
368     }
369
370     public abstract class Invoke extends Expr {
371         public final Expr[] arguments;
372         public final Type.Class.Method method;
373         protected Invoke(Type.Class.Method m, Expr[] a) { this.arguments = a; this.method = m; } 
374
375         public Type getType() { return method.getReturnType(); }
376         protected void args(StringBuffer sb) {
377             sb.append("(");
378             for(int i=0; i<arguments.length; i++) {
379                 if (i>0) sb.append(", ");
380                 sb.append(arguments[i]+"");
381             }
382             sb.append(")");
383         }
384
385         public String toString() {
386             StringBuffer sb = new StringBuffer();
387             sb.append(method.getDeclaringClass() == JSSA.this.method.getDeclaringClass()
388                       ? method.name
389                       : (method.getDeclaringClass() + "." + method.name));
390             args(sb);
391             return sb.toString();
392         }
393     }
394     public class InvokeStatic    extends Invoke  { public InvokeStatic(Type.Class.Method m, Expr[] a) { super(m,a); } }
395     public class InvokeSpecial   extends InvokeVirtual {
396         public InvokeSpecial(Type.Class.Method m, Expr[] a, Expr e) { super(m,a,e); }
397         public String toString() {
398             StringBuffer sb = new StringBuffer();
399             sb.append(method.name.equals("<init>") ? "super" : method.name);
400             args(sb);
401             return sb.toString();
402         }
403     }
404     public class InvokeInterface extends InvokeVirtual{public InvokeInterface(Type.Class.Method m, Expr[] a, Expr e){super(m,a,e);}}
405     public class InvokeVirtual   extends Invoke  {
406         public final Expr instance;
407         public InvokeVirtual(Type.Class.Method m, Expr[] a, Expr e) { super(m, a); instance = e; }
408         public String toString() {
409             StringBuffer sb = new StringBuffer();
410             sb.append(method.name);
411             args(sb);
412             return sb.toString();
413         }
414     }
415
416     public class Constant extends Expr {
417         private final Object o;
418         public Constant(int i) { this(new Integer(i)); }
419         public Constant(Object o) { this.o = o; }
420         public String toString() { return o.toString(); }
421         public Type getType() {
422             if (o instanceof Byte) return Type.BYTE;
423             if (o instanceof Short) return Type.SHORT;
424             if (o instanceof Character) return Type.CHAR;
425             if (o instanceof Boolean) return Type.BOOLEAN;
426             if (o instanceof Long) return Type.LONG;
427             if (o instanceof Double) return Type.DOUBLE;
428             if (o instanceof Float) return Type.FLOAT;
429             if (o instanceof ConstantPool.Ent) throw new Error("unimplemented");
430             throw new Error("this should not happen");
431         }
432     }
433
434
435     // Implementation //////////////////////////////////////////////////////////////////////////////
436
437     private Object addOp(int op, Object arg) {
438         int i1 = 0;
439         int i2 = 0;
440         if (op==WIDE) {
441             MethodGen.Wide w = (MethodGen.Wide)arg;
442             op = w.op;
443             arg = null;
444             i1 = w.varNum;
445             i2 = w.n;
446         }
447         if (op==IINC) {
448             MethodGen.Pair p = (MethodGen.Pair)arg;
449             arg = null;
450             i1 = p.i1;
451             i2 = p.i2;
452         }
453         switch(op) {
454
455             case NOP: return null;
456
457                 // Stack manipulations //////////////////////////////////////////////////////////////////////////////
458
459             case ACONST_NULL:                                                      return stack[sp++] = new Constant(null);
460             case ICONST_M1:                                                        return stack[sp++] = new Constant(-1);
461             case ICONST_0: case LCONST_0: case FCONST_0: case DCONST_0:            push(new Constant(0)); return null;
462             case ICONST_1: case LCONST_1: case FCONST_1: case DCONST_1:            push(new Constant(1)); return null;
463             case ICONST_2: case FCONST_2:                                          push(new Constant(2)); return null;
464             case ICONST_3:                                                         push(new Constant(3)); return null;
465             case ICONST_4:                                                         push(new Constant(4)); return null;
466             case ICONST_5:                                                         push(new Constant(5)); return null;
467             case ILOAD:    case LLOAD:    case FLOAD:    case DLOAD:    case ALOAD:    return push(local[i1]);
468             case ILOAD_0:  case LLOAD_0:  case FLOAD_0:  case DLOAD_0:  case ALOAD_0:  return push(local[0]);
469             case ILOAD_1:  case LLOAD_1:  case FLOAD_1:  case DLOAD_1:  case ALOAD_1:  return push(local[1]);
470             case ALOAD_2:  case DLOAD_2:  case FLOAD_2:  case LLOAD_2:  case ILOAD_2:  return push(local[2]);
471             case ILOAD_3:  case LLOAD_3:  case FLOAD_3:  case DLOAD_3:  case ALOAD_3:  return push(local[3]);
472             case ISTORE:   case LSTORE:   case FSTORE:   case DSTORE:   case ASTORE:   local[i1] = pop(); return null;
473             case ISTORE_0: case LSTORE_0: case FSTORE_0: case DSTORE_0: case ASTORE_0: local[0]  = pop(); return null;
474             case ISTORE_1: case LSTORE_1: case FSTORE_1: case DSTORE_1: case ASTORE_1: local[1]  = pop(); return null;
475             case ASTORE_2: case DSTORE_2: case FSTORE_2: case LSTORE_2: case ISTORE_2: local[2]  = pop(); return null;
476             case ISTORE_3: case LSTORE_3: case FSTORE_3: case DSTORE_3: case ASTORE_3: local[3]  = pop(); return null;
477             case POP:      stack[--sp] = null;                    
478             case POP2:     stack[--sp] = null; stack[--sp] = null;   /** fixme: pops a WORD, not an item */
479             case DUP:      stack[sp] = stack[sp-1]; sp++;
480             case DUP2:     stack[sp] = stack[sp-2]; stack[sp+1] = stack[sp-1]; sp+=2;
481
482                 // Conversions //////////////////////////////////////////////////////////////////////////////
483
484                 // coercions are added as-needed when converting from JSSA back to bytecode, so we can
485                 // simply discard them here (assuming the bytecode we're reading in was valid in the first place)
486
487             case I2L: case F2L: case D2L:               push(new Cast(pop(), Type.LONG)); return null;
488             case I2F: case L2F: case D2F:               push(new Cast(pop(), Type.FLOAT)); return null;
489             case I2D: case L2D: case F2D:               push(new Cast(pop(), Type.DOUBLE)); return null;
490             case L2I: case F2I: case D2I:               push(new Cast(pop(), Type.INT)); return null;
491             case I2B:                                   push(new Cast(pop(), Type.BYTE)); return null;
492             case I2C:                                   push(new Cast(pop(), Type.CHAR)); return null;
493             case I2S:                                   push(new Cast(pop(), Type.SHORT)); return null;
494             case SWAP:                                  { Expr e1 = pop(), e2 = pop(); push(e2);  push(e1); return null; }
495
496                 // Math //////////////////////////////////////////////////////////////////////////////
497                    
498             case IADD: case LADD: case FADD: case DADD: push(new Add(pop(), pop())); return null;
499             case ISUB: case LSUB: case FSUB: case DSUB: push(new Sub(pop(), pop())); return null;
500             case IMUL: case LMUL: case FMUL: case DMUL: push(new Mul(pop(), pop())); return null;
501             case IREM: case LREM: case FREM: case DREM: push(new Rem(pop(), pop())); return null;
502                 //case INEG: case LNEG: case FNEG: case DNEG: push(new Neg(pop())); return null;
503             case IDIV: case LDIV: case FDIV: case DDIV: push(new Div(pop(), pop())); return null;
504             case ISHL: case LSHL:                       push(new Shl(pop(), pop())); return null;
505             case ISHR: case LSHR:                       push(new Shr(pop(), pop())); return null;
506             case IUSHR: case LUSHR:                     push(new Ushr(pop(), pop())); return null;
507             case IAND: case LAND:                       push(new And(pop(), pop())); return null;
508             case IOR:  case LOR:                        push(new Or(pop(), pop())); return null;
509             case IXOR: case LXOR:                       push(new Xor(pop(), pop())); return null;
510             case IINC:                                  return local[i1] = new Add(local[i1], new Constant(i2));
511
512                 // Control and branching //////////////////////////////////////////////////////////////////////////////
513
514             case IFNULL:                                return new Branch(new Eq(pop(), new Constant(null)), new Label(i1));
515             case IFNONNULL:                             return new Branch(new Not(new Eq(pop(),new Constant(null))),new Label(i1));
516             case IFEQ:                                  return new Branch(    new Eq(new Constant(0), pop()),  arg);
517             case IFNE:                                  return new Branch(new Not(new Eq(new Constant(0), pop())), arg);
518             case IFLT:                                  return new Branch(    new Lt(new Constant(0), pop()),  arg);
519             case IFGE:                                  return new Branch(new Not(new Lt(new Constant(0), pop())), arg);
520             case IFGT:                                  return new Branch(    new Gt(new Constant(0), pop()),  arg);
521             case IFLE:                                  return new Branch(new Not(new Gt(new Constant(0), pop())), arg);
522             case IF_ICMPEQ:                             return new Branch(    new Eq(pop(), pop()),  arg);
523             case IF_ICMPNE:                             return new Branch(new Not(new Eq(pop(), pop())), arg);
524             case IF_ICMPLT:                             return new Branch(    new Lt(pop(), pop()),  arg);
525             case IF_ICMPGE:                             return new Branch(new Not(new Lt(pop(), pop())), arg);
526             case IF_ICMPGT:                             return new Branch(    new Gt(pop(), pop()),  arg);
527             case IF_ICMPLE:                             return new Branch(new Not(new Gt(pop(), pop())), arg);
528             case IF_ACMPEQ:                             return new Branch(    new Eq(pop(), pop()),  arg);
529             case IF_ACMPNE:                             return new Branch(new Not(new Eq(pop(), pop())), arg);
530             case ATHROW:                                return new Throw(pop());
531             case GOTO:                                  return new Branch(new Label(i1));
532             case JSR:                                   return new JSR(new Label(i1));
533             case RET:                                   return new RET();
534             case RETURN:                                return new Return();
535             case IRETURN: case LRETURN: case FRETURN: case DRETURN: case ARETURN:
536                 return new Return(pop());
537
538                 // Array manipulations //////////////////////////////////////////////////////////////////////////////
539
540             case IALOAD:  case LALOAD:  case FALOAD:  case DALOAD:  case AALOAD:
541             case BALOAD:  case CALOAD:  case SALOAD:                                  push(new ArrayGet(pop(), pop())); return null;
542             case IASTORE: case LASTORE: case FASTORE: case DASTORE: case AASTORE:
543             case BASTORE: case CASTORE: case SASTORE:                                 return new ArrayPut(pop(), pop(), pop());
544
545                 // Invocation //////////////////////////////////////////////////////////////////////////////
546
547             case INVOKEVIRTUAL: case INVOKESPECIAL: case INVOKESTATIC: case INVOKEINTERFACE: {
548                 Type.Class.Method method = (Type.Class.Method)arg;
549                 Expr args[] = new Expr[method.getNumArgs()];
550                 for(int i=0; i<args.length; i++) args[args.length-i-1] = pop();
551                 switch(op) {
552                     case INVOKEVIRTUAL:   return push(new InvokeVirtual(method, args, pop()));
553                     case INVOKEINTERFACE: return push(new InvokeInterface(method, args, pop()));
554                     case INVOKESPECIAL:   return push(new InvokeSpecial(method, args, pop()));
555                     case INVOKESTATIC:    return push(new InvokeStatic(method, args));
556                 }
557             }
558
559                 // Field Access //////////////////////////////////////////////////////////////////////////////
560
561             case GETSTATIC:         push(new Get((Type.Class.Field)arg, null)); return null;
562             case PUTSTATIC:         return new Put((Type.Class.Field)arg, pop(), null);
563             case GETFIELD:          push(new Get((Type.Class.Field)arg, pop())); return null;
564             case PUTFIELD:          return new Put((Type.Class.Field)arg, pop(), pop());
565
566                 // Allocation //////////////////////////////////////////////////////////////////////////////
567
568             case NEW:               push(new New((Type.Class)arg)); return null;
569             case NEWARRAY: {
570                 Type base;
571                 switch(((Integer)arg).intValue()) {
572                     case 4: base = Type.BOOLEAN; break;
573                     case 5: base = Type.CHAR; break;
574                     case 6: base = Type.FLOAT; break;
575                     case 7: base = Type.DOUBLE; break;
576                     case 8: base = Type.BYTE; break;
577                     case 9: base = Type.SHORT; break;
578                     case 10: base = Type.INT; break;
579                     case 11: base = Type.LONG; break;
580                     default: throw new IllegalStateException("invalid array type");
581                 }
582                 push(new NewArray(base.makeArray(),pop()));
583                 return null;
584             }
585             case ANEWARRAY:         push(new NewArray(((Type.Ref)arg).makeArray(), pop())); return null;
586             case MULTIANEWARRAY: {
587                 MethodGen.MultiANewArray mana = (MethodGen.MultiANewArray) arg;
588                 Expr[] dims = new Expr[mana.dims];
589                 for(int i=0;i<dims.length;i++) dims[i] = pop();
590                 push(new NewArray(mana.type, dims));
591                 return null;
592             }
593             case ARRAYLENGTH:       push(new ArrayLength(pop())); return null;
594
595                 // Runtime Type information //////////////////////////////////////////////////////////////////////////////
596
597             case CHECKCAST:         push(new Cast(pop(), (Type.Ref)arg)); return null;
598             case INSTANCEOF:        push(new InstanceOf(pop(), (Type.Ref)arg)); return null;
599
600             case LDC: case LDC_W: case LDC2_W: push(new Constant(arg)); return null;
601
602             case BIPUSH:    push(new Constant(i1));  // FIXME return null;
603             case SIPUSH:    push(new Constant(i1));  // FIXME return null;
604
605             case TABLESWITCH:    new Branch((MethodGen.Switch)arg);
606             case LOOKUPSWITCH:   new Branch((MethodGen.Switch)arg);
607
608                 /*
609             case MONITORENTER:   Op.monitorEnter(pop());
610             case MONITOREXIT:    Op.monitorExit(pop());
611                 */
612
613             case DUP_X1:         throw new Error("unimplemented");
614             case DUP_X2:         throw new Error("unimplemented");
615             case DUP2_X1:         throw new Error("unimplemented");
616             case DUP2_X2:         throw new Error("unimplemented");
617             case LCMP:         throw new Error("unimplemented");
618             case FCMPL:         throw new Error("unimplemented");
619             case FCMPG:         throw new Error("unimplemented");
620             case DCMPL:         throw new Error("unimplemented");
621             case DCMPG:         throw new Error("unimplemented");
622             case GOTO_W:         throw new Error("unimplemented");
623             case JSR_W:         throw new Error("unimplemented");
624             default:          throw new Error("unhandled");
625         }
626     }
627
628     public static void main(String[] args) throws Exception {
629         InputStream is = Class.forName(args[0]).getClassLoader().getResourceAsStream(args[0].replace('.', '/')+".class");
630         System.out.println(new ClassFile(new DataInputStream(is), true).toString());
631     }
632 }