1 /*
   2  * Copyright (c) 2015, 2019, 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.hotspot.meta;
  26 
  27 import static jdk.vm.ci.meta.DeoptimizationAction.None;
  28 import static jdk.vm.ci.meta.DeoptimizationReason.TransferToInterpreter;
  29 import static org.graalvm.compiler.core.common.GraalOptions.ImmutableCode;
  30 
  31 import java.lang.reflect.Field;
  32 
  33 import org.graalvm.compiler.core.common.CompilationIdentifier;
  34 import org.graalvm.compiler.core.common.type.StampFactory;
  35 import org.graalvm.compiler.core.common.type.StampPair;
  36 import org.graalvm.compiler.hotspot.GraalHotSpotVMConfig;
  37 import org.graalvm.compiler.hotspot.HotSpotCompilationIdentifier;
  38 import org.graalvm.compiler.hotspot.nodes.CurrentJavaThreadNode;
  39 import org.graalvm.compiler.hotspot.word.HotSpotWordTypes;
  40 import org.graalvm.compiler.nodes.ConstantNode;
  41 import org.graalvm.compiler.nodes.FixedGuardNode;
  42 import org.graalvm.compiler.nodes.FixedWithNextNode;
  43 import org.graalvm.compiler.nodes.LogicNode;
  44 import org.graalvm.compiler.nodes.NamedLocationIdentity;
  45 import org.graalvm.compiler.nodes.StructuredGraph;
  46 import org.graalvm.compiler.nodes.ValueNode;
  47 import org.graalvm.compiler.nodes.calc.IntegerEqualsNode;
  48 import org.graalvm.compiler.nodes.extended.GuardingNode;
  49 import org.graalvm.compiler.nodes.graphbuilderconf.GraphBuilderContext;
  50 import org.graalvm.compiler.nodes.graphbuilderconf.GraphBuilderTool;
  51 import org.graalvm.compiler.nodes.graphbuilderconf.InlineInvokePlugin;
  52 import org.graalvm.compiler.nodes.graphbuilderconf.NodePlugin;
  53 import org.graalvm.compiler.nodes.graphbuilderconf.TypePlugin;
  54 import org.graalvm.compiler.nodes.memory.HeapAccess.BarrierType;
  55 import org.graalvm.compiler.nodes.memory.ReadNode;
  56 import org.graalvm.compiler.nodes.memory.address.AddressNode;
  57 import org.graalvm.compiler.nodes.memory.address.OffsetAddressNode;
  58 import org.graalvm.compiler.nodes.util.ConstantFoldUtil;
  59 import org.graalvm.compiler.word.Word;
  60 import org.graalvm.compiler.word.WordOperationPlugin;
  61 import jdk.internal.vm.compiler.word.LocationIdentity;
  62 
  63 import jdk.vm.ci.hotspot.HotSpotCompilationRequest;
  64 import jdk.vm.ci.meta.JavaConstant;
  65 import jdk.vm.ci.meta.JavaKind;
  66 import jdk.vm.ci.meta.JavaType;
  67 import jdk.vm.ci.meta.JavaTypeProfile;
  68 import jdk.vm.ci.meta.ResolvedJavaField;
  69 import jdk.vm.ci.meta.ResolvedJavaMethod;
  70 import jdk.vm.ci.meta.ResolvedJavaType;
  71 import sun.misc.Unsafe;
  72 
  73 /**
  74  * This plugin does HotSpot-specific customization of bytecode parsing:
  75  * <ul>
  76  * <li>{@link Word}-type rewriting for {@link GraphBuilderContext#parsingIntrinsic intrinsic}
  77  * functions (snippets and method substitutions), by forwarding to the {@link WordOperationPlugin}.
  78  * Note that we forward the {@link NodePlugin} and {@link TypePlugin} methods, but not the
  79  * {@link InlineInvokePlugin} methods implemented by {@link WordOperationPlugin}. The latter is not
  80  * necessary because HotSpot only uses the {@link Word} type in methods that are force-inlined,
  81  * i.e., there are never non-inlined invokes that involve the {@link Word} type.</li>
  82  * <li>Constant folding of field loads.</li>
  83  * </ul>
  84  */
  85 public final class HotSpotNodePlugin implements NodePlugin, TypePlugin {
  86     protected final WordOperationPlugin wordOperationPlugin;
  87     private final GraalHotSpotVMConfig config;
  88     private final HotSpotWordTypes wordTypes;
  89 
  90     public HotSpotNodePlugin(WordOperationPlugin wordOperationPlugin, GraalHotSpotVMConfig config, HotSpotWordTypes wordTypes) {
  91         this.wordOperationPlugin = wordOperationPlugin;
  92         this.config = config;
  93         this.wordTypes = wordTypes;
  94     }
  95 
  96     @Override
  97     public boolean canChangeStackKind(GraphBuilderContext b) {
  98         if (b.parsingIntrinsic()) {
  99             return wordOperationPlugin.canChangeStackKind(b);
 100         }
 101         return false;
 102     }
 103 
 104     @Override
 105     public StampPair interceptType(GraphBuilderTool b, JavaType declaredType, boolean nonNull) {
 106         if (b.parsingIntrinsic()) {
 107             return wordOperationPlugin.interceptType(b, declaredType, nonNull);
 108         }
 109         return null;
 110     }
 111 
 112     @Override
 113     public boolean handleInvoke(GraphBuilderContext b, ResolvedJavaMethod method, ValueNode[] args) {
 114         if (b.parsingIntrinsic() && wordOperationPlugin.handleInvoke(b, method, args)) {
 115             return true;
 116         }
 117         return false;
 118     }
 119 
 120     @Override
 121     public boolean handleLoadField(GraphBuilderContext b, ValueNode object, ResolvedJavaField field) {
 122         if (!ImmutableCode.getValue(b.getOptions()) || b.parsingIntrinsic()) {
 123             if (object.isConstant()) {
 124                 JavaConstant asJavaConstant = object.asJavaConstant();
 125                 if (tryReadField(b, field, asJavaConstant)) {
 126                     return true;
 127                 }
 128             }
 129         }
 130         if (b.parsingIntrinsic() && wordOperationPlugin.handleLoadField(b, object, field)) {
 131             return true;
 132         }
 133         return false;
 134     }
 135 
 136     @Override
 137     public boolean handleLoadStaticField(GraphBuilderContext b, ResolvedJavaField field) {
 138         if (!ImmutableCode.getValue(b.getOptions()) || b.parsingIntrinsic()) {
 139             if (tryReadField(b, field, null)) {
 140                 return true;
 141             }
 142         }
 143         if (b.parsingIntrinsic() && wordOperationPlugin.handleLoadStaticField(b, field)) {
 144             return true;
 145         }
 146         return false;
 147     }
 148 
 149     private static boolean tryReadField(GraphBuilderContext b, ResolvedJavaField field, JavaConstant object) {
 150         return tryConstantFold(b, field, object);
 151     }
 152 
 153     private static boolean tryConstantFold(GraphBuilderContext b, ResolvedJavaField field, JavaConstant object) {
 154         ConstantNode result = ConstantFoldUtil.tryConstantFold(b.getConstantFieldProvider(), b.getConstantReflection(), b.getMetaAccess(), field, object, b.getOptions());
 155         if (result != null) {
 156             result = b.getGraph().unique(result);
 157             b.push(field.getJavaKind(), result);
 158             return true;
 159         }
 160         return false;
 161     }
 162 
 163     @Override
 164     public boolean handleStoreField(GraphBuilderContext b, ValueNode object, ResolvedJavaField field, ValueNode value) {
 165         if (b.parsingIntrinsic() && wordOperationPlugin.handleStoreField(b, object, field, value)) {
 166             return true;
 167         }
 168         return false;
 169     }
 170 
 171     @Override
 172     public boolean handleStoreStaticField(GraphBuilderContext b, ResolvedJavaField field, ValueNode value) {
 173         if (b.parsingIntrinsic() && wordOperationPlugin.handleStoreStaticField(b, field, value)) {
 174             return true;
 175         }
 176         return false;
 177     }
 178 
 179     @Override
 180     public boolean handleLoadIndexed(GraphBuilderContext b, ValueNode array, ValueNode index, GuardingNode boundsCheck, JavaKind elementKind) {
 181         if (b.parsingIntrinsic() && wordOperationPlugin.handleLoadIndexed(b, array, index, boundsCheck, elementKind)) {
 182             return true;
 183         }
 184         return false;
 185     }
 186 
 187     @Override
 188     public boolean handleStoreIndexed(GraphBuilderContext b, ValueNode array, ValueNode index, GuardingNode boundsCheck, GuardingNode storeCheck, JavaKind elementKind, ValueNode value) {
 189         if (b.parsingIntrinsic() && wordOperationPlugin.handleStoreIndexed(b, array, index, boundsCheck, storeCheck, elementKind, value)) {
 190             return true;
 191         }
 192         return false;
 193     }
 194 
 195     @Override
 196     public boolean handleCheckCast(GraphBuilderContext b, ValueNode object, ResolvedJavaType type, JavaTypeProfile profile) {
 197         if (b.parsingIntrinsic() && wordOperationPlugin.handleCheckCast(b, object, type, profile)) {
 198             return true;
 199         }
 200         return false;
 201     }
 202 
 203     @Override
 204     public boolean handleInstanceOf(GraphBuilderContext b, ValueNode object, ResolvedJavaType type, JavaTypeProfile profile) {
 205         if (b.parsingIntrinsic() && wordOperationPlugin.handleInstanceOf(b, object, type, profile)) {
 206             return true;
 207         }
 208         return false;
 209     }
 210 
 211     @Override
 212     public FixedWithNextNode instrumentExceptionDispatch(StructuredGraph graph, FixedWithNextNode afterExceptionLoaded) {
 213         CompilationIdentifier id = graph.compilationId();
 214         if (id instanceof HotSpotCompilationIdentifier) {
 215             HotSpotCompilationRequest request = ((HotSpotCompilationIdentifier) id).getRequest();
 216             if (request != null) {
 217                 long compileState = request.getJvmciEnv();
 218                 if (compileState != 0 &&
 219                                 config.jvmciCompileStateCanPostOnExceptionsOffset != Integer.MIN_VALUE &&
 220                                 config.javaThreadShouldPostOnExceptionsFlagOffset != Integer.MIN_VALUE) {
 221                     long canPostOnExceptionsOffset = compileState + config.jvmciCompileStateCanPostOnExceptionsOffset;
 222                     boolean canPostOnExceptions = UNSAFE.getByte(canPostOnExceptionsOffset) != 0;
 223                     if (canPostOnExceptions) {
 224                         // If the exception capability is set, then generate code
 225                         // to check the JavaThread.should_post_on_exceptions flag to see
 226                         // if we actually need to report exception events for the current
 227                         // thread. If not, take the fast path otherwise deoptimize.
 228                         CurrentJavaThreadNode thread = graph.unique(new CurrentJavaThreadNode(wordTypes.getWordKind()));
 229                         ValueNode offset = graph.unique(ConstantNode.forLong(config.javaThreadShouldPostOnExceptionsFlagOffset));
 230                         AddressNode address = graph.unique(new OffsetAddressNode(thread, offset));
 231                         ReadNode shouldPostException = graph.add(new ReadNode(address, JAVA_THREAD_SHOULD_POST_ON_EXCEPTIONS_FLAG_LOCATION, StampFactory.intValue(), BarrierType.NONE));
 232                         afterExceptionLoaded.setNext(shouldPostException);
 233                         ValueNode zero = graph.unique(ConstantNode.forInt(0));
 234                         LogicNode cond = graph.unique(new IntegerEqualsNode(shouldPostException, zero));
 235                         FixedGuardNode check = graph.add(new FixedGuardNode(cond, TransferToInterpreter, None, false));
 236                         shouldPostException.setNext(check);
 237                         return check;
 238                     }
 239                 }
 240             }
 241         }
 242         return afterExceptionLoaded;
 243     }
 244 
 245     private static final LocationIdentity JAVA_THREAD_SHOULD_POST_ON_EXCEPTIONS_FLAG_LOCATION = NamedLocationIdentity.mutable("JavaThread::_should_post_on_exceptions_flag");
 246     static final Unsafe UNSAFE = initUnsafe();
 247 
 248     static Unsafe initUnsafe() {
 249         try {
 250             // Fast path when we are trusted.
 251             return Unsafe.getUnsafe();
 252         } catch (SecurityException se) {
 253             // Slow path when we are not trusted.
 254             try {
 255                 Field theUnsafe = Unsafe.class.getDeclaredField("theUnsafe");
 256                 theUnsafe.setAccessible(true);
 257                 return (Unsafe) theUnsafe.get(Unsafe.class);
 258             } catch (Exception e) {
 259                 throw new RuntimeException("exception while trying to get Unsafe", e);
 260             }
 261         }
 262     }
 263 }