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.replacements; 26 27 import static jdk.vm.ci.code.MemoryBarriers.JMM_POST_VOLATILE_READ; 28 import static jdk.vm.ci.code.MemoryBarriers.JMM_POST_VOLATILE_WRITE; 29 import static jdk.vm.ci.code.MemoryBarriers.JMM_PRE_VOLATILE_READ; 30 import static jdk.vm.ci.code.MemoryBarriers.JMM_PRE_VOLATILE_WRITE; 31 import static jdk.vm.ci.code.MemoryBarriers.LOAD_LOAD; 32 import static jdk.vm.ci.code.MemoryBarriers.LOAD_STORE; 33 import static jdk.vm.ci.code.MemoryBarriers.STORE_LOAD; 34 import static jdk.vm.ci.code.MemoryBarriers.STORE_STORE; 35 import static org.graalvm.compiler.nodes.NamedLocationIdentity.OFF_HEAP_LOCATION; 36 import static org.graalvm.compiler.serviceprovider.GraalServices.Java11OrEarlier; 37 import static org.graalvm.compiler.serviceprovider.GraalServices.Java8OrEarlier; 38 39 import java.lang.reflect.Array; 40 import java.lang.reflect.Field; 41 import java.util.Arrays; 42 43 import org.graalvm.compiler.api.directives.GraalDirectives; 44 import org.graalvm.compiler.api.replacements.SnippetReflectionProvider; 45 import org.graalvm.compiler.bytecode.BytecodeProvider; 46 import org.graalvm.compiler.core.common.calc.Condition; 47 import org.graalvm.compiler.core.common.calc.Condition.CanonicalizedCondition; 48 import org.graalvm.compiler.core.common.calc.UnsignedMath; 49 import org.graalvm.compiler.core.common.type.ObjectStamp; 50 import org.graalvm.compiler.core.common.type.Stamp; 51 import org.graalvm.compiler.core.common.type.StampFactory; 52 import org.graalvm.compiler.core.common.type.TypeReference; 53 import org.graalvm.compiler.debug.GraalError; 54 import org.graalvm.compiler.graph.Edges; 55 import org.graalvm.compiler.graph.Node; 56 import org.graalvm.compiler.graph.NodeList; 57 import org.graalvm.compiler.java.IntegerExactOpSpeculation; 58 import org.graalvm.compiler.java.IntegerExactOpSpeculation.IntegerExactOp; 59 import org.graalvm.compiler.nodes.AbstractBeginNode; 60 import org.graalvm.compiler.nodes.BeginNode; 61 import org.graalvm.compiler.nodes.ConstantNode; 62 import org.graalvm.compiler.nodes.DeoptimizeNode; 63 import org.graalvm.compiler.nodes.EndNode; 64 import org.graalvm.compiler.nodes.FixedGuardNode; 65 import org.graalvm.compiler.nodes.FixedWithNextNode; 66 import org.graalvm.compiler.nodes.IfNode; 67 import org.graalvm.compiler.nodes.LogicNode; 68 import org.graalvm.compiler.nodes.MergeNode; 69 import org.graalvm.compiler.nodes.NodeView; 70 import org.graalvm.compiler.nodes.StateSplit; 71 import org.graalvm.compiler.nodes.StructuredGraph; 72 import org.graalvm.compiler.nodes.ValueNode; 73 import org.graalvm.compiler.nodes.ValuePhiNode; 74 import org.graalvm.compiler.nodes.calc.AbsNode; 75 import org.graalvm.compiler.nodes.calc.CompareNode; 76 import org.graalvm.compiler.nodes.calc.ConditionalNode; 77 import org.graalvm.compiler.nodes.calc.FloatEqualsNode; 78 import org.graalvm.compiler.nodes.calc.IntegerEqualsNode; 79 import org.graalvm.compiler.nodes.calc.IsNullNode; 80 import org.graalvm.compiler.nodes.calc.NarrowNode; 81 import org.graalvm.compiler.nodes.calc.ReinterpretNode; 82 import org.graalvm.compiler.nodes.calc.RightShiftNode; 83 import org.graalvm.compiler.nodes.calc.SignExtendNode; 84 import org.graalvm.compiler.nodes.calc.SqrtNode; 85 import org.graalvm.compiler.nodes.calc.UnsignedDivNode; 86 import org.graalvm.compiler.nodes.calc.UnsignedRemNode; 87 import org.graalvm.compiler.nodes.calc.ZeroExtendNode; 88 import org.graalvm.compiler.nodes.debug.BindToRegisterNode; 89 import org.graalvm.compiler.nodes.debug.BlackholeNode; 90 import org.graalvm.compiler.nodes.debug.ControlFlowAnchorNode; 91 import org.graalvm.compiler.nodes.debug.OpaqueNode; 92 import org.graalvm.compiler.nodes.debug.SpillRegistersNode; 93 import org.graalvm.compiler.nodes.extended.BoxNode; 94 import org.graalvm.compiler.nodes.extended.BranchProbabilityNode; 95 import org.graalvm.compiler.nodes.extended.BytecodeExceptionNode.BytecodeExceptionKind; 96 import org.graalvm.compiler.nodes.extended.GetClassNode; 97 import org.graalvm.compiler.nodes.extended.MembarNode; 98 import org.graalvm.compiler.nodes.extended.RawLoadNode; 99 import org.graalvm.compiler.nodes.extended.RawStoreNode; 100 import org.graalvm.compiler.nodes.extended.UnboxNode; 101 import org.graalvm.compiler.nodes.extended.UnsafeMemoryLoadNode; 102 import org.graalvm.compiler.nodes.extended.UnsafeMemoryStoreNode; 103 import org.graalvm.compiler.nodes.graphbuilderconf.GraphBuilderContext; 104 import org.graalvm.compiler.nodes.graphbuilderconf.InvocationPlugin; 105 import org.graalvm.compiler.nodes.graphbuilderconf.InvocationPlugin.Receiver; 106 import org.graalvm.compiler.nodes.graphbuilderconf.InvocationPlugins; 107 import org.graalvm.compiler.nodes.graphbuilderconf.InvocationPlugins.Registration; 108 import org.graalvm.compiler.nodes.java.ClassIsAssignableFromNode; 109 import org.graalvm.compiler.nodes.java.DynamicNewArrayNode; 110 import org.graalvm.compiler.nodes.java.DynamicNewInstanceNode; 111 import org.graalvm.compiler.nodes.java.InstanceOfDynamicNode; 112 import org.graalvm.compiler.nodes.java.LoadFieldNode; 113 import org.graalvm.compiler.nodes.java.RegisterFinalizerNode; 114 import org.graalvm.compiler.nodes.java.UnsafeCompareAndExchangeNode; 115 import org.graalvm.compiler.nodes.java.UnsafeCompareAndSwapNode; 116 import org.graalvm.compiler.nodes.type.StampTool; 117 import org.graalvm.compiler.nodes.util.GraphUtil; 118 import org.graalvm.compiler.nodes.virtual.EnsureVirtualizedNode; 119 import org.graalvm.compiler.replacements.nodes.ReverseBytesNode; 120 import org.graalvm.compiler.replacements.nodes.VirtualizableInvokeMacroNode; 121 import org.graalvm.compiler.replacements.nodes.arithmetic.IntegerAddExactNode; 122 import org.graalvm.compiler.replacements.nodes.arithmetic.IntegerAddExactSplitNode; 123 import org.graalvm.compiler.replacements.nodes.arithmetic.IntegerExactArithmeticNode; 124 import org.graalvm.compiler.replacements.nodes.arithmetic.IntegerExactArithmeticSplitNode; 125 import org.graalvm.compiler.replacements.nodes.arithmetic.IntegerMulExactNode; 126 import org.graalvm.compiler.replacements.nodes.arithmetic.IntegerMulExactSplitNode; 127 import org.graalvm.compiler.replacements.nodes.arithmetic.IntegerSubExactNode; 128 import org.graalvm.compiler.replacements.nodes.arithmetic.IntegerSubExactSplitNode; 129 import jdk.internal.vm.compiler.word.LocationIdentity; 130 131 import jdk.vm.ci.code.BytecodePosition; 132 import jdk.vm.ci.meta.DeoptimizationAction; 133 import jdk.vm.ci.meta.DeoptimizationReason; 134 import jdk.vm.ci.meta.JavaConstant; 135 import jdk.vm.ci.meta.JavaKind; 136 import jdk.vm.ci.meta.MetaAccessProvider; 137 import jdk.vm.ci.meta.ResolvedJavaField; 138 import jdk.vm.ci.meta.ResolvedJavaMethod; 139 import jdk.vm.ci.meta.ResolvedJavaType; 140 import jdk.vm.ci.meta.SpeculationLog; 141 import jdk.vm.ci.meta.SpeculationLog.Speculation; 142 import jdk.vm.ci.meta.SpeculationLog.SpeculationReason; 143 import sun.misc.Unsafe; 144 145 /** 146 * Provides non-runtime specific {@link InvocationPlugin}s. 147 */ 148 public class StandardGraphBuilderPlugins { 149 150 public static void registerInvocationPlugins(MetaAccessProvider metaAccess, SnippetReflectionProvider snippetReflection, InvocationPlugins plugins, BytecodeProvider bytecodeProvider, 151 boolean allowDeoptimization, boolean explicitUnsafeNullChecks) { 152 registerObjectPlugins(plugins); 153 registerClassPlugins(plugins); 154 registerMathPlugins(plugins, allowDeoptimization); 155 registerUnsignedMathPlugins(plugins); 156 registerStringPlugins(plugins, bytecodeProvider, snippetReflection); 157 registerCharacterPlugins(plugins); 158 registerShortPlugins(plugins); 159 registerIntegerLongPlugins(plugins, JavaKind.Int); 160 registerIntegerLongPlugins(plugins, JavaKind.Long); 161 registerFloatPlugins(plugins); 162 registerDoublePlugins(plugins); 163 registerArraysPlugins(plugins, bytecodeProvider); 164 registerArrayPlugins(plugins, bytecodeProvider); 165 registerUnsafePlugins(plugins, bytecodeProvider, explicitUnsafeNullChecks); 166 registerEdgesPlugins(metaAccess, plugins); 167 registerGraalDirectivesPlugins(plugins); 168 registerBoxingPlugins(plugins); 169 registerJMHBlackholePlugins(plugins, bytecodeProvider); 170 registerJFRThrowablePlugins(plugins, bytecodeProvider); 171 registerMethodHandleImplPlugins(plugins, snippetReflection, bytecodeProvider); 172 registerJcovCollectPlugins(plugins, bytecodeProvider); 173 } 174 175 private static final Field STRING_VALUE_FIELD; 176 private static final Field STRING_CODER_FIELD; 177 178 static { 179 Field coder = null; 180 try { 181 STRING_VALUE_FIELD = String.class.getDeclaredField("value"); 182 if (!Java8OrEarlier) { 183 coder = String.class.getDeclaredField("coder"); 184 } 185 } catch (NoSuchFieldException e) { 186 throw new GraalError(e); 187 } 188 STRING_CODER_FIELD = coder; 189 } 190 191 private static void registerStringPlugins(InvocationPlugins plugins, BytecodeProvider bytecodeProvider, SnippetReflectionProvider snippetReflection) { 192 final Registration r = new Registration(plugins, String.class, bytecodeProvider); 193 r.register1("hashCode", Receiver.class, new InvocationPlugin() { 194 @Override 195 public boolean apply(GraphBuilderContext b, ResolvedJavaMethod targetMethod, Receiver receiver) { 196 if (receiver.isConstant()) { 197 String s = snippetReflection.asObject(String.class, (JavaConstant) receiver.get().asConstant()); 198 b.addPush(JavaKind.Int, b.add(ConstantNode.forInt(s.hashCode()))); 199 return true; 200 } 201 return false; 202 } 203 }); 204 205 if (Java8OrEarlier) { 206 r.registerMethodSubstitution(StringSubstitutions.class, "equals", Receiver.class, Object.class); 207 208 r.register7("indexOf", char[].class, int.class, int.class, char[].class, int.class, int.class, int.class, new StringIndexOfConstantPlugin()); 209 210 Registration sr = new Registration(plugins, StringSubstitutions.class); 211 sr.register1("getValue", String.class, new InvocationPlugin() { 212 @Override 213 public boolean apply(GraphBuilderContext b, ResolvedJavaMethod targetMethod, Receiver receiver, ValueNode value) { 214 ResolvedJavaField field = b.getMetaAccess().lookupJavaField(STRING_VALUE_FIELD); 215 b.addPush(JavaKind.Object, LoadFieldNode.create(b.getConstantFieldProvider(), b.getConstantReflection(), b.getMetaAccess(), 216 b.getOptions(), b.getAssumptions(), value, field, false, false)); 217 return true; 218 } 219 }); 220 } else { 221 r.registerMethodSubstitution(JDK9StringSubstitutions.class, "equals", Receiver.class, Object.class); 222 223 final Registration latin1r = new Registration(plugins, "java.lang.StringLatin1", bytecodeProvider); 224 latin1r.register5("indexOf", byte[].class, int.class, byte[].class, int.class, int.class, new StringLatin1IndexOfConstantPlugin()); 225 226 final Registration utf16r = new Registration(plugins, "java.lang.StringUTF16", bytecodeProvider); 227 utf16r.register5("indexOfUnsafe", byte[].class, int.class, byte[].class, int.class, int.class, new StringUTF16IndexOfConstantPlugin()); 228 229 Registration sr = new Registration(plugins, JDK9StringSubstitutions.class); 230 sr.register1("getValue", String.class, new InvocationPlugin() { 231 @Override 232 public boolean apply(GraphBuilderContext b, ResolvedJavaMethod targetMethod, Receiver receiver, ValueNode value) { 233 ResolvedJavaField field = b.getMetaAccess().lookupJavaField(STRING_VALUE_FIELD); 234 b.addPush(JavaKind.Object, LoadFieldNode.create(b.getConstantFieldProvider(), b.getConstantReflection(), b.getMetaAccess(), 235 b.getOptions(), b.getAssumptions(), value, field, false, false)); 236 return true; 237 } 238 }); 239 sr.register1("getCoder", String.class, new InvocationPlugin() { 240 @Override 241 public boolean apply(GraphBuilderContext b, ResolvedJavaMethod targetMethod, Receiver receiver, ValueNode value) { 242 ResolvedJavaField field = b.getMetaAccess().lookupJavaField(STRING_CODER_FIELD); 243 b.addPush(JavaKind.Int, LoadFieldNode.create(b.getConstantFieldProvider(), b.getConstantReflection(), b.getMetaAccess(), 244 b.getOptions(), b.getAssumptions(), value, field, false, false)); 245 return true; 246 } 247 }); 248 } 249 } 250 251 private static void registerArraysPlugins(InvocationPlugins plugins, BytecodeProvider bytecodeProvider) { 252 Registration r = new Registration(plugins, Arrays.class, bytecodeProvider); 253 r.registerMethodSubstitution(ArraysSubstitutions.class, "equals", boolean[].class, boolean[].class); 254 r.registerMethodSubstitution(ArraysSubstitutions.class, "equals", byte[].class, byte[].class); 255 r.registerMethodSubstitution(ArraysSubstitutions.class, "equals", short[].class, short[].class); 256 r.registerMethodSubstitution(ArraysSubstitutions.class, "equals", char[].class, char[].class); 257 r.registerMethodSubstitution(ArraysSubstitutions.class, "equals", int[].class, int[].class); 258 r.registerMethodSubstitution(ArraysSubstitutions.class, "equals", long[].class, long[].class); 259 } 260 261 private static void registerArrayPlugins(InvocationPlugins plugins, BytecodeProvider bytecodeProvider) { 262 Registration r = new Registration(plugins, Array.class, bytecodeProvider); 263 r.register2("newInstance", Class.class, int.class, new InvocationPlugin() { 264 @Override 265 public boolean apply(GraphBuilderContext b, ResolvedJavaMethod targetMethod, Receiver unused, ValueNode componentType, ValueNode length) { 266 b.addPush(JavaKind.Object, new DynamicNewArrayNode(componentType, length, true)); 267 return true; 268 } 269 }); 270 r.registerMethodSubstitution(ArraySubstitutions.class, "getLength", Object.class); 271 } 272 273 private abstract static class UnsafeCompareAndUpdatePluginsRegistrar { 274 public void register(Registration r, String casPrefix, boolean explicitUnsafeNullChecks, JavaKind[] compareAndSwapTypes, boolean java11OrEarlier) { 275 for (JavaKind kind : compareAndSwapTypes) { 276 Class<?> javaClass = kind == JavaKind.Object ? Object.class : kind.toJavaClass(); 277 String kindName = (kind == JavaKind.Object && !java11OrEarlier) ? "Reference" : kind.name(); 278 r.register5(casPrefix + kindName, Receiver.class, Object.class, long.class, javaClass, javaClass, new UnsafeAccessPlugin(returnKind(kind), explicitUnsafeNullChecks) { 279 @Override 280 public boolean apply(GraphBuilderContext b, ResolvedJavaMethod targetMethod, Receiver unsafe, ValueNode object, ValueNode offset, ValueNode expected, ValueNode x) { 281 // Emits a null-check for the otherwise unused receiver 282 unsafe.get(); 283 createUnsafeAccess(object, b, (obj, loc) -> UnsafeCompareAndUpdatePluginsRegistrar.this.createNode(obj, offset, expected, x, kind, loc)); 284 return true; 285 } 286 }); 287 } 288 } 289 290 public abstract FixedWithNextNode createNode(ValueNode object, ValueNode offset, ValueNode expected, ValueNode newValue, JavaKind kind, LocationIdentity identity); 291 292 public abstract JavaKind returnKind(JavaKind accessKind); 293 } 294 295 private static class UnsafeCompareAndSwapPluginsRegistrar extends UnsafeCompareAndUpdatePluginsRegistrar { 296 @Override 297 public FixedWithNextNode createNode(ValueNode object, ValueNode offset, ValueNode expected, ValueNode newValue, JavaKind kind, LocationIdentity identity) { 298 return new UnsafeCompareAndSwapNode(object, offset, expected, newValue, kind, identity); 299 } 300 301 @Override 302 public JavaKind returnKind(JavaKind accessKind) { 303 return JavaKind.Boolean.getStackKind(); 304 } 305 } 306 307 private static UnsafeCompareAndSwapPluginsRegistrar unsafeCompareAndSwapPluginsRegistrar = new UnsafeCompareAndSwapPluginsRegistrar(); 308 309 private static class UnsafeCompareAndExchangePluginsRegistrar extends UnsafeCompareAndUpdatePluginsRegistrar { 310 @Override 311 public FixedWithNextNode createNode(ValueNode object, ValueNode offset, ValueNode expected, ValueNode newValue, JavaKind kind, LocationIdentity identity) { 312 return new UnsafeCompareAndExchangeNode(object, offset, expected, newValue, kind, identity); 313 } 314 315 @Override 316 public JavaKind returnKind(JavaKind accessKind) { 317 if (accessKind.isNumericInteger()) { 318 return accessKind.getStackKind(); 319 } else { 320 return accessKind; 321 } 322 } 323 } 324 325 private static UnsafeCompareAndExchangePluginsRegistrar unsafeCompareAndExchangePluginsRegistrar = new UnsafeCompareAndExchangePluginsRegistrar(); 326 327 public static void registerPlatformSpecificUnsafePlugins(InvocationPlugins plugins, BytecodeProvider bytecodeProvider, boolean explicitUnsafeNullChecks, JavaKind[] supportedCasKinds) { 328 registerPlatformSpecificUnsafePlugins(supportedCasKinds, new Registration(plugins, Unsafe.class), true, explicitUnsafeNullChecks); 329 if (!Java8OrEarlier) { 330 registerPlatformSpecificUnsafePlugins(supportedCasKinds, new Registration(plugins, "jdk.internal.misc.Unsafe", bytecodeProvider), false, explicitUnsafeNullChecks); 331 } 332 333 } 334 335 private static void registerPlatformSpecificUnsafePlugins(JavaKind[] supportedCasKinds, Registration r, boolean java8OrEarlier, boolean explicitUnsafeNullChecks) { 336 if (java8OrEarlier) { 337 unsafeCompareAndSwapPluginsRegistrar.register(r, "compareAndSwap", explicitUnsafeNullChecks, new JavaKind[]{JavaKind.Int, JavaKind.Long, JavaKind.Object}, true); 338 } else { 339 unsafeCompareAndSwapPluginsRegistrar.register(r, "compareAndSet", explicitUnsafeNullChecks, supportedCasKinds, Java11OrEarlier); 340 unsafeCompareAndExchangePluginsRegistrar.register(r, "compareAndExchange", explicitUnsafeNullChecks, supportedCasKinds, Java11OrEarlier); 341 } 342 } 343 344 private static void registerUnsafePlugins(InvocationPlugins plugins, BytecodeProvider bytecodeProvider, boolean explicitUnsafeNullChecks) { 345 registerUnsafePlugins(new Registration(plugins, Unsafe.class), true, explicitUnsafeNullChecks); 346 if (!Java8OrEarlier) { 347 registerUnsafePlugins(new Registration(plugins, "jdk.internal.misc.Unsafe", bytecodeProvider), false, explicitUnsafeNullChecks); 348 } 349 } 350 351 private static void registerUnsafePlugins(Registration r, boolean sunMiscUnsafe, boolean explicitUnsafeNullChecks) { 352 for (JavaKind kind : JavaKind.values()) { 353 if ((kind.isPrimitive() && kind != JavaKind.Void) || kind == JavaKind.Object) { 354 Class<?> javaClass = kind == JavaKind.Object ? Object.class : kind.toJavaClass(); 355 String kindName = (kind == JavaKind.Object && !sunMiscUnsafe && !Java11OrEarlier) ? "Reference" : kind.name(); 356 String getName = "get" + kindName; 357 String putName = "put" + kindName; 358 // Object-based accesses 359 r.register3(getName, Receiver.class, Object.class, long.class, new UnsafeGetPlugin(kind, explicitUnsafeNullChecks)); 360 r.register4(putName, Receiver.class, Object.class, long.class, javaClass, new UnsafePutPlugin(kind, explicitUnsafeNullChecks)); 361 // Volatile object-based accesses 362 r.register3(getName + "Volatile", Receiver.class, Object.class, long.class, new UnsafeGetPlugin(kind, AccessKind.VOLATILE, explicitUnsafeNullChecks)); 363 r.register4(putName + "Volatile", Receiver.class, Object.class, long.class, javaClass, new UnsafePutPlugin(kind, AccessKind.VOLATILE, explicitUnsafeNullChecks)); 364 // Ordered object-based accesses 365 if (sunMiscUnsafe) { 366 if (kind == JavaKind.Int || kind == JavaKind.Long || kind == JavaKind.Object) { 367 r.register4("putOrdered" + kindName, Receiver.class, Object.class, long.class, javaClass, new UnsafePutPlugin(kind, AccessKind.RELEASE_ACQUIRE, explicitUnsafeNullChecks)); 368 } 369 } else { 370 r.register4("put" + kindName + "Release", Receiver.class, Object.class, long.class, javaClass, new UnsafePutPlugin(kind, AccessKind.RELEASE_ACQUIRE, explicitUnsafeNullChecks)); 371 r.register3("get" + kindName + "Acquire", Receiver.class, Object.class, long.class, new UnsafeGetPlugin(kind, AccessKind.RELEASE_ACQUIRE, explicitUnsafeNullChecks)); 372 r.register4("put" + kindName + "Opaque", Receiver.class, Object.class, long.class, javaClass, new UnsafePutPlugin(kind, AccessKind.OPAQUE, explicitUnsafeNullChecks)); 373 r.register3("get" + kindName + "Opaque", Receiver.class, Object.class, long.class, new UnsafeGetPlugin(kind, AccessKind.OPAQUE, explicitUnsafeNullChecks)); 374 } 375 if (kind != JavaKind.Boolean && kind != JavaKind.Object) { 376 // Raw accesses to memory addresses 377 r.register2(getName, Receiver.class, long.class, new UnsafeGetPlugin(kind, explicitUnsafeNullChecks)); 378 r.register3(putName, Receiver.class, long.class, kind.toJavaClass(), new UnsafePutPlugin(kind, explicitUnsafeNullChecks)); 379 } 380 } 381 } 382 383 // Accesses to native memory addresses. 384 r.register2("getAddress", Receiver.class, long.class, new UnsafeGetPlugin(JavaKind.Long, explicitUnsafeNullChecks)); 385 r.register3("putAddress", Receiver.class, long.class, long.class, new UnsafePutPlugin(JavaKind.Long, explicitUnsafeNullChecks)); 386 387 r.register2("allocateInstance", Receiver.class, Class.class, new InvocationPlugin() { 388 389 @Override 390 public boolean apply(GraphBuilderContext b, ResolvedJavaMethod targetMethod, Receiver unsafe, ValueNode clazz) { 391 // Emits a null-check for the otherwise unused receiver 392 unsafe.get(); 393 b.addPush(JavaKind.Object, new DynamicNewInstanceNode(b.nullCheckedValue(clazz, DeoptimizationAction.None), true)); 394 return true; 395 } 396 397 }); 398 399 r.register1("loadFence", Receiver.class, new UnsafeFencePlugin(LOAD_LOAD | LOAD_STORE)); 400 r.register1("storeFence", Receiver.class, new UnsafeFencePlugin(STORE_STORE | LOAD_STORE)); 401 r.register1("fullFence", Receiver.class, new UnsafeFencePlugin(LOAD_LOAD | STORE_STORE | LOAD_STORE | STORE_LOAD)); 402 } 403 404 private static void registerIntegerLongPlugins(InvocationPlugins plugins, JavaKind kind) { 405 Class<?> declaringClass = kind.toBoxedJavaClass(); 406 Class<?> type = kind.toJavaClass(); 407 Registration r = new Registration(plugins, declaringClass); 408 r.register1("reverseBytes", type, new InvocationPlugin() { 409 @Override 410 public boolean apply(GraphBuilderContext b, ResolvedJavaMethod targetMethod, Receiver receiver, ValueNode value) { 411 b.push(kind, b.append(new ReverseBytesNode(value).canonical(null))); 412 return true; 413 } 414 }); 415 r.register2("divideUnsigned", type, type, new InvocationPlugin() { 416 @Override 417 public boolean apply(GraphBuilderContext b, ResolvedJavaMethod targetMethod, Receiver receiver, ValueNode dividend, ValueNode divisor) { 418 b.push(kind, b.append(UnsignedDivNode.create(dividend, divisor, null, NodeView.DEFAULT))); 419 return true; 420 } 421 }); 422 r.register2("remainderUnsigned", type, type, new InvocationPlugin() { 423 @Override 424 public boolean apply(GraphBuilderContext b, ResolvedJavaMethod targetMethod, Receiver receiver, ValueNode dividend, ValueNode divisor) { 425 b.push(kind, b.append(UnsignedRemNode.create(dividend, divisor, null, NodeView.DEFAULT))); 426 return true; 427 } 428 }); 429 } 430 431 private static void registerCharacterPlugins(InvocationPlugins plugins) { 432 Registration r = new Registration(plugins, Character.class); 433 r.register1("reverseBytes", char.class, new InvocationPlugin() { 434 @Override 435 public boolean apply(GraphBuilderContext b, ResolvedJavaMethod targetMethod, Receiver receiver, ValueNode value) { 436 // return (char) (Integer.reverse(i) >> 16); 437 ReverseBytesNode reverse = b.add(new ReverseBytesNode(value)); 438 RightShiftNode rightShift = b.add(new RightShiftNode(reverse, b.add(ConstantNode.forInt(16)))); 439 ZeroExtendNode charCast = b.add(new ZeroExtendNode(b.add(new NarrowNode(rightShift, 16)), 32)); 440 b.push(JavaKind.Char, b.append(charCast.canonical(null))); 441 return true; 442 } 443 }); 444 } 445 446 private static void registerShortPlugins(InvocationPlugins plugins) { 447 Registration r = new Registration(plugins, Short.class); 448 r.register1("reverseBytes", short.class, new InvocationPlugin() { 449 @Override 450 public boolean apply(GraphBuilderContext b, ResolvedJavaMethod targetMethod, Receiver receiver, ValueNode value) { 451 // return (short) (Integer.reverse(i) >> 16); 452 ReverseBytesNode reverse = b.add(new ReverseBytesNode(value)); 453 RightShiftNode rightShift = b.add(new RightShiftNode(reverse, b.add(ConstantNode.forInt(16)))); 454 SignExtendNode charCast = b.add(new SignExtendNode(b.add(new NarrowNode(rightShift, 16)), 32)); 455 b.push(JavaKind.Short, b.append(charCast.canonical(null))); 456 return true; 457 } 458 }); 459 } 460 461 private static void registerFloatPlugins(InvocationPlugins plugins) { 462 Registration r = new Registration(plugins, Float.class); 463 r.register1("floatToRawIntBits", float.class, new InvocationPlugin() { 464 @Override 465 public boolean apply(GraphBuilderContext b, ResolvedJavaMethod targetMethod, Receiver receiver, ValueNode value) { 466 b.push(JavaKind.Int, b.append(ReinterpretNode.create(JavaKind.Int, value, NodeView.DEFAULT))); 467 return true; 468 } 469 }); 470 r.register1("floatToIntBits", float.class, new InvocationPlugin() { 471 @Override 472 public boolean apply(GraphBuilderContext b, ResolvedJavaMethod targetMethod, Receiver receiver, ValueNode value) { 473 LogicNode notNan = b.append(FloatEqualsNode.create(value, value, NodeView.DEFAULT)); 474 ValueNode raw = b.append(ReinterpretNode.create(JavaKind.Int, value, NodeView.DEFAULT)); 475 ValueNode result = b.append(ConditionalNode.create(notNan, raw, ConstantNode.forInt(0x7fc00000), NodeView.DEFAULT)); 476 b.push(JavaKind.Int, result); 477 return true; 478 } 479 }); 480 r.register1("intBitsToFloat", int.class, new InvocationPlugin() { 481 @Override 482 public boolean apply(GraphBuilderContext b, ResolvedJavaMethod targetMethod, Receiver receiver, ValueNode value) { 483 b.push(JavaKind.Float, b.append(ReinterpretNode.create(JavaKind.Float, value, NodeView.DEFAULT))); 484 return true; 485 } 486 }); 487 } 488 489 private static void registerDoublePlugins(InvocationPlugins plugins) { 490 Registration r = new Registration(plugins, Double.class); 491 r.register1("doubleToRawLongBits", double.class, new InvocationPlugin() { 492 @Override 493 public boolean apply(GraphBuilderContext b, ResolvedJavaMethod targetMethod, Receiver receiver, ValueNode value) { 494 b.push(JavaKind.Long, b.append(ReinterpretNode.create(JavaKind.Long, value, NodeView.DEFAULT))); 495 return true; 496 } 497 }); 498 r.register1("doubleToLongBits", double.class, new InvocationPlugin() { 499 @Override 500 public boolean apply(GraphBuilderContext b, ResolvedJavaMethod targetMethod, Receiver receiver, ValueNode value) { 501 LogicNode notNan = b.append(FloatEqualsNode.create(value, value, NodeView.DEFAULT)); 502 ValueNode raw = b.append(ReinterpretNode.create(JavaKind.Long, value, NodeView.DEFAULT)); 503 ValueNode result = b.append(ConditionalNode.create(notNan, raw, ConstantNode.forLong(0x7ff8000000000000L), NodeView.DEFAULT)); 504 b.push(JavaKind.Long, result); 505 return true; 506 } 507 }); 508 r.register1("longBitsToDouble", long.class, new InvocationPlugin() { 509 @Override 510 public boolean apply(GraphBuilderContext b, ResolvedJavaMethod targetMethod, Receiver receiver, ValueNode value) { 511 b.push(JavaKind.Double, b.append(ReinterpretNode.create(JavaKind.Double, value, NodeView.DEFAULT))); 512 return true; 513 } 514 }); 515 } 516 517 private static ValueNode createIntegerExactArithmeticNode(ValueNode x, ValueNode y, SpeculationReason speculation, IntegerExactOp op) { 518 switch (op) { 519 case INTEGER_ADD_EXACT: 520 case INTEGER_INCREMENT_EXACT: 521 return new IntegerAddExactNode(x, y, speculation); 522 case INTEGER_SUBTRACT_EXACT: 523 case INTEGER_DECREMENT_EXACT: 524 return new IntegerSubExactNode(x, y, speculation); 525 case INTEGER_MULTIPLY_EXACT: 526 return new IntegerMulExactNode(x, y, speculation); 527 default: 528 throw GraalError.shouldNotReachHere("Unknown integer exact operation."); 529 } 530 } 531 532 private static IntegerExactArithmeticSplitNode createIntegerExactSplit(ValueNode x, ValueNode y, AbstractBeginNode exceptionEdge, IntegerExactOp op) { 533 switch (op) { 534 case INTEGER_ADD_EXACT: 535 case INTEGER_INCREMENT_EXACT: 536 return new IntegerAddExactSplitNode(x.stamp(NodeView.DEFAULT).unrestricted(), x, y, null, exceptionEdge); 537 case INTEGER_SUBTRACT_EXACT: 538 case INTEGER_DECREMENT_EXACT: 539 return new IntegerSubExactSplitNode(x.stamp(NodeView.DEFAULT).unrestricted(), x, y, null, exceptionEdge); 540 case INTEGER_MULTIPLY_EXACT: 541 return new IntegerMulExactSplitNode(x.stamp(NodeView.DEFAULT).unrestricted(), x, y, null, exceptionEdge); 542 default: 543 throw GraalError.shouldNotReachHere("Unknown integer exact operation."); 544 } 545 } 546 547 private static void createIntegerExactOperation(GraphBuilderContext b, JavaKind kind, ValueNode x, ValueNode y, IntegerExactOp op) { 548 if (b.needsExplicitException()) { 549 BytecodeExceptionKind exceptionKind = kind == JavaKind.Int ? BytecodeExceptionKind.INTEGER_EXACT_OVERFLOW : BytecodeExceptionKind.LONG_EXACT_OVERFLOW; 550 AbstractBeginNode exceptionEdge = b.genExplicitExceptionEdge(exceptionKind); 551 IntegerExactArithmeticSplitNode split = b.addPush(kind, createIntegerExactSplit(x, y, exceptionEdge, op)); 552 split.setNext(b.add(new BeginNode())); 553 } else { 554 SpeculationLog log = b.getGraph().getSpeculationLog(); 555 if (log == null || (x.isConstant() && y.isConstant())) { 556 b.addPush(kind, createIntegerExactArithmeticNode(x, y, null, op)); 557 } else { 558 SpeculationReason speculation = new IntegerExactOpSpeculation(b.getMethod(), op); 559 if (log.maySpeculate(speculation)) { 560 b.addPush(kind, createIntegerExactArithmeticNode(x, y, speculation, op)); 561 } else { 562 BeginNode begin = b.add(new BeginNode()); 563 IntegerExactArithmeticNode node = (IntegerExactArithmeticNode) b.addPush(kind, createIntegerExactArithmeticNode(x, y, null, op)); 564 node.setAnchor(begin); 565 } 566 } 567 } 568 } 569 570 private static void registerMathPlugins(InvocationPlugins plugins, boolean allowDeoptimization) { 571 Registration r = new Registration(plugins, Math.class); 572 if (allowDeoptimization) { 573 for (JavaKind kind : new JavaKind[]{JavaKind.Int, JavaKind.Long}) { 574 Class<?> type = kind.toJavaClass(); 575 576 r.register1("decrementExact", type, new InvocationPlugin() { 577 @Override 578 public boolean apply(GraphBuilderContext b, ResolvedJavaMethod targetMethod, Receiver receiver, ValueNode x) { 579 ConstantNode y = b.add(ConstantNode.forIntegerKind(kind, 1)); 580 createIntegerExactOperation(b, kind, x, y, IntegerExactOp.INTEGER_DECREMENT_EXACT); 581 return true; 582 } 583 }); 584 585 r.register1("incrementExact", type, new InvocationPlugin() { 586 @Override 587 public boolean apply(GraphBuilderContext b, ResolvedJavaMethod targetMethod, Receiver receiver, ValueNode x) { 588 ConstantNode y = b.add(ConstantNode.forIntegerKind(kind, 1)); 589 createIntegerExactOperation(b, kind, x, y, IntegerExactOp.INTEGER_INCREMENT_EXACT); 590 return true; 591 } 592 }); 593 594 r.register2("addExact", type, type, new InvocationPlugin() { 595 @Override 596 public boolean apply(GraphBuilderContext b, ResolvedJavaMethod targetMethod, Receiver receiver, ValueNode x, ValueNode y) { 597 createIntegerExactOperation(b, kind, x, y, IntegerExactOp.INTEGER_ADD_EXACT); 598 return true; 599 } 600 }); 601 602 r.register2("subtractExact", type, type, new InvocationPlugin() { 603 @Override 604 public boolean apply(GraphBuilderContext b, ResolvedJavaMethod targetMethod, Receiver receiver, ValueNode x, ValueNode y) { 605 createIntegerExactOperation(b, kind, x, y, IntegerExactOp.INTEGER_SUBTRACT_EXACT); 606 return true; 607 } 608 }); 609 610 r.register2("multiplyExact", type, type, new InvocationPlugin() { 611 @Override 612 public boolean apply(GraphBuilderContext b, ResolvedJavaMethod targetMethod, Receiver receiver, ValueNode x, ValueNode y) { 613 createIntegerExactOperation(b, kind, x, y, IntegerExactOp.INTEGER_MULTIPLY_EXACT); 614 return true; 615 } 616 }); 617 } 618 } 619 r.register1("abs", Float.TYPE, new InvocationPlugin() { 620 621 @Override 622 public boolean apply(GraphBuilderContext b, ResolvedJavaMethod targetMethod, Receiver receiver, ValueNode value) { 623 b.push(JavaKind.Float, b.append(new AbsNode(value).canonical(null))); 624 return true; 625 } 626 }); 627 r.register1("abs", Double.TYPE, new InvocationPlugin() { 628 @Override 629 public boolean apply(GraphBuilderContext b, ResolvedJavaMethod targetMethod, Receiver receiver, ValueNode value) { 630 b.push(JavaKind.Double, b.append(new AbsNode(value).canonical(null))); 631 return true; 632 } 633 }); 634 r.register1("sqrt", Double.TYPE, new InvocationPlugin() { 635 @Override 636 public boolean apply(GraphBuilderContext b, ResolvedJavaMethod targetMethod, Receiver receiver, ValueNode value) { 637 b.push(JavaKind.Double, b.append(SqrtNode.create(value, NodeView.DEFAULT))); 638 return true; 639 } 640 }); 641 } 642 643 public static final class StringIndexOfConstantPlugin implements InvocationPlugin { 644 @Override 645 public boolean inlineOnly() { 646 return true; 647 } 648 649 @Override 650 public boolean apply(GraphBuilderContext b, ResolvedJavaMethod targetMethod, InvocationPlugin.Receiver receiver, ValueNode source, ValueNode sourceOffset, ValueNode sourceCount, 651 ValueNode target, ValueNode targetOffset, ValueNode targetCount, ValueNode origFromIndex) { 652 if (target.isConstant()) { 653 b.addPush(JavaKind.Int, new StringIndexOfNode(b.getInvokeKind(), targetMethod, b.bci(), b.getInvokeReturnStamp(b.getAssumptions()), source, sourceOffset, sourceCount, 654 target, targetOffset, targetCount, origFromIndex)); 655 return true; 656 } 657 return false; 658 } 659 } 660 661 public static final class StringLatin1IndexOfConstantPlugin implements InvocationPlugin { 662 @Override 663 public boolean inlineOnly() { 664 return true; 665 } 666 667 @Override 668 public boolean apply(GraphBuilderContext b, ResolvedJavaMethod targetMethod, InvocationPlugin.Receiver receiver, 669 ValueNode source, ValueNode sourceCount, ValueNode target, ValueNode targetCount, ValueNode origFromIndex) { 670 if (target.isConstant()) { 671 b.addPush(JavaKind.Int, new StringLatin1IndexOfNode(b.getInvokeKind(), targetMethod, b.bci(), b.getInvokeReturnStamp(b.getAssumptions()), 672 source, sourceCount, target, targetCount, origFromIndex)); 673 return true; 674 } 675 return false; 676 } 677 } 678 679 public static final class StringUTF16IndexOfConstantPlugin implements InvocationPlugin { 680 @Override 681 public boolean inlineOnly() { 682 return true; 683 } 684 685 @Override 686 public boolean apply(GraphBuilderContext b, ResolvedJavaMethod targetMethod, InvocationPlugin.Receiver receiver, 687 ValueNode source, ValueNode sourceCount, ValueNode target, ValueNode targetCount, ValueNode origFromIndex) { 688 if (target.isConstant()) { 689 b.addPush(JavaKind.Int, new StringUTF16IndexOfNode(b.getInvokeKind(), targetMethod, b.bci(), b.getInvokeReturnStamp(b.getAssumptions()), 690 source, sourceCount, target, targetCount, origFromIndex)); 691 return true; 692 } 693 return false; 694 } 695 } 696 697 public static class UnsignedMathPlugin implements InvocationPlugin { 698 private final Condition condition; 699 700 public UnsignedMathPlugin(Condition condition) { 701 this.condition = condition; 702 } 703 704 @Override 705 public boolean apply(GraphBuilderContext b, ResolvedJavaMethod targetMethod, Receiver receiver, ValueNode x, ValueNode y) { 706 CanonicalizedCondition canonical = condition.canonicalize(); 707 StructuredGraph graph = b.getGraph(); 708 709 ValueNode lhs = canonical.mustMirror() ? y : x; 710 ValueNode rhs = canonical.mustMirror() ? x : y; 711 712 ValueNode trueValue = ConstantNode.forBoolean(!canonical.mustNegate(), graph); 713 ValueNode falseValue = ConstantNode.forBoolean(canonical.mustNegate(), graph); 714 715 LogicNode compare = CompareNode.createCompareNode(graph, b.getConstantReflection(), b.getMetaAccess(), b.getOptions(), null, canonical.getCanonicalCondition(), lhs, rhs, NodeView.DEFAULT); 716 b.addPush(JavaKind.Boolean, new ConditionalNode(compare, trueValue, falseValue)); 717 return true; 718 } 719 } 720 721 private static void registerUnsignedMathPlugins(InvocationPlugins plugins) { 722 Registration r = new Registration(plugins, UnsignedMath.class); 723 r.register2("aboveThan", int.class, int.class, new UnsignedMathPlugin(Condition.AT)); 724 r.register2("aboveThan", long.class, long.class, new UnsignedMathPlugin(Condition.AT)); 725 r.register2("belowThan", int.class, int.class, new UnsignedMathPlugin(Condition.BT)); 726 r.register2("belowThan", long.class, long.class, new UnsignedMathPlugin(Condition.BT)); 727 r.register2("aboveOrEqual", int.class, int.class, new UnsignedMathPlugin(Condition.AE)); 728 r.register2("aboveOrEqual", long.class, long.class, new UnsignedMathPlugin(Condition.AE)); 729 r.register2("belowOrEqual", int.class, int.class, new UnsignedMathPlugin(Condition.BE)); 730 r.register2("belowOrEqual", long.class, long.class, new UnsignedMathPlugin(Condition.BE)); 731 } 732 733 protected static void registerBoxingPlugins(InvocationPlugins plugins) { 734 for (JavaKind kind : JavaKind.values()) { 735 if (kind.isPrimitive() && kind != JavaKind.Void) { 736 new BoxPlugin(kind).register(plugins); 737 new UnboxPlugin(kind).register(plugins); 738 } 739 } 740 } 741 742 private static void registerObjectPlugins(InvocationPlugins plugins) { 743 Registration r = new Registration(plugins, Object.class); 744 r.register1("<init>", Receiver.class, new InvocationPlugin() { 745 @Override 746 public boolean apply(GraphBuilderContext b, ResolvedJavaMethod targetMethod, Receiver receiver) { 747 /* 748 * Object.<init> is a common instrumentation point so only perform this rewrite if 749 * the current definition is the normal empty method with a single return bytecode. 750 * The finalizer registration will instead be performed by the BytecodeParser. 751 */ 752 if (targetMethod.getCodeSize() == 1) { 753 ValueNode object = receiver.get(); 754 if (RegisterFinalizerNode.mayHaveFinalizer(object, b.getAssumptions())) { 755 b.add(new RegisterFinalizerNode(object)); 756 } 757 return true; 758 } 759 return false; 760 } 761 }); 762 r.register1("getClass", Receiver.class, new InvocationPlugin() { 763 @Override 764 public boolean apply(GraphBuilderContext b, ResolvedJavaMethod targetMethod, Receiver receiver) { 765 ValueNode object = receiver.get(); 766 ValueNode folded = GetClassNode.tryFold(b.getMetaAccess(), b.getConstantReflection(), NodeView.DEFAULT, GraphUtil.originalValue(object)); 767 if (folded != null) { 768 b.addPush(JavaKind.Object, folded); 769 } else { 770 Stamp stamp = StampFactory.objectNonNull(TypeReference.createTrusted(b.getAssumptions(), b.getMetaAccess().lookupJavaType(Class.class))); 771 b.addPush(JavaKind.Object, new GetClassNode(stamp, object)); 772 } 773 return true; 774 } 775 }); 776 } 777 778 private static void registerClassPlugins(InvocationPlugins plugins) { 779 Registration r = new Registration(plugins, Class.class); 780 r.register2("isInstance", Receiver.class, Object.class, new InvocationPlugin() { 781 @Override 782 public boolean apply(GraphBuilderContext b, ResolvedJavaMethod targetMethod, Receiver type, ValueNode object) { 783 LogicNode condition = b.append(InstanceOfDynamicNode.create(b.getAssumptions(), b.getConstantReflection(), type.get(), object, false)); 784 b.push(JavaKind.Boolean, b.append(new ConditionalNode(condition).canonical(null))); 785 return true; 786 } 787 }); 788 r.register2("isAssignableFrom", Receiver.class, Class.class, new InvocationPlugin() { 789 @Override 790 public boolean apply(GraphBuilderContext b, ResolvedJavaMethod targetMethod, Receiver type, ValueNode otherType) { 791 ClassIsAssignableFromNode condition = b.append(new ClassIsAssignableFromNode(type.get(), otherType)); 792 b.push(JavaKind.Boolean, b.append(new ConditionalNode(condition).canonical(null))); 793 return true; 794 } 795 }); 796 } 797 798 /** 799 * Substitutions for improving the performance of some critical methods in {@link Edges}. These 800 * substitutions improve the performance by forcing the relevant methods to be inlined 801 * (intrinsification being a special form of inlining) and removing a checked cast. 802 */ 803 private static void registerEdgesPlugins(MetaAccessProvider metaAccess, InvocationPlugins plugins) { 804 Registration r = new Registration(plugins, Edges.class); 805 for (Class<?> c : new Class<?>[]{Node.class, NodeList.class}) { 806 r.register2("get" + c.getSimpleName() + "Unsafe", Node.class, long.class, new InvocationPlugin() { 807 @Override 808 public boolean apply(GraphBuilderContext b, ResolvedJavaMethod targetMethod, Receiver receiver, ValueNode node, ValueNode offset) { 809 ObjectStamp stamp = StampFactory.object(TypeReference.createTrusted(b.getAssumptions(), metaAccess.lookupJavaType(c))); 810 RawLoadNode value = b.add(new RawLoadNode(stamp, node, offset, LocationIdentity.any(), JavaKind.Object)); 811 b.addPush(JavaKind.Object, value); 812 return true; 813 } 814 }); 815 r.register3("put" + c.getSimpleName() + "Unsafe", Node.class, long.class, c, new InvocationPlugin() { 816 @Override 817 public boolean apply(GraphBuilderContext b, ResolvedJavaMethod targetMethod, Receiver receiver, ValueNode node, ValueNode offset, ValueNode value) { 818 b.add(new RawStoreNode(node, offset, value, JavaKind.Object, LocationIdentity.any())); 819 return true; 820 } 821 }); 822 } 823 } 824 825 public static class BoxPlugin implements InvocationPlugin { 826 827 private final JavaKind kind; 828 829 BoxPlugin(JavaKind kind) { 830 this.kind = kind; 831 } 832 833 @Override 834 public boolean apply(GraphBuilderContext b, ResolvedJavaMethod targetMethod, Receiver receiver, ValueNode value) { 835 if (b.parsingIntrinsic()) { 836 ResolvedJavaMethod rootMethod = b.getGraph().method(); 837 if (b.getMetaAccess().lookupJavaType(BoxingSnippets.class).isAssignableFrom(rootMethod.getDeclaringClass())) { 838 // Disable invocation plugins for boxing snippets so that the 839 // original JDK methods are inlined 840 return false; 841 } 842 } 843 ResolvedJavaType resultType = b.getMetaAccess().lookupJavaType(kind.toBoxedJavaClass()); 844 b.addPush(JavaKind.Object, new BoxNode(value, resultType, kind)); 845 return true; 846 } 847 848 void register(InvocationPlugins plugins) { 849 plugins.register(this, kind.toBoxedJavaClass(), "valueOf", kind.toJavaClass()); 850 } 851 } 852 853 public static class UnboxPlugin implements InvocationPlugin { 854 855 private final JavaKind kind; 856 857 UnboxPlugin(JavaKind kind) { 858 this.kind = kind; 859 } 860 861 @Override 862 public boolean apply(GraphBuilderContext b, ResolvedJavaMethod targetMethod, Receiver receiver) { 863 if (b.parsingIntrinsic()) { 864 ResolvedJavaMethod rootMethod = b.getGraph().method(); 865 if (b.getMetaAccess().lookupJavaType(BoxingSnippets.class).isAssignableFrom(rootMethod.getDeclaringClass())) { 866 // Disable invocation plugins for unboxing snippets so that the 867 // original JDK methods are inlined 868 return false; 869 } 870 } 871 ValueNode valueNode = UnboxNode.create(b.getMetaAccess(), b.getConstantReflection(), receiver.get(), kind); 872 b.addPush(kind, valueNode); 873 return true; 874 } 875 876 void register(InvocationPlugins plugins) { 877 String name = kind.toJavaClass().getSimpleName() + "Value"; 878 plugins.register(this, kind.toBoxedJavaClass(), name, Receiver.class); 879 } 880 } 881 882 /** 883 * The new memory order modes (JDK9+) are defined with cumulative effect, from weakest to 884 * strongest: Plain, Opaque, Release/Acquire, and Volatile. The existing Plain and Volatile 885 * modes are defined compatibly with their pre-JDK 9 forms. Any guaranteed property of a weaker 886 * mode, plus more, holds for a stronger mode. (Conversely, implementations are allowed to use a 887 * stronger mode than requested for any access.) In JDK 9, these are provided without a full 888 * formal specification. 889 */ 890 enum AccessKind { 891 PLAIN(0, 0, 0, 0, false), 892 /** 893 * Opaque accesses are wrapped by dummy membars to avoid floating/hoisting, this is stronger 894 * than required since Opaque mode does not directly impose any ordering constraints with 895 * respect to other variables beyond Plain mode. 896 */ 897 OPAQUE(0, 0, 0, 0, true), 898 RELEASE_ACQUIRE(0, LOAD_LOAD | LOAD_STORE, LOAD_STORE | STORE_STORE, 0, true), 899 VOLATILE(JMM_PRE_VOLATILE_READ, JMM_POST_VOLATILE_READ, JMM_PRE_VOLATILE_WRITE, JMM_POST_VOLATILE_WRITE, true); 900 901 public final boolean emitBarriers; 902 public final int preReadBarriers; 903 public final int postReadBarriers; 904 public final int preWriteBarriers; 905 public final int postWriteBarriers; 906 907 AccessKind(int preReadBarriers, int postReadBarriers, int preWriteBarriers, int postWriteBarriers, boolean emitBarriers) { 908 this.emitBarriers = emitBarriers; 909 this.preReadBarriers = preReadBarriers; 910 this.postReadBarriers = postReadBarriers; 911 this.preWriteBarriers = preWriteBarriers; 912 this.postWriteBarriers = postWriteBarriers; 913 } 914 } 915 916 /** 917 * Unsafe access relative to null object is an access to off-heap memory. As linear pointer 918 * compression uses non-zero null, here null object must be replaced with zero constant. 919 */ 920 public abstract static class UnsafeAccessPlugin implements InvocationPlugin { 921 @FunctionalInterface 922 public interface UnsafeNodeConstructor { 923 FixedWithNextNode create(ValueNode value, LocationIdentity location); 924 } 925 926 protected final JavaKind unsafeAccessKind; 927 private final boolean explicitUnsafeNullChecks; 928 929 public UnsafeAccessPlugin(JavaKind kind, boolean explicitUnsafeNullChecks) { 930 unsafeAccessKind = kind; 931 this.explicitUnsafeNullChecks = explicitUnsafeNullChecks; 932 } 933 934 private static FixedWithNextNode createObjectAccessNode(ValueNode value, UnsafeNodeConstructor nodeConstructor) { 935 return nodeConstructor.create(value, LocationIdentity.ANY_LOCATION); 936 } 937 938 private static FixedWithNextNode createMemoryAccessNode(StructuredGraph graph, UnsafeNodeConstructor nodeConstructor) { 939 return nodeConstructor.create(ConstantNode.forLong(0L, graph), OFF_HEAP_LOCATION); 940 } 941 942 private static boolean isLoad(ValueNode node) { 943 return node.getStackKind() != JavaKind.Void; 944 } 945 946 private void setResult(ValueNode node, GraphBuilderContext b) { 947 if (isLoad(node)) { 948 b.addPush(unsafeAccessKind, node); 949 } else { 950 b.add(node); 951 } 952 } 953 954 protected final void createUnsafeAccess(ValueNode value, GraphBuilderContext b, UnsafeNodeConstructor nodeConstructor) { 955 StructuredGraph graph = b.getGraph(); 956 graph.markUnsafeAccess(); 957 /* For unsafe access object pointers can only be stored in the heap */ 958 if (unsafeAccessKind == JavaKind.Object) { 959 setResult(createObjectAccessNode(value, nodeConstructor), b); 960 } else if (StampTool.isPointerAlwaysNull(value)) { 961 setResult(createMemoryAccessNode(graph, nodeConstructor), b); 962 } else if (!explicitUnsafeNullChecks || StampTool.isPointerNonNull(value)) { 963 setResult(createObjectAccessNode(value, nodeConstructor), b); 964 } else { 965 FixedWithNextNode objectAccess = graph.add(createObjectAccessNode(value, nodeConstructor)); 966 FixedWithNextNode memoryAccess = graph.add(createMemoryAccessNode(graph, nodeConstructor)); 967 FixedWithNextNode[] accessNodes = new FixedWithNextNode[]{objectAccess, memoryAccess}; 968 969 LogicNode condition = graph.addOrUniqueWithInputs(IsNullNode.create(value)); 970 b.add(new IfNode(condition, memoryAccess, objectAccess, 0.5)); 971 972 MergeNode merge = b.append(new MergeNode()); 973 for (FixedWithNextNode node : accessNodes) { 974 EndNode endNode = graph.add(new EndNode()); 975 node.setNext(endNode); 976 if (node instanceof StateSplit) { 977 b.setStateAfter((StateSplit) node); 978 } 979 merge.addForwardEnd(endNode); 980 } 981 982 if (isLoad(objectAccess)) { 983 ValuePhiNode phi = new ValuePhiNode(objectAccess.stamp(NodeView.DEFAULT), merge, accessNodes); 984 b.push(unsafeAccessKind, graph.addOrUnique(phi)); 985 } 986 b.setStateAfter(merge); 987 } 988 } 989 } 990 991 public static class UnsafeGetPlugin extends UnsafeAccessPlugin { 992 private final AccessKind accessKind; 993 994 public UnsafeGetPlugin(JavaKind returnKind, boolean explicitUnsafeNullChecks) { 995 this(returnKind, AccessKind.PLAIN, explicitUnsafeNullChecks); 996 } 997 998 public UnsafeGetPlugin(JavaKind kind, AccessKind accessKind, boolean explicitUnsafeNullChecks) { 999 super(kind, explicitUnsafeNullChecks); 1000 this.accessKind = accessKind; 1001 } 1002 1003 @Override 1004 public boolean apply(GraphBuilderContext b, ResolvedJavaMethod targetMethod, Receiver unsafe, ValueNode address) { 1005 // Emits a null-check for the otherwise unused receiver 1006 unsafe.get(); 1007 b.addPush(unsafeAccessKind, new UnsafeMemoryLoadNode(address, unsafeAccessKind, OFF_HEAP_LOCATION)); 1008 b.getGraph().markUnsafeAccess(); 1009 return true; 1010 } 1011 1012 @Override 1013 public boolean apply(GraphBuilderContext b, ResolvedJavaMethod targetMethod, Receiver unsafe, ValueNode object, ValueNode offset) { 1014 // Emits a null-check for the otherwise unused receiver 1015 unsafe.get(); 1016 if (accessKind.emitBarriers) { 1017 b.add(new MembarNode(accessKind.preReadBarriers)); 1018 } 1019 createUnsafeAccess(object, b, (obj, loc) -> new RawLoadNode(obj, offset, unsafeAccessKind, loc)); 1020 if (accessKind.emitBarriers) { 1021 b.add(new MembarNode(accessKind.postReadBarriers)); 1022 } 1023 return true; 1024 } 1025 } 1026 1027 public static class UnsafePutPlugin extends UnsafeAccessPlugin { 1028 private final AccessKind accessKind; 1029 1030 public UnsafePutPlugin(JavaKind kind, boolean explicitUnsafeNullChecks) { 1031 this(kind, AccessKind.PLAIN, explicitUnsafeNullChecks); 1032 } 1033 1034 private UnsafePutPlugin(JavaKind kind, AccessKind accessKind, boolean explicitUnsafeNullChecks) { 1035 super(kind, explicitUnsafeNullChecks); 1036 this.accessKind = accessKind; 1037 } 1038 1039 @Override 1040 public boolean apply(GraphBuilderContext b, ResolvedJavaMethod targetMethod, Receiver unsafe, ValueNode address, ValueNode value) { 1041 assert !accessKind.emitBarriers : "Barriers for address based Unsafe put is not supported."; 1042 // Emits a null-check for the otherwise unused receiver 1043 unsafe.get(); 1044 b.add(new UnsafeMemoryStoreNode(address, value, unsafeAccessKind, OFF_HEAP_LOCATION)); 1045 b.getGraph().markUnsafeAccess(); 1046 return true; 1047 } 1048 1049 @Override 1050 public boolean apply(GraphBuilderContext b, ResolvedJavaMethod targetMethod, Receiver unsafe, ValueNode object, ValueNode offset, ValueNode value) { 1051 // Emits a null-check for the otherwise unused receiver 1052 unsafe.get(); 1053 if (accessKind.emitBarriers) { 1054 b.add(new MembarNode(accessKind.preWriteBarriers)); 1055 } 1056 ValueNode maskedValue = b.maskSubWordValue(value, unsafeAccessKind); 1057 createUnsafeAccess(object, b, (obj, loc) -> new RawStoreNode(obj, offset, maskedValue, unsafeAccessKind, loc)); 1058 if (accessKind.emitBarriers) { 1059 b.add(new MembarNode(accessKind.postWriteBarriers)); 1060 } 1061 return true; 1062 } 1063 } 1064 1065 public static class UnsafeFencePlugin implements InvocationPlugin { 1066 1067 private final int barriers; 1068 1069 public UnsafeFencePlugin(int barriers) { 1070 this.barriers = barriers; 1071 } 1072 1073 @Override 1074 public boolean apply(GraphBuilderContext b, ResolvedJavaMethod targetMethod, Receiver unsafe) { 1075 // Emits a null-check for the otherwise unused receiver 1076 unsafe.get(); 1077 b.add(new MembarNode(barriers)); 1078 return true; 1079 } 1080 } 1081 1082 private static final class DirectiveSpeculationReason implements SpeculationLog.SpeculationReason { 1083 private final BytecodePosition pos; 1084 1085 private DirectiveSpeculationReason(BytecodePosition pos) { 1086 this.pos = pos; 1087 } 1088 1089 @Override 1090 public int hashCode() { 1091 return pos.hashCode(); 1092 } 1093 1094 @Override 1095 public boolean equals(Object obj) { 1096 return obj instanceof DirectiveSpeculationReason && ((DirectiveSpeculationReason) obj).pos.equals(this.pos); 1097 } 1098 } 1099 1100 private static void registerGraalDirectivesPlugins(InvocationPlugins plugins) { 1101 Registration r = new Registration(plugins, GraalDirectives.class); 1102 r.register0("deoptimize", new InvocationPlugin() { 1103 @Override 1104 public boolean apply(GraphBuilderContext b, ResolvedJavaMethod targetMethod, Receiver receiver) { 1105 b.add(new DeoptimizeNode(DeoptimizationAction.None, DeoptimizationReason.TransferToInterpreter)); 1106 return true; 1107 } 1108 }); 1109 1110 r.register0("deoptimizeAndInvalidate", new InvocationPlugin() { 1111 @Override 1112 public boolean apply(GraphBuilderContext b, ResolvedJavaMethod targetMethod, Receiver receiver) { 1113 b.add(new DeoptimizeNode(DeoptimizationAction.InvalidateReprofile, DeoptimizationReason.TransferToInterpreter)); 1114 return true; 1115 } 1116 }); 1117 1118 r.register0("deoptimizeAndInvalidateWithSpeculation", new InvocationPlugin() { 1119 @Override 1120 public boolean apply(GraphBuilderContext b, ResolvedJavaMethod targetMethod, Receiver receiver) { 1121 GraalError.guarantee(b.getGraph().getSpeculationLog() != null, "A speculation log is need to use `deoptimizeAndInvalidateWithSpeculation`"); 1122 BytecodePosition pos = new BytecodePosition(null, b.getMethod(), b.bci()); 1123 DirectiveSpeculationReason reason = new DirectiveSpeculationReason(pos); 1124 Speculation speculation; 1125 if (b.getGraph().getSpeculationLog().maySpeculate(reason)) { 1126 speculation = b.getGraph().getSpeculationLog().speculate(reason); 1127 } else { 1128 speculation = SpeculationLog.NO_SPECULATION; 1129 } 1130 b.add(new DeoptimizeNode(DeoptimizationAction.InvalidateReprofile, DeoptimizationReason.TransferToInterpreter, speculation)); 1131 return true; 1132 } 1133 }); 1134 1135 r.register0("inCompiledCode", new InvocationPlugin() { 1136 @Override 1137 public boolean apply(GraphBuilderContext b, ResolvedJavaMethod targetMethod, Receiver receiver) { 1138 b.addPush(JavaKind.Boolean, ConstantNode.forBoolean(true)); 1139 return true; 1140 } 1141 }); 1142 1143 r.register0("controlFlowAnchor", new InvocationPlugin() { 1144 @Override 1145 public boolean apply(GraphBuilderContext b, ResolvedJavaMethod targetMethod, Receiver receiver) { 1146 b.add(new ControlFlowAnchorNode()); 1147 return true; 1148 } 1149 }); 1150 1151 r.register2("injectBranchProbability", double.class, boolean.class, new InvocationPlugin() { 1152 @Override 1153 public boolean apply(GraphBuilderContext b, ResolvedJavaMethod targetMethod, Receiver receiver, ValueNode probability, ValueNode condition) { 1154 b.addPush(JavaKind.Boolean, new BranchProbabilityNode(probability, condition)); 1155 return true; 1156 } 1157 }); 1158 1159 InvocationPlugin blackholePlugin = new InvocationPlugin() { 1160 @Override 1161 public boolean apply(GraphBuilderContext b, ResolvedJavaMethod targetMethod, Receiver receiver, ValueNode value) { 1162 b.add(new BlackholeNode(value)); 1163 return true; 1164 } 1165 }; 1166 1167 InvocationPlugin bindToRegisterPlugin = new InvocationPlugin() { 1168 @Override 1169 public boolean apply(GraphBuilderContext b, ResolvedJavaMethod targetMethod, Receiver receiver, ValueNode value) { 1170 b.add(new BindToRegisterNode(value)); 1171 return true; 1172 } 1173 }; 1174 for (JavaKind kind : JavaKind.values()) { 1175 if ((kind.isPrimitive() && kind != JavaKind.Void) || kind == JavaKind.Object) { 1176 Class<?> javaClass = kind == JavaKind.Object ? Object.class : kind.toJavaClass(); 1177 r.register1("blackhole", javaClass, blackholePlugin); 1178 r.register1("bindToRegister", javaClass, bindToRegisterPlugin); 1179 1180 r.register1("opaque", javaClass, new InvocationPlugin() { 1181 @Override 1182 public boolean apply(GraphBuilderContext b, ResolvedJavaMethod targetMethod, Receiver receiver, ValueNode value) { 1183 b.addPush(kind, new OpaqueNode(value)); 1184 return true; 1185 } 1186 }); 1187 } 1188 } 1189 1190 InvocationPlugin spillPlugin = new InvocationPlugin() { 1191 @Override 1192 public boolean apply(GraphBuilderContext b, ResolvedJavaMethod targetMethod, Receiver receiver) { 1193 b.add(new SpillRegistersNode()); 1194 return true; 1195 } 1196 }; 1197 r.register0("spillRegisters", spillPlugin); 1198 1199 r.register1("guardingNonNull", Object.class, new InvocationPlugin() { 1200 @Override 1201 public boolean apply(GraphBuilderContext b, ResolvedJavaMethod targetMethod, Receiver receiver, ValueNode value) { 1202 b.addPush(value.getStackKind(), b.nullCheckedValue(value)); 1203 return true; 1204 } 1205 }); 1206 1207 r.register1("ensureVirtualized", Object.class, new InvocationPlugin() { 1208 @Override 1209 public boolean apply(GraphBuilderContext b, ResolvedJavaMethod targetMethod, Receiver receiver, ValueNode object) { 1210 b.add(new EnsureVirtualizedNode(object, false)); 1211 return true; 1212 } 1213 }); 1214 r.register1("ensureVirtualizedHere", Object.class, new InvocationPlugin() { 1215 @Override 1216 public boolean apply(GraphBuilderContext b, ResolvedJavaMethod targetMethod, Receiver receiver, ValueNode object) { 1217 b.add(new EnsureVirtualizedNode(object, true)); 1218 return true; 1219 } 1220 }); 1221 } 1222 1223 private static void registerJMHBlackholePlugins(InvocationPlugins plugins, BytecodeProvider bytecodeProvider) { 1224 InvocationPlugin blackholePlugin = new InvocationPlugin() { 1225 @Override 1226 public boolean apply(GraphBuilderContext b, ResolvedJavaMethod targetMethod, Receiver blackhole, ValueNode value) { 1227 blackhole.get(); 1228 b.add(new BlackholeNode(value)); 1229 return true; 1230 } 1231 1232 @Override 1233 public boolean isDecorator() { 1234 return true; 1235 } 1236 }; 1237 String[] names = {"org.openjdk.jmh.infra.Blackhole", "org.openjdk.jmh.logic.BlackHole"}; 1238 for (String name : names) { 1239 Registration r = new Registration(plugins, name, bytecodeProvider); 1240 for (JavaKind kind : JavaKind.values()) { 1241 if ((kind.isPrimitive() && kind != JavaKind.Void) || kind == JavaKind.Object) { 1242 Class<?> javaClass = kind == JavaKind.Object ? Object.class : kind.toJavaClass(); 1243 r.registerOptional2("consume", Receiver.class, javaClass, blackholePlugin); 1244 } 1245 } 1246 r.registerOptional2("consume", Receiver.class, Object[].class, blackholePlugin); 1247 } 1248 } 1249 1250 private static void registerJFRThrowablePlugins(InvocationPlugins plugins, BytecodeProvider bytecodeProvider) { 1251 Registration r = new Registration(plugins, "oracle.jrockit.jfr.jdkevents.ThrowableTracer", bytecodeProvider); 1252 r.register2("traceThrowable", Throwable.class, String.class, new InvocationPlugin() { 1253 @Override 1254 public boolean apply(GraphBuilderContext b, ResolvedJavaMethod targetMethod, Receiver receiver, ValueNode throwable, ValueNode message) { 1255 b.add(new VirtualizableInvokeMacroNode(b.getInvokeKind(), targetMethod, b.bci(), b.getInvokeReturnStamp(b.getAssumptions()), throwable, message)); 1256 return true; 1257 } 1258 1259 @Override 1260 public boolean inlineOnly() { 1261 return true; 1262 } 1263 }); 1264 } 1265 1266 private static void registerMethodHandleImplPlugins(InvocationPlugins plugins, SnippetReflectionProvider snippetReflection, BytecodeProvider bytecodeProvider) { 1267 Registration r = new Registration(plugins, "java.lang.invoke.MethodHandleImpl", bytecodeProvider); 1268 r.register2("profileBoolean", boolean.class, int[].class, new InvocationPlugin() { 1269 @Override 1270 public boolean apply(GraphBuilderContext b, ResolvedJavaMethod targetMethod, Receiver receiver, ValueNode result, ValueNode counters) { 1271 if (result.isConstant()) { 1272 b.push(JavaKind.Boolean, result); 1273 return true; 1274 } 1275 if (counters.isConstant()) { 1276 ValueNode newResult = result; 1277 int[] ctrs = snippetReflection.asObject(int[].class, (JavaConstant) counters.asConstant()); 1278 if (ctrs != null && ctrs.length == 2) { 1279 int falseCount = ctrs[0]; 1280 int trueCount = ctrs[1]; 1281 int totalCount = trueCount + falseCount; 1282 1283 if (totalCount == 0) { 1284 b.add(new DeoptimizeNode(DeoptimizationAction.InvalidateReprofile, DeoptimizationReason.TransferToInterpreter)); 1285 } else if (falseCount == 0 || trueCount == 0) { 1286 boolean expected = falseCount == 0; 1287 LogicNode condition = b.addWithInputs( 1288 IntegerEqualsNode.create(b.getConstantReflection(), b.getMetaAccess(), b.getOptions(), null, result, b.add(ConstantNode.forBoolean(!expected)), 1289 NodeView.DEFAULT)); 1290 b.append(new FixedGuardNode(condition, DeoptimizationReason.UnreachedCode, DeoptimizationAction.InvalidateReprofile, true)); 1291 newResult = b.add(ConstantNode.forBoolean(expected)); 1292 } else { 1293 // We cannot use BranchProbabilityNode here since there's no guarantee 1294 // the result of MethodHandleImpl.profileBoolean() is used as the 1295 // test in an `if` statement (as required by BranchProbabilityNode). 1296 } 1297 } 1298 b.addPush(JavaKind.Boolean, newResult); 1299 return true; 1300 } 1301 return false; 1302 } 1303 }); 1304 } 1305 1306 /** 1307 * Registers a plugin to ignore {@code com.sun.tdk.jcov.runtime.Collect.hit} within an 1308 * intrinsic. 1309 */ 1310 private static void registerJcovCollectPlugins(InvocationPlugins plugins, BytecodeProvider bytecodeProvider) { 1311 Registration r = new Registration(plugins, "com.sun.tdk.jcov.runtime.Collect", bytecodeProvider); 1312 r.register1("hit", int.class, new InvocationPlugin() { 1313 @Override 1314 public boolean apply(GraphBuilderContext b, ResolvedJavaMethod targetMethod, Receiver receiver, ValueNode object) { 1315 if (b.parsingIntrinsic()) { 1316 return true; 1317 } 1318 return false; 1319 } 1320 }); 1321 } 1322 }