1 package org.ibex.nestedvm;
4 import org.ibex.nestedvm.util.*;
6 import org.apache.bcel.generic.*;
8 // FEATURE: Use BCEL to do peephole optimization
9 // FEATURE: Special mode to support single-precision only - regs are floats not ints
11 /* FEATURE: Span large binaries across several classfiles
12 * We should be able to do this with no performance penalty
13 * Every method in the inner classes is static and takes the main class as an arg
14 * This makes them look just like methods in the main class because arg1 gets loaded into
18 /* FEATURE: smarter with local regs
19 * Be even smarter with the use of local registers. We need to only load fields into
20 * local regs when they are actually used and only write to fields if the regs could have
21 * changed. This should allow us to put more regs in local vars. Right now putting all used
22 * regs local vars makes code like this slower.
24 * void work(int a, int b) {
31 * Because all the regs used in "real work" are loaded/restored even for fast path
35 public class ClassFileCompiler extends Compiler implements org.apache.bcel.Constants {
36 /** The stream to write the compiled output to */
37 private OutputStream os;
38 private PrintStream warn = System.err;
41 private ConstantPoolGen cp;
42 private InstructionList clinitExtras = new InstructionList();
43 private InstructionList initExtras = new InstructionList();
44 private InstructionFactory fac;
46 // Handy wrappers around the BCEL functions
47 private InstructionList insnList;
48 private void selectMethod(MethodGen m) { insnList = m.getInstructionList(); }
49 private void selectList(InstructionList l) { insnList = l; }
50 private InstructionHandle a(Instruction i) { return insnList.append(i); }
51 private BranchHandle a(BranchInstruction i) { return insnList.append(i); }
52 private InstructionHandle a(InstructionList l) { return insnList.append(l); }
53 private InstructionHandle a(CompoundInstruction c) { return insnList.append(c); }
55 // This works around a bug in InstructionList
56 // FEATURE: fix this in bcel, send them a patch, etc
57 private static class FixedInstructionList extends InstructionList {
58 public void move(InstructionHandle start, InstructionHandle end, InstructionHandle target) {
59 InstructionHandle extra = target != null && target == getEnd() ? append(InstructionConstants.NOP) : null;
60 super.move(start,end,target);
61 if(extra != null) try { delete(extra); } catch (TargetLostException e) { /* won't happen */ }
65 private MethodGen newMethod(int flags, Type ret, Type[] args, String name) {
66 return new MethodGen(flags,ret,args,null,name,fullClassName,new FixedInstructionList(),cp);
69 public ClassFileCompiler(String path, String className, OutputStream os) throws IOException { this(new Seekable.File(path),className,os); }
70 public ClassFileCompiler(Seekable binary, String className, OutputStream os) throws IOException {
71 super(binary,className);
75 public void setWarnWriter(PrintStream warn) { this.warn = warn; }
77 protected void _go() throws Exn, IOException {
78 if(lessConstants) throw new Exn("ClassFileCompiler doesn't support -o lessconstants");
79 if(!pruneCases) throw new Exn("-o prunecases MUST be enabled for ClassFileCompiler");
82 cl = new ClassGen(fullClassName,runtimeClass,source,ACC_SUPER|ACC_PUBLIC|ACC_FINAL,null);
83 cp = cl.getConstantPool();
84 fac = new InstructionFactory(cl,cp);
87 cl.addField(new FieldGen(ACC_PRIVATE,Type.INT,"pc",cp).getField());
89 cl.addField(new FieldGen(ACC_PRIVATE,Type.INT,"r"+i,cp).getField());
91 cl.addField(new FieldGen(ACC_PRIVATE,Type.INT,"f"+i,cp).getField());
93 cl.addField(new FieldGen(ACC_PRIVATE,Type.INT,"hi",cp).getField());
94 cl.addField(new FieldGen(ACC_PRIVATE,Type.INT,"lo",cp).getField());
95 cl.addField(new FieldGen(ACC_PRIVATE,Type.INT,"fcsr",cp).getField());
98 cl.addField(new FieldGen(ACC_PRIVATE|ACC_FINAL,new ArrayType(Type.INT,1),"page",cp).getField());
100 selectList(initExtras);
101 a(InstructionConstants.ALOAD_0);
102 a(InstructionConstants.DUP);
103 a(fac.createFieldAccess(fullClassName,"readPages",new ArrayType(Type.INT, 2), GETFIELD));
105 a(InstructionConstants.AALOAD);
106 a(fac.createFieldAccess(fullClassName,"page",new ArrayType(Type.INT,1), PUTFIELD));
110 cl.addField(new FieldGen(ACC_PRIVATE|ACC_STATIC|ACC_FINAL,Type.getType("L"+hashClass.replace('.','/')+";"),"symbols",cp).getField());
114 for(int i=0;i<elf.sheaders.length;i++) {
115 ELF.SHeader sheader = elf.sheaders[i];
116 String name = sheader.name;
117 // if this section doesn't get loaded into our address space don't worry about it
118 if(sheader.addr == 0x0) continue;
120 highestAddr = Math.max(highestAddr, sheader.addr + sheader.size);
122 if(name.equals(".text"))
123 emitText(sheader.addr, new DataInputStream(sheader.getInputStream()),sheader.size);
124 else if(name.equals(".data") || name.equals(".sdata") || name.equals(".rodata") || name.equals(".ctors") || name.equals(".dtors"))
125 emitData(sheader.addr, new DataInputStream(sheader.getInputStream()), sheader.size,name.equals(".rodata"));
126 else if(name.equals(".bss") || name.equals(".sbss"))
127 emitBSS(sheader.addr,sheader.size);
129 throw new Exn("Unknown segment: " + name);
132 ELF.SHeader text = elf.sectionWithName(".text");
135 MethodGen tramp = newMethod(ACC_PRIVATE,Type.VOID, Type.NO_ARGS, "trampoline");
136 tramp.addException("org.ibex.nestedvm.Runtime$ExecutionException");
139 InstructionHandle start = a(InstructionConstants.ALOAD_0);
140 a(fac.createFieldAccess(fullClassName,"state",Type.INT, GETFIELD));
141 pushConst(Runtime.RUNNING);
142 BranchInstruction stateCheck = InstructionFactory.createBranchInstruction(IF_ICMPNE,null);
144 a(InstructionConstants.ALOAD_0);
145 a(InstructionConstants.ALOAD_0);
146 a(fac.createFieldAccess(fullClassName,"pc",Type.INT, GETFIELD));
147 pushConst(methodShift);
148 a(InstructionConstants.IUSHR);
150 int beg = text.addr >>> methodShift;
151 int end = ((text.addr + text.size) >>> methodShift);
153 // This data is redundant but BCEL wants it
154 int[] matches = new int[end-beg+1];
155 for(int i=beg;i<=end;i++) matches[i-beg] = i;
156 TABLESWITCH ts = new TABLESWITCH(matches,new InstructionHandle[matches.length],null);
158 for(int n=beg;n<=end;n++){
159 InstructionHandle h = a(fac.createInvoke(fullClassName,"run_"+toHex(n<<methodShift),Type.VOID,Type.NO_ARGS,INVOKESPECIAL));
160 a(InstructionFactory.createBranchInstruction(GOTO,start));
161 ts.setTarget(n-beg,h);
164 ts.setTarget(a(InstructionConstants.POP)); // default case
165 a(fac.createNew("org.ibex.nestedvm.Runtime$ExecutionException"));
166 a(InstructionConstants.DUP);
167 a(fac.createNew("java.lang.StringBuffer"));
168 a(InstructionConstants.DUP);
169 a(new PUSH(cp,"Jumped to invalid address in trampoline (r2: "));
170 a(fac.createInvoke("java.lang.StringBuffer","<init>",Type.VOID,new Type[]{Type.STRING},INVOKESPECIAL));
171 a(InstructionConstants.ALOAD_0);
172 a(fac.createFieldAccess(fullClassName,"r2",Type.INT, GETFIELD));
173 a(fac.createInvoke("java.lang.StringBuffer","append",Type.STRINGBUFFER,new Type[]{Type.INT},INVOKEVIRTUAL));
174 a(new PUSH(cp," pc:"));
175 a(fac.createInvoke("java.lang.StringBuffer","append",Type.STRINGBUFFER,new Type[]{Type.STRING},INVOKEVIRTUAL));
176 a(InstructionConstants.ALOAD_0);
177 a(fac.createFieldAccess(fullClassName,"pc",Type.INT, GETFIELD));
178 a(fac.createInvoke("java.lang.StringBuffer","append",Type.STRINGBUFFER,new Type[]{Type.INT},INVOKEVIRTUAL));
180 a(fac.createInvoke("java.lang.StringBuffer","append",Type.STRINGBUFFER,new Type[]{Type.CHAR},INVOKEVIRTUAL));
181 a(fac.createInvoke("java.lang.StringBuffer","toString",Type.STRING,Type.NO_ARGS,INVOKEVIRTUAL));
182 a(fac.createInvoke("org.ibex.nestedvm.Runtime$ExecutionException","<init>",Type.VOID,new Type[]{Type.STRING},INVOKESPECIAL));
183 a(InstructionConstants.ATHROW);
185 stateCheck.setTarget(a(InstructionConstants.RETURN));
188 tramp.setMaxLocals();
190 cl.addMethod(tramp.getMethod());
191 } catch(ClassGenException e) {
192 e.printStackTrace(warn);
193 throw new Exn("Generation of the trampoline method failed. Try increasing maxInsnPerMethod");
196 addConstReturnMethod("gp",gp.addr);
197 addConstReturnMethod("entryPoint",elf.header.entry);
198 addConstReturnMethod("heapStart",highestAddr);
200 if(userInfo != null) {
201 addConstReturnMethod("userInfoBase",userInfo.addr);
202 addConstReturnMethod("userInfoSize",userInfo.size);
205 // FEATURE: Allow specification of memory size at runtime (numpages)
207 MethodGen init = newMethod(ACC_PUBLIC,Type.VOID, Type.NO_ARGS, "<init>");
209 a(InstructionConstants.ALOAD_0);
211 pushConst(totalPages);
212 a(fac.createInvoke(runtimeClass,"<init>",Type.VOID,new Type[]{Type.INT,Type.INT},INVOKESPECIAL));
216 a(InstructionConstants.RETURN);
220 cl.addMethod(init.getMethod());
223 MethodGen clinit = newMethod(ACC_PRIVATE|ACC_STATIC,Type.VOID, Type.NO_ARGS, "<clinit>");
224 selectMethod(clinit);
228 a(fac.createNew(hashClass));
229 a(InstructionConstants.DUP);
230 a(InstructionConstants.DUP);
231 a(fac.createInvoke(hashClass,"<init>",Type.VOID,Type.NO_ARGS,INVOKESPECIAL));
232 a(fac.createFieldAccess(fullClassName,"symbols",Type.getType("L"+hashClass.replace('.','/')+";"), PUTSTATIC));
233 ELF.Symbol[] symbols = elf.getSymtab().symbols;
234 for(int i=0;i<symbols.length;i++) {
235 ELF.Symbol s = symbols[i];
236 if(s.type == ELF.Symbol.STT_FUNC && s.binding == ELF.Symbol.STB_GLOBAL && (s.name.equals("_call_helper") || !s.name.startsWith("_"))) {
237 a(InstructionConstants.DUP);
238 a(new PUSH(cp,s.name));
239 a(fac.createNew("java.lang.Integer"));
240 a(InstructionConstants.DUP);
241 a(new PUSH(cp,s.addr));
242 a(fac.createInvoke("java.lang.Integer","<init>",Type.VOID,new Type[]{Type.INT},INVOKESPECIAL));
243 a(fac.createInvoke(hashClass,"put",Type.OBJECT,new Type[]{Type.OBJECT,Type.OBJECT},INVOKEVIRTUAL));
244 a(InstructionConstants.POP);
247 a(InstructionConstants.POP);
250 a(InstructionConstants.RETURN);
251 clinit.setMaxLocals();
252 clinit.setMaxStack();
253 cl.addMethod(clinit.getMethod());
256 MethodGen lookupSymbol = newMethod(ACC_PROTECTED,Type.INT,new Type[]{Type.STRING},"lookupSymbol");
257 selectMethod(lookupSymbol);
258 a(fac.createFieldAccess(fullClassName,"symbols",Type.getType("L"+hashClass.replace('.','/')+";"), GETSTATIC));
259 a(InstructionConstants.ALOAD_1);
260 a(fac.createInvoke(hashClass,"get",Type.OBJECT,new Type[]{Type.OBJECT},INVOKEVIRTUAL));
261 a(InstructionConstants.DUP);
262 BranchHandle bh = a(InstructionFactory.createBranchInstruction(IFNULL,null));
263 a(fac.createCheckCast(new ObjectType("java.lang.Integer")));
264 a(fac.createInvoke("java.lang.Integer","intValue",Type.INT,Type.NO_ARGS,INVOKEVIRTUAL));
265 a(InstructionConstants.IRETURN);
266 bh.setTarget(a(InstructionConstants.ICONST_M1));
267 a(InstructionConstants.IRETURN);
268 lookupSymbol.setMaxLocals();
269 lookupSymbol.setMaxStack();
270 cl.addMethod(lookupSymbol.getMethod());
273 MethodGen setCPUState = newMethod(ACC_PROTECTED,Type.VOID,new Type[]{Type.getType("Lorg/ibex/nestedvm/Runtime$CPUState;")},"setCPUState");
274 selectMethod(setCPUState);
275 a(InstructionConstants.ALOAD_1);
276 a(fac.createFieldAccess("org.ibex.nestedvm.Runtime$CPUState","r",new ArrayType(Type.INT,1),GETFIELD));
277 a(InstructionConstants.ASTORE_2);
278 for(int i=1;i<32;i++) {
279 a(InstructionConstants.ALOAD_0);
280 a(InstructionConstants.ALOAD_2);
282 a(InstructionConstants.IALOAD);
283 a(fac.createFieldAccess(fullClassName,"r"+i,Type.INT, PUTFIELD));
285 a(InstructionConstants.ALOAD_1);
286 a(fac.createFieldAccess("org.ibex.nestedvm.Runtime$CPUState","f",new ArrayType(Type.INT,1),GETFIELD));
287 a(InstructionConstants.ASTORE_2);
288 for(int i=0;i<32;i++) {
289 a(InstructionConstants.ALOAD_0);
290 a(InstructionConstants.ALOAD_2);
292 a(InstructionConstants.IALOAD);
293 a(fac.createFieldAccess(fullClassName,"f"+i,Type.INT, PUTFIELD));
295 a(InstructionConstants.ALOAD_0);
296 a(InstructionConstants.ALOAD_1);
297 a(fac.createFieldAccess("org.ibex.nestedvm.Runtime$CPUState","hi",Type.INT,GETFIELD));
298 a(fac.createFieldAccess(fullClassName,"hi",Type.INT, PUTFIELD));
299 a(InstructionConstants.ALOAD_0);
300 a(InstructionConstants.ALOAD_1);
301 a(fac.createFieldAccess("org.ibex.nestedvm.Runtime$CPUState","lo",Type.INT,GETFIELD));
302 a(fac.createFieldAccess(fullClassName,"lo",Type.INT, PUTFIELD));
303 a(InstructionConstants.ALOAD_0);
304 a(InstructionConstants.ALOAD_1);
305 a(fac.createFieldAccess("org.ibex.nestedvm.Runtime$CPUState","fcsr",Type.INT,GETFIELD));
306 a(fac.createFieldAccess(fullClassName,"fcsr",Type.INT, PUTFIELD));
307 a(InstructionConstants.ALOAD_0);
308 a(InstructionConstants.ALOAD_1);
309 a(fac.createFieldAccess("org.ibex.nestedvm.Runtime$CPUState","pc",Type.INT,GETFIELD));
310 a(fac.createFieldAccess(fullClassName,"pc",Type.INT, PUTFIELD));
312 a(InstructionConstants.RETURN);
313 setCPUState.setMaxLocals();
314 setCPUState.setMaxStack();
315 cl.addMethod(setCPUState.getMethod());
317 MethodGen getCPUState = newMethod(ACC_PROTECTED,Type.VOID,new Type[]{Type.getType("Lorg/ibex/nestedvm/Runtime$CPUState;")},"getCPUState");
318 selectMethod(getCPUState);
319 a(InstructionConstants.ALOAD_1);
320 a(fac.createFieldAccess("org.ibex.nestedvm.Runtime$CPUState","r",new ArrayType(Type.INT,1),GETFIELD));
321 a(InstructionConstants.ASTORE_2);
322 for(int i=1;i<32;i++) {
323 a(InstructionConstants.ALOAD_2);
325 a(InstructionConstants.ALOAD_0);
326 a(fac.createFieldAccess(fullClassName,"r"+i,Type.INT, GETFIELD));
327 a(InstructionConstants.IASTORE);
330 a(InstructionConstants.ALOAD_1);
331 a(fac.createFieldAccess("org.ibex.nestedvm.Runtime$CPUState","f",new ArrayType(Type.INT,1),GETFIELD));
332 a(InstructionConstants.ASTORE_2);
333 for(int i=0;i<32;i++) {
334 a(InstructionConstants.ALOAD_2);
336 a(InstructionConstants.ALOAD_0);
337 a(fac.createFieldAccess(fullClassName,"f"+i,Type.INT, GETFIELD));
338 a(InstructionConstants.IASTORE);
340 a(InstructionConstants.ALOAD_1);
341 a(InstructionConstants.ALOAD_0);
342 a(fac.createFieldAccess(fullClassName,"hi",Type.INT, GETFIELD));
343 a(fac.createFieldAccess("org.ibex.nestedvm.Runtime$CPUState","hi",Type.INT,PUTFIELD));
344 a(InstructionConstants.ALOAD_1);
345 a(InstructionConstants.ALOAD_0);
346 a(fac.createFieldAccess(fullClassName,"lo",Type.INT, GETFIELD));
347 a(fac.createFieldAccess("org.ibex.nestedvm.Runtime$CPUState","lo",Type.INT,PUTFIELD));
348 a(InstructionConstants.ALOAD_1);
349 a(InstructionConstants.ALOAD_0);
350 a(fac.createFieldAccess(fullClassName,"fcsr",Type.INT, GETFIELD));
351 a(fac.createFieldAccess("org.ibex.nestedvm.Runtime$CPUState","fcsr",Type.INT,PUTFIELD));
352 a(InstructionConstants.ALOAD_1);
353 a(InstructionConstants.ALOAD_0);
354 a(fac.createFieldAccess(fullClassName,"pc",Type.INT, GETFIELD));
355 a(fac.createFieldAccess("org.ibex.nestedvm.Runtime$CPUState","pc",Type.INT,PUTFIELD));
357 a(InstructionConstants.RETURN);
358 getCPUState.setMaxLocals();
359 getCPUState.setMaxStack();
360 cl.addMethod(getCPUState.getMethod());
363 MethodGen execute = newMethod(ACC_PROTECTED,Type.VOID,Type.NO_ARGS,"_execute");
364 selectMethod(execute);
365 InstructionHandle tryStart = a(InstructionConstants.ALOAD_0);
366 InstructionHandle tryEnd = a(fac.createInvoke(fullClassName,"trampoline",Type.VOID,Type.NO_ARGS,INVOKESPECIAL));
367 a(InstructionConstants.RETURN);
369 InstructionHandle catchInsn = a(InstructionConstants.ASTORE_1);
370 a(fac.createNew("org.ibex.nestedvm.Runtime$FaultException"));
371 a(InstructionConstants.DUP);
372 a(InstructionConstants.ALOAD_1);
373 a(fac.createInvoke("org.ibex.nestedvm.Runtime$FaultException","<init>",Type.VOID,new Type[]{new ObjectType("java.lang.RuntimeException")},INVOKESPECIAL));
374 a(InstructionConstants.ATHROW);
376 execute.addExceptionHandler(tryStart,tryEnd,catchInsn,new ObjectType("java.lang.RuntimeException"));
377 execute.setMaxLocals();
378 execute.setMaxStack();
379 cl.addMethod(execute.getMethod());
382 MethodGen main = newMethod(ACC_STATIC|ACC_PUBLIC,Type.VOID,new Type[]{new ArrayType(Type.STRING,1)},"main");
384 a(fac.createNew(fullClassName));
385 a(InstructionConstants.DUP);
386 a(fac.createInvoke(fullClassName,"<init>",Type.VOID,Type.NO_ARGS,INVOKESPECIAL));
387 a(new PUSH(cp,fullClassName));
388 a(InstructionConstants.ALOAD_0);
390 a(fac.createInvoke("org.ibex.nestedvm.UnixRuntime","runAndExec",Type.INT,
391 new Type[]{Type.getType("Lorg/ibex/nestedvm/UnixRuntime;"),Type.STRING,new ArrayType(Type.STRING,1)},
394 a(fac.createInvoke(fullClassName,"run",Type.INT,new Type[]{Type.STRING,new ArrayType(Type.STRING,1)},INVOKEVIRTUAL));
395 a(fac.createInvoke("java.lang.System","exit",Type.VOID,new Type[]{Type.INT},INVOKESTATIC));
396 a(InstructionConstants.RETURN);
399 cl.addMethod(main.getMethod());
402 System.out.println("Constant Pool Size: " + cp.getSize());
403 cl.getJavaClass().dump(os);
406 private void addConstReturnMethod(String name, int val) {
407 MethodGen method = newMethod(ACC_PROTECTED,Type.INT, Type.NO_ARGS,name);
408 selectMethod(method);
410 a(InstructionConstants.IRETURN);
411 method.setMaxLocals();
412 method.setMaxStack();
413 cl.addMethod(method.getMethod());
416 private static int initDataCount;
417 private void emitData(int addr, DataInputStream dis, int size, boolean readOnly) throws Exn,IOException {
418 if((addr&3)!=0 || (size&3)!=0) throw new Exn("Data section on weird boundaries");
419 int last = addr + size;
421 int segSize = Math.min(size,28000); // must be a multiple of 56
422 StringBuffer sb = new StringBuffer();
423 for(int i=0;i<segSize;i+=7) {
425 for(int j=0;j<7;j++) {
427 byte b = (i+j < size) ? dis.readByte() : 1;
431 sb.append((char) ((l>>>(7*(7-j)))&0x7f));
433 String fieldname = "_data" + (++initDataCount);
434 cl.addField(new FieldGen(ACC_PRIVATE|ACC_STATIC|ACC_FINAL,new ArrayType(Type.INT,1),fieldname,cp).getField());
436 selectList(clinitExtras);
437 a(new PUSH(cp,sb.toString()));
438 a(new PUSH(cp,segSize/4));
439 a(fac.createInvoke("org.ibex.nestedvm.Runtime","decodeData",new ArrayType(Type.INT,1),new Type[]{Type.STRING,Type.INT},INVOKESTATIC));
440 a(fac.createPutStatic(fullClassName,fieldname,new ArrayType(Type.INT,1)));
442 selectList(initExtras);
443 a(InstructionConstants.ALOAD_0);
444 a(fac.createGetStatic(fullClassName,fieldname,new ArrayType(Type.INT,1)));
445 a(new PUSH(cp,addr));
446 a(new PUSH(cp,readOnly));
447 a(fac.createInvoke(fullClassName,"initPages",Type.VOID,new Type[]{new ArrayType(Type.INT,1),Type.INT,Type.BOOLEAN},INVOKEVIRTUAL));
455 private void emitBSS(int addr, int size) throws Exn {
456 if((addr&3)!=0) throw new Exn("BSS section on weird boundaries");
459 selectList(initExtras);
460 a(InstructionConstants.ALOAD_0);
461 a(new PUSH(cp,addr));
462 a(new PUSH(cp,count));
463 a(fac.createInvoke(fullClassName,"clearPages",Type.VOID,new Type[]{Type.INT,Type.INT},INVOKEVIRTUAL));
467 private boolean textDone;
468 private int startOfMethod = 0;
469 private int endOfMethod = 0;
470 private boolean unreachable = false;
471 private InstructionHandle[] jumpHandles;
472 private InstructionHandle defaultHandle;
473 private InstructionHandle returnHandle;
474 private InstructionHandle realStart;
475 private MethodGen curMethod;
477 private boolean jumpable(int addr) { return jumpableAddresses.contains(new Integer(addr)); }
479 private void emitText(int addr, DataInputStream dis, int size) throws Exn,IOException {
480 if(textDone) throw new Exn("Multiple text segments");
483 if((addr&3)!=0 || (size&3)!=0) throw new Exn("Section on weird boundaries");
485 int insn,nextInsn=-1;
486 boolean skipNext = true;
488 for(int i=0;i<count;i++,addr+=4) {
489 insn = skipNext ? dis.readInt() : nextInsn;
490 nextInsn = (i == count-1) ? -1 : dis.readInt();
491 if(addr >= endOfMethod) { endMethod(addr); startMethod(addr); }
492 if(jumpHandles[(addr-startOfMethod)/4] != null) {
493 // Move the fake jump target to the current location
494 insnList.move(jumpHandles[(addr-startOfMethod)/4],insnList.getEnd());
496 } else if(unreachable) {
500 skipNext = emitInstruction(addr,insn,nextInsn);
501 } catch(RuntimeException e) {
502 warn.println("Exception at " + toHex(addr));
505 if(skipNext) { addr+=4; i++; }
511 private void startMethod(int first) {
512 startOfMethod = first & methodMask;
513 endOfMethod = startOfMethod + maxBytesPerMethod;
514 curMethod = newMethod(ACC_PRIVATE,Type.VOID,Type.NO_ARGS,"run_" + toHex(startOfMethod));
515 selectMethod(curMethod);
517 int[] buf = new int[maxBytesPerMethod/4];
518 jumpHandles = new InstructionHandle[maxBytesPerMethod/4];
520 for(int addr=first;addr<endOfMethod;addr+=4) {
523 // append NOPs for GOTO jumps (these will be moved to the correct location later)
524 jumpHandles[(addr-startOfMethod)/4] = a(InstructionConstants.NOP);
528 // append NOP for default case (throw exn) (this will be moved later)
529 defaultHandle = a(InstructionConstants.NOP);
530 returnHandle = a(InstructionConstants.NOP);
532 int[] matches = new int[n];
533 System.arraycopy(buf,0,matches,0,n);
534 InstructionHandle[] targets = new InstructionHandle[n];
535 for(int i=0;i<matches.length;i++)
536 targets[i] = jumpHandles[(matches[i]-startOfMethod)/4];
539 // First instruction of the actual method - everything above this should be removed
540 // before we get to the end
541 realStart = a(InstructionConstants.NOP);
544 a(InstructionConstants.ALOAD_0);
545 a(fac.createFieldAccess(fullClassName,"page",new ArrayType(Type.INT,1), GETFIELD));
546 a(InstructionConstants.ASTORE_2);
548 a(InstructionConstants.ALOAD_0);
549 a(fac.createFieldAccess(fullClassName,"readPages",new ArrayType(Type.INT,2), GETFIELD));
550 a(InstructionConstants.ASTORE_2);
551 a(InstructionConstants.ALOAD_0);
552 a(fac.createFieldAccess(fullClassName,"writePages",new ArrayType(Type.INT,2), GETFIELD));
553 a(InstructionFactory.createStore(Type.OBJECT,3));
556 LOOKUPSWITCH initialSwitch = new LOOKUPSWITCH(matches,targets,defaultHandle);
557 a(InstructionConstants.ALOAD_0);
558 a(fac.createFieldAccess(fullClassName,"pc",Type.INT, GETFIELD));
562 private void endMethod(int firstAddrOfNext) {
563 if(startOfMethod == 0) return;
567 pushConst(firstAddrOfNext);
569 // mark the start of the next method as jumpable
570 jumpableAddresses.add(new Integer(firstAddrOfNext));
573 insnList.move(returnHandle,insnList.getEnd());
575 a(InstructionConstants.RETURN);
577 // move the default jump target (lookupswitch) to before the throw
578 insnList.move(defaultHandle,insnList.getEnd());
580 a(fac.createNew("org.ibex.nestedvm.Runtime$ExecutionException"));
581 a(InstructionConstants.DUP);
582 a(fac.createNew("java.lang.StringBuffer"));
583 a(InstructionConstants.DUP);
584 a(new PUSH(cp,"Jumped to invalid address: "));
585 a(fac.createInvoke("java.lang.StringBuffer","<init>",Type.VOID,new Type[]{Type.STRING},INVOKESPECIAL));
586 a(InstructionConstants.ALOAD_0);
587 a(fac.createFieldAccess(fullClassName,"pc",Type.INT, GETFIELD));
588 a(fac.createInvoke("java.lang.StringBuffer","append",Type.STRINGBUFFER,new Type[]{Type.INT},INVOKEVIRTUAL));
589 a(fac.createInvoke("java.lang.StringBuffer","toString",Type.STRING,Type.NO_ARGS,INVOKEVIRTUAL));
590 a(fac.createInvoke("org.ibex.nestedvm.Runtime$ExecutionException","<init>",Type.VOID,new Type[]{Type.STRING},INVOKESPECIAL));
591 a(InstructionConstants.ATHROW);
593 a(fac.createNew("org.ibex.nestedvm.Runtime$ExecutionException"));
594 a(InstructionConstants.DUP);
595 a(new PUSH(cp,"Jumped to invalid address"));
596 a(fac.createInvoke("org.ibex.nestedvm.Runtime$ExecutionException","<init>",Type.VOID,new Type[]{Type.STRING},INVOKESPECIAL));
597 a(InstructionConstants.ATHROW);
600 if(insnList.getStart() != realStart) {
601 System.err.println(insnList);
602 throw new Error("A jumpHandle wasn't moved into place");
605 curMethod.removeNOPs();
606 curMethod.setMaxLocals();
607 curMethod.setMaxStack();
609 cl.addMethod(curMethod.getMethod());
611 endOfMethod = startOfMethod = 0;
615 private void leaveMethod() {
616 a(InstructionFactory.createBranchInstruction(GOTO,returnHandle));
619 private void branch(int pc, int target) {
620 if((pc&methodMask) == (target&methodMask)) {
621 a(InstructionFactory.createBranchInstruction(GOTO,jumpHandles[(target-startOfMethod)/4]));
630 // This assumes everything needed by ifInsn is already on the stack
631 private boolean doIfInstruction(short op, int pc, int target, int nextInsn) throws Exn {
632 emitInstruction(-1,nextInsn,-1); // delay slot
634 IfInstruction ifInsn = (IfInstruction) InstructionFactory.createBranchInstruction(op,null);
635 if((target&methodMask) == (pc&methodMask)) {
637 h.setTarget(jumpHandles[(target-startOfMethod)/4]);
639 h = a(ifInsn.negate());
641 h.setTarget(a(InstructionConstants.NOP));
643 if(!jumpable(pc+4)) return true; // done - skip it
645 //System.err.println("Delay slot is jumpable - This code is untested + " + toHex(nextInsn));
646 if(pc+4==endOfMethod) {
647 // the delay slot is at the start of the next method
648 jumpableAddresses.add(new Integer(pc+8)); // make the 2nd insn of the next method jumpable
649 branch(pc,pc+8); // jump over it
650 //System.err.println("delay slot: " + toHex(pc+8));
652 return false; // we still need to output it
654 //System.err.println("jumped over delay slot: " + toHex(pc+4));
655 // add another copy and jump over
656 h = a(InstructionFactory.createBranchInstruction(GOTO,null));
657 insnList.move(jumpHandles[(pc+4-startOfMethod)/4],insnList.getEnd());
658 emitInstruction(-1,nextInsn,-1); // delay slot
659 h.setTarget(a(InstructionConstants.NOP));
664 private boolean emitInstruction(int pc, int insn, int nextInsn) throws Exn {
665 if(insn == -1) throw new Exn("insn is -1");
667 int op = (insn >>> 26) & 0xff; // bits 26-31
668 int rs = (insn >>> 21) & 0x1f; // bits 21-25
669 int rt = (insn >>> 16) & 0x1f; // bits 16-20
670 int ft = (insn >>> 16) & 0x1f;
671 int rd = (insn >>> 11) & 0x1f; // bits 11-15
672 int fs = (insn >>> 11) & 0x1f;
673 int shamt = (insn >>> 6) & 0x1f; // bits 6-10
674 int fd = (insn >>> 6) & 0x1f;
675 int subcode = insn & 0x3f; // bits 0-5
676 int breakCode = (insn >>> 6) & 0xfffff; // bits 6-20
678 int jumpTarget = (insn & 0x03ffffff); // bits 0-25
679 int unsignedImmediate = insn & 0xffff;
680 int signedImmediate = (insn << 16) >> 16;
681 int branchTarget = signedImmediate;
694 a(InstructionConstants.ISHL);
701 a(InstructionConstants.IUSHR);
708 a(InstructionConstants.ISHR);
715 a(InstructionConstants.ISHL);
722 a(InstructionConstants.IUSHR);
729 a(InstructionConstants.ISHR);
733 if(pc == -1) throw new Exn("pc modifying insn in delay slot");
734 emitInstruction(-1,nextInsn,-1);
742 if(pc == -1) throw new Exn("pc modifying insn in delay slot");
743 emitInstruction(-1,nextInsn,-1);
759 restoreChangedRegs();
762 a(InstructionConstants.ALOAD_0);
768 a(fac.createInvoke(fullClassName,"syscall",Type.INT,new Type[]{Type.INT,Type.INT,Type.INT,Type.INT,Type.INT},INVOKEVIRTUAL));
771 a(InstructionConstants.ALOAD_0);
772 a(fac.createFieldAccess(fullClassName,"state",Type.INT, GETFIELD));
773 pushConst(Runtime.RUNNING);
774 b1 = a(InstructionFactory.createBranchInstruction(IF_ICMPEQ,null));
779 b1.setTarget(a(InstructionConstants.NOP));
783 a(fac.createNew("org.ibex.nestedvm.Runtime$ExecutionException"));
784 a(InstructionConstants.DUP);
785 a(new PUSH(cp,"BREAK Code " + toHex(breakCode)));
786 a(fac.createInvoke("org.ibex.nestedvm.Runtime$ExecutionException","<init>",Type.VOID,new Type[]{Type.STRING},INVOKESPECIAL));
787 a(InstructionConstants.ATHROW);
812 a(InstructionConstants.I2L);
814 a(InstructionConstants.I2L);
815 a(InstructionConstants.LMUL);
816 a(InstructionConstants.DUP2);
818 a(InstructionConstants.L2I);
820 a(InstructionConstants.SWAP);
824 a(InstructionConstants.LUSHR);
825 a(InstructionConstants.L2I);
827 a(InstructionConstants.SWAP);
833 a(InstructionConstants.I2L);
834 pushConst(0xffffffffL);
835 a(InstructionConstants.LAND);
837 a(InstructionConstants.I2L);
838 pushConst(0xffffffffL);
839 a(InstructionConstants.LAND);
840 a(InstructionConstants.LMUL);
841 a(InstructionConstants.DUP2);
843 a(InstructionConstants.L2I);
845 a(InstructionConstants.SWAP);
849 a(InstructionConstants.LUSHR);
850 a(InstructionConstants.L2I);
852 a(InstructionConstants.SWAP);
859 a(InstructionConstants.DUP2);
861 a(InstructionConstants.IDIV);
863 a(InstructionConstants.SWAP);
866 a(InstructionConstants.IREM);
868 a(InstructionConstants.SWAP);
874 a(InstructionConstants.DUP);
876 b1 = a(InstructionFactory.createBranchInstruction(IFEQ,null));
879 a(InstructionConstants.I2L);
880 pushConst(0xffffffffL);
881 a(InstructionConstants.LAND);
882 a(InstructionConstants.DUP2);
884 a(InstructionConstants.I2L);
885 pushConst(0xffffffffL);
887 a(InstructionConstants.LAND);
888 a(InstructionConstants.DUP2_X2);
889 a(InstructionConstants.LDIV);
891 a(InstructionConstants.L2I);
893 a(InstructionConstants.SWAP);
896 a(InstructionConstants.LREM);
897 a(InstructionConstants.L2I);
899 a(InstructionConstants.SWAP);
902 b1.setTarget(a(InstructionConstants.NOP));
907 throw new Exn("ADD (add with oveflow trap) not suported");
910 if(rt != 0 && rs != 0) {
913 a(InstructionConstants.IADD);
922 throw new Exn("SUB (add with oveflow trap) not suported");
925 if(rt != 0 && rs != 0) {
928 a(InstructionConstants.ISUB);
931 a(InstructionConstants.INEG);
941 a(InstructionConstants.IAND);
948 a(InstructionConstants.IOR);
955 a(InstructionConstants.IXOR);
960 if(rs != 0 || rt != 0) {
961 if(rs != 0 && rt != 0) {
964 a(InstructionConstants.IOR);
970 a(InstructionConstants.ICONST_M1);
971 a(InstructionConstants.IXOR);
982 b1 = a(InstructionFactory.createBranchInstruction(IF_ICMPLT,null));
983 a(InstructionConstants.ICONST_0);
984 b2 = a(InstructionFactory.createBranchInstruction(GOTO,null));
985 b1.setTarget(a(InstructionConstants.ICONST_1));
986 b2.setTarget(a(InstructionConstants.NOP));
997 a(InstructionConstants.I2L);
998 pushConst(0xffffffffL);
999 a(InstructionConstants.LAND);
1001 a(InstructionConstants.I2L);
1002 pushConst(0xffffffffL);
1003 a(InstructionConstants.LAND);
1004 a(InstructionConstants.LCMP);
1005 b1 = a(InstructionFactory.createBranchInstruction(IFLT,null));
1008 b1 = a(InstructionFactory.createBranchInstruction(IFNE,null));
1010 a(InstructionConstants.ICONST_0);
1011 b2 = a(InstructionFactory.createBranchInstruction(GOTO,null));
1012 b1.setTarget(a(InstructionConstants.ICONST_1));
1013 b2.setTarget(a(InstructionConstants.NOP));
1020 throw new Exn("Illegal instruction 0/" + subcode);
1027 if(pc == -1) throw new Exn("pc modifying insn in delay slot");
1029 return doIfInstruction(IFLT,pc,pc+branchTarget*4+4,nextInsn);
1031 if(pc == -1) throw new Exn("pc modifying insn in delay slot");
1033 return doIfInstruction(IFGE,pc,pc+branchTarget*4+4,nextInsn);
1035 if(pc == -1) throw new Exn("pc modifying insn in delay slot");
1037 b1 = a(InstructionFactory.createBranchInstruction(IFGE,null));
1038 emitInstruction(-1,nextInsn,-1);
1042 branch(pc,pc+branchTarget*4+4);
1043 b1.setTarget(a(InstructionConstants.NOP));
1046 if(pc == -1) throw new Exn("pc modifying insn in delay slot");
1048 if(rs != 0) { // r0 is always >= 0
1050 b1 = a(InstructionFactory.createBranchInstruction(IFLT,null));
1052 emitInstruction(-1,nextInsn,-1);
1056 branch(pc,pc+branchTarget*4+4);
1057 if(b1 != null) b1.setTarget(a(InstructionConstants.NOP));
1058 if(b1 == null) unreachable = true;
1061 throw new Exn("Illegal Instruction 1/" + rt);
1066 if(pc == -1) throw new Exn("pc modifying insn in delay slot");
1067 emitInstruction(-1,nextInsn,-1);
1068 branch(pc,(pc&0xf0000000)|(jumpTarget << 2));
1073 if(pc == -1) throw new Exn("pc modifying insn in delay slot");
1074 int target = (pc&0xf0000000)|(jumpTarget << 2);
1075 emitInstruction(-1,nextInsn,-1);
1084 if(pc == -1) throw new Exn("pc modifying insn in delay slot");
1086 emitInstruction(-1,nextInsn,-1);
1087 branch(pc,pc+branchTarget*4+4);
1089 } else if(rs == 0 || rt == 0) {
1090 pushReg(rt == 0 ? R+rs : R+rt);
1091 return doIfInstruction(IFEQ,pc,pc+branchTarget*4+4,nextInsn);
1095 return doIfInstruction(IF_ICMPEQ,pc,pc+branchTarget*4+4,nextInsn);
1099 if(pc == -1) throw new Exn("pc modifying insn in delay slot");
1102 return doIfInstruction(IFNE,pc,pc+branchTarget*4+4,nextInsn);
1105 return doIfInstruction(IF_ICMPNE,pc,pc+branchTarget*4+4,nextInsn);
1108 if(pc == -1) throw new Exn("pc modifying insn in delay slot");
1110 return doIfInstruction(IFLE,pc,pc+branchTarget*4+4,nextInsn);
1112 if(pc == -1) throw new Exn("pc modifying insn in delay slot");
1114 return doIfInstruction(IFGT,pc,pc+branchTarget*4+4,nextInsn);
1116 throw new Exn("ADDI (add immediate with oveflow trap) not suported");
1119 addiu(rs,signedImmediate);
1125 pushConst(signedImmediate);
1126 b1 = a(InstructionFactory.createBranchInstruction(IF_ICMPLT,null));
1127 a(InstructionConstants.ICONST_0);
1128 b2 = a(InstructionFactory.createBranchInstruction(GOTO,null));
1129 b1.setTarget(a(InstructionConstants.ICONST_1));
1130 b2.setTarget(a(InstructionConstants.NOP));
1136 a(InstructionConstants.I2L);
1137 pushConst(0xffffffffL);
1138 a(InstructionConstants.LAND);
1139 // Yes, this is correct, you have to sign extend the immediate then do an UNSIGNED comparison
1140 pushConst(signedImmediate&0xffffffffL);
1141 a(InstructionConstants.LCMP);
1143 b1 = a(InstructionFactory.createBranchInstruction(IFLT,null));
1144 a(InstructionConstants.ICONST_0);
1145 b2 = a(InstructionFactory.createBranchInstruction(GOTO,null));
1146 b1.setTarget(a(InstructionConstants.ICONST_1));
1147 b2.setTarget(a(InstructionConstants.NOP));
1154 pushConst(unsignedImmediate);
1155 a(InstructionConstants.IAND);
1160 if(rs != 0 && unsignedImmediate != 0) {
1162 pushConst(unsignedImmediate);
1163 a(InstructionConstants.IOR);
1167 pushConst(unsignedImmediate);
1174 pushConst(unsignedImmediate);
1175 a(InstructionConstants.IXOR);
1180 pushConst(unsignedImmediate << 16);
1184 throw new Exn("TLB/Exception support not implemented");
1193 if(fs != 31) throw new Exn("FCR " + fs + " unavailable");
1207 if(fs != 31) throw new Exn("FCR " + fs + " unavailable");
1212 case 8: {// BC1F, BC1T
1214 pushConst(0x800000);
1215 a(InstructionConstants.IAND);
1216 return doIfInstruction(((insn>>>16)&1) == 0 ? IFEQ : IFNE,pc,pc+branchTarget*4+4,nextInsn);
1220 { // Single/Double math
1221 boolean d = rs == 17;
1224 preSetDouble(F+fd,d);
1227 a(d ? InstructionConstants.DADD : InstructionConstants.FADD);
1231 preSetDouble(F+fd,d);
1234 a(d ? InstructionConstants.DSUB : InstructionConstants.FSUB);
1238 preSetDouble(F+fd,d);
1241 a(d ? InstructionConstants.DMUL : InstructionConstants.FMUL);
1245 preSetDouble(F+fd,d);
1248 a(d ? InstructionConstants.DDIV : InstructionConstants.FDIV);
1252 preSetDouble(F+fd,d);
1253 // NOTE: We can't use fneg/dneg here since they'll turn +0.0 into -0.0
1256 a(d ? InstructionConstants.DUP2 : InstructionConstants.DUP);
1257 a(d ? InstructionConstants.DCONST_0 : InstructionConstants.FCONST_0);
1258 a(d ? InstructionConstants.DCMPG : InstructionConstants.FCMPG);
1260 b1 = a(InstructionFactory.createBranchInstruction(IFGT,null));
1261 a(d ? InstructionConstants.DCONST_0 : InstructionConstants.FCONST_0);
1263 a(InstructionConstants.DUP2_X2);
1264 a(InstructionConstants.POP2);
1266 a(InstructionConstants.POP);
1268 a(InstructionConstants.DSUB);
1270 b1.setTarget(setDouble(d));
1284 preSetDouble(F+fd,d);
1286 a(d ? InstructionConstants.DNEG : InstructionConstants.FNEG);
1292 if(d) a(InstructionConstants.D2F);
1298 if(!d) a(InstructionConstants.F2D);
1301 case 36: { // CVT.W.D
1302 int[] matches = new int[4];
1303 for(int i=0;i<4;i++) matches[i] = i;
1305 TABLESWITCH ts = new TABLESWITCH(matches,new InstructionHandle[4], null);
1310 a(InstructionConstants.ICONST_3);
1311 a(InstructionConstants.IAND);
1314 // Round towards plus infinity
1315 ts.setTarget(2,a(InstructionConstants.NOP));
1316 if(!d) a(InstructionConstants.F2D); // Ugh.. java.lang.Math doesn't have a float ceil/floor
1317 a(fac.createInvoke("java.lang.Math","ceil",Type.DOUBLE,new Type[]{Type.DOUBLE},INVOKESTATIC));
1318 if(!d) a(InstructionConstants.D2F);
1319 b1 = a(InstructionFactory.createBranchInstruction(GOTO,null));
1322 ts.setTarget(0,d ? pushConst(0.5d) : pushConst(0.5f));
1323 a(d ? InstructionConstants.DADD : InstructionConstants.FADD);
1326 // Round towards minus infinity
1327 ts.setTarget(3,a(InstructionConstants.NOP));
1328 if(!d) a(InstructionConstants.F2D);
1329 a(fac.createInvoke("java.lang.Math","floor",Type.DOUBLE,new Type[]{Type.DOUBLE},INVOKESTATIC));
1330 if(!d) a(InstructionConstants.D2F);
1332 InstructionHandle h = a(d ? InstructionConstants.D2I : InstructionConstants.F2I);
1346 pushConst(~0x800000);
1347 a(InstructionConstants.IAND);
1350 a(d ? InstructionConstants.DCMPG : InstructionConstants.FCMPG);
1352 case 50: b1 = a(InstructionFactory.createBranchInstruction(IFEQ,null)); break;
1353 case 60: b1 = a(InstructionFactory.createBranchInstruction(IFLT,null)); break;
1354 case 62: b1 = a(InstructionFactory.createBranchInstruction(IFLE,null)); break;
1358 pushConst(0x000000);
1359 b2 = a(InstructionFactory.createBranchInstruction(GOTO,null));
1360 b1.setTarget(pushConst(0x800000));
1361 b2.setTarget(a(InstructionConstants.IOR));
1364 default: throw new Exn("Invalid Instruction 17/" + rs + "/" + subcode);
1368 case 20: { // Integer
1373 a(InstructionConstants.I2F);
1379 a(InstructionConstants.I2D);
1382 default: throw new Exn("Invalid Instruction 17/" + rs + "/" + subcode);
1387 throw new Exn("Invalid Instruction 17/" + rs);
1392 throw new Exn("coprocessor 2 and 3 instructions not available");
1395 addiu(R+rs,signedImmediate);
1402 a(InstructionConstants.ICONST_M1);
1403 a(InstructionConstants.IXOR);
1404 a(InstructionConstants.ICONST_3);
1405 a(InstructionConstants.IAND);
1406 a(InstructionConstants.ICONST_3);
1407 a(InstructionConstants.ISHL);
1408 a(InstructionConstants.IUSHR);
1409 a(InstructionConstants.I2B);
1415 addiu(R+rs,signedImmediate);
1422 a(InstructionConstants.ICONST_M1);
1423 a(InstructionConstants.IXOR);
1424 a(InstructionConstants.ICONST_2);
1425 a(InstructionConstants.IAND);
1426 a(InstructionConstants.ICONST_3);
1427 a(InstructionConstants.ISHL);
1428 a(InstructionConstants.IUSHR);
1429 a(InstructionConstants.I2S);
1435 addiu(R+rs,signedImmediate);
1439 pushConst(0x00ffffff);
1442 a(InstructionConstants.ICONST_M1);
1443 a(InstructionConstants.IXOR);
1444 a(InstructionConstants.ICONST_3);
1445 a(InstructionConstants.IAND);
1446 a(InstructionConstants.ICONST_3);
1447 a(InstructionConstants.ISHL);
1448 a(InstructionConstants.IUSHR);
1449 a(InstructionConstants.IAND);
1456 a(InstructionConstants.ICONST_3);
1457 a(InstructionConstants.IAND);
1458 a(InstructionConstants.ICONST_3);
1459 a(InstructionConstants.ISHL);
1460 a(InstructionConstants.ISHL);
1461 a(InstructionConstants.IOR);
1470 memRead(R+rs,signedImmediate);
1475 addiu(R+rs,signedImmediate);
1482 a(InstructionConstants.ICONST_M1);
1483 a(InstructionConstants.IXOR);
1484 a(InstructionConstants.ICONST_3);
1485 a(InstructionConstants.IAND);
1486 a(InstructionConstants.ICONST_3);
1487 a(InstructionConstants.ISHL);
1488 a(InstructionConstants.IUSHR);
1490 a(InstructionConstants.IAND);
1496 addiu(R+rs,signedImmediate);
1503 a(InstructionConstants.ICONST_M1);
1504 a(InstructionConstants.IXOR);
1505 a(InstructionConstants.ICONST_2);
1506 a(InstructionConstants.IAND);
1507 a(InstructionConstants.ICONST_3);
1508 a(InstructionConstants.ISHL);
1509 a(InstructionConstants.IUSHR);
1511 // chars are unsigend so this works
1512 a(InstructionConstants.I2C);
1518 addiu(R+rs,signedImmediate);
1522 pushConst(0xffffff00);
1525 a(InstructionConstants.ICONST_3);
1526 a(InstructionConstants.IAND);
1527 a(InstructionConstants.ICONST_3);
1528 a(InstructionConstants.ISHL);
1529 a(InstructionConstants.ISHL);
1530 a(InstructionConstants.IAND);
1537 a(InstructionConstants.ICONST_M1);
1538 a(InstructionConstants.IXOR);
1539 a(InstructionConstants.ICONST_3);
1540 a(InstructionConstants.IAND);
1541 a(InstructionConstants.ICONST_3);
1542 a(InstructionConstants.ISHL);
1543 a(InstructionConstants.IUSHR);
1544 a(InstructionConstants.IOR);
1551 addiu(R+rs,signedImmediate);
1554 // FEATURE: DO the preMemRead(true) thing for the rest of the S* instructions
1559 pushConst(0xff000000);
1562 a(InstructionConstants.ICONST_3);
1563 a(InstructionConstants.IAND);
1564 a(InstructionConstants.ICONST_3);
1565 a(InstructionConstants.ISHL);
1566 a(InstructionConstants.IUSHR);
1567 a(InstructionConstants.ICONST_M1);
1568 a(InstructionConstants.IXOR);
1569 a(InstructionConstants.IAND);
1574 a(InstructionConstants.IAND);
1580 a(InstructionConstants.ICONST_M1);
1581 a(InstructionConstants.IXOR);
1582 a(InstructionConstants.ICONST_3);
1583 a(InstructionConstants.IAND);
1584 a(InstructionConstants.ICONST_3);
1585 a(InstructionConstants.ISHL);
1586 a(InstructionConstants.ISHL);
1587 a(InstructionConstants.IOR);
1596 addiu(R+rs,signedImmediate);
1598 a(InstructionConstants.DUP);
1610 a(InstructionConstants.ICONST_2);
1611 a(InstructionConstants.IAND);
1612 a(InstructionConstants.ICONST_3);
1613 a(InstructionConstants.ISHL);
1614 a(InstructionConstants.ISHL);
1615 a(InstructionConstants.IAND);
1620 a(InstructionConstants.IAND);
1626 a(InstructionConstants.ICONST_M1);
1627 a(InstructionConstants.IXOR);
1628 a(InstructionConstants.ICONST_2);
1629 a(InstructionConstants.IAND);
1630 a(InstructionConstants.ICONST_3);
1631 a(InstructionConstants.ISHL);
1632 a(InstructionConstants.ISHL);
1633 a(InstructionConstants.IOR);
1642 addiu(R+rs,signedImmediate);
1643 a(InstructionConstants.DUP);
1652 pushConst(0xffffff00);
1655 a(InstructionConstants.ICONST_M1);
1656 a(InstructionConstants.IXOR);
1657 a(InstructionConstants.ICONST_3);
1658 a(InstructionConstants.IAND);
1659 a(InstructionConstants.ICONST_3);
1660 a(InstructionConstants.ISHL);
1661 a(InstructionConstants.ISHL);
1662 a(InstructionConstants.IAND);
1667 a(InstructionConstants.ICONST_3);
1668 a(InstructionConstants.IAND);
1669 a(InstructionConstants.ICONST_3);
1670 a(InstructionConstants.ISHL);
1671 a(InstructionConstants.IUSHR);
1672 a(InstructionConstants.IOR);
1680 preMemWrite2(R+rs,signedImmediate);
1687 addiu(R+rs,signedImmediate);
1688 a(InstructionConstants.DUP);
1697 pushConst(0x00ffffff);
1700 a(InstructionConstants.ICONST_3);
1701 a(InstructionConstants.IAND);
1702 a(InstructionConstants.ICONST_3);
1703 a(InstructionConstants.ISHL);
1704 a(InstructionConstants.IUSHR);
1705 a(InstructionConstants.IAND);
1710 a(InstructionConstants.ICONST_M1);
1711 a(InstructionConstants.IXOR);
1712 a(InstructionConstants.ICONST_3);
1713 a(InstructionConstants.IAND);
1714 a(InstructionConstants.ICONST_3);
1715 a(InstructionConstants.ISHL);
1716 a(InstructionConstants.ISHL);
1717 a(InstructionConstants.IOR);
1722 // This need to be atomic if we ever support threads (see SWC0/SC)
1725 memRead(R+rs,signedImmediate);
1731 memRead(R+rs,signedImmediate);
1735 /* This needs to fail (set rt to 0) if the memory location was modified
1736 * between the LL and SC if we every support threads.
1741 preMemWrite2(R+rs,signedImmediate);
1750 preMemWrite2(R+rs,signedImmediate);
1755 throw new Exn("Invalid Instruction: " + op + " at " + toHex(pc));
1760 // Helper functions for emitText
1762 private static final int R = 0;
1763 private static final int F = 32;
1764 private static final int HI = 64;
1765 private static final int LO = 65;
1766 private static final int FCSR = 66;
1767 private static final int REG_COUNT=67;
1769 private int[] regLocalMapping = new int[REG_COUNT];
1770 private int[] regLocalReadCount = new int[REG_COUNT];
1771 private int[] regLocalWriteCount = new int[REG_COUNT];
1772 private int nextAvailLocal;
1774 private int getLocalForReg(int reg) {
1775 if(regLocalMapping[reg] != 0) return regLocalMapping[reg];
1776 if(nextAvailLocal == 0) nextAvailLocal = onePage ? 3 : 4;
1777 regLocalMapping[reg] = nextAvailLocal++;
1778 return regLocalMapping[reg];
1781 private void fixupRegs() {
1782 InstructionHandle prev = realStart;
1783 for(int i=0;i<REG_COUNT;i++) {
1784 if(regLocalMapping[i] == 0) continue;
1786 prev = insnList.append(prev,InstructionConstants.ALOAD_0);
1787 prev = insnList.append(prev,fac.createFieldAccess(fullClassName,regField(i),Type.INT, GETFIELD));
1788 prev = insnList.append(prev,InstructionFactory.createStore(Type.INT,regLocalMapping[i]));
1790 if(regLocalWriteCount[i] > 0) {
1791 a(InstructionConstants.ALOAD_0);
1792 a(InstructionFactory.createLoad(Type.INT,regLocalMapping[i]));
1793 a(fac.createFieldAccess(fullClassName,regField(i),Type.INT, PUTFIELD));
1796 regLocalMapping[i] = regLocalReadCount[i] = regLocalWriteCount[i] = 0;
1801 private void restoreChangedRegs() {
1802 for(int i=0;i<REG_COUNT;i++) {
1803 if(regLocalWriteCount[i] > 0) {
1804 a(InstructionConstants.ALOAD_0);
1805 a(InstructionFactory.createLoad(Type.INT,regLocalMapping[i]));
1806 a(fac.createFieldAccess(fullClassName,regField(i),Type.INT, PUTFIELD));
1811 private String regField(int reg) {
1814 case HI: field = "hi"; break;
1815 case LO: field = "lo"; break;
1816 case FCSR: field = "fcsr"; break;
1818 if(reg > R && reg < R+32) field="r"+(reg-R);
1819 else if(reg >= F && reg < F+32) field="f"+(reg-F);
1820 else throw new IllegalArgumentException(""+reg);
1825 private boolean doLocal(int reg) {
1827 return reg == R+2 || reg == R+3 || reg == R+4 || reg == R+29;
1830 private InstructionHandle pushRegWZ(int reg) {
1832 warn.println("Warning: Pushing r0!");
1833 new Exception().printStackTrace(warn);
1835 return pushRegZ(reg);
1838 private InstructionHandle pushRegZ(int reg) {
1839 if(reg == R+0) return pushConst(0);
1840 else return pushReg(reg);
1844 private InstructionHandle pushReg(int reg) {
1845 InstructionHandle h;
1847 regLocalReadCount[reg]++;
1848 h = a(InstructionFactory.createLoad(Type.INT,getLocalForReg(reg)));
1850 h = a(InstructionConstants.ALOAD_0);
1851 a(fac.createFieldAccess(fullClassName,regField(reg),Type.INT, GETFIELD));
1856 private int preSetRegStackPos;
1857 private int[] preSetRegStack = new int[8];
1859 // This can push ONE or ZERO words to the stack. If it pushed one it returns true
1860 private boolean preSetReg(int reg) {
1861 regField(reg); // just to check for validity
1862 preSetRegStack[preSetRegStackPos] = reg;
1863 preSetRegStackPos++;
1867 a(InstructionConstants.ALOAD_0);
1872 private InstructionHandle setReg() {
1873 if(preSetRegStackPos==0) throw new RuntimeException("didn't do preSetReg");
1874 preSetRegStackPos--;
1875 int reg = preSetRegStack[preSetRegStackPos];
1876 InstructionHandle h;
1878 h = a(InstructionFactory.createStore(Type.INT,getLocalForReg(reg)));
1879 regLocalWriteCount[reg]++;
1881 h = a(fac.createFieldAccess(fullClassName,regField(reg),Type.INT, PUTFIELD));
1886 private InstructionHandle preSetPC() { return a(InstructionConstants.ALOAD_0); }
1887 private InstructionHandle setPC() { return a(fac.createFieldAccess(fullClassName,"pc",Type.INT, PUTFIELD)); }
1889 //unused - private InstructionHandle pushFloat(int reg) throws CompilationException { return pushDouble(reg,false); }
1890 //unused - private InstructionHandle pushDouble(int reg) throws CompilationException { return pushDouble(reg,true); }
1891 private InstructionHandle pushDouble(int reg, boolean d) throws Exn {
1892 if(reg < F || reg >= F+32) throw new IllegalArgumentException(""+reg);
1893 InstructionHandle h;
1895 if(reg == F+31) throw new Exn("Tried to use a double in f31");
1897 a(InstructionConstants.I2L);
1899 a(InstructionConstants.LSHL);
1901 a(InstructionConstants.I2L);
1902 pushConst(0xffffffffL);
1903 a(InstructionConstants.LAND);
1904 a(InstructionConstants.LOR);
1905 //p("invokestatic java/lang/Double/longBitsToDouble(J)D");
1906 a(fac.createInvoke("java.lang.Double","longBitsToDouble",Type.DOUBLE,new Type[]{Type.LONG},INVOKESTATIC));
1909 a(fac.createInvoke("java.lang.Float","intBitsToFloat",Type.FLOAT,new Type[]{Type.INT},INVOKESTATIC));
1914 private void preSetFloat(int reg) { preSetDouble(reg,false); }
1915 private void preSetDouble(int reg) { preSetDouble(reg,true); }
1916 private void preSetDouble(int reg, boolean d) { preSetReg(reg); }
1918 private InstructionHandle setFloat() throws Exn { return setDouble(false); }
1919 private InstructionHandle setDouble() throws Exn { return setDouble(true); }
1920 private InstructionHandle setDouble(boolean d) throws Exn {
1921 int reg = preSetRegStack[preSetRegStackPos-1];
1922 if(reg < F || reg >= F+32) throw new IllegalArgumentException(""+reg);
1923 //p("invokestatic java/lang/Double/doubleToLongBits(D)J");
1924 InstructionHandle h;
1926 if(reg == F+31) throw new Exn("Tried to use a double in f31");
1927 h = a(fac.createInvoke("java.lang.Double","doubleToLongBits",Type.LONG,new Type[]{Type.DOUBLE},INVOKESTATIC));
1928 a(InstructionConstants.DUP2);
1930 a(InstructionConstants.LUSHR);
1931 a(InstructionConstants.L2I);
1932 if(preSetReg(reg+1))
1933 a(InstructionConstants.SWAP);
1935 a(InstructionConstants.L2I);
1936 setReg(); // preSetReg was already done for this by preSetDouble
1938 h = a(fac.createInvoke("java.lang.Float","floatToRawIntBits",Type.INT,new Type[]{Type.FLOAT},INVOKESTATIC));
1944 private InstructionHandle pushConst(int n) {
1945 if(n >= 0 && n <= 5) {
1947 case 0: return a(InstructionConstants.ICONST_0);
1948 case 1: return a(InstructionConstants.ICONST_1);
1949 case 2: return a(InstructionConstants.ICONST_2);
1950 case 3: return a(InstructionConstants.ICONST_3);
1951 case 4: return a(InstructionConstants.ICONST_4);
1952 case 5: return a(InstructionConstants.ICONST_5);
1953 default: return null;
1955 } else if(n == -1) {
1956 return a(InstructionConstants.ICONST_M1);
1957 } else if(n >= -128 && n <= 127) {
1958 return a(new BIPUSH((byte) n));
1959 } else if(n >= -32768 && n <= 32767) {
1960 return a(new SIPUSH((short) n));
1962 return a(new PUSH(cp,n));
1966 private InstructionHandle pushConst(long l) { return a(new PUSH(cp,l)); }
1967 private InstructionHandle pushConst(float f) { return a(new PUSH(cp,f)); }
1968 private InstructionHandle pushConst(double d) { return a(new PUSH(cp,d)); }
1970 private void pushTmp() { a(InstructionConstants.ILOAD_1); }
1971 private void setTmp() { a(InstructionConstants.ISTORE_1); }
1973 private void addiu(int reg, int offset) {
1974 if(reg != R+0 && offset != 0) {
1977 a(InstructionConstants.IADD);
1978 } else if(reg != R+0) {
1984 private int memWriteStage;
1985 private void preMemWrite1() {
1986 if(memWriteStage!=0) throw new Error("pending preMemWrite1/2");
1989 a(InstructionConstants.ALOAD_2);
1991 a(InstructionFactory.createLoad(Type.OBJECT,3));
1993 a(InstructionConstants.ALOAD_0);
1996 private void preMemWrite2(int reg, int offset) {
2001 private void preMemWrite2() { preMemWrite2(false); }
2002 private void preMemWrite2(boolean addrInTmp) {
2003 if(memWriteStage!=1) throw new Error("pending preMemWrite2 or no preMemWrite1");
2006 if(nullPointerCheck) {
2007 a(InstructionConstants.DUP);
2008 a(InstructionConstants.ALOAD_0);
2009 a(InstructionConstants.SWAP);
2010 a(fac.createInvoke(fullClassName,"nullPointerCheck",Type.VOID,new Type[]{Type.INT},INVOKEVIRTUAL));
2014 a(InstructionConstants.ICONST_2);
2015 a(InstructionConstants.IUSHR);
2016 } else if(fastMem) {
2018 a(InstructionConstants.DUP_X1);
2019 pushConst(pageShift);
2020 a(InstructionConstants.IUSHR);
2021 a(InstructionConstants.AALOAD);
2025 a(InstructionConstants.SWAP);
2026 a(InstructionConstants.ICONST_2);
2027 a(InstructionConstants.IUSHR);
2028 pushConst((pageSize>>2)-1);
2029 a(InstructionConstants.IAND);
2033 // pops an address and value off the stack, sets *addr to value
2034 private void memWrite() {
2035 if(memWriteStage!=2) throw new Error("didn't do preMemWrite1 or preMemWrite2");
2039 a(InstructionConstants.IASTORE);
2040 } else if(fastMem) {
2041 a(InstructionConstants.IASTORE);
2043 a(fac.createInvoke(fullClassName,"unsafeMemWrite",Type.VOID,new Type[]{Type.INT,Type.INT},INVOKEVIRTUAL));
2048 // reads the word at r[reg]+offset
2049 private void memRead(int reg, int offset) {
2055 private boolean didPreMemRead;
2056 private boolean preMemReadDoPreWrite;
2058 private void preMemRead() { preMemRead(false); }
2059 private void preMemRead(boolean preWrite) {
2060 if(didPreMemRead) throw new Error("pending preMemRead");
2061 didPreMemRead = true;
2062 preMemReadDoPreWrite = preWrite;
2064 a(InstructionConstants.ALOAD_2);
2066 a(InstructionFactory.createLoad(Type.OBJECT,preWrite ? 3 : 2));
2068 a(InstructionConstants.ALOAD_0);
2070 // memRead pops an address off the stack, reads the value at that addr, and pushed the value
2071 // preMemRead MUST be called BEFORE the addresses is pushed
2072 private void memRead() { memRead(false); }
2074 private void memRead(boolean addrInTmp) {
2075 if(!didPreMemRead) throw new Error("didn't do preMemRead");
2076 didPreMemRead = false;
2077 if(preMemReadDoPreWrite)
2080 if(nullPointerCheck) {
2081 a(InstructionConstants.DUP);
2082 a(InstructionConstants.ALOAD_0);
2083 a(InstructionConstants.SWAP);
2084 a(fac.createInvoke(fullClassName,"nullPointerCheck",Type.VOID,new Type[]{Type.INT},INVOKEVIRTUAL));
2088 // p(target + "= page[(" + addr + ")>>>2];");
2089 a(InstructionConstants.ICONST_2);
2090 a(InstructionConstants.IUSHR);
2091 if(preMemReadDoPreWrite)
2092 a(InstructionConstants.DUP2);
2093 a(InstructionConstants.IALOAD);
2094 } else if(fastMem) {
2095 //p(target + " = readPages[("+addr+")>>>"+pageShift+"][(("+addr+")>>>2)&"+toHex((pageSize>>2)-1)+"];");
2098 a(InstructionConstants.DUP_X1);
2099 pushConst(pageShift);
2100 a(InstructionConstants.IUSHR);
2101 a(InstructionConstants.AALOAD);
2105 a(InstructionConstants.SWAP);
2106 a(InstructionConstants.ICONST_2);
2107 a(InstructionConstants.IUSHR);
2108 pushConst((pageSize>>2)-1);
2109 a(InstructionConstants.IAND);
2110 if(preMemReadDoPreWrite)
2111 a(InstructionConstants.DUP2);
2112 a(InstructionConstants.IALOAD);
2115 if(preMemReadDoPreWrite)
2116 a(InstructionConstants.DUP2);
2117 a(fac.createInvoke(fullClassName,"unsafeMemWrite",Type.INT,new Type[]{Type.INT},INVOKEVIRTUAL));
2122 // This might come in handy for something else
2123 /*private boolean touchesReg(int insn, int reg) {
2124 if((reg < R+0 || reg >= R+32) && reg != FCSR) throw new IllegalArgumentException(""+reg);
2125 if(reg == R+0) return false; // r0 is never modified
2126 int op = (insn >>> 26) & 0xff; // bits 26-31
2127 int subcode = insn & 0x3f; // bits 0-5
2128 int rd = (insn >>> 11) & 0x1f; // bits 11-15
2129 int rt = (insn >>> 16) & 0x1f; // bits 16-20
2130 int rs = (insn >>> 21) & 0x1f; // bits 21-25
2134 if(subcode >= 0 && subcode <= 7) return reg == R+rd; // Shift ops
2135 if(subcode >= 32 && subcode <= 43) return reg == R+rd; // Other math ops
2136 if(subcode >= 24 && subcode <= 27) return reg == HI || reg == LO; // MULT/DIV
2138 case 13: return false; // BREAK
2141 case 0: return reg == R+rt; // MFC.1
2142 case 2: return reg == R+rt; // CFC.1
2143 case 4: return false; // MTC.1
2144 case 6: return false; // CTC.1
2147 if(subcode == 50 || subcode == 60 || subcode == 62) return reg == FCSR;
2148 return false; // everything else just touches f0-f31
2149 case 20: return false; // Integer - just touches f0-f31
2153 if(op >= 8 && op <= 15) return reg == R+rt; // XXXI instructions
2154 if(op >= 40 && op <= 46) return false; // Memory WRITE ops
2155 if(op == 49) return reg == F+rt; // LWC1
2156 if(op == 57) return false; // SWC1
2159 warn.println("Unknown instruction in touchesReg()- assuming it modifies all regs " + op + " " + subcode);
2160 new Exception().fillInStackTrace().printStackTrace(warn);