001    /*
002     * Licensed to the Apache Software Foundation (ASF) under one or more
003     * contributor license agreements.  See the NOTICE file distributed with
004     * this work for additional information regarding copyright ownership.
005     * The ASF licenses this file to You under the Apache License, Version 2.0
006     * (the "License"); you may not use this file except in compliance with
007     * the License.  You may obtain a copy of the License at
008     *
009     *      http://www.apache.org/licenses/LICENSE-2.0
010     *
011     * Unless required by applicable law or agreed to in writing, software
012     * distributed under the License is distributed on an "AS IS" BASIS,
013     * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014     * See the License for the specific language governing permissions and
015     * limitations under the License.
016     */
017    package org.apache.commons.nabla.forward.trimming;
018    
019    import org.objectweb.asm.Opcodes;
020    import org.objectweb.asm.tree.AbstractInsnNode;
021    import org.objectweb.asm.tree.InsnList;
022    import org.objectweb.asm.tree.VarInsnNode;
023    
024    /** Trimmer replacing (DUP2_X2, POP2, DSTORE i, DSTORE j) with (DSTORE j, DSTORE i).
025     * @version $Id$
026     */
027    public class SwappedDstoreTrimmer extends BytecodeTrimmer {
028    
029        /** Simple constructor.
030         */
031        public SwappedDstoreTrimmer() {
032            super(4);
033        }
034    
035        /** {@inheritDoc} */
036        @Override
037        protected boolean trimWindow(final InsnList instructions,
038                                     final AbstractInsnNode[] window) {
039    
040            if ((window[0].getOpcode() == Opcodes.DUP2_X2) &&
041                (window[1].getOpcode() == Opcodes.POP2) &&
042                (window[2].getOpcode() == Opcodes.DSTORE) &&
043                (window[3].getOpcode() == Opcodes.DSTORE)) {
044    
045                // reverse the DSTORE orders
046                final int tmp = ((VarInsnNode) window[2]).var;
047                ((VarInsnNode) window[2]).var = ((VarInsnNode) window[3]).var;
048                ((VarInsnNode) window[3]).var = tmp;
049    
050                // remove the operand stack swap instructions
051                instructions.remove(window[0]);
052                instructions.remove(window[1]);
053    
054                // update lookahead instructions
055                window[0] = window[2];
056                window[1] = window[3];
057                window[2] = window[1].getNext();
058                window[3] = (window[2] == null) ? null : window[2].getNext();
059                return true;
060    
061            }
062    
063            // nothing have been done
064            return false;
065    
066        }
067    
068    }