001    /*
002     * Copyright 2010-2014 JetBrains s.r.o.
003     *
004     * Licensed under the Apache License, Version 2.0 (the "License");
005     * you may not use this file except in compliance with the License.
006     * You may obtain a copy of the License at
007     *
008     * http://www.apache.org/licenses/LICENSE-2.0
009     *
010     * Unless required by applicable law or agreed to in writing, software
011     * distributed under the License is distributed on an "AS IS" BASIS,
012     * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013     * See the License for the specific language governing permissions and
014     * limitations under the License.
015     */
016    
017    package org.jetbrains.jet.codegen.optimization;
018    
019    import org.jetbrains.annotations.NotNull;
020    import org.jetbrains.annotations.Nullable;
021    import org.jetbrains.jet.codegen.inline.InlineCodegenUtil;
022    import org.jetbrains.jet.codegen.optimization.boxing.RedundantBoxingMethodTransformer;
023    import org.jetbrains.jet.codegen.optimization.boxing.RedundantNullCheckMethodTransformer;
024    import org.jetbrains.jet.codegen.optimization.transformer.MethodTransformer;
025    import org.jetbrains.org.objectweb.asm.MethodVisitor;
026    import org.jetbrains.org.objectweb.asm.Opcodes;
027    import org.jetbrains.org.objectweb.asm.tree.LocalVariableNode;
028    import org.jetbrains.org.objectweb.asm.tree.MethodNode;
029    import org.jetbrains.org.objectweb.asm.util.Textifier;
030    import org.jetbrains.org.objectweb.asm.util.TraceMethodVisitor;
031    
032    import java.util.ArrayList;
033    import java.util.List;
034    
035    public class OptimizationMethodVisitor extends MethodVisitor {
036        private static final int MEMORY_LIMIT_BY_METHOD_MB = 50;
037        private static final MethodTransformer[] TRANSFORMERS = new MethodTransformer[]{
038                new RedundantNullCheckMethodTransformer(), new RedundantBoxingMethodTransformer(),
039                new RedundantGotoMethodTransformer(), new StoreStackBeforeInlineMethodTransformer()
040        };
041    
042        private final MethodNode methodNode;
043        private final MethodVisitor delegate;
044    
045        public OptimizationMethodVisitor(
046                @NotNull MethodVisitor delegate,
047                int access,
048                @NotNull String name,
049                @NotNull String desc,
050                @Nullable String signature,
051                @Nullable String[] exceptions
052        ) {
053            super(Opcodes.ASM5);
054            this.delegate = delegate;
055            this.methodNode = new MethodNode(access, name, desc, signature, exceptions);
056            this.methodNode.localVariables = new ArrayList<LocalVariableNode>(5);
057            this.mv = InlineCodegenUtil.wrapWithMaxLocalCalc(methodNode);
058        }
059    
060        @Override
061        public void visitEnd() {
062            // force mv to calculate maxStack/maxLocals in case it didn't yet done
063            if (methodNode.maxLocals <= 0 || methodNode.maxStack <= 0) {
064                mv.visitMaxs(-1, -1);
065            }
066    
067            super.visitEnd();
068    
069            if (canBeAnalyzed(methodNode)) {
070                for (MethodTransformer transformer : TRANSFORMERS) {
071                    transformer.transform("fake", methodNode);
072                }
073            }
074    
075            methodNode.accept(new EndIgnoringMethodVisitorDecorator(Opcodes.ASM5, delegate));
076    
077    
078            // In case of empty instructions list MethodNode.accept doesn't call visitLocalVariables of delegate
079            // So we just do it here
080            if (methodNode.instructions.size() == 0) {
081                List<LocalVariableNode> localVariables = methodNode.localVariables;
082                // visits local variables
083                int n = localVariables == null ? 0 : localVariables.size();
084                for (int i = 0; i < n; ++i) {
085                    localVariables.get(i).accept(delegate);
086                }
087            }
088    
089            delegate.visitEnd();
090        }
091    
092        /**
093         * You can use it when you need to ignore visit end
094         */
095        private static class EndIgnoringMethodVisitorDecorator extends MethodVisitor {
096            public EndIgnoringMethodVisitorDecorator(int api, @NotNull MethodVisitor mv) {
097                super(api, mv);
098            }
099    
100            @Override
101            public void visitEnd() {
102    
103            }
104        }
105    
106        @Nullable
107        public TraceMethodVisitor getTraceMethodVisitorIfPossible() {
108            TraceMethodVisitor traceMethodVisitor = new TraceMethodVisitor(new Textifier());
109            try {
110                methodNode.accept(traceMethodVisitor);
111            }
112            catch (Throwable e) {
113                return null;
114            }
115    
116            return traceMethodVisitor;
117        }
118    
119        private static boolean canBeAnalyzed(@NotNull MethodNode node) {
120            int totalFramesSizeMb = node.instructions.size() *
121                                  (node.maxLocals + node.maxStack) / (1024 * 1024);
122    
123            return node.instructions.size() > 0 &&
124                   totalFramesSizeMb < MEMORY_LIMIT_BY_METHOD_MB;
125        }
126    }