Example usage for org.objectweb.asm Opcodes BIPUSH

List of usage examples for org.objectweb.asm Opcodes BIPUSH

Introduction

In this page you can find the example usage for org.objectweb.asm Opcodes BIPUSH.

Prototype

int BIPUSH

To view the source code for org.objectweb.asm Opcodes BIPUSH.

Click Source Link

Usage

From source file:edu.mit.streamjit.util.bytecode.MethodResolver.java

License:Open Source License

private void interpret(IntInsnNode insn, FrameState frame, BBInfo block) {
    int operand = insn.operand;
    switch (insn.getOpcode()) {
    case Opcodes.BIPUSH:
    case Opcodes.SIPUSH:
        frame.stack.push(module.constants().getSmallestIntConstant(insn.operand));
        break;//from   w  ww  .  ja va 2 s .  c om
    case Opcodes.NEWARRAY:
        ArrayType t;
        switch (operand) {
        case Opcodes.T_BOOLEAN:
            t = module.types().getArrayType(boolean[].class);
            break;
        case Opcodes.T_BYTE:
            t = module.types().getArrayType(byte[].class);
            break;
        case Opcodes.T_CHAR:
            t = module.types().getArrayType(char[].class);
            break;
        case Opcodes.T_SHORT:
            t = module.types().getArrayType(short[].class);
            break;
        case Opcodes.T_INT:
            t = module.types().getArrayType(int[].class);
            break;
        case Opcodes.T_LONG:
            t = module.types().getArrayType(long[].class);
            break;
        case Opcodes.T_FLOAT:
            t = module.types().getArrayType(float[].class);
            break;
        case Opcodes.T_DOUBLE:
            t = module.types().getArrayType(double[].class);
            break;
        default:
            throw new AssertionError(operand);
        }
        NewArrayInst i = new NewArrayInst(t, frame.stack.pop());
        block.block.instructions().add(i);
        frame.stack.push(i);
        break;
    default:
        throw new UnsupportedOperationException("" + insn.getOpcode());
    }
}

From source file:edu.mit.streamjit.util.bytecode.MethodUnresolver.java

License:Open Source License

private AbstractInsnNode loadIntegerConstant(int c) {
    if (c == -1)/*w  w  w  .  j  a va 2 s .  c  o  m*/
        return new InsnNode(Opcodes.ICONST_M1);
    if (c == 0)
        return new InsnNode(Opcodes.ICONST_0);
    if (c == 1)
        return new InsnNode(Opcodes.ICONST_1);
    if (c == 2)
        return new InsnNode(Opcodes.ICONST_2);
    if (c == 3)
        return new InsnNode(Opcodes.ICONST_3);
    if (c == 4)
        return new InsnNode(Opcodes.ICONST_4);
    if (c == 5)
        return new InsnNode(Opcodes.ICONST_5);
    if (Byte.MIN_VALUE <= c && c <= Byte.MAX_VALUE)
        return new IntInsnNode(Opcodes.BIPUSH, c);
    if (Short.MIN_VALUE <= c && c <= Short.MAX_VALUE)
        return new IntInsnNode(Opcodes.SIPUSH, c);
    return new LdcInsnNode(c);
}

From source file:instrumentation.InstrumentationMethodAdapter.java

License:Open Source License

private void insertCode(int opcode, String type) {
    mv.visitInsn(Opcodes.DUP);/* w  w  w .j  a  va2 s  . c o m*/
    mv.visitIntInsn(Opcodes.BIPUSH, opcode);
    mv.visitMethodInsn(Opcodes.INVOKESTATIC, "dimmunix/TrackDelegate", "track" + type,
            "(Ljava/lang/Object;B)V");
    addedInstructions += 2;
}

From source file:instrumentj.impl.InstrumentMethodVisitor.java

License:Apache License

/**
 * Adds a call to/* w  w  w .  j a v a2s .c om*/
 * {@link StaticProfilerInterface#objectAllocationProbes(String)} in the
 * case of constructor calls and also a call to
 * {@link StaticProfilerInterface#methodEnterProbes(String, String)}
 * <br>
 * <br>
 * {@inheritDoc}
 */
@Override
protected void onMethodEnter() {
    final boolean constructor = "<init>".equals(methodName);
    if (constructor) {
        visitLdcInsn(className);

        visitMethodInsn(INVOKESTATIC, INSTRUMENTJ_STATIC_PROFILER_INTERFACE, OBJECT_ALLOCATION_PROBES,
                OBJECT_ALLOCATION_PROBES_DESC);
    }

    visitLdcInsn(className);
    visitLdcInsn(methodName);
    visitLdcInsn(methodDescription);

    final Type[] argTypes = Type.getArgumentTypes(methodDescription);
    final int argCount = argTypes.length;

    if (argCount > 0) {
        loadArgArray();
    } else {
        visitIntInsn(Opcodes.BIPUSH, 1);
        visitTypeInsn(Opcodes.ANEWARRAY, "java/lang/Object");
    }

    visitMethodInsn(INVOKESTATIC, INSTRUMENTJ_STATIC_PROFILER_INTERFACE, METHOD_ENTER_PROBES,
            METHOD_ENTER_PROBES_DESC);
}

From source file:jpcsp.Allegrex.compiler.CompilerContext.java

License:Open Source License

@Override
public void loadImm(Integer imm) {
    switch (imm) {
    case -1:/*  w  ww .  ja v a  2s.  c  o m*/
        mv.visitInsn(Opcodes.ICONST_M1);
        break;
    case 0:
        mv.visitInsn(Opcodes.ICONST_0);
        break;
    case 1:
        mv.visitInsn(Opcodes.ICONST_1);
        break;
    case 2:
        mv.visitInsn(Opcodes.ICONST_2);
        break;
    case 3:
        mv.visitInsn(Opcodes.ICONST_3);
        break;
    case 4:
        mv.visitInsn(Opcodes.ICONST_4);
        break;
    case 5:
        mv.visitInsn(Opcodes.ICONST_5);
        break;
    default:
        if (Byte.MIN_VALUE <= imm && imm < Byte.MAX_VALUE) {
            mv.visitIntInsn(Opcodes.BIPUSH, imm);
        } else if (Short.MIN_VALUE <= imm && imm < Short.MAX_VALUE) {
            mv.visitIntInsn(Opcodes.SIPUSH, imm);
        } else {
            mv.visitLdcInsn(imm);
        }
        break;
    }
}

From source file:lapin.comp.asm.ASMByteCodeGenerator.java

License:Open Source License

private void generateCall(CallableInfo ci, Env env) {
    /*//from   w  w  w  .j a  v a2 s .  co m
     * local variables
     * <Callable#call>
     * 0: this
     * 1: args (list of arguments)
     * 2: env
     *
     * <Callable0#call0>
     * 0: this
     * 1: env
     *
     * <Callable1#call1>
     * 0: this
     * 1: arg0
     * 2: env
     *
     * <Callable2#call2>
     * 0: this
     * 1: arg0
     * 2: arg1
     * 3: env
     *
     * ...
     *
     */
    MethodVisitor mv = _cw.visitMethod(
            ci.mi.implCallable() ? Opcodes.ACC_PUBLIC + Opcodes.ACC_FINAL : Opcodes.ACC_FINAL, ci.mi.name(),
            Type.getMethodDescriptor(ci.retType, ci.paramTypes), null, null);

    // instruction list
    int len = ci.mi.instLen();
    // label
    Label label = null;

    // generate code
    for (int i = 0; i < len; i++) {
        Object inst = ci.mi.getInst(i);
        if (Logger.tracelevelp(env))
            Logger.trace("[asm:gen]" + i + ":\t~S", Lists.list(inst), env);

        // inst is symbol
        // -> convert tag (Symbol) to label (ASMe Label object)
        if (Data.isSymbol(inst)) {
            Symbol tag = Data.symbol(inst);
            Label l = (Label) ci.labelTable.get(tag);
            if (l == null) {
                throw new NotReachedException("label is null: ~S.", Lists.list(tag));
            } else if (l != label) {
                mv.visitLabel(l);
                label = l;
                if (Logger.tracelevelp(env))
                    Logger.trace("[asm:gen]" + i + ":\ttag ~S -> label ~S", Lists.list(tag, l), env);
            } else {
                if (Logger.tracelevelp(env))
                    Logger.trace("[asm:gen]" + i + ":\ttag ~S -> label ~S" + " (dup)", Lists.list(tag, l), env);
            }
            continue;
        }

        // inst must be the form of (id <arg1> <arg2> ....)
        Object id = Lists.car(inst);
        if (id == Insts.CONST) {
            /* push const on the stack. */
            Object obj = Lists.cadr(inst);
            String val = Data.string(constTable.get(obj));
            mv.visitVarInsn(Opcodes.ALOAD, 0);
            mv.visitFieldInsn(Opcodes.GETFIELD, toInternalName(super.classInfo.classname()), val,
                    TYPE_OBJECT.getDescriptor());
        } else if (id == Insts.VAR) {
            /* push var on the stack */
            Object var = Lists.cadr(inst);
            String val = Data.string(varTable.get(var));
            mv.visitVarInsn(Opcodes.ALOAD, 0);
            mv.visitFieldInsn(Opcodes.GETFIELD, toInternalName(super.classInfo.classname()), val,
                    TYPE_SYMBOL.getDescriptor());
        } else if (id == Insts.LAMBDA_LIST) {
            /* push lambdaList on the stack */
            Object var = Lists.cadr(inst);
            /* push _ll_<i> on the stack */
            String val = Data.string(llTable.get(var));
            mv.visitVarInsn(Opcodes.ALOAD, 0);
            mv.visitFieldInsn(Opcodes.GETFIELD, toInternalName(super.classInfo.classname()), val,
                    TYPE_LAMBDA_LIST.getDescriptor());
        } else if (id == Insts.ENV_GET) {
            /* env.get */
            Class type = Data.javaClass(Lists.cadr(inst));
            if (type.equals(int.class)) {
                mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, TYPE_ENV.getInternalName(), "getInt",
                        Type.getMethodDescriptor(Type.INT_TYPE, new Type[] { TYPE_SYMBOL }));
            } else if (type.equals(double.class)) {
                mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, TYPE_ENV.getInternalName(), "getDouble",
                        Type.getMethodDescriptor(Type.DOUBLE_TYPE, new Type[] { TYPE_SYMBOL }));
            } else if (type.equals(char.class)) {
                mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, TYPE_ENV.getInternalName(), "getChar",
                        Type.getMethodDescriptor(Type.CHAR_TYPE, new Type[] { TYPE_SYMBOL }));
            } else if (Object.class.isAssignableFrom(type)) {
                mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, TYPE_ENV.getInternalName(), "get",
                        Type.getMethodDescriptor(TYPE_OBJECT, new Type[] { TYPE_SYMBOL }));
            } else {
                throw new NotReachedException("unsupported type: ~S.", Lists.list(type));
            }
        } else if (id == Insts.ENV_SET) {
            /* env.set */
            Class type = Data.javaClass(Lists.cadr(inst));
            if (type.equals(int.class)) {
                mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, TYPE_ENV.getInternalName(), "set",
                        Type.getMethodDescriptor(Type.VOID_TYPE, new Type[] { TYPE_SYMBOL, Type.INT_TYPE }));
            } else if (type.equals(double.class)) {
                mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, TYPE_ENV.getInternalName(), "set",
                        Type.getMethodDescriptor(Type.VOID_TYPE, new Type[] { TYPE_SYMBOL, Type.DOUBLE_TYPE }));
            } else if (type.equals(char.class)) {
                mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, TYPE_ENV.getInternalName(), "set",
                        Type.getMethodDescriptor(Type.VOID_TYPE, new Type[] { TYPE_SYMBOL, Type.CHAR_TYPE }));
            } else if (Object.class.isAssignableFrom(type)) {
                mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, TYPE_ENV.getInternalName(), "set",
                        Type.getMethodDescriptor(Type.VOID_TYPE, new Type[] { TYPE_SYMBOL, TYPE_OBJECT }));
            } else {
                throw new NotReachedException("unsupported type: ~S.", Lists.list(type));
            }
        } else if (id == Insts.ENV_BIND) {
            /* env.bind */
            Class type = Data.javaClass(Lists.cadr(inst));
            if (type.equals(int.class)) {
                mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, TYPE_ENV.getInternalName(), "bind",
                        Type.getMethodDescriptor(Type.VOID_TYPE, new Type[] { TYPE_SYMBOL, Type.INT_TYPE }));
            } else if (type.equals(double.class)) {
                mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, TYPE_ENV.getInternalName(), "bind",
                        Type.getMethodDescriptor(Type.VOID_TYPE, new Type[] { TYPE_SYMBOL, Type.DOUBLE_TYPE }));
            } else if (type.equals(char.class)) {
                mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, TYPE_ENV.getInternalName(), "bind",
                        Type.getMethodDescriptor(Type.VOID_TYPE, new Type[] { TYPE_SYMBOL, Type.CHAR_TYPE }));
            } else if (Object.class.isAssignableFrom(type)) {
                mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, TYPE_ENV.getInternalName(), "bind",
                        Type.getMethodDescriptor(Type.VOID_TYPE, new Type[] { TYPE_SYMBOL, TYPE_OBJECT }));
            } else {
                throw new NotReachedException("unsupported type: ~S.", Lists.list(type));
            }
        } else if (id == Insts.ENV_UNBIND) {
            /* env.unbind */
            Class type = Data.javaClass(Lists.cadr(inst));
            if (type.equals(int.class)) {
                mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, TYPE_ENV.getInternalName(), "unbindInt",
                        Type.getMethodDescriptor(Type.INT_TYPE, new Type[] { TYPE_SYMBOL }));
            } else if (type.equals(double.class)) {
                mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, TYPE_ENV.getInternalName(), "unbindDouble",
                        Type.getMethodDescriptor(Type.DOUBLE_TYPE, new Type[] { TYPE_SYMBOL }));
            } else if (type.equals(char.class)) {
                mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, TYPE_ENV.getInternalName(), "unbindChar",
                        Type.getMethodDescriptor(Type.CHAR_TYPE, new Type[] { TYPE_SYMBOL }));
            } else if (Object.class.isAssignableFrom(type)) {
                mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, TYPE_ENV.getInternalName(), "unbind",
                        Type.getMethodDescriptor(TYPE_OBJECT, new Type[] { TYPE_SYMBOL }));
            } else {
                throw new NotReachedException("unsupported type: ~S.", Lists.list(type));
            }
        } else if (id == Insts.ENV_CHILD) {
            /* env.child */
            Object oldEnvVar = Lists.cadr(inst);
            Object newEnvVar = Lists.caddr(inst);
            Object oldSlot = Lists.cadr(oldEnvVar);
            Object newSlot = Lists.cadr(newEnvVar);
            int oldLocal = Data.fixnum(ci.localTable.get(oldSlot)).intValue();
            int newLocal = Data.fixnum(ci.localTable.get(newSlot)).intValue();
            if (Logger.tracelevelp(env))
                Logger.trace("[asm:gen]" + i + ":\tenv-child: local ~S -> ~S",
                        Lists.list(Data.toFixnum(oldLocal), Data.toFixnum(newLocal)), env);
            mv.visitVarInsn(Opcodes.ALOAD, oldLocal);
            mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, TYPE_ENV.getInternalName(), "child",
                    Type.getMethodDescriptor(TYPE_ENV, TYPE_NO_ARGS));
            mv.visitVarInsn(Opcodes.ASTORE, newLocal);
        } else if (id == Insts.CALL) {
            /* funcall */
            int nargs = Data.fixnum(Lists.cadr(inst)).intValue();
            String className = "lapin.eval.Funcall";
            String methodName = nargs < 0 ? "funcall" : "funcall" + nargs;
            Class rType = Object.class;
            Class[] pTypes;
            if (nargs < 0) {
                pTypes = new Class[] { Function.class, Object.class, // list of args
                        Env.class };
            } else {
                pTypes = new Class[nargs + 2];
                pTypes[0] = Function.class;
                for (int j = 0; j < nargs; j++) {
                    pTypes[j + 1] = Object.class;
                }
                pTypes[nargs + 1] = Env.class;
            }

            Type retType = Type.getType(rType);
            Type[] paramTypes = new Type[pTypes.length];
            for (int j = 0; j < pTypes.length; j++)
                paramTypes[j] = Type.getType(pTypes[j]);

            mv.visitMethodInsn(Opcodes.INVOKESTATIC, toInternalName(className), methodName,
                    Type.getMethodDescriptor(retType, paramTypes));
        } else if (id == Insts.CALL_DIRECT) {
            /*
             * public class Foo
             *   extends CompiledExpr implements Callable2 {
             *  public Object call2(Object arg0, Object arg1, Env env) {
             *   ...
             *  }
             * }
             */
            MethodInfo mi = (MethodInfo) Lists.cadr(inst);
            String className = mi.classInfo().classname();
            int nargs = mi.nargs();
            boolean rest = mi.rest();
            String methodName = mi.name();
            Class rType = mi.retType();
            Class[] pTypes = mi.paramTypes();

            Type retType = Type.getType(rType);
            Type[] paramTypes = new Type[pTypes.length];
            for (int j = 0; j < pTypes.length; j++)
                paramTypes[j] = Type.getType(pTypes[j]);

            mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, toInternalName(className), methodName,
                    Type.getMethodDescriptor(retType, paramTypes));
        } else if (id == Insts.COMPILED_EXPR) {
            /*
             * public class Foo extends CompiledExpr {
             *  static public Foo SELF;
             *  ...
             * }
             */
            String className = Data.string(Lists.cadr(inst));
            String fieldName = "SELF";
            String typeName = className;
            mv.visitFieldInsn(Opcodes.GETSTATIC, toInternalName(className), fieldName,
                    toTypeDescriptor(typeName));
        } else if (id == Insts.RETURN) {
            /* return */
            Class type = Data.javaClass(Lists.cadr(inst));
            if (type.equals(int.class) || type.equals(short.class) || type.equals(byte.class)
                    || type.equals(char.class)) {
                mv.visitInsn(Opcodes.IRETURN);
            } else if (type.equals(long.class)) {
                mv.visitInsn(Opcodes.LRETURN);
            } else if (type.equals(float.class)) {
                mv.visitInsn(Opcodes.FRETURN);
            } else if (type.equals(double.class)) {
                mv.visitInsn(Opcodes.DRETURN);
            } else if (type.equals(void.class)) {
                //mv.visitInsn(Opcodes.RETURN);
                throw new NotReachedException("unsupported returnType: ~S.", Lists.list(type));
            } else {
                mv.visitInsn(Opcodes.ARETURN);
            }
        } else if (id == Insts.IFEQ) {
            /* conditional jump */
            Symbol tag = Data.symbol(Lists.cadr(inst));
            Label l = (Label) ci.labelTable.get(tag);
            if (l == null) {
                throw new NotReachedException("label not found: ~S.", Lists.list(tag));
            }
            mv.visitJumpInsn(Opcodes.IFEQ, l);
        } else if (id == Insts.IFNE) {
            /* conditional jump */
            Symbol tag = Data.symbol(Lists.cadr(inst));
            Label l = (Label) ci.labelTable.get(tag);
            if (l == null) {
                throw new NotReachedException("label not found: ~S.", Lists.list(tag));
            }
            mv.visitJumpInsn(Opcodes.IFNE, l);
        } else if (id == Insts.GOTO) {
            /* jump */
            Symbol tag = Data.symbol(Lists.cadr(inst));
            Label l = (Label) ci.labelTable.get(tag);
            if (l == null) {
                throw new NotReachedException("label not found: ~S.", Lists.list(tag));
            }
            mv.visitJumpInsn(Opcodes.GOTO, l);
        } else if (id == Insts.LOAD) {
            /* local -> stack */
            Object localVar = Lists.cadr(inst);
            Object slot = Lists.cadr(localVar);
            Class type = Data.javaClass(Lists.caddr(localVar));
            int local = Data.fixnum(ci.localTable.get(slot)).intValue();
            int op = Type.getType(type).getOpcode(Opcodes.ILOAD);
            if (Logger.tracelevelp(env))
                Logger.trace("[asm:gen]" + i + ":\tload: local=~S type=~S",
                        Lists.list(Data.toFixnum(local), type), env);
            mv.visitVarInsn(op, local);
        } else if (id == Insts.STORE) {
            /* stack -> local */
            Object localVar = Lists.cadr(inst);
            Object slot = Lists.cadr(localVar);
            Class type = Data.javaClass(Lists.caddr(localVar));
            int local = Data.fixnum(ci.localTable.get(slot)).intValue();
            int op = Type.getType(type).getOpcode(Opcodes.ISTORE);
            if (Logger.tracelevelp(env))
                Logger.trace("[asm:gen]" + i + ":\tstore: local=~S type=~S",
                        Lists.list(Data.toFixnum(local), type), env);
            mv.visitVarInsn(op, local);
        } else if (id == Insts.POP) {
            /* pop a value and discard it */
            Class type = Data.javaClass(Lists.cadr(inst));
            int op;
            switch (Classes.sizeOf(type)) {
            case 1:
                op = Opcodes.POP;
                break;
            case 2:
                op = Opcodes.POP2;
                break;
            default:
                throw new NotReachedException("unsupported type: ~S.", Lists.list(type));
            }
            mv.visitInsn(op);
        } else if (id == Insts.DUP) {
            /* peek a value and duplicate it */
            Class type = Data.javaClass(Lists.cadr(inst));
            int op;
            switch (Classes.sizeOf(type)) {
            case 1:
                op = Opcodes.DUP;
                break;
            case 2:
                op = Opcodes.DUP2;
                break;
            default:
                throw new NotReachedException("unsupported type: ~S.", Lists.list(type));
            }
            mv.visitInsn(op);
        } else if (id == Insts.PUSH) {
            /* push a constant */
            Object val = Lists.cadr(inst);
            if (Data.isJavaBoolean(val)) {
                if (Data.javaBoolean(val).booleanValue())
                    mv.visitInsn(Opcodes.ICONST_1);
                else
                    mv.visitInsn(Opcodes.ICONST_0);
            } else if (val instanceof Byte || val instanceof Short || val instanceof Integer) {
                int n = Data.javaNumber(val).intValue();
                if (n == -1)
                    mv.visitInsn(Opcodes.ICONST_M1);
                else if (n == 0)
                    mv.visitInsn(Opcodes.ICONST_0);
                else if (n == 1)
                    mv.visitInsn(Opcodes.ICONST_1);
                else if (n == 2)
                    mv.visitInsn(Opcodes.ICONST_2);
                else if (n == 3)
                    mv.visitInsn(Opcodes.ICONST_3);
                else if (n == 4)
                    mv.visitInsn(Opcodes.ICONST_4);
                else if (n == 5)
                    mv.visitInsn(Opcodes.ICONST_5);
                else if (Byte.MIN_VALUE <= n && n <= Byte.MAX_VALUE)
                    mv.visitIntInsn(Opcodes.BIPUSH, n);
                else if (Short.MIN_VALUE <= n && n <= Short.MAX_VALUE)
                    mv.visitIntInsn(Opcodes.SIPUSH, n);
                else
                    mv.visitLdcInsn(Data.toFixnum(n));
            } else if (val instanceof Long) {
                long n = Data.javaNumber(val).longValue();
                if (n == 0L)
                    mv.visitInsn(Opcodes.LCONST_0);
                else if (n == 1L)
                    mv.visitInsn(Opcodes.LCONST_1);
                else
                    mv.visitLdcInsn(val);
            } else if (val instanceof Float) {
                float n = Data.javaNumber(val).floatValue();
                if (n == 0.0f)
                    mv.visitInsn(Opcodes.FCONST_0);
                else if (n == 1.0f)
                    mv.visitInsn(Opcodes.FCONST_1);
                else if (n == 2.0f)
                    mv.visitInsn(Opcodes.FCONST_2);
                else
                    mv.visitLdcInsn(val);
            } else if (val instanceof Double) {
                double n = Data.javaNumber(val).doubleValue();
                if (n == 0.0)
                    mv.visitInsn(Opcodes.DCONST_0);
                else if (n == 1.0)
                    mv.visitInsn(Opcodes.DCONST_1);
                else
                    mv.visitLdcInsn(val);
            } else if (Data.isCharacter(val)) {
                Character c = Data.character(val);
                int n = (int) c.charValue();
                if (Byte.MIN_VALUE <= n && n <= Byte.MAX_VALUE)
                    mv.visitIntInsn(Opcodes.BIPUSH, n);
                else if (Short.MIN_VALUE <= n && n <= Short.MAX_VALUE)
                    mv.visitIntInsn(Opcodes.SIPUSH, n);
                else
                    mv.visitLdcInsn(Data.toFixnum(n));
            } else if (Data.isString(val)) {
                mv.visitLdcInsn(val);
            } else {
                throw new NotReachedException("cannot push: ~S.", Lists.list(val));
            }
        } else if (id == Insts.GET) {
            Field f = Data.javaField(Lists.cadr(inst));
            String fieldName = f.getName();
            Class c = f.getDeclaringClass();
            String className = c.getName();
            Class t = f.getType();
            String typeName = t.getName();

            boolean isStatic = Classes.isStatic(f);
            int op = isStatic ? Opcodes.GETSTATIC : Opcodes.GETFIELD;

            mv.visitFieldInsn(op, toInternalName(className), fieldName, toTypeDescriptor(typeName));
        } else if (id == Insts.PUT) {
            Field f = Data.javaField(Lists.cadr(inst));
            String fieldName = f.getName();
            Class c = f.getDeclaringClass();
            String className = c.getName();
            Class t = f.getType();
            String typeName = t.getName();

            boolean isStatic = Classes.isStatic(f);
            int op = isStatic ? Opcodes.PUTSTATIC : Opcodes.PUTFIELD;

            mv.visitFieldInsn(op, toInternalName(className), fieldName, toTypeDescriptor(typeName));
        } else if (id == Insts.INVOKE) {
            Method m = Data.javaMethod(Lists.cadr(inst));
            String methodName = m.getName();
            Class c = m.getDeclaringClass();
            String className = c.getName();
            Class rType = m.getReturnType();
            Class[] pTypes = m.getParameterTypes();
            if (rType.equals(void.class)) {
                throw new NotReachedException("unsupported returnType: ~S.", Lists.list(rType));
            }
            Type retType = Type.getType(rType);
            Type[] paramTypes = new Type[pTypes.length];
            for (int j = 0; j < pTypes.length; j++)
                paramTypes[j] = Type.getType(pTypes[j]);

            boolean isStatic = Classes.isStatic(m);
            boolean isInterface = c.isInterface();
            int op = isStatic ? Opcodes.INVOKESTATIC
                    : isInterface ? Opcodes.INVOKEINTERFACE : Opcodes.INVOKEVIRTUAL;

            mv.visitMethodInsn(op, toInternalName(className), methodName,
                    Type.getMethodDescriptor(retType, paramTypes));
        } else if (id == Insts.CHECKCAST) {
            Class c = Data.javaClass(Lists.cadr(inst));
            Type t = Type.getType(c);
            mv.visitTypeInsn(Opcodes.CHECKCAST, t.getInternalName());
        } else if (id == Insts.THROW) {
            mv.visitInsn(Opcodes.ATHROW);
        } else if (id == Insts.CATCH) {
            Symbol tagS = Data.symbol(Lists.cadr(inst));
            Symbol tagE = Data.symbol(Lists.caddr(inst));
            Symbol tagH = Data.symbol(Lists.cadddr(inst));
            String className;
            if (Lists.isEnd(Lists.cddddr(inst))) {
                className = null;
            } else {
                Class c = Data.javaClass(Lists.car(Lists.cddddr(inst)));
                className = toInternalName(c.getName());
            }
            Label labelS = (Label) ci.labelTable.get(tagS);
            if (labelS == null) {
                throw new NotReachedException("label not found: ~S.", Lists.list(tagS));
            }
            Label labelE = (Label) ci.labelTable.get(tagE);
            if (labelE == null) {
                throw new NotReachedException("label not found: ~S.", Lists.list(tagE));
            }
            Label labelH = (Label) ci.labelTable.get(tagH);
            if (labelH == null) {
                throw new NotReachedException("label not found: ~S.", Lists.list(tagH));
            }
            mv.visitTryCatchBlock(labelS, labelE, labelH, className);
        }
        //else if (id == Insts.CATCH_FROM ||
        //         id == Insts.CATCH_TO ||
        //         id == Insts.CATCH_HANDLER) {
        //    /* nothing emitted */
        //    continue;
        //}
        else {
            throw new NotReachedException("unknown inst: ~S.", Lists.list(inst));
        }
    }
    mv.visitMaxs(0, 0);
    mv.visitEnd();
}

From source file:lucee.transformer.bytecode.statement.tag.TagLoop.java

License:Open Source License

/**
 * write out list loop//from www  .  java2s  .co  m
 * @param adapter
 * @throws TemplateException
 */
private void writeOutTypeListArray(BytecodeContext bc, boolean isArray) throws BytecodeException {
    ForVisitor forVisitor = new ForVisitor();
    loopVisitor = forVisitor;
    GeneratorAdapter adapter = bc.getAdapter();

    //List.listToArrayRemoveEmpty("", 'c')
    int array = adapter.newLocal(Types.ARRAY);
    int len = adapter.newLocal(Types.INT_VALUE);

    if (isArray) {
        getAttribute("array").getValue().writeOut(bc, Expression.MODE_REF);
    } else {
        // array=List.listToArrayRemoveEmpty(list, delimter)
        getAttribute("list").getValue().writeOut(bc, Expression.MODE_REF);
        if (containsAttribute("delimiters")) {
            getAttribute("delimiters").getValue().writeOut(bc, Expression.MODE_REF);
            adapter.invokeStatic(Types.LIST_UTIL, LIST_TO_ARRAY_REMOVE_EMPTY_SS);
        } else {
            adapter.visitIntInsn(Opcodes.BIPUSH, 44);// ','
            //adapter.push(',');
            adapter.invokeStatic(Types.LIST_UTIL, LIST_TO_ARRAY_REMOVE_EMPTY_SC);
        }
    }
    adapter.storeLocal(array);

    // int len=array.size();
    adapter.loadLocal(array);
    adapter.invokeInterface(Types.ARRAY, SIZE);
    adapter.storeLocal(len);

    //VariableInterpreter.getVariableReference(pc,Caster.toString(index));
    Attribute attrIndex = getAttribute("index");
    int index = -1;
    if (attrIndex != null) {
        index = adapter.newLocal(Types.VARIABLE_REFERENCE);
        adapter.loadArg(0);
        attrIndex.getValue().writeOut(bc, Expression.MODE_REF);
        adapter.invokeStatic(Types.VARIABLE_INTERPRETER, GET_VARIABLE_REFERENCE);
        adapter.storeLocal(index);
    }

    //VariableInterpreter.getVariableReference(pc,Caster.toString(item));
    Attribute attrItem = getAttribute("item");
    int item = -1;
    if (attrItem != null) {
        item = adapter.newLocal(Types.VARIABLE_REFERENCE);
        adapter.loadArg(0);
        attrItem.getValue().writeOut(bc, Expression.MODE_REF);
        adapter.invokeStatic(Types.VARIABLE_INTERPRETER, GET_VARIABLE_REFERENCE);
        adapter.storeLocal(item);
    }

    int obj = 0;
    if (isArray)
        obj = adapter.newLocal(Types.OBJECT);

    // for(int i=1;i<=len;i++) {      
    int i = forVisitor.visitBegin(adapter, 1, false);
    // index.set(pc, list.get(i));

    if (isArray) {

        // value
        adapter.loadLocal(array);
        adapter.visitVarInsn(Opcodes.ILOAD, i);
        ASMConstants.NULL(adapter);
        adapter.invokeInterface(Types.ARRAY, GET);
        adapter.dup();
        adapter.storeLocal(obj);
        Label endIf = new Label();
        //adapter.loadLocal(obj);
        adapter.visitJumpInsn(Opcodes.IFNONNULL, endIf);
        adapter.goTo(forVisitor.getContinueLabel());
        adapter.visitLabel(endIf);

        if (item == -1)
            adapter.loadLocal(index);
        else
            adapter.loadLocal(item);

        adapter.loadArg(0);

        adapter.loadLocal(obj);

    } else {
        if (item == -1)
            adapter.loadLocal(index);
        else
            adapter.loadLocal(item);
        adapter.loadArg(0);
        adapter.loadLocal(array);
        adapter.visitVarInsn(Opcodes.ILOAD, i);
        adapter.invokeInterface(Types.ARRAY, GETE);

    }
    adapter.invokeVirtual(Types.VARIABLE_REFERENCE, SET);
    adapter.pop();

    // key
    if (index != -1 && item != -1) {
        adapter.loadLocal(index);
        adapter.loadArg(0);
        adapter.visitVarInsn(Opcodes.ILOAD, i);
        adapter.cast(Types.INT_VALUE, Types.DOUBLE_VALUE);
        adapter.invokeStatic(Types.CASTER, Methods_Caster.TO_DOUBLE[Methods_Caster.DOUBLE]);
        adapter.invokeVirtual(Types.VARIABLE_REFERENCE, SET);
        adapter.pop();
    }

    getBody().writeOut(bc);
    forVisitor.visitEnd(bc, len, true, getStart());
}

From source file:name.martingeisse.minimal.compiler.Compiler.java

License:Open Source License

/**
 * Compiles a {@link MethodNode} to MCode.
 * //from www .j a v a  2 s .  c  o  m
 * @param methodNode the method node to compile
 * @return the compiled code
 */
public ImmutableList<MCodeEntry> compile(final MethodNode methodNode) {
    for (int i = 0; i < methodNode.instructions.size(); i++) {
        final AbstractInsnNode instruction = methodNode.instructions.get(i);
        if (instruction instanceof LineNumberNode) {
            // ignored
        } else if (instruction instanceof FrameNode) {
            // this could be useful in the future
        } else if (instruction instanceof LabelNode) {
            label(((LabelNode) instruction).getLabel());
        } else if (instruction instanceof InsnNode) {
            switch (instruction.getOpcode()) {

            case Opcodes.ICONST_M1:
                iconst(-1);
                break;

            case Opcodes.ICONST_0:
                iconst(0);
                break;

            case Opcodes.ICONST_1:
                iconst(1);
                break;

            case Opcodes.ICONST_2:
                iconst(2);
                break;

            case Opcodes.ICONST_3:
                iconst(3);
                break;

            case Opcodes.ICONST_4:
                iconst(4);
                break;

            case Opcodes.ICONST_5:
                iconst(5);
                break;

            default:
                unsupported(instruction);
                break;

            }
        } else if (instruction instanceof VarInsnNode) {
            final VarInsnNode varInsnNode = (VarInsnNode) instruction;
            switch (varInsnNode.getOpcode()) {

            case Opcodes.ILOAD:
                iload(varInsnNode.var);
                break;

            case Opcodes.ISTORE:
                istore(varInsnNode.var);
                break;

            default:
                unsupported(instruction);
                break;

            }
        } else if (instruction instanceof IincInsnNode) {
            final IincInsnNode iincInsnNode = (IincInsnNode) instruction;
            iinc(iincInsnNode.var, iincInsnNode.incr);
        } else if (instruction instanceof JumpInsnNode) {
            final JumpInsnNode jumpInsnNode = (JumpInsnNode) instruction;
            switch (jumpInsnNode.getOpcode()) {

            case Opcodes.IFEQ:
            case Opcodes.IFNE:
            case Opcodes.IFLT:
            case Opcodes.IFGE:
            case Opcodes.IFGT:
            case Opcodes.IFLE:
                branch1(jumpInsnNode.label.getLabel(), jumpInsnNode.getOpcode());
                break;

            case Opcodes.IF_ICMPEQ:
            case Opcodes.IF_ICMPNE:
            case Opcodes.IF_ICMPLT:
            case Opcodes.IF_ICMPGE:
            case Opcodes.IF_ICMPGT:
            case Opcodes.IF_ICMPLE:
                branch2(jumpInsnNode.label.getLabel(), jumpInsnNode.getOpcode());
                break;

            case Opcodes.IFNULL:
            case Opcodes.IFNONNULL:
                // unsupported: one-argument reference comparison operator
                unsupported(instruction);
                break;

            case Opcodes.IF_ACMPEQ:
            case Opcodes.IF_ACMPNE:
                // unsupported: two-argument reference comparison operator
                unsupported(instruction);
                break;

            case Opcodes.GOTO:
                jump(jumpInsnNode.label.getLabel());
                break;

            case Opcodes.JSR:
                jsr(jumpInsnNode.label.getLabel());
                break;

            default:
                unsupported(instruction);
                break;

            }
        } else if (instruction instanceof IntInsnNode) {
            final IntInsnNode intInsnNode = (IntInsnNode) instruction;
            if (instruction.getOpcode() == Opcodes.BIPUSH || instruction.getOpcode() == Opcodes.SIPUSH) {
                iconst(intInsnNode.operand);
            } else {
                // NEWARRAY
                unsupported(instruction);
            }
        } else if (instruction instanceof MethodInsnNode) {
            final MethodInsnNode methodInsnNode = (MethodInsnNode) instruction;
            if (methodInsnNode.getOpcode() == Opcodes.INVOKESTATIC) {
                if (methodInsnNode.owner.replace('/', '.').equals(Native.class.getName())) {
                    nativeCall(methodInsnNode.name, methodInsnNode.desc);
                } else {
                    unsupported(instruction);
                }
            } else {
                unsupported(instruction);
            }
        } else {
            unsupported(instruction);
        }
    }
    return builder.build();
}

From source file:net.yrom.tools.RSymbols.java

License:Apache License

private void drainSymbols(Path file) {
    final String filename = file.getFileName().toString();
    String typeName = filename.substring(0, filename.length() - ".class".length());
    byte[] bytes;
    try {//from  w  w w .  ja  v  a2 s  .c  o  m
        bytes = Files.readAllBytes(file);
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
    ClassVisitor visitor = new ClassVisitor(Opcodes.ASM5) {
        @Override
        public FieldVisitor visitField(int access, String name, String desc, String signature, Object value) {
            // read constant value
            if (value instanceof Integer) {
                String key = typeName + '.' + name;
                Integer old = symbols.get(key);
                if (old != null && !old.equals(value)) {
                    throw new IllegalStateException("Value of " + key + " mismatched! " + "Excepted 0x"
                            + Integer.toHexString(old) + " but was 0x" + Integer.toHexString((Integer) value));
                } else {
                    symbols.put(key, (Integer) value);
                }
            }
            return null;
        }

        @Override
        public MethodVisitor visitMethod(int access, String name, String desc, String signature,
                String[] exceptions) {
            if (access == Opcodes.ACC_STATIC && "<clinit>".equals(name)) {

                return new MethodVisitor(Opcodes.ASM5) {
                    int[] current = null;
                    LinkedList<Integer> intStack = new LinkedList<>();

                    @Override
                    public void visitIntInsn(int opcode, int operand) {
                        if (opcode == Opcodes.NEWARRAY && operand == Opcodes.T_INT) {
                            current = new int[intStack.pop()];
                        } else if (opcode == Opcodes.BIPUSH) {
                            intStack.push(operand);
                        }
                    }

                    @Override
                    public void visitLdcInsn(Object cst) {
                        if (cst instanceof Integer) {
                            intStack.push((Integer) cst);
                        }
                    }

                    @Override
                    public void visitInsn(int opcode) {
                        if (opcode >= Opcodes.ICONST_0 && opcode <= Opcodes.ICONST_5) {
                            intStack.push(opcode - Opcodes.ICONST_0);
                        } else if (opcode == Opcodes.IASTORE) {
                            int value = intStack.pop();
                            int index = intStack.pop();
                            current[index] = value;
                        }
                    }

                    @Override
                    public void visitFieldInsn(int opcode, String owner, String name, String desc) {
                        if (opcode == Opcodes.PUTSTATIC) {
                            int[] old = styleables.get(name);
                            if (old != null && old.length != current.length && !Arrays.equals(old, current)) {
                                throw new IllegalStateException("Value of styleable." + name + " mismatched! "
                                        + "Excepted " + Arrays.toString(old) + " but was "
                                        + Arrays.toString(current));
                            } else {
                                styleables.put(name, current);
                            }
                            current = null;
                            intStack.clear();
                        }
                    }
                };
            }
            return null;
        }
    };

    new ClassReader(bytes).accept(visitor, SKIP_DEBUG | SKIP_FRAMES);
}

From source file:net.yrom.tools.ShrinkRClassVisitor.java

License:Apache License

private static void pushInt(MethodVisitor mv, int i) {
    if (0 <= i && i <= 5) {
        mv.visitInsn(Opcodes.ICONST_0 + i); //  ICONST_0 ~ ICONST_5
    } else if (i <= Byte.MAX_VALUE) {
        mv.visitIntInsn(Opcodes.BIPUSH, i);
    } else if (i <= Short.MAX_VALUE) {
        mv.visitIntInsn(Opcodes.SIPUSH, i);
    } else {/*  w  w w  .ja  v  a  2 s .  c o  m*/
        mv.visitLdcInsn(i);
    }
}