1 /*
   2  * Copyright (c) 2015, 2018, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  */
  23 
  24 
  25 package org.graalvm.compiler.nodes.graphbuilderconf;
  26 
  27 import static jdk.vm.ci.services.Services.IS_IN_NATIVE_IMAGE;
  28 import static org.graalvm.compiler.nodes.graphbuilderconf.InvocationPlugins.resolveType;
  29 
  30 import java.lang.reflect.Method;
  31 import java.lang.reflect.Modifier;
  32 import java.lang.reflect.Type;
  33 import java.util.Arrays;
  34 import java.util.stream.Collectors;
  35 
  36 import org.graalvm.compiler.bytecode.BytecodeProvider;
  37 import org.graalvm.compiler.debug.GraalError;
  38 import org.graalvm.compiler.nodes.ValueNode;
  39 
  40 import jdk.vm.ci.meta.MetaAccessProvider;
  41 import jdk.vm.ci.meta.ResolvedJavaMethod;
  42 
  43 /**
  44  * An {@link InvocationPlugin} for a method where the implementation of the method is provided by a
  45  * {@linkplain #getSubstitute(MetaAccessProvider) substitute} method. A substitute method must be
  46  * static even if the substituted method is not.
  47  *
  48  * While performing intrinsification with method substitutions is simpler than writing an
  49  * {@link InvocationPlugin} that does manual graph weaving, it has a higher compile time cost than
  50  * the latter; parsing bytecodes to create nodes is slower than simply creating nodes. As such, the
  51  * recommended practice is to use {@link MethodSubstitutionPlugin} only for complex
  52  * intrinsifications which is typically those using non-straight-line control flow.
  53  */
  54 public final class MethodSubstitutionPlugin implements InvocationPlugin {
  55 
  56     private ResolvedJavaMethod cachedSubstitute;
  57 
  58     /**
  59      * The class in which the substitute method is declared.
  60      */
  61     private final Class<?> declaringClass;
  62 
  63     /**
  64      * The name of the original and substitute method.
  65      */
  66     private final String name;
  67 
  68     /**
  69      * The parameter types of the substitute method.
  70      */
  71     private final Type[] parameters;
  72 
  73     private final boolean originalIsStatic;
  74 
  75     private final BytecodeProvider bytecodeProvider;
  76 
  77     /**
  78      * Creates a method substitution plugin.
  79      *
  80      * @param bytecodeProvider used to get the bytecodes to parse for the substitute method
  81      * @param declaringClass the class in which the substitute method is declared
  82      * @param name the name of the substitute method
  83      * @param parameters the parameter types of the substitute method. If the original method is not
  84      *            static, then {@code parameters[0]} must be the {@link Class} value denoting
  85      *            {@link InvocationPlugin.Receiver}
  86      */
  87     public MethodSubstitutionPlugin(BytecodeProvider bytecodeProvider, Class<?> declaringClass, String name, Type... parameters) {
  88         this.bytecodeProvider = bytecodeProvider;
  89         this.declaringClass = declaringClass;
  90         this.name = name;
  91         this.parameters = parameters;
  92         this.originalIsStatic = parameters.length == 0 || parameters[0] != InvocationPlugin.Receiver.class;
  93     }
  94 
  95     @Override
  96     public boolean inlineOnly() {
  97         // Conservatively assume MacroNodes may be used in a substitution
  98         return true;
  99     }
 100 
 101     /**
 102      * Gets the substitute method, resolving it first if necessary.
 103      */
 104     public ResolvedJavaMethod getSubstitute(MetaAccessProvider metaAccess) {
 105         if (cachedSubstitute == null) {
 106             cachedSubstitute = metaAccess.lookupJavaMethod(getJavaSubstitute());
 107         }
 108         return cachedSubstitute;
 109     }
 110 
 111     /**
 112      * Gets the object used to access the bytecodes of the substitute method.
 113      */
 114     public BytecodeProvider getBytecodeProvider() {
 115         return bytecodeProvider;
 116     }
 117 
 118     /**
 119      * Gets the reflection API version of the substitution method.
 120      */
 121     Method getJavaSubstitute() throws GraalError {
 122         Method substituteMethod = lookupSubstitute();
 123         int modifiers = substituteMethod.getModifiers();
 124         if (Modifier.isAbstract(modifiers) || Modifier.isNative(modifiers)) {
 125             throw new GraalError("Substitution method must not be abstract or native: " + substituteMethod);
 126         }
 127         if (!Modifier.isStatic(modifiers)) {
 128             throw new GraalError("Substitution method must be static: " + substituteMethod);
 129         }
 130         return substituteMethod;
 131     }
 132 
 133     /**
 134      * Determines if a given method is the substitute method of this plugin.
 135      */
 136     private boolean isSubstitute(Method m) {
 137         if (Modifier.isStatic(m.getModifiers()) && m.getName().equals(name)) {
 138             if (parameters.length == m.getParameterCount()) {
 139                 Class<?>[] mparams = m.getParameterTypes();
 140                 int start = 0;
 141                 if (!originalIsStatic) {
 142                     start = 1;
 143                     if (!mparams[0].isAssignableFrom(resolveType(parameters[0], false))) {
 144                         return false;
 145                     }
 146                 }
 147                 for (int i = start; i < mparams.length; i++) {
 148                     if (mparams[i] != resolveType(parameters[i], false)) {
 149                         return false;
 150                     }
 151                 }
 152                 return true;
 153             }
 154         }
 155         return false;
 156     }
 157 
 158     private Method lookupSubstitute(Method excluding) {
 159         for (Method m : declaringClass.getDeclaredMethods()) {
 160             if (!m.equals(excluding) && isSubstitute(m)) {
 161                 return m;
 162             }
 163         }
 164         return null;
 165     }
 166 
 167     /**
 168      * Gets the substitute method of this plugin.
 169      */
 170     private Method lookupSubstitute() {
 171         Method m = lookupSubstitute(null);
 172         if (m != null) {
 173             assert lookupSubstitute(m) == null : String.format("multiple matches found for %s:%n%s%n%s", this, m, lookupSubstitute(m));
 174             return m;
 175         }
 176         throw new GraalError("No method found specified by %s", this);
 177     }
 178 
 179     @Override
 180     public boolean execute(GraphBuilderContext b, ResolvedJavaMethod targetMethod, InvocationPlugin.Receiver receiver, ValueNode[] argsIncludingReceiver) {
 181         if (IS_IN_NATIVE_IMAGE) {
 182             // these are currently unimplemented
 183             return false;
 184         }
 185         ResolvedJavaMethod subst = getSubstitute(b.getMetaAccess());
 186         return b.intrinsify(bytecodeProvider, targetMethod, subst, receiver, argsIncludingReceiver);
 187     }
 188 
 189     @Override
 190     public StackTraceElement getApplySourceLocation(MetaAccessProvider metaAccess) {
 191         Class<?> c = getClass();
 192         for (Method m : c.getDeclaredMethods()) {
 193             if (m.getName().equals("execute")) {
 194                 return metaAccess.lookupJavaMethod(m).asStackTraceElement(0);
 195             }
 196         }
 197         throw new GraalError("could not find method named \"execute\" in " + c.getName());
 198     }
 199 
 200     @Override
 201     public String toString() {
 202         return String.format("%s[%s.%s(%s)]", getClass().getSimpleName(), declaringClass.getName(), name,
 203                         Arrays.asList(parameters).stream().map(c -> c.getTypeName()).collect(Collectors.joining(", ")));
 204     }
 205 }