com.sun.org.apache.bcel.internal.generic.InstructionHandle Java Examples

The following examples show how to use com.sun.org.apache.bcel.internal.generic.InstructionHandle. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source Project: jdk1.8-source-analysis   Author: raysonfang   File: Mode.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Compiles the default action for DOM text nodes and attribute nodes:
 * output the node's text value
 */
private InstructionList compileDefaultText(ClassGenerator classGen,
                                           MethodGenerator methodGen,
                                           InstructionHandle next) {
    final ConstantPoolGen cpg = classGen.getConstantPool();
    final InstructionList il = new InstructionList();

    final int chars = cpg.addInterfaceMethodref(DOM_INTF,
                                                CHARACTERS,
                                                CHARACTERS_SIG);
    il.append(methodGen.loadDOM());
    il.append(new ILOAD(_currentIndex));
    il.append(methodGen.loadHandler());
    il.append(new INVOKEINTERFACE(chars, 3));
    il.append(new GOTO_W(next));
    return il;
}
 
Example #2
Source Project: jdk8u60   Author: chenghanpeng   File: Mode.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Compiles the default handling for DOM elements: traverse all children
 */
private InstructionList compileDefaultRecursion(ClassGenerator classGen,
                                                MethodGenerator methodGen,
                                                InstructionHandle next) {
    final ConstantPoolGen cpg = classGen.getConstantPool();
    final InstructionList il = new InstructionList();
    final String applyTemplatesSig = classGen.getApplyTemplatesSig();
    final int git = cpg.addInterfaceMethodref(DOM_INTF,
                                              GET_CHILDREN,
                                              GET_CHILDREN_SIG);
    final int applyTemplates = cpg.addMethodref(getClassName(),
                                                functionName(),
                                                applyTemplatesSig);
    il.append(classGen.loadTranslet());
    il.append(methodGen.loadDOM());

    il.append(methodGen.loadDOM());
    il.append(new ILOAD(_currentIndex));
    il.append(new INVOKEINTERFACE(git, 2));
    il.append(methodGen.loadHandler());
    il.append(new INVOKEVIRTUAL(applyTemplates));
    il.append(new GOTO_W(next));
    return il;
}
 
Example #3
Source Project: jdk8u60   Author: chenghanpeng   File: FlowList.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Redirect the handles from oldList to newList. "This" flow list
 * is assumed to be relative to oldList.
 */
public FlowList copyAndRedirect(InstructionList oldList,
    InstructionList newList)
{
    final FlowList result = new FlowList();
    if (_elements == null) {
        return result;
    }

    final int n = _elements.size();
    final Iterator oldIter = oldList.iterator();
    final Iterator newIter = newList.iterator();

    while (oldIter.hasNext()) {
        final InstructionHandle oldIh = (InstructionHandle) oldIter.next();
        final InstructionHandle newIh = (InstructionHandle) newIter.next();

        for (int i = 0; i < n; i++) {
            if (_elements.elementAt(i) == oldIh) {
                result.add(newIh);
            }
        }
    }
    return result;
}
 
Example #4
Source Project: openjdk-jdk8u   Author: AdoptOpenJDK   File: Mode.java    License: GNU General Public License v2.0 6 votes vote down vote up
private void compileTemplateCalls(ClassGenerator classGen,
                                  MethodGenerator methodGen,
                                  InstructionHandle next, int min, int max){
    for (Template template : _neededTemplates.keySet()) {
        final int prec = template.getImportPrecedence();
        if ((prec >= min) && (prec < max)) {
            if (template.hasContents()) {
                InstructionList til = template.compile(classGen, methodGen);
                til.append(new GOTO_W(next));
                _templateILs.put(template, til);
                _templateIHs.put(template, til.getStart());
            }
            else {
                // empty template
                _templateIHs.put(template, next);
            }
        }
    }
}
 
Example #5
Source Project: TencentKona-8   Author: Tencent   File: FlowList.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Redirect the handles from oldList to newList. "This" flow list
 * is assumed to be relative to oldList.
 */
public FlowList copyAndRedirect(InstructionList oldList,
    InstructionList newList)
{
    final FlowList result = new FlowList();
    if (_elements == null) {
        return result;
    }

    final int n = _elements.size();
    final Iterator oldIter = oldList.iterator();
    final Iterator newIter = newList.iterator();

    while (oldIter.hasNext()) {
        final InstructionHandle oldIh = (InstructionHandle) oldIter.next();
        final InstructionHandle newIh = (InstructionHandle) newIter.next();

        for (int i = 0; i < n; i++) {
            if (_elements.elementAt(i) == oldIh) {
                result.add(newIh);
            }
        }
    }
    return result;
}
 
Example #6
Source Project: JDKSourceCode1.8   Author: wupeixuan   File: Mode.java    License: MIT License 6 votes vote down vote up
/**
 * Compiles the default action for DOM text nodes and attribute nodes:
 * output the node's text value
 */
private InstructionList compileDefaultText(ClassGenerator classGen,
                                           MethodGenerator methodGen,
                                           InstructionHandle next) {
    final ConstantPoolGen cpg = classGen.getConstantPool();
    final InstructionList il = new InstructionList();

    final int chars = cpg.addInterfaceMethodref(DOM_INTF,
                                                CHARACTERS,
                                                CHARACTERS_SIG);
    il.append(methodGen.loadDOM());
    il.append(new ILOAD(_currentIndex));
    il.append(methodGen.loadHandler());
    il.append(new INVOKEINTERFACE(chars, 3));
    il.append(new GOTO_W(next));
    return il;
}
 
Example #7
Source Project: JDKSourceCode1.8   Author: wupeixuan   File: MethodGenerator.java    License: MIT License 5 votes vote down vote up
/**
 * <p>Get all {@link Method}s generated by this {@link MethodGenerator}.
 * The {@link MethodGen#getMethod()} only returns a single
 * <code>Method</code> object.  This method takes into account the Java
 * Virtual Machine Specification limit of 64KB on the size of a method, and
 * may return more than one <code>Method</code>.</p>
 * <p>If the code associated with the <code>MethodGenerator</code> would
 * exceed the 64KB limit, this method will attempt to split the code in
 * the {@link InstructionList} associated with this
 * <code>MethodGenerator</code> into several methods.</p>
 * @param classGen the {@link ClassGenerator} of which these methods are
 *                 members
 * @return an array of all the <code>Method</code>s generated
 */
Method[] getGeneratedMethods(ClassGenerator classGen) {
    Method[] generatedMethods;
    InstructionList il = getInstructionList();
    InstructionHandle last = il.getEnd();

    il.setPositions();

    int instructionListSize =
                last.getPosition() + last.getInstruction().getLength();

    // Need to look for any branch target offsets that exceed the range
    // [-32768,32767]
    if (instructionListSize > MAX_BRANCH_TARGET_OFFSET) {
        boolean ilChanged = widenConditionalBranchTargetOffsets();

        // If any branch instructions needed widening, recompute the size
        // of the byte code for the method
        if (ilChanged) {
            il.setPositions();
            last = il.getEnd();
            instructionListSize =
                    last.getPosition() + last.getInstruction().getLength();
        }
    }

    if (instructionListSize > MAX_METHOD_SIZE) {
        generatedMethods = outlineChunks(classGen, instructionListSize);
    } else {
        generatedMethods = new Method[] {getThisMethod()};
    }
    return generatedMethods;
}
 
Example #8
Source Project: JDKSourceCode1.8   Author: wupeixuan   File: MethodGenerator.java    License: MIT License 5 votes vote down vote up
public LocalVariableGen addLocalVariable2(String name, Type type,
                                          InstructionHandle start)
{
    LocalVariableGen lvg = super.addLocalVariable(name, type,
                                          _slotAllocator.allocateSlot(type),
                                          start, null);
    getLocalVariableRegistry().registerLocalVariable(lvg);
    return lvg;
}
 
Example #9
Source Project: openjdk-jdk8u   Author: AdoptOpenJDK   File: AlternativePattern.java    License: GNU General Public License v2.0 5 votes vote down vote up
public void translate(ClassGenerator classGen, MethodGenerator methodGen) {
    final InstructionList il = methodGen.getInstructionList();

    _left.translate(classGen, methodGen);
    final InstructionHandle gotot = il.append(new GOTO(null));
    il.append(methodGen.loadContextNode());
    _right.translate(classGen, methodGen);

    _left._trueList.backPatch(gotot);
    _left._falseList.backPatch(gotot.getNext());

    _trueList.append(_right._trueList.add(gotot));
    _falseList.append(_right._falseList);
}
 
Example #10
Source Project: openjdk-jdk8u   Author: AdoptOpenJDK   File: FlowList.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Back patch a flow list. All instruction handles must be branch handles.
 */
public void backPatch(InstructionHandle target) {
    if (_elements != null) {
        final int n = _elements.size();
        for (int i = 0; i < n; i++) {
            BranchHandle bh = (BranchHandle)_elements.elementAt(i);
            bh.setTarget(target);
        }
        _elements.clear();          // avoid backpatching more than once
    }
}
 
Example #11
Source Project: jdk1.8-source-analysis   Author: raysonfang   File: Stylesheet.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Peephole optimization: Remove sequences of [ALOAD, POP].
 */
private void peepHoleOptimization(MethodGenerator methodGen) {
    final String pattern = "`aload'`pop'`instruction'";
    final InstructionList il = methodGen.getInstructionList();
    final InstructionFinder find = new InstructionFinder(il);
    for(Iterator iter=find.search(pattern); iter.hasNext(); ) {
        InstructionHandle[] match = (InstructionHandle[])iter.next();
        try {
            il.delete(match[0], match[1]);
        }
        catch (TargetLostException e) {
            // TODO: move target down into the list
        }
    }
}
 
Example #12
Source Project: jdk1.8-source-analysis   Author: raysonfang   File: Whitespace.java    License: Apache License 2.0 5 votes vote down vote up
public static void compileStripSpace(BranchHandle strip[],
                                     int sCount,
                                     InstructionList il) {
    final InstructionHandle target = il.append(ICONST_1);
    il.append(IRETURN);
    for (int i = 0; i < sCount; i++) {
        strip[i].setTarget(target);
    }
}
 
Example #13
Source Project: jdk8u60   Author: chenghanpeng   File: If.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Translate the "test" expression and contents of this element.
 * The contents will be ignored if we know the test will always fail.
 */
public void translate(ClassGenerator classGen, MethodGenerator methodGen) {
    final InstructionList il = methodGen.getInstructionList();
    _test.translateDesynthesized(classGen, methodGen);
    // remember end of condition
    final InstructionHandle truec = il.getEnd();
    if (!_ignore) {
        translateContents(classGen, methodGen);
    }
    _test.backPatchFalseList(il.append(NOP));
    _test.backPatchTrueList(truec.getNext());
}
 
Example #14
Source Project: JDKSourceCode1.8   Author: wupeixuan   File: FlowList.java    License: MIT License 5 votes vote down vote up
/**
 * Back patch a flow list. All instruction handles must be branch handles.
 */
public void backPatch(InstructionHandle target) {
    if (_elements != null) {
        final int n = _elements.size();
        for (int i = 0; i < n; i++) {
            BranchHandle bh = (BranchHandle)_elements.elementAt(i);
            bh.setTarget(target);
        }
        _elements.clear();          // avoid backpatching more than once
    }
}
 
Example #15
Source Project: TencentKona-8   Author: Tencent   File: Stylesheet.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Peephole optimization: Remove sequences of [ALOAD, POP].
 */
private void peepHoleOptimization(MethodGenerator methodGen) {
    final String pattern = "`aload'`pop'`instruction'";
    final InstructionList il = methodGen.getInstructionList();
    final InstructionFinder find = new InstructionFinder(il);
    for(Iterator iter=find.search(pattern); iter.hasNext(); ) {
        InstructionHandle[] match = (InstructionHandle[])iter.next();
        try {
            il.delete(match[0], match[1]);
        }
        catch (TargetLostException e) {
            // TODO: move target down into the list
        }
    }
}
 
Example #16
Source Project: openjdk-jdk8u   Author: AdoptOpenJDK   File: If.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Translate the "test" expression and contents of this element.
 * The contents will be ignored if we know the test will always fail.
 */
public void translate(ClassGenerator classGen, MethodGenerator methodGen) {
    final InstructionList il = methodGen.getInstructionList();
    _test.translateDesynthesized(classGen, methodGen);
    // remember end of condition
    final InstructionHandle truec = il.getEnd();
    if (!_ignore) {
        translateContents(classGen, methodGen);
    }
    _test.backPatchFalseList(il.append(NOP));
    _test.backPatchTrueList(truec.getNext());
}
 
Example #17
Source Project: TencentKona-8   Author: Tencent   File: Whitespace.java    License: GNU General Public License v2.0 5 votes vote down vote up
public static void compilePreserveSpace(BranchHandle preserve[],
                                        int pCount,
                                        InstructionList il) {
    final InstructionHandle target = il.append(ICONST_0);
    il.append(IRETURN);
    for (int i = 0; i < pCount; i++) {
        preserve[i].setTarget(target);
    }
}
 
Example #18
Source Project: TencentKona-8   Author: Tencent   File: MethodGenerator.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Allocates a local variable. If the slot allocator has already been
 * initialized, then call addLocalVariable2() so that the new variable
 * is known to the allocator. Failing to do this may cause the allocator
 * to return a slot that is already in use.
 */
public LocalVariableGen addLocalVariable(String name, Type type,
                                         InstructionHandle start,
                                         InstructionHandle end)
{
    LocalVariableGen lvg;

    if (_allocatorInit) {
        lvg = addLocalVariable2(name, type, start);
    } else {
        lvg = super.addLocalVariable(name, type, start, end);
        getLocalVariableRegistry().registerLocalVariable(lvg);
    }
    return lvg;
}
 
Example #19
Source Project: TencentKona-8   Author: Tencent   File: MethodGenerator.java    License: GNU General Public License v2.0 5 votes vote down vote up
public LocalVariableGen addLocalVariable2(String name, Type type,
                                          InstructionHandle start)
{
    LocalVariableGen lvg = super.addLocalVariable(name, type,
                                          _slotAllocator.allocateSlot(type),
                                          start, null);
    getLocalVariableRegistry().registerLocalVariable(lvg);
    return lvg;
}
 
Example #20
Source Project: TencentKona-8   Author: Tencent   File: MethodGenerator.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * <p>Get all {@link Method}s generated by this {@link MethodGenerator}.
 * The {@link MethodGen#getMethod()} only returns a single
 * <code>Method</code> object.  This method takes into account the Java
 * Virtual Machine Specification limit of 64KB on the size of a method, and
 * may return more than one <code>Method</code>.</p>
 * <p>If the code associated with the <code>MethodGenerator</code> would
 * exceed the 64KB limit, this method will attempt to split the code in
 * the {@link InstructionList} associated with this
 * <code>MethodGenerator</code> into several methods.</p>
 * @param classGen the {@link ClassGenerator} of which these methods are
 *                 members
 * @return an array of all the <code>Method</code>s generated
 */
Method[] getGeneratedMethods(ClassGenerator classGen) {
    Method[] generatedMethods;
    InstructionList il = getInstructionList();
    InstructionHandle last = il.getEnd();

    il.setPositions();

    int instructionListSize =
                last.getPosition() + last.getInstruction().getLength();

    // Need to look for any branch target offsets that exceed the range
    // [-32768,32767]
    if (instructionListSize > MAX_BRANCH_TARGET_OFFSET) {
        boolean ilChanged = widenConditionalBranchTargetOffsets();

        // If any branch instructions needed widening, recompute the size
        // of the byte code for the method
        if (ilChanged) {
            il.setPositions();
            last = il.getEnd();
            instructionListSize =
                    last.getPosition() + last.getInstruction().getLength();
        }
    }

    if (instructionListSize > MAX_METHOD_SIZE) {
        generatedMethods = outlineChunks(classGen, instructionListSize);
    } else {
        generatedMethods = new Method[] {getThisMethod()};
    }
    return generatedMethods;
}
 
Example #21
Source Project: openjdk-jdk8u   Author: AdoptOpenJDK   File: Key.java    License: GNU General Public License v2.0 4 votes vote down vote up
/**
 * Gather all nodes that match the expression in the attribute "match"
 * and add one (or more) entries in this key's index.
 */
public void translate(ClassGenerator classGen, MethodGenerator methodGen) {

    final ConstantPoolGen cpg = classGen.getConstantPool();
    final InstructionList il = methodGen.getInstructionList();
    final int current = methodGen.getLocalIndex("current");

    // AbstractTranslet.buildKeyIndex(name,node_id,value) => void
    final int key = cpg.addMethodref(TRANSLET_CLASS,
                                     "buildKeyIndex",
                                     "("+STRING_SIG+"I"+STRING_SIG+")V");

    // AbstractTranslet.SetKeyIndexDom(name, Dom) => void
    final int keyDom = cpg.addMethodref(TRANSLET_CLASS,
                                     "setKeyIndexDom",
                                     "("+STRING_SIG+DOM_INTF_SIG+")V");

    final int getNodeIdent = cpg.addInterfaceMethodref(DOM_INTF,
                                                       "getNodeIdent",
                                                       "(I)"+NODE_SIG);

    // DOM.getAxisIterator(root) => NodeIterator
    final int git = cpg.addInterfaceMethodref(DOM_INTF,
                                              "getAxisIterator",
                                              "(I)"+NODE_ITERATOR_SIG);

    il.append(methodGen.loadCurrentNode());
    il.append(methodGen.loadIterator());

    // Get an iterator for all nodes in the DOM
    il.append(methodGen.loadDOM());
    il.append(new PUSH(cpg,Axis.DESCENDANT));
    il.append(new INVOKEINTERFACE(git, 2));

    // Reset the iterator to start with the root node
    il.append(methodGen.loadCurrentNode());
    il.append(methodGen.setStartNode());
    il.append(methodGen.storeIterator());

    // Loop for traversing all nodes in the DOM
    final BranchHandle nextNode = il.append(new GOTO(null));
    final InstructionHandle loop = il.append(NOP);

    // Check if the current node matches the pattern in "match"
    il.append(methodGen.loadCurrentNode());
    _match.translate(classGen, methodGen);
    _match.synthesize(classGen, methodGen); // Leaves 0 or 1 on stack
    final BranchHandle skipNode = il.append(new IFEQ(null));

    // If this is a node-set we must go through each node in the set
    if (_useType instanceof NodeSetType) {
        // Pass current node as parameter (we're indexing on that node)
        il.append(methodGen.loadCurrentNode());
        traverseNodeSet(classGen, methodGen, key);
    }
    else {
        il.append(classGen.loadTranslet());
        il.append(DUP);
        il.append(new PUSH(cpg, _name.toString()));
        il.append(DUP_X1);
        il.append(methodGen.loadCurrentNode());
        _use.translate(classGen, methodGen);
        il.append(new INVOKEVIRTUAL(key));

        il.append(methodGen.loadDOM());
        il.append(new INVOKEVIRTUAL(keyDom));
    }

    // Get the next node from the iterator and do loop again...
    final InstructionHandle skip = il.append(NOP);

    il.append(methodGen.loadIterator());
    il.append(methodGen.nextNode());
    il.append(DUP);
    il.append(methodGen.storeCurrentNode());
    il.append(new IFGT(loop));

    // Restore current node and current iterator from the stack
    il.append(methodGen.storeIterator());
    il.append(methodGen.storeCurrentNode());

    nextNode.setTarget(skip);
    skipNode.setTarget(skip);
}
 
Example #22
Source Project: JDKSourceCode1.8   Author: wupeixuan   File: StepPattern.java    License: MIT License 4 votes vote down vote up
private void translateSimpleContext(ClassGenerator classGen,
                                    MethodGenerator methodGen) {
    int index;
    final ConstantPoolGen cpg = classGen.getConstantPool();
    final InstructionList il = methodGen.getInstructionList();

    // Store matching node into a local variable
    LocalVariableGen match;
    match = methodGen.addLocalVariable("step_pattern_tmp1",
                                       Util.getJCRefType(NODE_SIG),
                                       null, null);
    match.setStart(il.append(new ISTORE(match.getIndex())));

    // If pattern not reduced then check kernel
    if (!_isEpsilon) {
        il.append(new ILOAD(match.getIndex()));
        translateKernel(classGen, methodGen);
    }

    // Push current iterator and current node on the stack
    il.append(methodGen.loadCurrentNode());
    il.append(methodGen.loadIterator());

    // Create a new matching iterator using the matching node
    index = cpg.addMethodref(MATCHING_ITERATOR, "<init>",
                             "(I" + NODE_ITERATOR_SIG + ")V");

    // Backwards branches are prohibited if an uninitialized object is
    // on the stack by section 4.9.4 of the JVM Specification, 2nd Ed.
    // We don't know whether this code might contain backwards branches,
    // so we mustn't create the new object until after we've created
    // the suspect arguments to its constructor.  Instead we calculate
    // the values of the arguments to the constructor first, store them
    // in temporary variables, create the object and reload the
    // arguments from the temporaries to avoid the problem.

    _step.translate(classGen, methodGen);
    LocalVariableGen stepIteratorTemp =
            methodGen.addLocalVariable("step_pattern_tmp2",
                                       Util.getJCRefType(NODE_ITERATOR_SIG),
                                       null, null);
    stepIteratorTemp.setStart(
            il.append(new ASTORE(stepIteratorTemp.getIndex())));

    il.append(new NEW(cpg.addClass(MATCHING_ITERATOR)));
    il.append(DUP);
    il.append(new ILOAD(match.getIndex()));
    stepIteratorTemp.setEnd(
            il.append(new ALOAD(stepIteratorTemp.getIndex())));
    il.append(new INVOKESPECIAL(index));

    // Get the parent of the matching node
    il.append(methodGen.loadDOM());
    il.append(new ILOAD(match.getIndex()));
    index = cpg.addInterfaceMethodref(DOM_INTF, GET_PARENT, GET_PARENT_SIG);
    il.append(new INVOKEINTERFACE(index, 2));

    // Start the iterator with the parent
    il.append(methodGen.setStartNode());

    // Overwrite current iterator and current node
    il.append(methodGen.storeIterator());
    match.setEnd(il.append(new ILOAD(match.getIndex())));
    il.append(methodGen.storeCurrentNode());

    // Translate the expression of the predicate
    Predicate pred = (Predicate) _predicates.elementAt(0);
    Expression exp = pred.getExpr();
    exp.translateDesynthesized(classGen, methodGen);

    // Backpatch true list and restore current iterator/node
    InstructionHandle restore = il.append(methodGen.storeIterator());
    il.append(methodGen.storeCurrentNode());
    exp.backPatchTrueList(restore);
    BranchHandle skipFalse = il.append(new GOTO(null));

    // Backpatch false list and restore current iterator/node
    restore = il.append(methodGen.storeIterator());
    il.append(methodGen.storeCurrentNode());
    exp.backPatchFalseList(restore);
    _falseList.add(il.append(new GOTO(null)));

    // True list falls through
    skipFalse.setTarget(il.append(NOP));
}
 
Example #23
Source Project: jdk1.8-source-analysis   Author: raysonfang   File: TestSeq.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Compile the code for this test sequence. Compile patterns
 * from highest to lowest priority. Note that since patterns
 * can be share by multiple test sequences, instruction lists
 * must be copied before backpatching.
 */
public InstructionHandle compile(ClassGenerator classGen,
                                 MethodGenerator methodGen,
                                 InstructionHandle continuation)
{
    // Returned cached value if already compiled
    if (_start != null) {
        return _start;
    }

    // If not patterns, then return handle for default template
    final int count = _patterns.size();
    if (count == 0) {
        return (_start = getTemplateHandle(_default));
    }

    // Init handle to jump when all patterns failed
    InstructionHandle fail = (_default == null) ? continuation
        : getTemplateHandle(_default);

    // Compile all patterns in reverse order
    for (int n = count - 1; n >= 0; n--) {
        final LocationPathPattern pattern = getPattern(n);
        final Template template = pattern.getTemplate();
        final InstructionList il = new InstructionList();

        // Patterns expect current node on top of stack
        il.append(methodGen.loadCurrentNode());

        // Apply the test-code compiled for the pattern
        InstructionList ilist = methodGen.getInstructionList(pattern);
        if (ilist == null) {
            ilist = pattern.compile(classGen, methodGen);
            methodGen.addInstructionList(pattern, ilist);
        }

        // Make a copy of the instruction list for backpatching
        InstructionList copyOfilist = ilist.copy();

        FlowList trueList = pattern.getTrueList();
        if (trueList != null) {
            trueList = trueList.copyAndRedirect(ilist, copyOfilist);
        }
        FlowList falseList = pattern.getFalseList();
        if (falseList != null) {
            falseList = falseList.copyAndRedirect(ilist, copyOfilist);
        }

        il.append(copyOfilist);

        // On success branch to the template code
        final InstructionHandle gtmpl = getTemplateHandle(template);
        final InstructionHandle success = il.append(new GOTO_W(gtmpl));

        if (trueList != null) {
            trueList.backPatch(success);
        }
        if (falseList != null) {
            falseList.backPatch(fail);
        }

        // Next pattern's 'fail' target is this pattern's first instruction
        fail = il.getStart();

        // Append existing instruction list to the end of this one
        if (_instructionList != null) {
            il.append(_instructionList);
        }

        // Set current instruction list to be this one
        _instructionList = il;
    }
    return (_start = fail);
}
 
Example #24
Source Project: openjdk-jdk8u   Author: AdoptOpenJDK   File: LogicalExpr.java    License: GNU General Public License v2.0 4 votes vote down vote up
/**
 * Compile expression and update true/false-lists
 */
public void translateDesynthesized(ClassGenerator classGen,
                                   MethodGenerator methodGen) {

    final InstructionList il = methodGen.getInstructionList();
    final SyntaxTreeNode parent = getParent();

    // Compile AND-expression
    if (_op == AND) {

        // Translate left hand side - must be true
        _left.translateDesynthesized(classGen, methodGen);

        // Need this for chaining any OR-expression children
        InstructionHandle middle = il.append(NOP);

        // Translate left right side - must be true
        _right.translateDesynthesized(classGen, methodGen);

        // Need this for chaining any OR-expression children
        InstructionHandle after = il.append(NOP);

        // Append child expression false-lists to our false-list
        _falseList.append(_right._falseList.append(_left._falseList));

        // Special case for OR-expression as a left child of AND.
        // The true-list of OR must point to second clause of AND.
        if ((_left instanceof LogicalExpr) &&
            (((LogicalExpr)_left).getOp() == OR)) {
            _left.backPatchTrueList(middle);
        }
        else if (_left instanceof NotCall) {
            _left.backPatchTrueList(middle);
        }
        else {
            _trueList.append(_left._trueList);
        }

        // Special case for OR-expression as a right child of AND
        // The true-list of OR must point to true-list of AND.
        if ((_right instanceof LogicalExpr) &&
            (((LogicalExpr)_right).getOp() == OR)) {
            _right.backPatchTrueList(after);
        }
        else if (_right instanceof NotCall) {
            _right.backPatchTrueList(after);
        }
        else {
            _trueList.append(_right._trueList);
        }
    }
    // Compile OR-expression
    else {
        // Translate left-hand side expression and produce true/false list
        _left.translateDesynthesized(classGen, methodGen);

        // This GOTO is used to skip over the code for the last test
        // in the case where the the first test succeeds
        InstructionHandle ih = il.append(new GOTO(null));

        // Translate right-hand side expression and produce true/false list
        _right.translateDesynthesized(classGen, methodGen);

        _left._trueList.backPatch(ih);
        _left._falseList.backPatch(ih.getNext());

        _falseList.append(_right._falseList);
        _trueList.add(ih).append(_right._trueList);
    }
}
 
Example #25
Source Project: jdk1.8-source-analysis   Author: raysonfang   File: Copy.java    License: Apache License 2.0 4 votes vote down vote up
public void translate(ClassGenerator classGen, MethodGenerator methodGen) {
    final ConstantPoolGen cpg = classGen.getConstantPool();
    final InstructionList il = methodGen.getInstructionList();

    final LocalVariableGen name =
        methodGen.addLocalVariable2("name",
                                    Util.getJCRefType(STRING_SIG),
                                    null);
    final LocalVariableGen length =
        methodGen.addLocalVariable2("length",
                                    Util.getJCRefType("I"),
                                    null);

    // Get the name of the node to copy and save for later
    il.append(methodGen.loadDOM());
    il.append(methodGen.loadCurrentNode());
    il.append(methodGen.loadHandler());
    final int cpy = cpg.addInterfaceMethodref(DOM_INTF,
                                              "shallowCopy",
                                              "("
                                              + NODE_SIG
                                              + TRANSLET_OUTPUT_SIG
                                              + ")" + STRING_SIG);
    il.append(new INVOKEINTERFACE(cpy, 3));
    il.append(DUP);
    name.setStart(il.append(new ASTORE(name.getIndex())));
    final BranchHandle ifBlock1 = il.append(new IFNULL(null));

    // Get the length of the node name and save for later
    il.append(new ALOAD(name.getIndex()));
    final int lengthMethod = cpg.addMethodref(STRING_CLASS,"length","()I");
    il.append(new INVOKEVIRTUAL(lengthMethod));
    il.append(DUP);
    length.setStart(il.append(new ISTORE(length.getIndex())));

    // Ignore attribute sets if current node is ROOT. DOM.shallowCopy()
    // returns "" for ROOT, so skip attribute sets if length == 0
    final BranchHandle ifBlock4 = il.append(new IFEQ(null));

    // Copy in attribute sets if specified
    if (_useSets != null) {
        // If the parent of this element will result in an element being
        // output then we know that it is safe to copy out the attributes
        final SyntaxTreeNode parent = getParent();
        if ((parent instanceof LiteralElement) ||
            (parent instanceof LiteralElement)) {
            _useSets.translate(classGen, methodGen);
        }
        // If not we have to check to see if the copy will result in an
        // element being output.
        else {
            // check if element; if not skip to translate body
            il.append(new ILOAD(length.getIndex()));
            final BranchHandle ifBlock2 = il.append(new IFEQ(null));
            // length != 0 -> element -> do attribute sets
            _useSets.translate(classGen, methodGen);
            // not an element; root
            ifBlock2.setTarget(il.append(NOP));
        }
    }

    // Instantiate body of xsl:copy
    ifBlock4.setTarget(il.append(NOP));
    translateContents(classGen, methodGen);

    // Call the output handler's endElement() if we copied an element
    // (The DOM.shallowCopy() method calls startElement().)
    length.setEnd(il.append(new ILOAD(length.getIndex())));
    final BranchHandle ifBlock3 = il.append(new IFEQ(null));
    il.append(methodGen.loadHandler());
    name.setEnd(il.append(new ALOAD(name.getIndex())));
    il.append(methodGen.endElement());

    final InstructionHandle end = il.append(NOP);
    ifBlock1.setTarget(end);
    ifBlock3.setTarget(end);
    methodGen.removeLocalVariable(name);
    methodGen.removeLocalVariable(length);
}
 
Example #26
Source Project: jdk1.8-source-analysis   Author: raysonfang   File: AbsolutePathPattern.java    License: Apache License 2.0 4 votes vote down vote up
public void translate(ClassGenerator classGen, MethodGenerator methodGen) {
    final ConstantPoolGen cpg = classGen.getConstantPool();
    final InstructionList il = methodGen.getInstructionList();

    if (_left != null) {
        if (_left instanceof StepPattern) {
            final LocalVariableGen local =
                // absolute path pattern temporary
                methodGen.addLocalVariable2("apptmp",
                                            Util.getJCRefType(NODE_SIG),
                                            null);
            il.append(DUP);
            local.setStart(il.append(new ISTORE(local.getIndex())));
            _left.translate(classGen, methodGen);
            il.append(methodGen.loadDOM());
            local.setEnd(il.append(new ILOAD(local.getIndex())));
            methodGen.removeLocalVariable(local);
        }
        else {
            _left.translate(classGen, methodGen);
        }
    }

    final int getParent = cpg.addInterfaceMethodref(DOM_INTF,
                                                    GET_PARENT,
                                                    GET_PARENT_SIG);
    final int getType = cpg.addInterfaceMethodref(DOM_INTF,
                                                  "getExpandedTypeID",
                                                  "(I)I");

    InstructionHandle begin = il.append(methodGen.loadDOM());
    il.append(SWAP);
    il.append(new INVOKEINTERFACE(getParent, 2));
    if (_left instanceof AncestorPattern) {
        il.append(methodGen.loadDOM());
        il.append(SWAP);
    }
    il.append(new INVOKEINTERFACE(getType, 2));
    il.append(new PUSH(cpg, DTM.DOCUMENT_NODE));

    final BranchHandle skip = il.append(new IF_ICMPEQ(null));
    _falseList.add(il.append(new GOTO_W(null)));
    skip.setTarget(il.append(NOP));

    if (_left != null) {
        _left.backPatchTrueList(begin);

        /*
         * If _left is an ancestor pattern, backpatch this pattern's false
         * list to the loop that searches for more ancestors.
         */
        if (_left instanceof AncestorPattern) {
            final AncestorPattern ancestor = (AncestorPattern) _left;
            _falseList.backPatch(ancestor.getLoopHandle());         // clears list
        }
        _falseList.append(_left._falseList);
    }
}
 
Example #27
Source Project: jdk8u60   Author: chenghanpeng   File: ParentPattern.java    License: GNU General Public License v2.0 4 votes vote down vote up
public void translate(ClassGenerator classGen, MethodGenerator methodGen) {
    final ConstantPoolGen cpg = classGen.getConstantPool();
    final InstructionList il = methodGen.getInstructionList();
    final LocalVariableGen local =
        methodGen.addLocalVariable2("ppt",
                                    Util.getJCRefType(NODE_SIG),
                                    null);

    final com.sun.org.apache.bcel.internal.generic.Instruction loadLocal =
        new ILOAD(local.getIndex());
    final com.sun.org.apache.bcel.internal.generic.Instruction storeLocal =
        new ISTORE(local.getIndex());

    if (_right.isWildcard()) {
        il.append(methodGen.loadDOM());
        il.append(SWAP);
    }
    else if (_right instanceof StepPattern) {
        il.append(DUP);
        local.setStart(il.append(storeLocal));

        _right.translate(classGen, methodGen);

        il.append(methodGen.loadDOM());
        local.setEnd(il.append(loadLocal));
    }
    else {
        _right.translate(classGen, methodGen);

        if (_right instanceof AncestorPattern) {
            il.append(methodGen.loadDOM());
            il.append(SWAP);
        }
    }

    final int getParent = cpg.addInterfaceMethodref(DOM_INTF,
                                                    GET_PARENT,
                                                    GET_PARENT_SIG);
    il.append(new INVOKEINTERFACE(getParent, 2));

    final SyntaxTreeNode p = getParent();
    if (p == null || p instanceof Instruction ||
        p instanceof TopLevelElement)
    {
        _left.translate(classGen, methodGen);
    }
    else {
        il.append(DUP);
        InstructionHandle storeInst = il.append(storeLocal);

        if (local.getStart() == null) {
            local.setStart(storeInst);
        }

        _left.translate(classGen, methodGen);

        il.append(methodGen.loadDOM());
        local.setEnd(il.append(loadLocal));
    }

    methodGen.removeLocalVariable(local);

    /*
     * If _right is an ancestor pattern, backpatch _left false
     * list to the loop that searches for more ancestors.
     */
    if (_right instanceof AncestorPattern) {
        final AncestorPattern ancestor = (AncestorPattern) _right;
        _left.backPatchFalseList(ancestor.getLoopHandle());    // clears list
    }

    _trueList.append(_right._trueList.append(_left._trueList));
    _falseList.append(_right._falseList.append(_left._falseList));
}
 
Example #28
Source Project: jdk1.8-source-analysis   Author: raysonfang   File: AncestorPattern.java    License: Apache License 2.0 4 votes vote down vote up
public InstructionHandle getLoopHandle() {
    return _loop;
}
 
Example #29
Source Project: openjdk-jdk8u   Author: AdoptOpenJDK   File: StepPattern.java    License: GNU General Public License v2.0 4 votes vote down vote up
private void translateNoContext(ClassGenerator classGen,
                                MethodGenerator methodGen) {
    final ConstantPoolGen cpg = classGen.getConstantPool();
    final InstructionList il = methodGen.getInstructionList();

    // Push current node on the stack
    il.append(methodGen.loadCurrentNode());
    il.append(SWAP);

    // Overwrite current node with matching node
    il.append(methodGen.storeCurrentNode());

    // If pattern not reduced then check kernel
    if (!_isEpsilon) {
        il.append(methodGen.loadCurrentNode());
        translateKernel(classGen, methodGen);
    }

    // Compile the expressions within the predicates
    final int n = _predicates.size();
    for (int i = 0; i < n; i++) {
        Predicate pred = (Predicate)_predicates.elementAt(i);
        Expression exp = pred.getExpr();
        exp.translateDesynthesized(classGen, methodGen);
        _trueList.append(exp._trueList);
        _falseList.append(exp._falseList);
    }

    // Backpatch true list and restore current iterator/node
    InstructionHandle restore;
    restore = il.append(methodGen.storeCurrentNode());
    backPatchTrueList(restore);
    BranchHandle skipFalse = il.append(new GOTO(null));

    // Backpatch false list and restore current iterator/node
    restore = il.append(methodGen.storeCurrentNode());
    backPatchFalseList(restore);
    _falseList.add(il.append(new GOTO(null)));

    // True list falls through
    skipFalse.setTarget(il.append(NOP));
}
 
Example #30
Source Project: jdk1.8-source-analysis   Author: raysonfang   File: Key.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * This method is called if the "use" attribute of the key contains a
 * node set. In this case we must traverse all nodes in the set and
 * create one entry in this key's index for each node in the set.
 */
public void traverseNodeSet(ClassGenerator classGen,
                            MethodGenerator methodGen,
                            int buildKeyIndex) {
    final ConstantPoolGen cpg = classGen.getConstantPool();
    final InstructionList il = methodGen.getInstructionList();

    // DOM.getStringValueX(nodeIndex) => String
    final int getNodeValue = cpg.addInterfaceMethodref(DOM_INTF,
                                                       GET_NODE_VALUE,
                                                       "(I)"+STRING_SIG);

    final int getNodeIdent = cpg.addInterfaceMethodref(DOM_INTF,
                                                       "getNodeIdent",
                                                       "(I)"+NODE_SIG);

    // AbstractTranslet.SetKeyIndexDom(name, Dom) => void
    final int keyDom = cpg.addMethodref(TRANSLET_CLASS,
                                     "setKeyIndexDom",
                                     "("+STRING_SIG+DOM_INTF_SIG+")V");


    // This variable holds the id of the node we found with the "match"
    // attribute of xsl:key. This is the id we store, with the value we
    // get from the nodes we find here, in the index for this key.
    final LocalVariableGen parentNode =
        methodGen.addLocalVariable("parentNode",
                                   Util.getJCRefType("I"),
                                   null, null);

    // Get the 'parameter' from the stack and store it in a local var.
    parentNode.setStart(il.append(new ISTORE(parentNode.getIndex())));

    // Save current node and current iterator on the stack
    il.append(methodGen.loadCurrentNode());
    il.append(methodGen.loadIterator());

    // Overwrite current iterator with one that gives us only what we want
    _use.translate(classGen, methodGen);
    _use.startIterator(classGen, methodGen);
    il.append(methodGen.storeIterator());

    final BranchHandle nextNode = il.append(new GOTO(null));
    final InstructionHandle loop = il.append(NOP);

    // Prepare to call buildKeyIndex(String name, int node, String value);
    il.append(classGen.loadTranslet());
    il.append(new PUSH(cpg, _name.toString()));
    parentNode.setEnd(il.append(new ILOAD(parentNode.getIndex())));

    // Now get the node value and push it on the parameter stack
    il.append(methodGen.loadDOM());
    il.append(methodGen.loadCurrentNode());
    il.append(new INVOKEINTERFACE(getNodeValue, 2));

    // Finally do the call to add an entry in the index for this key.
    il.append(new INVOKEVIRTUAL(buildKeyIndex));

    il.append(classGen.loadTranslet());
    il.append(new PUSH(cpg, getName()));
    il.append(methodGen.loadDOM());
    il.append(new INVOKEVIRTUAL(keyDom));

    nextNode.setTarget(il.append(methodGen.loadIterator()));
    il.append(methodGen.nextNode());

    il.append(DUP);
    il.append(methodGen.storeCurrentNode());
    il.append(new IFGE(loop)); // Go on to next matching node....

    // Restore current node and current iterator from the stack
    il.append(methodGen.storeIterator());
    il.append(methodGen.storeCurrentNode());
}