1 /*
   2  * Copyright (c) 2015, 2016, 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 package org.graalvm.compiler.replacements;
  24 
  25 import static jdk.vm.ci.code.MemoryBarriers.JMM_POST_VOLATILE_READ;
  26 import static jdk.vm.ci.code.MemoryBarriers.JMM_POST_VOLATILE_WRITE;
  27 import static jdk.vm.ci.code.MemoryBarriers.JMM_PRE_VOLATILE_READ;
  28 import static jdk.vm.ci.code.MemoryBarriers.JMM_PRE_VOLATILE_WRITE;
  29 import static jdk.vm.ci.code.MemoryBarriers.LOAD_LOAD;
  30 import static jdk.vm.ci.code.MemoryBarriers.LOAD_STORE;
  31 import static jdk.vm.ci.code.MemoryBarriers.STORE_LOAD;
  32 import static jdk.vm.ci.code.MemoryBarriers.STORE_STORE;
  33 import static org.graalvm.compiler.serviceprovider.JDK9Method.Java8OrEarlier;
  34 
  35 import java.lang.reflect.Array;
  36 import java.lang.reflect.Field;
  37 import java.util.Arrays;
  38 
  39 import org.graalvm.compiler.api.directives.GraalDirectives;
  40 import org.graalvm.compiler.api.replacements.SnippetReflectionProvider;
  41 import org.graalvm.compiler.bytecode.BytecodeProvider;
  42 import org.graalvm.compiler.core.common.calc.Condition;
  43 import org.graalvm.compiler.core.common.calc.UnsignedMath;
  44 import org.graalvm.compiler.core.common.type.ObjectStamp;
  45 import org.graalvm.compiler.core.common.type.Stamp;
  46 import org.graalvm.compiler.core.common.type.StampFactory;
  47 import org.graalvm.compiler.core.common.type.TypeReference;
  48 import org.graalvm.compiler.debug.GraalError;
  49 import org.graalvm.compiler.graph.Edges;
  50 import org.graalvm.compiler.graph.Node;
  51 import org.graalvm.compiler.graph.NodeList;
  52 import org.graalvm.compiler.nodes.ConstantNode;
  53 import org.graalvm.compiler.nodes.DeoptimizeNode;
  54 import org.graalvm.compiler.nodes.FixedGuardNode;
  55 import org.graalvm.compiler.nodes.LogicNode;
  56 import org.graalvm.compiler.nodes.StructuredGraph;
  57 import org.graalvm.compiler.nodes.ValueNode;
  58 import org.graalvm.compiler.nodes.calc.AbsNode;
  59 import org.graalvm.compiler.nodes.calc.CompareNode;
  60 import org.graalvm.compiler.nodes.calc.ConditionalNode;
  61 import org.graalvm.compiler.nodes.calc.IntegerEqualsNode;
  62 import org.graalvm.compiler.nodes.calc.NarrowNode;
  63 import org.graalvm.compiler.nodes.calc.ReinterpretNode;
  64 import org.graalvm.compiler.nodes.calc.RightShiftNode;
  65 import org.graalvm.compiler.nodes.calc.SignExtendNode;
  66 import org.graalvm.compiler.nodes.calc.SqrtNode;
  67 import org.graalvm.compiler.nodes.calc.UnsignedDivNode;
  68 import org.graalvm.compiler.nodes.calc.UnsignedRemNode;
  69 import org.graalvm.compiler.nodes.calc.ZeroExtendNode;
  70 import org.graalvm.compiler.nodes.debug.BindToRegisterNode;
  71 import org.graalvm.compiler.nodes.debug.BlackholeNode;
  72 import org.graalvm.compiler.nodes.debug.ControlFlowAnchorNode;
  73 import org.graalvm.compiler.nodes.debug.OpaqueNode;
  74 import org.graalvm.compiler.nodes.debug.SpillRegistersNode;
  75 import org.graalvm.compiler.nodes.extended.BoxNode;
  76 import org.graalvm.compiler.nodes.extended.BranchProbabilityNode;
  77 import org.graalvm.compiler.nodes.extended.GetClassNode;
  78 import org.graalvm.compiler.nodes.extended.MembarNode;
  79 import org.graalvm.compiler.nodes.extended.RawLoadNode;
  80 import org.graalvm.compiler.nodes.extended.RawStoreNode;
  81 import org.graalvm.compiler.nodes.extended.UnboxNode;
  82 import org.graalvm.compiler.nodes.extended.UnsafeMemoryLoadNode;
  83 import org.graalvm.compiler.nodes.extended.UnsafeMemoryStoreNode;
  84 import org.graalvm.compiler.nodes.graphbuilderconf.GraphBuilderContext;
  85 import org.graalvm.compiler.nodes.graphbuilderconf.InvocationPlugin;
  86 import org.graalvm.compiler.nodes.graphbuilderconf.InvocationPlugin.Receiver;
  87 import org.graalvm.compiler.nodes.graphbuilderconf.InvocationPlugins;
  88 import org.graalvm.compiler.nodes.graphbuilderconf.InvocationPlugins.Registration;
  89 import org.graalvm.compiler.nodes.java.ClassIsAssignableFromNode;
  90 import org.graalvm.compiler.nodes.java.DynamicNewArrayNode;
  91 import org.graalvm.compiler.nodes.java.DynamicNewInstanceNode;
  92 import org.graalvm.compiler.nodes.java.InstanceOfDynamicNode;
  93 import org.graalvm.compiler.nodes.java.LoadFieldNode;
  94 import org.graalvm.compiler.nodes.java.RegisterFinalizerNode;
  95 import org.graalvm.compiler.nodes.java.UnsafeCompareAndSwapNode;
  96 import org.graalvm.compiler.nodes.util.GraphUtil;
  97 import org.graalvm.compiler.nodes.virtual.EnsureVirtualizedNode;
  98 import org.graalvm.compiler.replacements.nodes.ReverseBytesNode;
  99 import org.graalvm.compiler.replacements.nodes.VirtualizableInvokeMacroNode;
 100 import org.graalvm.compiler.replacements.nodes.arithmetic.IntegerAddExactNode;
 101 import org.graalvm.compiler.replacements.nodes.arithmetic.IntegerMulExactNode;
 102 import org.graalvm.compiler.replacements.nodes.arithmetic.IntegerSubExactNode;
 103 import org.graalvm.word.LocationIdentity;
 104 
 105 import jdk.vm.ci.meta.DeoptimizationAction;
 106 import jdk.vm.ci.meta.DeoptimizationReason;
 107 import jdk.vm.ci.meta.JavaConstant;
 108 import jdk.vm.ci.meta.JavaKind;
 109 import jdk.vm.ci.meta.MetaAccessProvider;
 110 import jdk.vm.ci.meta.ResolvedJavaField;
 111 import jdk.vm.ci.meta.ResolvedJavaMethod;
 112 import jdk.vm.ci.meta.ResolvedJavaType;
 113 import sun.misc.Unsafe;
 114 
 115 /**
 116  * Provides non-runtime specific {@link InvocationPlugin}s.
 117  */
 118 public class StandardGraphBuilderPlugins {
 119 
 120     public static void registerInvocationPlugins(MetaAccessProvider metaAccess, SnippetReflectionProvider snippetReflection, InvocationPlugins plugins, BytecodeProvider bytecodeProvider,
 121                     boolean allowDeoptimization) {
 122         registerObjectPlugins(plugins);
 123         registerClassPlugins(plugins);
 124         registerMathPlugins(plugins, allowDeoptimization);
 125         registerUnsignedMathPlugins(plugins);
 126         registerStringPlugins(plugins, bytecodeProvider, snippetReflection);
 127         registerCharacterPlugins(plugins);
 128         registerShortPlugins(plugins);
 129         registerIntegerLongPlugins(plugins, JavaKind.Int);
 130         registerIntegerLongPlugins(plugins, JavaKind.Long);
 131         registerFloatPlugins(plugins);
 132         registerDoublePlugins(plugins);
 133         registerArraysPlugins(plugins, bytecodeProvider);
 134         registerArrayPlugins(plugins, bytecodeProvider);
 135         registerUnsafePlugins(plugins, bytecodeProvider);
 136         registerEdgesPlugins(metaAccess, plugins);
 137         registerGraalDirectivesPlugins(plugins);
 138         registerBoxingPlugins(plugins);
 139         registerJMHBlackholePlugins(plugins, bytecodeProvider);
 140         registerJFRThrowablePlugins(plugins, bytecodeProvider);
 141         registerMethodHandleImplPlugins(plugins, snippetReflection, bytecodeProvider);
 142     }
 143 
 144     private static final Field STRING_VALUE_FIELD;
 145 
 146     static {
 147         try {
 148             STRING_VALUE_FIELD = String.class.getDeclaredField("value");
 149         } catch (NoSuchFieldException e) {
 150             throw new GraalError(e);
 151         }
 152     }
 153 
 154     private static void registerStringPlugins(InvocationPlugins plugins, BytecodeProvider bytecodeProvider, SnippetReflectionProvider snippetReflection) {
 155         final Registration r = new Registration(plugins, String.class, bytecodeProvider);
 156         r.register1("hashCode", Receiver.class, new InvocationPlugin() {
 157             @Override
 158             public boolean apply(GraphBuilderContext b, ResolvedJavaMethod targetMethod, Receiver receiver) {
 159                 if (receiver.isConstant()) {
 160                     String s = snippetReflection.asObject(String.class, (JavaConstant) receiver.get().asConstant());
 161                     b.addPush(JavaKind.Int, b.add(ConstantNode.forInt(s.hashCode())));
 162                     return true;
 163                 }
 164                 return false;
 165             }
 166         });
 167 
 168         if (Java8OrEarlier) {
 169             r.registerMethodSubstitution(StringSubstitutions.class, "equals", Receiver.class, Object.class);
 170             r.register7("indexOf", char[].class, int.class, int.class, char[].class, int.class, int.class, int.class, new StringIndexOfConstantPlugin());
 171 
 172             Registration sr = new Registration(plugins, StringSubstitutions.class);
 173             sr.register1("getValue", String.class, new InvocationPlugin() {
 174                 @Override
 175                 public boolean apply(GraphBuilderContext b, ResolvedJavaMethod targetMethod, Receiver receiver, ValueNode value) {
 176                     ResolvedJavaField field = b.getMetaAccess().lookupJavaField(STRING_VALUE_FIELD);
 177                     b.addPush(JavaKind.Object, LoadFieldNode.create(b.getConstantFieldProvider(), b.getConstantReflection(), b.getMetaAccess(),
 178                                     b.getOptions(), b.getAssumptions(), value, field, false, false));
 179                     return true;
 180                 }
 181             });
 182         }
 183     }
 184 
 185     private static void registerArraysPlugins(InvocationPlugins plugins, BytecodeProvider bytecodeProvider) {
 186         Registration r = new Registration(plugins, Arrays.class, bytecodeProvider);
 187         r.registerMethodSubstitution(ArraysSubstitutions.class, "equals", boolean[].class, boolean[].class);
 188         r.registerMethodSubstitution(ArraysSubstitutions.class, "equals", byte[].class, byte[].class);
 189         r.registerMethodSubstitution(ArraysSubstitutions.class, "equals", short[].class, short[].class);
 190         r.registerMethodSubstitution(ArraysSubstitutions.class, "equals", char[].class, char[].class);
 191         r.registerMethodSubstitution(ArraysSubstitutions.class, "equals", int[].class, int[].class);
 192         r.registerMethodSubstitution(ArraysSubstitutions.class, "equals", long[].class, long[].class);
 193     }
 194 
 195     private static void registerArrayPlugins(InvocationPlugins plugins, BytecodeProvider bytecodeProvider) {
 196         Registration r = new Registration(plugins, Array.class, bytecodeProvider);
 197         r.register2("newInstance", Class.class, int.class, new InvocationPlugin() {
 198             @Override
 199             public boolean apply(GraphBuilderContext b, ResolvedJavaMethod targetMethod, Receiver unused, ValueNode componentType, ValueNode length) {
 200                 b.addPush(JavaKind.Object, new DynamicNewArrayNode(componentType, length, true));
 201                 return true;
 202             }
 203         });
 204         r.registerMethodSubstitution(ArraySubstitutions.class, "getLength", Object.class);
 205     }
 206 
 207     private static void registerUnsafePlugins(InvocationPlugins plugins, BytecodeProvider bytecodeProvider) {
 208         Registration r;
 209         if (Java8OrEarlier) {
 210             r = new Registration(plugins, Unsafe.class);
 211         } else {
 212             r = new Registration(plugins, "jdk.internal.misc.Unsafe", bytecodeProvider);
 213         }
 214 
 215         for (JavaKind kind : JavaKind.values()) {
 216             if ((kind.isPrimitive() && kind != JavaKind.Void) || kind == JavaKind.Object) {
 217                 Class<?> javaClass = kind == JavaKind.Object ? Object.class : kind.toJavaClass();
 218                 String kindName = kind.name();
 219                 String getName = "get" + kindName;
 220                 String putName = "put" + kindName;
 221                 // Object-based accesses
 222                 r.register3(getName, Receiver.class, Object.class, long.class, new UnsafeGetPlugin(kind, false));
 223                 r.register4(putName, Receiver.class, Object.class, long.class, javaClass, new UnsafePutPlugin(kind, false));
 224                 // Volatile object-based accesses
 225                 r.register3(getName + "Volatile", Receiver.class, Object.class, long.class, new UnsafeGetPlugin(kind, true));
 226                 r.register4(putName + "Volatile", Receiver.class, Object.class, long.class, javaClass, new UnsafePutPlugin(kind, true));
 227                 // Ordered object-based accesses
 228                 if (Java8OrEarlier) {
 229                     if (kind == JavaKind.Int || kind == JavaKind.Long || kind == JavaKind.Object) {
 230                         r.register4("putOrdered" + kindName, Receiver.class, Object.class, long.class, javaClass, new UnsafePutPlugin(kind, true));
 231                     }
 232                 } else {
 233                     r.register4("put" + kindName + "Release", Receiver.class, Object.class, long.class, javaClass, new UnsafePutPlugin(kind, true));
 234                 }
 235                 if (kind != JavaKind.Boolean && kind != JavaKind.Object) {
 236                     // Raw accesses to memory addresses
 237                     r.register2(getName, Receiver.class, long.class, new UnsafeGetPlugin(kind, false));
 238                     r.register3(putName, Receiver.class, long.class, kind.toJavaClass(), new UnsafePutPlugin(kind, false));
 239                 }
 240             }
 241         }
 242 
 243         // Accesses to native memory addresses.
 244         r.register2("getAddress", Receiver.class, long.class, new UnsafeGetPlugin(JavaKind.Long, false));
 245         r.register3("putAddress", Receiver.class, long.class, long.class, new UnsafePutPlugin(JavaKind.Long, false));
 246 
 247         for (JavaKind kind : new JavaKind[]{JavaKind.Int, JavaKind.Long, JavaKind.Object}) {
 248             Class<?> javaClass = kind == JavaKind.Object ? Object.class : kind.toJavaClass();
 249             String casName;
 250             if (Java8OrEarlier) {
 251                 casName = "compareAndSwap";
 252             } else {
 253                 casName = "compareAndSet";
 254             }
 255             r.register5(casName + kind.name(), Receiver.class, Object.class, long.class, javaClass, javaClass, new InvocationPlugin() {
 256                 @Override
 257                 public boolean apply(GraphBuilderContext b, ResolvedJavaMethod targetMethod, Receiver unsafe, ValueNode object, ValueNode offset, ValueNode expected, ValueNode x) {
 258                     // Emits a null-check for the otherwise unused receiver
 259                     unsafe.get();
 260                     b.addPush(JavaKind.Int, new UnsafeCompareAndSwapNode(object, offset, expected, x, kind, LocationIdentity.any()));
 261                     b.getGraph().markUnsafeAccess();
 262                     return true;
 263                 }
 264             });
 265         }
 266 
 267         r.register2("allocateInstance", Receiver.class, Class.class, new InvocationPlugin() {
 268 
 269             @Override
 270             public boolean apply(GraphBuilderContext b, ResolvedJavaMethod targetMethod, Receiver unsafe, ValueNode clazz) {
 271                 // Emits a null-check for the otherwise unused receiver
 272                 unsafe.get();
 273                 b.addPush(JavaKind.Object, new DynamicNewInstanceNode(b.nullCheckedValue(clazz, DeoptimizationAction.None), true));
 274                 return true;
 275             }
 276 
 277         });
 278 
 279         r.register1("loadFence", Receiver.class, new UnsafeFencePlugin(LOAD_LOAD | LOAD_STORE));
 280         r.register1("storeFence", Receiver.class, new UnsafeFencePlugin(STORE_STORE | LOAD_STORE));
 281         r.register1("fullFence", Receiver.class, new UnsafeFencePlugin(LOAD_LOAD | STORE_STORE | LOAD_STORE | STORE_LOAD));
 282     }
 283 
 284     private static void registerIntegerLongPlugins(InvocationPlugins plugins, JavaKind kind) {
 285         Class<?> declaringClass = kind.toBoxedJavaClass();
 286         Class<?> type = kind.toJavaClass();
 287         Registration r = new Registration(plugins, declaringClass);
 288         r.register1("reverseBytes", type, new InvocationPlugin() {
 289             @Override
 290             public boolean apply(GraphBuilderContext b, ResolvedJavaMethod targetMethod, Receiver receiver, ValueNode value) {
 291                 b.push(kind, b.append(new ReverseBytesNode(value).canonical(null)));
 292                 return true;
 293             }
 294         });
 295         r.register2("divideUnsigned", type, type, new InvocationPlugin() {
 296             @Override
 297             public boolean apply(GraphBuilderContext b, ResolvedJavaMethod targetMethod, Receiver receiver, ValueNode dividend, ValueNode divisor) {
 298                 b.push(kind, b.append(new UnsignedDivNode(dividend, divisor).canonical(null)));
 299                 return true;
 300             }
 301         });
 302         r.register2("remainderUnsigned", type, type, new InvocationPlugin() {
 303             @Override
 304             public boolean apply(GraphBuilderContext b, ResolvedJavaMethod targetMethod, Receiver receiver, ValueNode dividend, ValueNode divisor) {
 305                 b.push(kind, b.append(new UnsignedRemNode(dividend, divisor).canonical(null)));
 306                 return true;
 307             }
 308         });
 309     }
 310 
 311     private static void registerCharacterPlugins(InvocationPlugins plugins) {
 312         Registration r = new Registration(plugins, Character.class);
 313         r.register1("reverseBytes", char.class, new InvocationPlugin() {
 314             @Override
 315             public boolean apply(GraphBuilderContext b, ResolvedJavaMethod targetMethod, Receiver receiver, ValueNode value) {
 316                 // return (char) (Integer.reverse(i) >> 16);
 317                 ReverseBytesNode reverse = b.add(new ReverseBytesNode(value));
 318                 RightShiftNode rightShift = b.add(new RightShiftNode(reverse, b.add(ConstantNode.forInt(16))));
 319                 ZeroExtendNode charCast = b.add(new ZeroExtendNode(b.add(new NarrowNode(rightShift, 16)), 32));
 320                 b.push(JavaKind.Char, b.append(charCast.canonical(null)));
 321                 return true;
 322             }
 323         });
 324     }
 325 
 326     private static void registerShortPlugins(InvocationPlugins plugins) {
 327         Registration r = new Registration(plugins, Short.class);
 328         r.register1("reverseBytes", short.class, new InvocationPlugin() {
 329             @Override
 330             public boolean apply(GraphBuilderContext b, ResolvedJavaMethod targetMethod, Receiver receiver, ValueNode value) {
 331                 // return (short) (Integer.reverse(i) >> 16);
 332                 ReverseBytesNode reverse = b.add(new ReverseBytesNode(value));
 333                 RightShiftNode rightShift = b.add(new RightShiftNode(reverse, b.add(ConstantNode.forInt(16))));
 334                 SignExtendNode charCast = b.add(new SignExtendNode(b.add(new NarrowNode(rightShift, 16)), 32));
 335                 b.push(JavaKind.Short, b.append(charCast.canonical(null)));
 336                 return true;
 337             }
 338         });
 339     }
 340 
 341     private static void registerFloatPlugins(InvocationPlugins plugins) {
 342         Registration r = new Registration(plugins, Float.class);
 343         r.register1("floatToRawIntBits", float.class, new InvocationPlugin() {
 344             @Override
 345             public boolean apply(GraphBuilderContext b, ResolvedJavaMethod targetMethod, Receiver receiver, ValueNode value) {
 346                 b.push(JavaKind.Int, b.append(new ReinterpretNode(JavaKind.Int, value).canonical(null)));
 347                 return true;
 348             }
 349         });
 350         r.register1("intBitsToFloat", int.class, new InvocationPlugin() {
 351             @Override
 352             public boolean apply(GraphBuilderContext b, ResolvedJavaMethod targetMethod, Receiver receiver, ValueNode value) {
 353                 b.push(JavaKind.Float, b.append(new ReinterpretNode(JavaKind.Float, value).canonical(null)));
 354                 return true;
 355             }
 356         });
 357     }
 358 
 359     private static void registerDoublePlugins(InvocationPlugins plugins) {
 360         Registration r = new Registration(plugins, Double.class);
 361         r.register1("doubleToRawLongBits", double.class, new InvocationPlugin() {
 362             @Override
 363             public boolean apply(GraphBuilderContext b, ResolvedJavaMethod targetMethod, Receiver receiver, ValueNode value) {
 364                 b.push(JavaKind.Long, b.append(new ReinterpretNode(JavaKind.Long, value).canonical(null)));
 365                 return true;
 366             }
 367         });
 368         r.register1("longBitsToDouble", long.class, new InvocationPlugin() {
 369             @Override
 370             public boolean apply(GraphBuilderContext b, ResolvedJavaMethod targetMethod, Receiver receiver, ValueNode value) {
 371                 b.push(JavaKind.Double, b.append(new ReinterpretNode(JavaKind.Double, value).canonical(null)));
 372                 return true;
 373             }
 374         });
 375     }
 376 
 377     private static void registerMathPlugins(InvocationPlugins plugins, boolean allowDeoptimization) {
 378         Registration r = new Registration(plugins, Math.class);
 379         if (allowDeoptimization) {
 380             for (JavaKind kind : new JavaKind[]{JavaKind.Int, JavaKind.Long}) {
 381                 Class<?> type = kind.toJavaClass();
 382                 r.register2("addExact", type, type, new InvocationPlugin() {
 383                     @Override
 384                     public boolean apply(GraphBuilderContext b, ResolvedJavaMethod targetMethod, Receiver receiver, ValueNode x, ValueNode y) {
 385                         b.addPush(kind, new IntegerAddExactNode(x, y));
 386                         return true;
 387                     }
 388                 });
 389                 r.register2("subtractExact", type, type, new InvocationPlugin() {
 390                     @Override
 391                     public boolean apply(GraphBuilderContext b, ResolvedJavaMethod targetMethod, Receiver receiver, ValueNode x, ValueNode y) {
 392                         b.addPush(kind, new IntegerSubExactNode(x, y));
 393                         return true;
 394                     }
 395                 });
 396                 r.register2("multiplyExact", type, type, new InvocationPlugin() {
 397                     @Override
 398                     public boolean apply(GraphBuilderContext b, ResolvedJavaMethod targetMethod, Receiver receiver, ValueNode x, ValueNode y) {
 399                         b.addPush(kind, new IntegerMulExactNode(x, y));
 400                         return true;
 401                     }
 402                 });
 403             }
 404         }
 405         r.register1("abs", Float.TYPE, new InvocationPlugin() {
 406 
 407             @Override
 408             public boolean apply(GraphBuilderContext b, ResolvedJavaMethod targetMethod, Receiver receiver, ValueNode value) {
 409                 b.push(JavaKind.Float, b.append(new AbsNode(value).canonical(null)));
 410                 return true;
 411             }
 412         });
 413         r.register1("abs", Double.TYPE, new InvocationPlugin() {
 414             @Override
 415             public boolean apply(GraphBuilderContext b, ResolvedJavaMethod targetMethod, Receiver receiver, ValueNode value) {
 416                 b.push(JavaKind.Double, b.append(new AbsNode(value).canonical(null)));
 417                 return true;
 418             }
 419         });
 420         r.register1("sqrt", Double.TYPE, new InvocationPlugin() {
 421             @Override
 422             public boolean apply(GraphBuilderContext b, ResolvedJavaMethod targetMethod, Receiver receiver, ValueNode value) {
 423                 b.push(JavaKind.Double, b.append(new SqrtNode(value).canonical(null)));
 424                 return true;
 425             }
 426         });
 427     }
 428 
 429     public static final class StringIndexOfConstantPlugin implements InvocationPlugin {
 430         @Override
 431         public boolean inlineOnly() {
 432             return true;
 433         }
 434 
 435         @Override
 436         public boolean apply(GraphBuilderContext b, ResolvedJavaMethod targetMethod, InvocationPlugin.Receiver receiver, ValueNode source, ValueNode sourceOffset, ValueNode sourceCount,
 437                         ValueNode target, ValueNode targetOffset, ValueNode targetCount, ValueNode origFromIndex) {
 438             if (target.isConstant()) {
 439                 b.addPush(JavaKind.Int, new StringIndexOfNode(b.getInvokeKind(), targetMethod, b.bci(), b.getInvokeReturnStamp(b.getAssumptions()), source, sourceOffset, sourceCount,
 440                                 target, targetOffset, targetCount, origFromIndex));
 441                 return true;
 442             }
 443             return false;
 444         }
 445     }
 446 
 447     public static class UnsignedMathPlugin implements InvocationPlugin {
 448         private final Condition condition;
 449 
 450         public UnsignedMathPlugin(Condition condition) {
 451             this.condition = condition;
 452         }
 453 
 454         @Override
 455         public boolean apply(GraphBuilderContext b, ResolvedJavaMethod targetMethod, Receiver receiver, ValueNode x, ValueNode y) {
 456             // the mirroring and negation operations get the condition into canonical form
 457             boolean mirror = condition.canonicalMirror();
 458             boolean negate = condition.canonicalNegate();
 459             StructuredGraph graph = b.getGraph();
 460 
 461             ValueNode lhs = mirror ? y : x;
 462             ValueNode rhs = mirror ? x : y;
 463 
 464             ValueNode trueValue = ConstantNode.forBoolean(!negate, graph);
 465             ValueNode falseValue = ConstantNode.forBoolean(negate, graph);
 466 
 467             Condition cond = mirror ? condition.mirror() : condition;
 468             if (negate) {
 469                 cond = cond.negate();
 470             }
 471 
 472             LogicNode compare = CompareNode.createCompareNode(graph, b.getConstantReflection(), b.getMetaAccess(), b.getOptions(), null, cond, lhs, rhs);
 473             b.addPush(JavaKind.Boolean, new ConditionalNode(compare, trueValue, falseValue));
 474             return true;
 475         }
 476     }
 477 
 478     private static void registerUnsignedMathPlugins(InvocationPlugins plugins) {
 479         Registration r = new Registration(plugins, UnsignedMath.class);
 480         r.register2("aboveThan", int.class, int.class, new UnsignedMathPlugin(Condition.AT));
 481         r.register2("aboveThan", long.class, long.class, new UnsignedMathPlugin(Condition.AT));
 482         r.register2("belowThan", int.class, int.class, new UnsignedMathPlugin(Condition.BT));
 483         r.register2("belowThan", long.class, long.class, new UnsignedMathPlugin(Condition.BT));
 484         r.register2("aboveOrEqual", int.class, int.class, new UnsignedMathPlugin(Condition.AE));
 485         r.register2("aboveOrEqual", long.class, long.class, new UnsignedMathPlugin(Condition.AE));
 486         r.register2("belowOrEqual", int.class, int.class, new UnsignedMathPlugin(Condition.BE));
 487         r.register2("belowOrEqual", long.class, long.class, new UnsignedMathPlugin(Condition.BE));
 488     }
 489 
 490     protected static void registerBoxingPlugins(InvocationPlugins plugins) {
 491         for (JavaKind kind : JavaKind.values()) {
 492             if (kind.isPrimitive() && kind != JavaKind.Void) {
 493                 new BoxPlugin(kind).register(plugins);
 494                 new UnboxPlugin(kind).register(plugins);
 495             }
 496         }
 497     }
 498 
 499     private static void registerObjectPlugins(InvocationPlugins plugins) {
 500         Registration r = new Registration(plugins, Object.class);
 501         r.register1("<init>", Receiver.class, new InvocationPlugin() {
 502             @Override
 503             public boolean apply(GraphBuilderContext b, ResolvedJavaMethod targetMethod, Receiver receiver) {
 504                 /*
 505                  * Object.<init> is a common instrumentation point so only perform this rewrite if
 506                  * the current definition is the normal empty method with a single return bytecode.
 507                  * The finalizer registration will instead be performed by the BytecodeParser.
 508                  */
 509                 if (targetMethod.getCodeSize() == 1) {
 510                     ValueNode object = receiver.get();
 511                     if (RegisterFinalizerNode.mayHaveFinalizer(object, b.getAssumptions())) {
 512                         b.add(new RegisterFinalizerNode(object));
 513                     }
 514                     return true;
 515                 }
 516                 return false;
 517             }
 518         });
 519         r.register1("getClass", Receiver.class, new InvocationPlugin() {
 520             @Override
 521             public boolean apply(GraphBuilderContext b, ResolvedJavaMethod targetMethod, Receiver receiver) {
 522                 ValueNode object = receiver.get();
 523                 ValueNode folded = GetClassNode.tryFold(b.getMetaAccess(), b.getConstantReflection(), GraphUtil.originalValue(object));
 524                 if (folded != null) {
 525                     b.addPush(JavaKind.Object, folded);
 526                 } else {
 527                     Stamp stamp = StampFactory.objectNonNull(TypeReference.createTrusted(b.getAssumptions(), b.getMetaAccess().lookupJavaType(Class.class)));
 528                     b.addPush(JavaKind.Object, new GetClassNode(stamp, object));
 529                 }
 530                 return true;
 531             }
 532         });
 533     }
 534 
 535     private static void registerClassPlugins(InvocationPlugins plugins) {
 536         Registration r = new Registration(plugins, Class.class);
 537         r.register2("isInstance", Receiver.class, Object.class, new InvocationPlugin() {
 538             @Override
 539             public boolean apply(GraphBuilderContext b, ResolvedJavaMethod targetMethod, Receiver type, ValueNode object) {
 540                 LogicNode condition = b.append(InstanceOfDynamicNode.create(b.getAssumptions(), b.getConstantReflection(), type.get(), object, false));
 541                 b.push(JavaKind.Boolean, b.append(new ConditionalNode(condition).canonical(null)));
 542                 return true;
 543             }
 544         });
 545         r.register2("isAssignableFrom", Receiver.class, Class.class, new InvocationPlugin() {
 546             @Override
 547             public boolean apply(GraphBuilderContext b, ResolvedJavaMethod targetMethod, Receiver type, ValueNode otherType) {
 548                 ClassIsAssignableFromNode condition = b.append(new ClassIsAssignableFromNode(type.get(), otherType));
 549                 b.push(JavaKind.Boolean, b.append(new ConditionalNode(condition).canonical(null)));
 550                 return true;
 551             }
 552         });
 553     }
 554 
 555     /**
 556      * Substitutions for improving the performance of some critical methods in {@link Edges}. These
 557      * substitutions improve the performance by forcing the relevant methods to be inlined
 558      * (intrinsification being a special form of inlining) and removing a checked cast.
 559      */
 560     private static void registerEdgesPlugins(MetaAccessProvider metaAccess, InvocationPlugins plugins) {
 561         Registration r = new Registration(plugins, Edges.class);
 562         for (Class<?> c : new Class<?>[]{Node.class, NodeList.class}) {
 563             r.register2("get" + c.getSimpleName() + "Unsafe", Node.class, long.class, new InvocationPlugin() {
 564                 @Override
 565                 public boolean apply(GraphBuilderContext b, ResolvedJavaMethod targetMethod, Receiver receiver, ValueNode node, ValueNode offset) {
 566                     ObjectStamp stamp = StampFactory.object(TypeReference.createTrusted(b.getAssumptions(), metaAccess.lookupJavaType(c)));
 567                     RawLoadNode value = b.add(new RawLoadNode(stamp, node, offset, LocationIdentity.any(), JavaKind.Object));
 568                     b.addPush(JavaKind.Object, value);
 569                     return true;
 570                 }
 571             });
 572             r.register3("put" + c.getSimpleName() + "Unsafe", Node.class, long.class, c, new InvocationPlugin() {
 573                 @Override
 574                 public boolean apply(GraphBuilderContext b, ResolvedJavaMethod targetMethod, Receiver receiver, ValueNode node, ValueNode offset, ValueNode value) {
 575                     b.add(new RawStoreNode(node, offset, value, JavaKind.Object, LocationIdentity.any()));
 576                     return true;
 577                 }
 578             });
 579         }
 580     }
 581 
 582     public static class BoxPlugin implements InvocationPlugin {
 583 
 584         private final JavaKind kind;
 585 
 586         BoxPlugin(JavaKind kind) {
 587             this.kind = kind;
 588         }
 589 
 590         @Override
 591         public boolean apply(GraphBuilderContext b, ResolvedJavaMethod targetMethod, Receiver receiver, ValueNode value) {
 592             if (b.parsingIntrinsic()) {
 593                 ResolvedJavaMethod rootMethod = b.getGraph().method();
 594                 if (b.getMetaAccess().lookupJavaType(BoxingSnippets.class).isAssignableFrom(rootMethod.getDeclaringClass())) {
 595                     // Disable invocation plugins for boxing snippets so that the
 596                     // original JDK methods are inlined
 597                     return false;
 598                 }
 599             }
 600             ResolvedJavaType resultType = b.getMetaAccess().lookupJavaType(kind.toBoxedJavaClass());
 601             b.addPush(JavaKind.Object, new BoxNode(value, resultType, kind));
 602             return true;
 603         }
 604 
 605         void register(InvocationPlugins plugins) {
 606             plugins.register(this, kind.toBoxedJavaClass(), "valueOf", kind.toJavaClass());
 607         }
 608     }
 609 
 610     public static class UnboxPlugin implements InvocationPlugin {
 611 
 612         private final JavaKind kind;
 613 
 614         UnboxPlugin(JavaKind kind) {
 615             this.kind = kind;
 616         }
 617 
 618         @Override
 619         public boolean apply(GraphBuilderContext b, ResolvedJavaMethod targetMethod, Receiver receiver) {
 620             if (b.parsingIntrinsic()) {
 621                 ResolvedJavaMethod rootMethod = b.getGraph().method();
 622                 if (b.getMetaAccess().lookupJavaType(BoxingSnippets.class).isAssignableFrom(rootMethod.getDeclaringClass())) {
 623                     // Disable invocation plugins for unboxing snippets so that the
 624                     // original JDK methods are inlined
 625                     return false;
 626                 }
 627             }
 628             ValueNode valueNode = UnboxNode.create(b.getMetaAccess(), b.getConstantReflection(), receiver.get(), kind);
 629             b.addPush(kind, valueNode);
 630             return true;
 631         }
 632 
 633         void register(InvocationPlugins plugins) {
 634             String name = kind.toJavaClass().getSimpleName() + "Value";
 635             plugins.register(this, kind.toBoxedJavaClass(), name, Receiver.class);
 636         }
 637     }
 638 
 639     public static class UnsafeGetPlugin implements InvocationPlugin {
 640 
 641         private final JavaKind returnKind;
 642         private final boolean isVolatile;
 643 
 644         public UnsafeGetPlugin(JavaKind returnKind, boolean isVolatile) {
 645             this.returnKind = returnKind;
 646             this.isVolatile = isVolatile;
 647         }
 648 
 649         @Override
 650         public boolean apply(GraphBuilderContext b, ResolvedJavaMethod targetMethod, Receiver unsafe, ValueNode address) {
 651             // Emits a null-check for the otherwise unused receiver
 652             unsafe.get();
 653             b.addPush(returnKind, new UnsafeMemoryLoadNode(address, returnKind, LocationIdentity.any()));
 654             b.getGraph().markUnsafeAccess();
 655             return true;
 656         }
 657 
 658         @Override
 659         public boolean apply(GraphBuilderContext b, ResolvedJavaMethod targetMethod, Receiver unsafe, ValueNode object, ValueNode offset) {
 660             // Emits a null-check for the otherwise unused receiver
 661             unsafe.get();
 662             if (isVolatile) {
 663                 b.add(new MembarNode(JMM_PRE_VOLATILE_READ));
 664             }
 665             b.addPush(returnKind, new RawLoadNode(object, offset, returnKind, LocationIdentity.any()));
 666             if (isVolatile) {
 667                 b.add(new MembarNode(JMM_POST_VOLATILE_READ));
 668             }
 669             b.getGraph().markUnsafeAccess();
 670             return true;
 671         }
 672     }
 673 
 674     public static class UnsafePutPlugin implements InvocationPlugin {
 675 
 676         private final JavaKind kind;
 677         private final boolean isVolatile;
 678 
 679         public UnsafePutPlugin(JavaKind kind, boolean isVolatile) {
 680             this.kind = kind;
 681             this.isVolatile = isVolatile;
 682         }
 683 
 684         @Override
 685         public boolean apply(GraphBuilderContext b, ResolvedJavaMethod targetMethod, Receiver unsafe, ValueNode address, ValueNode value) {
 686             // Emits a null-check for the otherwise unused receiver
 687             unsafe.get();
 688             b.add(new UnsafeMemoryStoreNode(address, value, kind, LocationIdentity.any()));
 689             b.getGraph().markUnsafeAccess();
 690             return true;
 691         }
 692 
 693         @Override
 694         public boolean apply(GraphBuilderContext b, ResolvedJavaMethod targetMethod, Receiver unsafe, ValueNode object, ValueNode offset, ValueNode value) {
 695             // Emits a null-check for the otherwise unused receiver
 696             unsafe.get();
 697             if (isVolatile) {
 698                 b.add(new MembarNode(JMM_PRE_VOLATILE_WRITE));
 699             }
 700             b.add(new RawStoreNode(object, offset, value, kind, LocationIdentity.any()));
 701             if (isVolatile) {
 702                 b.add(new MembarNode(JMM_POST_VOLATILE_WRITE));
 703             }
 704             b.getGraph().markUnsafeAccess();
 705             return true;
 706         }
 707     }
 708 
 709     public static class UnsafeFencePlugin implements InvocationPlugin {
 710 
 711         private final int barriers;
 712 
 713         public UnsafeFencePlugin(int barriers) {
 714             this.barriers = barriers;
 715         }
 716 
 717         @Override
 718         public boolean apply(GraphBuilderContext b, ResolvedJavaMethod targetMethod, Receiver unsafe) {
 719             // Emits a null-check for the otherwise unused receiver
 720             unsafe.get();
 721             b.add(new MembarNode(barriers));
 722             return true;
 723         }
 724     }
 725 
 726     private static void registerGraalDirectivesPlugins(InvocationPlugins plugins) {
 727         Registration r = new Registration(plugins, GraalDirectives.class);
 728         r.register0("deoptimize", new InvocationPlugin() {
 729             @Override
 730             public boolean apply(GraphBuilderContext b, ResolvedJavaMethod targetMethod, Receiver receiver) {
 731                 b.add(new DeoptimizeNode(DeoptimizationAction.None, DeoptimizationReason.TransferToInterpreter));
 732                 return true;
 733             }
 734         });
 735 
 736         r.register0("deoptimizeAndInvalidate", new InvocationPlugin() {
 737             @Override
 738             public boolean apply(GraphBuilderContext b, ResolvedJavaMethod targetMethod, Receiver receiver) {
 739                 b.add(new DeoptimizeNode(DeoptimizationAction.InvalidateReprofile, DeoptimizationReason.TransferToInterpreter));
 740                 return true;
 741             }
 742         });
 743 
 744         r.register0("inCompiledCode", new InvocationPlugin() {
 745             @Override
 746             public boolean apply(GraphBuilderContext b, ResolvedJavaMethod targetMethod, Receiver receiver) {
 747                 b.addPush(JavaKind.Boolean, ConstantNode.forBoolean(true));
 748                 return true;
 749             }
 750         });
 751 
 752         r.register0("controlFlowAnchor", new InvocationPlugin() {
 753             @Override
 754             public boolean apply(GraphBuilderContext b, ResolvedJavaMethod targetMethod, Receiver receiver) {
 755                 b.add(new ControlFlowAnchorNode());
 756                 return true;
 757             }
 758         });
 759 
 760         r.register2("injectBranchProbability", double.class, boolean.class, new InvocationPlugin() {
 761             @Override
 762             public boolean apply(GraphBuilderContext b, ResolvedJavaMethod targetMethod, Receiver receiver, ValueNode probability, ValueNode condition) {
 763                 b.addPush(JavaKind.Boolean, new BranchProbabilityNode(probability, condition));
 764                 return true;
 765             }
 766         });
 767 
 768         InvocationPlugin blackholePlugin = new InvocationPlugin() {
 769             @Override
 770             public boolean apply(GraphBuilderContext b, ResolvedJavaMethod targetMethod, Receiver receiver, ValueNode value) {
 771                 b.add(new BlackholeNode(value));
 772                 return true;
 773             }
 774         };
 775 
 776         InvocationPlugin bindToRegisterPlugin = new InvocationPlugin() {
 777             @Override
 778             public boolean apply(GraphBuilderContext b, ResolvedJavaMethod targetMethod, Receiver receiver, ValueNode value) {
 779                 b.add(new BindToRegisterNode(value));
 780                 return true;
 781             }
 782         };
 783         for (JavaKind kind : JavaKind.values()) {
 784             if ((kind.isPrimitive() && kind != JavaKind.Void) || kind == JavaKind.Object) {
 785                 Class<?> javaClass = kind == JavaKind.Object ? Object.class : kind.toJavaClass();
 786                 r.register1("blackhole", javaClass, blackholePlugin);
 787                 r.register1("bindToRegister", javaClass, bindToRegisterPlugin);
 788 
 789                 r.register1("opaque", javaClass, new InvocationPlugin() {
 790                     @Override
 791                     public boolean apply(GraphBuilderContext b, ResolvedJavaMethod targetMethod, Receiver receiver, ValueNode value) {
 792                         b.addPush(kind, new OpaqueNode(value));
 793                         return true;
 794                     }
 795                 });
 796             }
 797         }
 798 
 799         InvocationPlugin spillPlugin = new InvocationPlugin() {
 800             @Override
 801             public boolean apply(GraphBuilderContext b, ResolvedJavaMethod targetMethod, Receiver receiver) {
 802                 b.add(new SpillRegistersNode());
 803                 return true;
 804             }
 805         };
 806         r.register0("spillRegisters", spillPlugin);
 807 
 808         r.register1("guardingNonNull", Object.class, new InvocationPlugin() {
 809             @Override
 810             public boolean apply(GraphBuilderContext b, ResolvedJavaMethod targetMethod, Receiver receiver, ValueNode value) {
 811                 b.addPush(value.getStackKind(), b.nullCheckedValue(value));
 812                 return true;
 813             }
 814         });
 815 
 816         r.register1("ensureVirtualized", Object.class, new InvocationPlugin() {
 817             @Override
 818             public boolean apply(GraphBuilderContext b, ResolvedJavaMethod targetMethod, Receiver receiver, ValueNode object) {
 819                 b.add(new EnsureVirtualizedNode(object, false));
 820                 return true;
 821             }
 822         });
 823         r.register1("ensureVirtualizedHere", Object.class, new InvocationPlugin() {
 824             @Override
 825             public boolean apply(GraphBuilderContext b, ResolvedJavaMethod targetMethod, Receiver receiver, ValueNode object) {
 826                 b.add(new EnsureVirtualizedNode(object, true));
 827                 return true;
 828             }
 829         });
 830     }
 831 
 832     private static void registerJMHBlackholePlugins(InvocationPlugins plugins, BytecodeProvider bytecodeProvider) {
 833         InvocationPlugin blackholePlugin = new InvocationPlugin() {
 834             @Override
 835             public boolean apply(GraphBuilderContext b, ResolvedJavaMethod targetMethod, Receiver blackhole, ValueNode value) {
 836                 blackhole.get();
 837                 b.add(new BlackholeNode(value));
 838                 return true;
 839             }
 840         };
 841         String[] names = {"org.openjdk.jmh.infra.Blackhole", "org.openjdk.jmh.logic.BlackHole"};
 842         for (String name : names) {
 843             Registration r = new Registration(plugins, name, bytecodeProvider);
 844             for (JavaKind kind : JavaKind.values()) {
 845                 if ((kind.isPrimitive() && kind != JavaKind.Void) || kind == JavaKind.Object) {
 846                     Class<?> javaClass = kind == JavaKind.Object ? Object.class : kind.toJavaClass();
 847                     r.registerOptional2("consume", Receiver.class, javaClass, blackholePlugin);
 848                 }
 849             }
 850             r.registerOptional2("consume", Receiver.class, Object[].class, blackholePlugin);
 851         }
 852     }
 853 
 854     private static void registerJFRThrowablePlugins(InvocationPlugins plugins, BytecodeProvider bytecodeProvider) {
 855         Registration r = new Registration(plugins, "oracle.jrockit.jfr.jdkevents.ThrowableTracer", bytecodeProvider);
 856         r.register2("traceThrowable", Throwable.class, String.class, new InvocationPlugin() {
 857             @Override
 858             public boolean apply(GraphBuilderContext b, ResolvedJavaMethod targetMethod, Receiver receiver, ValueNode throwable, ValueNode message) {
 859                 b.add(new VirtualizableInvokeMacroNode(b.getInvokeKind(), targetMethod, b.bci(), b.getInvokeReturnStamp(b.getAssumptions()), throwable, message));
 860                 return true;
 861             }
 862 
 863             @Override
 864             public boolean inlineOnly() {
 865                 return true;
 866             }
 867         });
 868     }
 869 
 870     private static void registerMethodHandleImplPlugins(InvocationPlugins plugins, SnippetReflectionProvider snippetReflection, BytecodeProvider bytecodeProvider) {
 871         Registration r = new Registration(plugins, "java.lang.invoke.MethodHandleImpl", bytecodeProvider);
 872         r.register2("profileBoolean", boolean.class, int[].class, new InvocationPlugin() {
 873             @Override
 874             public boolean apply(GraphBuilderContext b, ResolvedJavaMethod targetMethod, Receiver receiver, ValueNode result, ValueNode counters) {
 875                 if (result.isConstant()) {
 876                     b.push(JavaKind.Boolean, result);
 877                     return true;
 878                 }
 879                 if (counters.isConstant()) {
 880                     ValueNode newResult = result;
 881                     int[] ctrs = snippetReflection.asObject(int[].class, (JavaConstant) counters.asConstant());
 882                     if (ctrs != null && ctrs.length == 2) {
 883                         int falseCount = ctrs[0];
 884                         int trueCount = ctrs[1];
 885                         int totalCount = trueCount + falseCount;
 886 
 887                         if (totalCount == 0) {
 888                             b.add(new DeoptimizeNode(DeoptimizationAction.InvalidateReprofile, DeoptimizationReason.TransferToInterpreter));
 889                         } else if (falseCount == 0 || trueCount == 0) {
 890                             boolean expected = falseCount == 0;
 891                             LogicNode condition = b.addWithInputs(
 892                                             IntegerEqualsNode.create(b.getConstantReflection(), b.getMetaAccess(), b.getOptions(), null, result, b.add(ConstantNode.forBoolean(!expected))));
 893                             b.append(new FixedGuardNode(condition, DeoptimizationReason.UnreachedCode, DeoptimizationAction.InvalidateReprofile, true));
 894                             newResult = b.add(ConstantNode.forBoolean(expected));
 895                         } else {
 896                             // We cannot use BranchProbabilityNode here since there's no guarantee
 897                             // the result of MethodHandleImpl.profileBoolean() is used as the
 898                             // test in an `if` statement (as required by BranchProbabilityNode).
 899                         }
 900                     }
 901                     b.addPush(JavaKind.Boolean, newResult);
 902                     return true;
 903                 }
 904                 return false;
 905             }
 906         });
 907     }
 908 }