Example usage for org.objectweb.asm MethodVisitor visitIntInsn

List of usage examples for org.objectweb.asm MethodVisitor visitIntInsn

Introduction

In this page you can find the example usage for org.objectweb.asm MethodVisitor visitIntInsn.

Prototype

public void visitIntInsn(final int opcode, final int operand) 

Source Link

Document

Visits an instruction with a single int operand.

Usage

From source file:kilim.analysis.CallWeaver.java

License:Open Source License

/**
 * Yielding, but state hasn't been captured yet. We create a state object
 * and save each object in valInfoList in its corresponding field.
 * //from   www . jav a2s .co  m
 * Note that we save each stack item into a scratch register before loading
 * it into a field. The reason is that we need to get the State ref under
 * the stack item before we can do a putfield. The alternative is to load
 * the State item, then do a swap or a dup_x2;pop (depending on the value's
 * category). We'll go with the earlier approach because stack manipulations
 * don't seem to perform as well in the current crop of JVMs.
 * 
 * @param mv
 */
private void genSave(MethodVisitor mv, Label saveLabel) {
    mv.visitLabel(saveLabel);

    Frame f = bb.startFrame;
    // pop return value if any.
    String retType = getReturnType();
    if (retType != D_VOID) {
        // Yielding, so the return value from the called
        // function is a dummy value
        mv.visitInsn(TypeDesc.isDoubleWord(retType) ? POP2 : POP);
    }
    /*
     * Instantiate state class. Call one of new xxxState(this, pc, fiber),
     * or new xxxState(pc, fiber) depending whether this method is static or
     * not. Note that are not referring to the called method.
     * 
     * pc, "the program counter" is merely the index of the call weaver in
     * the method weaver's list. This allows us to do a switch in the
     * method's entry.
     */
    mv.visitTypeInsn(NEW, stateClassName);
    mv.visitInsn(DUP); // 
    // call constructor
    mv.visitMethodInsn(INVOKESPECIAL, stateClassName, "<init>", "()V");
    // save state in register
    int stateVar = allocVar(1);
    storeVar(mv, TOBJECT, stateVar);
    // state.self = this if the current executing method isn't static
    if (!bb.flow.isStatic()) {
        loadVar(mv, TOBJECT, stateVar);
        mv.visitInsn(ALOAD_0); // for state.self == this
        mv.visitFieldInsn(PUTFIELD, STATE_CLASS, "self", D_OBJECT);
    }
    int pc = methodWeaver.getPC(this);
    loadVar(mv, TOBJECT, stateVar); // state.pc
    if (pc < 6) {
        mv.visitInsn(ICONST_0 + pc);
    } else {
        mv.visitIntInsn(BIPUSH, pc);
    }
    mv.visitFieldInsn(PUTFIELD, STATE_CLASS, "pc", D_INT);

    // First save bottom stack into state
    int i = getNumBottom() - 1;
    for (; i >= 0; i--) {
        Value v = f.getStack(i);
        ValInfo vi = valInfoList.find(v);
        if (vi == null) {
            // it must be a constant or a duplicate, which is why we don't
            // have any information on it. just pop it.
            mv.visitInsn(v.category() == 2 ? POP2 : POP);
        } else {
            /**
             * xstore <scratchVar> ; send stack elem to some local var 
             * aload <stateVar>    ; load state 
             * xload <scratchVar>  ; get stack elem back 
             * putfield ...        ; state.fx =
             */
            int var = allocVar(vi.val.category());
            storeVar(mv, vi.vmt, var);
            loadVar(mv, VMType.TOBJECT, stateVar);
            loadVar(mv, vi.vmt, var);
            mv.visitFieldInsn(PUTFIELD, stateClassName, vi.fieldName, vi.fieldDesc());
            releaseVar(var, vi.val.category());
        }
    }

    // Now load up registers into fields
    int fieldNum = 0;
    for (ValInfo vi : valInfoList) {
        // Ignore values on stack
        if (vi.var == -1)
            continue;
        // aload state var
        // xload <var>
        loadVar(mv, TOBJECT, stateVar);
        loadVar(mv, vi.vmt, vi.var);
        mv.visitFieldInsn(PUTFIELD, stateClassName, vi.fieldName, vi.fieldDesc());
        fieldNum++;
    }

    // Fiber.setState(state);
    loadVar(mv, TOBJECT, methodWeaver.getFiberVar());
    loadVar(mv, TOBJECT, stateVar);
    mv.visitMethodInsn(INVOKEVIRTUAL, FIBER_CLASS, "setState", "(" + D_STATE + ")V");
    releaseVar(stateVar, 1);
    // Figure out the return type of the calling method and issue the
    // appropriate xRETURN instruction
    retType = TypeDesc.getReturnTypeDesc(bb.flow.desc);
    if (retType == D_VOID) {
        mv.visitInsn(RETURN);
    } else {
        int vmt = VMType.toVmType(retType);
        // ICONST_0, DCONST_0 etc.
        mv.visitInsn(VMType.constInsn[vmt]);
        // IRETURN, DRETURN, etc.
        mv.visitInsn(VMType.retInsn[vmt]);
    }
}

From source file:kilim.analysis.CallWeaver.java

License:Open Source License

private void loadConstant(MethodVisitor mv, Value v) {
    if (v.getTypeDesc() == D_NULL) {
        mv.visitInsn(ACONST_NULL);/* ww  w.  j  a  v a2 s .  c om*/
        return;
    }
    Object c = v.getConstVal();
    if (c instanceof Integer) {
        int i = (Integer) c;
        if (i > -1 && i <= 5) {
            mv.visitInsn(i + 1 + ICONST_M1);
            return;
        } else if (i >= Byte.MIN_VALUE && i <= Byte.MAX_VALUE) {
            mv.visitIntInsn(BIPUSH, i);
            return;
        } else if (i >= Short.MIN_VALUE && i <= Short.MAX_VALUE) {
            mv.visitIntInsn(SIPUSH, i);
            return;
        }
    } else if (c instanceof Float) {
        Float f = ((Float) c).floatValue();
        int insn = 0;
        if (f == 0.0)
            insn = FCONST_0;
        else if (f == 1.0)
            insn = FCONST_1;
        else if (f == 2.0)
            insn = FCONST_2;
        if (insn != 0) {
            mv.visitInsn(insn);
            return;
        }
    } else if (c instanceof Long) {
        Long l = ((Long) c).longValue();
        int insn = 0;
        if (l == 0L)
            insn = LCONST_0;
        else if (l == 1L)
            insn = LCONST_1;
        if (insn != 0) {
            mv.visitInsn(insn);
            return;
        }
    } else if (c instanceof Double) {
        Double d = ((Double) c).doubleValue();
        int insn = 0;
        if (d == 0.0)
            insn = DCONST_0;
        else if (d == 1.0)
            insn = DCONST_1;
        if (insn != 0) {
            mv.visitInsn(insn);
            return;
        }
    }
    // No special constants found.
    mv.visitLdcInsn(c);
}

From source file:kr.debop4j.core.reflect.MethodAccess.java

License:Apache License

/**
 *  ? ? ??   MethodAccess .//from  w w  w.  j  ava2 s  .com
 *
 * @param type 
 * @return the method access
 */
public static MethodAccess get(final Class type) {
    Guard.shouldNotBeNull(type, "type");

    List<Method> methods = Lists.newArrayList();
    Class nextClass = type;
    while (nextClass != Object.class) {
        Method[] declaredMethods = nextClass.getDeclaredMethods();
        for (Method method : declaredMethods) {
            int modifiers = method.getModifiers();
            if (Modifier.isStatic(modifiers))
                continue;
            if (Modifier.isPrivate(modifiers))
                continue;
            methods.add(method);
        }
        nextClass = nextClass.getSuperclass();
    }

    Class[][] parameterTypes = new Class[methods.size()][];
    String[] methodNames = new String[methods.size()];
    for (int i = 0, size = methodNames.length; i < size; i++) {
        Method method = methods.get(i);
        methodNames[i] = method.getName();
        parameterTypes[i] = method.getParameterTypes();
    }

    String className = type.getName();
    String accessClassName = className + "MethodAccess";
    if (accessClassName.startsWith("java."))
        accessClassName = ReflectConsts.BASE_PACKAGE + "." + accessClassName;

    Class accessClass;
    AccessClassLoader loader = AccessClassLoader.get(type);

    synchronized (loader) {
        try {
            accessClass = loader.loadClass(accessClassName);
        } catch (ClassNotFoundException ignored) {
            String accessClassNameInternal = accessClassName.replace('.', '/');
            String classNameInternal = className.replace('.', '/');

            ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS);
            MethodVisitor mv;
            cw.visit(V1_1, ACC_PUBLIC + ACC_SUPER, accessClassNameInternal, null,
                    ReflectConsts.METHOD_ACCESS_PATH, null);
            {
                mv = cw.visitMethod(ACC_PUBLIC, "<init>", "()V", null, null);
                mv.visitCode();
                mv.visitVarInsn(ALOAD, 0);
                mv.visitMethodInsn(INVOKESPECIAL, ReflectConsts.METHOD_ACCESS_PATH, "<init>", "()V");
                mv.visitInsn(RETURN);
                mv.visitMaxs(0, 0);
                mv.visitEnd();
            }
            {
                mv = cw.visitMethod(ACC_PUBLIC + ACC_VARARGS, "invoke",
                        "(Ljava/lang/Object;I[Ljava/lang/Object;)Ljava/lang/Object;", null, null);
                mv.visitCode();

                if (!methods.isEmpty()) {
                    mv.visitVarInsn(ALOAD, 1);
                    mv.visitTypeInsn(CHECKCAST, classNameInternal);
                    mv.visitVarInsn(ASTORE, 4);

                    mv.visitVarInsn(ILOAD, 2);
                    Label[] labels = new Label[methods.size()];
                    for (int i = 0, n = labels.length; i < n; i++)
                        labels[i] = new Label();
                    Label defaultLabel = new Label();
                    mv.visitTableSwitchInsn(0, labels.length - 1, defaultLabel, labels);

                    StringBuilder buffer = new StringBuilder(128);
                    for (int i = 0, n = labels.length; i < n; i++) {
                        mv.visitLabel(labels[i]);
                        if (i == 0)
                            mv.visitFrame(Opcodes.F_APPEND, 1, new Object[] { classNameInternal }, 0, null);
                        else
                            mv.visitFrame(Opcodes.F_SAME, 0, null, 0, null);
                        mv.visitVarInsn(ALOAD, 4);

                        buffer.setLength(0);
                        buffer.append('(');

                        Method method = methods.get(i);
                        Class[] paramTypes = method.getParameterTypes();
                        for (int paramIndex = 0; paramIndex < paramTypes.length; paramIndex++) {
                            mv.visitVarInsn(ALOAD, 3);
                            mv.visitIntInsn(BIPUSH, paramIndex);
                            mv.visitInsn(AALOAD);
                            Type paramType = Type.getType(paramTypes[paramIndex]);
                            switch (paramType.getSort()) {
                            case Type.BOOLEAN:
                                mv.visitTypeInsn(CHECKCAST, "java/lang/Boolean");
                                mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Boolean", "booleanValue", "()Z");
                                break;
                            case Type.BYTE:
                                mv.visitTypeInsn(CHECKCAST, "java/lang/Byte");
                                mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Byte", "byteValue", "()B");
                                break;
                            case Type.CHAR:
                                mv.visitTypeInsn(CHECKCAST, "java/lang/Character");
                                mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Character", "charValue", "()C");
                                break;
                            case Type.SHORT:
                                mv.visitTypeInsn(CHECKCAST, "java/lang/Short");
                                mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Short", "shortValue", "()S");
                                break;
                            case Type.INT:
                                mv.visitTypeInsn(CHECKCAST, "java/lang/Integer");
                                mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Integer", "intValue", "()I");
                                break;
                            case Type.FLOAT:
                                mv.visitTypeInsn(CHECKCAST, "java/lang/Float");
                                mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Float", "floatValue", "()F");
                                break;
                            case Type.LONG:
                                mv.visitTypeInsn(CHECKCAST, "java/lang/Long");
                                mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Long", "longValue", "()J");
                                break;
                            case Type.DOUBLE:
                                mv.visitTypeInsn(CHECKCAST, "java/lang/Double");
                                mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Double", "doubleValue", "()D");
                                break;
                            case Type.ARRAY:
                                mv.visitTypeInsn(CHECKCAST, paramType.getDescriptor());
                                break;
                            case Type.OBJECT:
                                mv.visitTypeInsn(CHECKCAST, paramType.getInternalName());
                                break;
                            }
                            buffer.append(paramType.getDescriptor());
                        }

                        buffer.append(')');
                        buffer.append(Type.getDescriptor(method.getReturnType()));
                        mv.visitMethodInsn(INVOKEVIRTUAL, classNameInternal, method.getName(),
                                buffer.toString());

                        switch (Type.getType(method.getReturnType()).getSort()) {
                        case Type.VOID:
                            mv.visitInsn(ACONST_NULL);
                            break;
                        case Type.BOOLEAN:
                            mv.visitMethodInsn(INVOKESTATIC, "java/lang/Boolean", "valueOf",
                                    "(Z)Ljava/lang/Boolean;");
                            break;
                        case Type.BYTE:
                            mv.visitMethodInsn(INVOKESTATIC, "java/lang/Byte", "valueOf",
                                    "(B)Ljava/lang/Byte;");
                            break;
                        case Type.CHAR:
                            mv.visitMethodInsn(INVOKESTATIC, "java/lang/Character", "valueOf",
                                    "(C)Ljava/lang/Character;");
                            break;
                        case Type.SHORT:
                            mv.visitMethodInsn(INVOKESTATIC, "java/lang/Short", "valueOf",
                                    "(S)Ljava/lang/Short;");
                            break;
                        case Type.INT:
                            mv.visitMethodInsn(INVOKESTATIC, "java/lang/Integer", "valueOf",
                                    "(I)Ljava/lang/Integer;");
                            break;
                        case Type.FLOAT:
                            mv.visitMethodInsn(INVOKESTATIC, "java/lang/Float", "valueOf",
                                    "(F)Ljava/lang/Float;");
                            break;
                        case Type.LONG:
                            mv.visitMethodInsn(INVOKESTATIC, "java/lang/Long", "valueOf",
                                    "(J)Ljava/lang/Long;");
                            break;
                        case Type.DOUBLE:
                            mv.visitMethodInsn(INVOKESTATIC, "java/lang/Double", "valueOf",
                                    "(D)Ljava/lang/Double;");
                            break;
                        }

                        mv.visitInsn(ARETURN);
                    }

                    mv.visitLabel(defaultLabel);
                    mv.visitFrame(Opcodes.F_SAME, 0, null, 0, null);
                }
                mv.visitTypeInsn(NEW, "java/lang/IllegalArgumentException");
                mv.visitInsn(DUP);
                mv.visitTypeInsn(NEW, "java/lang/StringBuilder");
                mv.visitInsn(DUP);
                mv.visitLdcInsn("Method not found: ");
                mv.visitMethodInsn(INVOKESPECIAL, "java/lang/StringBuilder", "<init>", "(Ljava/lang/String;)V");
                mv.visitVarInsn(ILOAD, 2);
                mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/StringBuilder", "append",
                        "(I)Ljava/lang/StringBuilder;");
                mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/StringBuilder", "toString",
                        "()Ljava/lang/String;");
                mv.visitMethodInsn(INVOKESPECIAL, "java/lang/IllegalArgumentException", "<init>",
                        "(Ljava/lang/String;)V");
                mv.visitInsn(ATHROW);
                mv.visitMaxs(0, 0);
                mv.visitEnd();
            }
            cw.visitEnd();
            byte[] data = cw.toByteArray();
            accessClass = loader.defineClass(accessClassName, data);
        }
    }

    try {
        MethodAccess access = (MethodAccess) accessClass.newInstance();
        access.methodNames = methodNames;
        access.parameterTypes = parameterTypes;

        return access;
    } catch (Exception ex) {
        throw new RuntimeException("Error constructing method access class=[" + accessClassName + "]", ex);
    }
}

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

License:Open Source License

private void generateCall(CallableInfo ci, Env env) {
    /*/*  w  ww  .  j av  a  2 s. c  om*/
     * 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:ldapbeans.bean.LdapBeanClassManager.java

License:LGPL

/**
 * generate code that initialize variable corresponding to temporary result
 * //from w  w w .  j a  v  a 2  s .c o  m
 * @param p_MethodVisitor
 *            The {@link MethodVisitor} of the generated method
 * @param p_Method
 *            the generated method
 * @param p_StartStack
 *            First index of the stack after parameters
 */
private void initializeTempResult(MethodVisitor p_MethodVisitor, int p_StartStack, Method p_Method) {
    MethodVisitor mv = p_MethodVisitor;
    mv.visitInsn(ICONST_0);
    mv.visitVarInsn(ISTORE, p_StartStack + 1);

    Class<?>[] parameterTypes = p_Method.getParameterTypes();
    ConvertAttribute[] annotations = getConvertAttributeAnnotation(p_Method);
    int nbArray = 0;
    for (int i = 0; i < parameterTypes.length; i++) {
        if ((parameterTypes[i].isArray() || Collection.class.isAssignableFrom(parameterTypes[i]))
                && annotations[i] == null) {
            int paramStackIndex = getStackIndexOfParameter(p_Method, i);
            mv.visitVarInsn(ILOAD, p_StartStack + 1);
            mv.visitVarInsn(ALOAD, paramStackIndex);
            if (parameterTypes[i].isArray()) {
                mv.visitInsn(ARRAYLENGTH);
            } else if (Collection.class.isAssignableFrom(parameterTypes[i])) {
                mv.visitMethodInsn(INVOKEINTERFACE, "java/util/Collection", "size", "()I");
            }
            mv.visitInsn(IADD);
            mv.visitVarInsn(ISTORE, p_StartStack + 1);
            nbArray++;
        }
    }
    if (nbArray != 0) {
        mv.visitVarInsn(ILOAD, p_StartStack + 1);
    }
    if (parameterTypes.length != nbArray) {
        mv.visitIntInsn(BIPUSH, parameterTypes.length - nbArray);
    }
    if (nbArray != 0 && parameterTypes.length != nbArray) {
        mv.visitInsn(IADD);
    }
    mv.visitTypeInsn(ANEWARRAY, "java/lang/String");
    mv.visitVarInsn(ASTORE, p_StartStack);
    mv.visitInsn(ICONST_0);
    mv.visitVarInsn(ISTORE, p_StartStack + 1);
}

From source file:mt.swift.Deserializer.java

License:Apache License

private void compileDeserializeMethod(StructureType type, ClassVisitor writer, String targetClassName,
        Class targetClass) {/* ww w  . ja v  a2 s  .  co m*/
    MethodVisitor methodVisitor = writer.visitMethod(
            ACC_PUBLIC, "deserialize", "(L" + Util.getInternalName(Deserializer.class)
                    + ";Lcom/facebook/thrift/protocol/TProtocol;)L" + targetClassName + ";",
            null, new String[] { "com/facebook/thrift/TException" });

    FrameRegisterManager context = new FrameRegisterManager();
    context.bindSlot("this", 0);
    context.bindSlot("deserializer", 1);
    context.bindSlot("protocol", 2);
    context.newSlot("target");
    context.newSlot("tfield");

    methodVisitor.visitCode();

    // <target> result = new <target>()
    methodVisitor.visitTypeInsn(NEW, targetClassName);
    methodVisitor.visitInsn(DUP);
    methodVisitor.visitMethodInsn(INVOKESPECIAL, targetClassName, "<init>", "()V");
    methodVisitor.visitVarInsn(ASTORE, context.getSlot("target"));

    // protocol.readStructBegin()
    methodVisitor.visitVarInsn(ALOAD, context.getSlot("protocol"));
    methodVisitor.visitMethodInsn(INVOKEVIRTUAL, "com/facebook/thrift/protocol/TProtocol", "readStructBegin",
            "()Lcom/facebook/thrift/protocol/TStruct;");
    methodVisitor.visitInsn(POP); // discard return value

    // while (true)
    Label whileLabel = new Label();
    methodVisitor.visitLabel(whileLabel);

    // TField tfield = protocol.readFieldBegin()
    methodVisitor.visitVarInsn(ALOAD, context.getSlot("protocol"));
    methodVisitor.visitMethodInsn(INVOKEVIRTUAL, "com/facebook/thrift/protocol/TProtocol", "readFieldBegin",
            "()Lcom/facebook/thrift/protocol/TField;");
    methodVisitor.visitVarInsn(ASTORE, context.getSlot("tfield"));

    // tfield.type
    methodVisitor.visitVarInsn(ALOAD, context.getSlot("tfield"));
    methodVisitor.visitFieldInsn(GETFIELD, "com/facebook/thrift/protocol/TField", "type", "B");

    methodVisitor.visitFieldInsn(GETSTATIC, "com/facebook/thrift/protocol/TType", "STOP", "B");

    // if (tfield.type == TType.STOP) { break; }
    Label endWhile = new Label();
    methodVisitor.visitJumpInsn(IF_ICMPEQ, endWhile);

    // tfield.id
    methodVisitor.visitVarInsn(ALOAD, context.getSlot("tfield"));
    methodVisitor.visitFieldInsn(GETFIELD, "com/facebook/thrift/protocol/TField", "id", "S");

    List<Field> fields = new ArrayList<Field>(type.getFields());
    int[] ids = new int[fields.size()];
    Label[] labels = new Label[fields.size()];
    for (int i = 0; i < fields.size(); ++i) {
        ids[i] = fields.get(i).getId();
        labels[i] = new Label();
    }

    Label fieldSkipped = new Label();

    methodVisitor.visitLookupSwitchInsn(fieldSkipped, ids, labels);

    for (int i = 0; i < fields.size(); ++i) {
        Field field = fields.get(i);

        methodVisitor.visitLabel(labels[i]);

        // if (tfield.type == ###)
        methodVisitor.visitVarInsn(ALOAD, context.getSlot("tfield"));
        methodVisitor.visitFieldInsn(GETFIELD, "com/facebook/thrift/protocol/TField", "type", "B");
        methodVisitor.visitIntInsn(BIPUSH, field.getType().getTType());
        methodVisitor.visitJumpInsn(IF_ICMPNE, fieldSkipped);

        methodVisitor.visitVarInsn(ALOAD, context.getSlot("target"));
        if (Map.class.isAssignableFrom(targetClass)) {
            methodVisitor.visitLdcInsn(field.getName());
            generateReadElement(methodVisitor, context, field.getType());
            generateAddToMap(targetClassName, methodVisitor, context, field);
        } else {
            generateReadElement(methodVisitor, context, field.getType());
            generateSetTargetField(targetClassName, methodVisitor, context, field);
        }

        methodVisitor.visitJumpInsn(GOTO, whileLabel);
    }

    methodVisitor.visitLabel(fieldSkipped);
    methodVisitor.visitVarInsn(ALOAD, context.getSlot("protocol"));
    methodVisitor.visitVarInsn(ALOAD, context.getSlot("tfield"));
    methodVisitor.visitFieldInsn(GETFIELD, "com/facebook/thrift/protocol/TField", "type", "B");
    methodVisitor.visitMethodInsn(INVOKESTATIC, "com/facebook/thrift/protocol/TProtocolUtil", "skip",
            "(Lcom/facebook/thrift/protocol/TProtocol;B)V");

    // end while
    methodVisitor.visitJumpInsn(GOTO, whileLabel);

    methodVisitor.visitLabel(endWhile);

    // protocol.readStructEnd()
    methodVisitor.visitVarInsn(ALOAD, context.getSlot("protocol"));
    methodVisitor.visitMethodInsn(INVOKEVIRTUAL, "com/facebook/thrift/protocol/TProtocol", "readStructEnd",
            "()V");

    // return result
    methodVisitor.visitVarInsn(ALOAD, context.getSlot("target"));
    methodVisitor.visitInsn(ARETURN);

    methodVisitor.visitMaxs(1, 1); // TODO: what should these be?
    methodVisitor.visitEnd();
}

From source file:mt.swift.Serializer.java

License:Apache License

private void pushValue(MethodVisitor methodVisitor, int value) {
    if (value <= Byte.MAX_VALUE) {
        pushValue(methodVisitor, (byte) value);
    } else {/*from   w  w  w  .j  a  v  a 2  s. c o m*/
        methodVisitor.visitIntInsn(SIPUSH, value);
    }
}

From source file:mt.swift.Serializer.java

License:Apache License

private void pushValue(MethodVisitor methodVisitor, byte value) {
    switch (value) {
    case -1://from  www  . j  a  v a2 s  .  c  o m
        methodVisitor.visitInsn(ICONST_M1);
        break;
    case 0:
        methodVisitor.visitInsn(ICONST_0);
        break;
    case 1:
        methodVisitor.visitInsn(ICONST_1);
        break;
    case 2:
        methodVisitor.visitInsn(ICONST_2);
        break;
    case 3:
        methodVisitor.visitInsn(ICONST_3);
        break;
    case 4:
        methodVisitor.visitInsn(ICONST_4);
        break;
    case 5:
        methodVisitor.visitInsn(ICONST_5);
        break;
    default:
        methodVisitor.visitIntInsn(BIPUSH, value);
    }
}

From source file:net.sourceforge.cobertura.instrument.pass3.AbstractCodeProvider.java

License:GNU General Public License

private void classMapContent(ClassVisitor cv, int nr, List<TouchPointDescriptor> touchPointDescriptors) {
    MethodVisitor mv = cv.visitMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC,
            COBERTURA_CLASSMAP_METHOD_NAME + "_" + nr,
            "(" + Type.getType(LightClassmapListener.class).toString() + ")V", null, null);
    mv.visitCode();/* w  w  w  .  j  a  v a  2s.  co  m*/
    mv.visitVarInsn(Opcodes.ALOAD, 0);
    for (TouchPointDescriptor tpd : touchPointDescriptors) {
        mv.visitInsn(Opcodes.DUP);
        mv.visitLdcInsn(tpd.getLineNumber());
        if (tpd instanceof LineTouchPointDescriptor) {
            mv.visitLdcInsn(((LineTouchPointDescriptor) tpd).getCounterId());
            mv.visitLdcInsn(((LineTouchPointDescriptor) tpd).getMethodName());
            mv.visitLdcInsn(((LineTouchPointDescriptor) tpd).getMethodSignature());
            mv.visitMethodInsn(Opcodes.INVOKEINTERFACE, CLASSMAP_LISTENER_INTERNALNAME, "putLineTouchPoint",
                    "(IILjava/lang/String;Ljava/lang/String;)V");
        } else if (tpd instanceof JumpTouchPointDescriptor) {
            mv.visitLdcInsn(((JumpTouchPointDescriptor) tpd).getCounterIdForTrue());
            mv.visitLdcInsn(((JumpTouchPointDescriptor) tpd).getCounterIdForFalse());
            mv.visitMethodInsn(Opcodes.INVOKEINTERFACE, CLASSMAP_LISTENER_INTERNALNAME, "putJumpTouchPoint",
                    "(III)V");
        } else if (tpd instanceof SwitchTouchPointDescriptor) {
            SwitchTouchPointDescriptor stpd = (SwitchTouchPointDescriptor) tpd;
            final String enum_sign = ((SwitchTouchPointDescriptor) tpd).getEnumType();
            if (enum_sign == null) {
                mv.visitLdcInsn(Integer.MAX_VALUE);
            } else {
                mv.visitMethodInsn(Opcodes.INVOKESTATIC, enum_sign, "values", "()[L" + enum_sign + ";");
                mv.visitInsn(Opcodes.ARRAYLENGTH);
            }
            Collection<Integer> ci = stpd.getCountersForLabels();
            mv.visitLdcInsn(ci.size());//Size of a new table
            mv.visitIntInsn(Opcodes.NEWARRAY, Opcodes.T_INT);
            int i = 0;
            for (Integer counterId : ci) {
                mv.visitInsn(Opcodes.DUP); //First for addition of items, second ad putSwitchTouchPoint parameter (or next loop iteration)
                mv.visitLdcInsn(i);
                mv.visitLdcInsn(counterId);
                mv.visitInsn(Opcodes.IASTORE);
                i++;
            }
            mv.visitMethodInsn(Opcodes.INVOKEINTERFACE, CLASSMAP_LISTENER_INTERNALNAME, "putSwitchTouchPoint",
                    "(II[I)V");
        }
    }
    mv.visitInsn(Opcodes.POP);
    mv.visitInsn(Opcodes.RETURN);
    mv.visitMaxs(0, 0);//will be recalculated by writer
    mv.visitEnd();
}

From source file:net.sourceforge.cobertura.instrument.pass3.AtomicArrayCodeProvider.java

License:GNU General Public License

/**
 * <pre>//w  w w  .  j  a v a 2s  . c o m
 * int[] __cobertura_get_and_reset_counters() {
 * int[] res = new int[counters.length()];
 * for(int i=0; i<counters.length(); i++){
 * res[i]=counters.getAndSet(i, 0);
 * }
 * return res;
 * }
 * </pre>
 */
public void generateCoberturaGetAndResetCountersMethod(ClassVisitor cv, String className) {
    MethodVisitor mv = cv.visitMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC,
            COBERTURA_GET_AND_RESET_COUNTERS_METHOD_NAME, "()[I", null, null);

    mv.visitCode();
    mv.visitFieldInsn(Opcodes.GETSTATIC, className, COBERTURA_COUNTERS_FIELD_NAME,
            COBERTURA_COUNTERS_FIELD_TYPE);
    mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/util/concurrent/atomic/AtomicIntegerArray", "length",
            "()I");
    mv.visitIntInsn(Opcodes.NEWARRAY, Opcodes.T_INT);
    mv.visitVarInsn(Opcodes.ASTORE, 0);
    mv.visitInsn(Opcodes.ICONST_0);
    mv.visitVarInsn(Opcodes.ISTORE, 1);
    Label l3 = new Label();
    mv.visitJumpInsn(Opcodes.GOTO, l3);
    Label l4 = new Label();
    mv.visitLabel(l4);
    mv.visitVarInsn(Opcodes.ALOAD, 0);
    mv.visitVarInsn(Opcodes.ILOAD, 1);
    mv.visitFieldInsn(Opcodes.GETSTATIC, className, COBERTURA_COUNTERS_FIELD_NAME,
            COBERTURA_COUNTERS_FIELD_TYPE);
    mv.visitVarInsn(Opcodes.ILOAD, 1);
    mv.visitInsn(Opcodes.ICONST_0);
    mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/util/concurrent/atomic/AtomicIntegerArray", "getAndSet",
            "(II)I");
    mv.visitInsn(Opcodes.IASTORE);
    mv.visitIincInsn(1, 1);
    mv.visitLabel(l3);
    mv.visitVarInsn(Opcodes.ILOAD, 1);
    mv.visitFieldInsn(Opcodes.GETSTATIC, className, COBERTURA_COUNTERS_FIELD_NAME,
            COBERTURA_COUNTERS_FIELD_TYPE);
    mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/util/concurrent/atomic/AtomicIntegerArray", "length",
            "()I");
    mv.visitJumpInsn(Opcodes.IF_ICMPLT, l4);
    mv.visitVarInsn(Opcodes.ALOAD, 0);
    mv.visitInsn(Opcodes.ARETURN);
    mv.visitMaxs(0, 0);//will be recalculated by writer
    mv.visitEnd();
}