1 /*
   2  * Copyright (c) 2015, 2018, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  */
  23 
  24 
  25 package org.graalvm.compiler.nodes.graphbuilderconf;
  26 
  27 import static jdk.vm.ci.meta.DeoptimizationAction.InvalidateReprofile;
  28 import static jdk.vm.ci.meta.DeoptimizationReason.NullCheckException;
  29 import static org.graalvm.compiler.core.common.type.StampFactory.objectNonNull;
  30 
  31 import org.graalvm.compiler.bytecode.Bytecode;
  32 import org.graalvm.compiler.bytecode.BytecodeProvider;
  33 import org.graalvm.compiler.core.common.type.AbstractPointerStamp;
  34 import org.graalvm.compiler.core.common.type.Stamp;
  35 import org.graalvm.compiler.core.common.type.StampFactory;
  36 import org.graalvm.compiler.core.common.type.StampPair;
  37 import org.graalvm.compiler.debug.GraalError;
  38 import org.graalvm.compiler.nodes.AbstractBeginNode;
  39 import org.graalvm.compiler.nodes.AbstractMergeNode;
  40 import org.graalvm.compiler.nodes.CallTargetNode;
  41 import org.graalvm.compiler.nodes.CallTargetNode.InvokeKind;
  42 import org.graalvm.compiler.nodes.ConstantNode;
  43 import org.graalvm.compiler.nodes.DynamicPiNode;
  44 import org.graalvm.compiler.nodes.FixedGuardNode;
  45 import org.graalvm.compiler.nodes.Invoke;
  46 import org.graalvm.compiler.nodes.LogicNode;
  47 import org.graalvm.compiler.nodes.NodeView;
  48 import org.graalvm.compiler.nodes.PiNode;
  49 import org.graalvm.compiler.nodes.StateSplit;
  50 import org.graalvm.compiler.nodes.ValueNode;
  51 import org.graalvm.compiler.nodes.calc.IsNullNode;
  52 import org.graalvm.compiler.nodes.calc.NarrowNode;
  53 import org.graalvm.compiler.nodes.calc.SignExtendNode;
  54 import org.graalvm.compiler.nodes.calc.ZeroExtendNode;
  55 import org.graalvm.compiler.nodes.extended.BytecodeExceptionNode.BytecodeExceptionKind;
  56 import org.graalvm.compiler.nodes.java.InstanceOfDynamicNode;
  57 import org.graalvm.compiler.nodes.type.StampTool;
  58 
  59 import jdk.vm.ci.code.BailoutException;
  60 import jdk.vm.ci.meta.Assumptions;
  61 import jdk.vm.ci.meta.DeoptimizationAction;
  62 import jdk.vm.ci.meta.DeoptimizationReason;
  63 import jdk.vm.ci.meta.JavaKind;
  64 import jdk.vm.ci.meta.JavaType;
  65 import jdk.vm.ci.meta.ResolvedJavaMethod;
  66 
  67 /**
  68  * Used by a {@link GraphBuilderPlugin} to interface with an object that parses the bytecode of a
  69  * single {@linkplain #getMethod() method} as part of building a {@linkplain #getGraph() graph} .
  70  */
  71 public interface GraphBuilderContext extends GraphBuilderTool {
  72 
  73     /**
  74      * Pushes a given value to the frame state stack using an explicit kind. This should be used
  75      * when {@code value.getJavaKind()} is different from the kind that the bytecode instruction
  76      * currently being parsed pushes to the stack.
  77      *
  78      * @param kind the kind to use when type checking this operation
  79      * @param value the value to push to the stack. The value must already have been
  80      *            {@linkplain #append(ValueNode) appended}.
  81      */
  82     void push(JavaKind kind, ValueNode value);
  83 
  84     /**
  85      * Pops a value from the frame state stack using an explicit kind.
  86      *
  87      * @param slotKind the kind to use when type checking this operation
  88      * @return the value on the top of the stack
  89      */
  90     default ValueNode pop(JavaKind slotKind) {
  91         throw GraalError.unimplemented();
  92     }
  93 
  94     /**
  95      * Adds a node and all its inputs to the graph. If the node is in the graph, returns
  96      * immediately. If the node is a {@link StateSplit} with a null
  97      * {@linkplain StateSplit#stateAfter() frame state} , the frame state is initialized.
  98      *
  99      * @param value the value to add to the graph and push to the stack. The
 100      *            {@code value.getJavaKind()} kind is used when type checking this operation.
 101      * @return a node equivalent to {@code value} in the graph
 102      */
 103     default <T extends ValueNode> T add(T value) {
 104         if (value.graph() != null) {
 105             assert !(value instanceof StateSplit) || ((StateSplit) value).stateAfter() != null;
 106             return value;
 107         }
 108         return GraphBuilderContextUtil.setStateAfterIfNecessary(this, append(value));
 109     }
 110 
 111     default ValueNode addNonNullCast(ValueNode value) {
 112         AbstractPointerStamp valueStamp = (AbstractPointerStamp) value.stamp(NodeView.DEFAULT);
 113         if (valueStamp.nonNull()) {
 114             return value;
 115         } else {
 116             LogicNode isNull = add(IsNullNode.create(value));
 117             FixedGuardNode fixedGuard = add(new FixedGuardNode(isNull, DeoptimizationReason.NullCheckException, DeoptimizationAction.None, true));
 118             Stamp newStamp = valueStamp.improveWith(StampFactory.objectNonNull());
 119             return add(PiNode.create(value, newStamp, fixedGuard));
 120         }
 121     }
 122 
 123     /**
 124      * Adds a node with a non-void kind to the graph, pushes it to the stack. If the returned node
 125      * is a {@link StateSplit} with a null {@linkplain StateSplit#stateAfter() frame state}, the
 126      * frame state is initialized.
 127      *
 128      * @param kind the kind to use when type checking this operation
 129      * @param value the value to add to the graph and push to the stack
 130      * @return a node equivalent to {@code value} in the graph
 131      */
 132     default <T extends ValueNode> T addPush(JavaKind kind, T value) {
 133         T equivalentValue = value.graph() != null ? value : append(value);
 134         push(kind, equivalentValue);
 135         return GraphBuilderContextUtil.setStateAfterIfNecessary(this, equivalentValue);
 136     }
 137 
 138     /**
 139      * Handles an invocation that a plugin determines can replace the original invocation (i.e., the
 140      * one for which the plugin was applied). This applies all standard graph builder processing to
 141      * the replaced invocation including applying any relevant plugins.
 142      *
 143      * @param invokeKind the kind of the replacement invocation
 144      * @param targetMethod the target of the replacement invocation
 145      * @param args the arguments to the replacement invocation
 146      * @param forceInlineEverything specifies if all invocations encountered in the scope of
 147      *            handling the replaced invoke are to be force inlined
 148      */
 149     Invoke handleReplacedInvoke(InvokeKind invokeKind, ResolvedJavaMethod targetMethod, ValueNode[] args, boolean forceInlineEverything);
 150 
 151     void handleReplacedInvoke(CallTargetNode callTarget, JavaKind resultType);
 152 
 153     /**
 154      * Intrinsifies an invocation of a given method by inlining the bytecodes of a given
 155      * substitution method.
 156      *
 157      * @param bytecodeProvider used to get the bytecodes to parse for the substitution method
 158      * @param targetMethod the method being intrinsified
 159      * @param substitute the intrinsic implementation
 160      * @param receiver the receiver, or null for static methods
 161      * @param argsIncludingReceiver the arguments with which to inline the invocation
 162      *
 163      * @return whether the intrinsification was successful
 164      */
 165     boolean intrinsify(BytecodeProvider bytecodeProvider, ResolvedJavaMethod targetMethod, ResolvedJavaMethod substitute, InvocationPlugin.Receiver receiver, ValueNode[] argsIncludingReceiver);
 166 
 167     /**
 168      * Creates a snap shot of the current frame state with the BCI of the instruction after the one
 169      * currently being parsed and assigns it to a given {@linkplain StateSplit#hasSideEffect() side
 170      * effect} node.
 171      *
 172      * @param sideEffect a side effect node just appended to the graph
 173      */
 174     void setStateAfter(StateSplit sideEffect);
 175 
 176     /**
 177      * Gets the parsing context for the method that inlines the method being parsed by this context.
 178      */
 179     GraphBuilderContext getParent();
 180 
 181     /**
 182      * Gets the first ancestor parsing context that is not parsing a {@linkplain #parsingIntrinsic()
 183      * intrinsic}.
 184      */
 185     default GraphBuilderContext getNonIntrinsicAncestor() {
 186         GraphBuilderContext ancestor = getParent();
 187         while (ancestor != null && ancestor.parsingIntrinsic()) {
 188             ancestor = ancestor.getParent();
 189         }
 190         return ancestor;
 191     }
 192 
 193     /**
 194      * Gets the code being parsed.
 195      */
 196     Bytecode getCode();
 197 
 198     /**
 199      * Gets the method being parsed by this context.
 200      */
 201     ResolvedJavaMethod getMethod();
 202 
 203     /**
 204      * Gets the index of the bytecode instruction currently being parsed.
 205      */
 206     int bci();
 207 
 208     /**
 209      * Gets the kind of invocation currently being parsed.
 210      */
 211     InvokeKind getInvokeKind();
 212 
 213     /**
 214      * Gets the return type of the invocation currently being parsed.
 215      */
 216     JavaType getInvokeReturnType();
 217 
 218     default StampPair getInvokeReturnStamp(Assumptions assumptions) {
 219         JavaType returnType = getInvokeReturnType();
 220         return StampFactory.forDeclaredType(assumptions, returnType, false);
 221     }
 222 
 223     /**
 224      * Gets the inline depth of this context. A return value of 0 implies that this is the context
 225      * for the parse root.
 226      */
 227     default int getDepth() {
 228         GraphBuilderContext parent = getParent();
 229         int result = 0;
 230         while (parent != null) {
 231             result++;
 232             parent = parent.getParent();
 233         }
 234         return result;
 235     }
 236 
 237     /**
 238      * Determines if this parsing context is within the bytecode of an intrinsic or a method inlined
 239      * by an intrinsic.
 240      */
 241     @Override
 242     default boolean parsingIntrinsic() {
 243         return getIntrinsic() != null;
 244     }
 245 
 246     /**
 247      * Gets the intrinsic of the current parsing context or {@code null} if not
 248      * {@link #parsingIntrinsic() parsing an intrinsic}.
 249      */
 250     IntrinsicContext getIntrinsic();
 251 
 252     BailoutException bailout(String string);
 253 
 254     default ValueNode nullCheckedValue(ValueNode value) {
 255         return nullCheckedValue(value, InvalidateReprofile);
 256     }
 257 
 258     /**
 259      * Gets a version of a given value that has a {@linkplain StampTool#isPointerNonNull(ValueNode)
 260      * non-null} stamp.
 261      */
 262     default ValueNode nullCheckedValue(ValueNode value, DeoptimizationAction action) {
 263         if (!StampTool.isPointerNonNull(value)) {
 264             LogicNode condition = getGraph().unique(IsNullNode.create(value));
 265             FixedGuardNode fixedGuard = append(new FixedGuardNode(condition, NullCheckException, action, true));
 266             ValueNode nonNullReceiver = getGraph().addOrUniqueWithInputs(PiNode.create(value, objectNonNull(), fixedGuard));
 267             // TODO: Propogating the non-null into the frame state would
 268             // remove subsequent null-checks on the same value. However,
 269             // it currently causes an assertion failure when merging states.
 270             //
 271             // frameState.replace(value, nonNullReceiver);
 272             return nonNullReceiver;
 273         }
 274         return value;
 275     }
 276 
 277     default void genCheckcastDynamic(ValueNode object, ValueNode javaClass) {
 278         LogicNode condition = InstanceOfDynamicNode.create(getAssumptions(), getConstantReflection(), javaClass, object, true);
 279         if (condition.isTautology()) {
 280             addPush(JavaKind.Object, object);
 281         } else {
 282             append(condition);
 283             FixedGuardNode fixedGuard = add(new FixedGuardNode(condition, DeoptimizationReason.ClassCastException, DeoptimizationAction.InvalidateReprofile, false));
 284             addPush(JavaKind.Object, DynamicPiNode.create(getAssumptions(), getConstantReflection(), object, fixedGuard, javaClass));
 285         }
 286     }
 287 
 288     @SuppressWarnings("unused")
 289     default void notifyReplacedCall(ResolvedJavaMethod targetMethod, ConstantNode node) {
 290 
 291     }
 292 
 293     /**
 294      * Interface whose instances hold inlining information about the current context, in a wider
 295      * sense. The wider sense in this case concerns graph building approaches that don't necessarily
 296      * keep a chain of {@link GraphBuilderContext} instances normally available through
 297      * {@linkplain #getParent()}. Examples of such approaches are partial evaluation and incremental
 298      * inlining.
 299      */
 300     interface ExternalInliningContext {
 301         int getInlinedDepth();
 302     }
 303 
 304     default ExternalInliningContext getExternalInliningContext() {
 305         return null;
 306     }
 307 
 308     /**
 309      * Adds masking to a given subword value according to a given {@Link JavaKind}, such that the
 310      * masked value falls in the range of the given kind. In the cases where the given kind is not a
 311      * subword kind, the input value is returned immediately.
 312      *
 313      * @param value the value to be masked
 314      * @param kind the kind that specifies the range of the masked value
 315      * @return the masked value
 316      */
 317     default ValueNode maskSubWordValue(ValueNode value, JavaKind kind) {
 318         if (kind == kind.getStackKind()) {
 319             return value;
 320         }
 321         // Subword value
 322         ValueNode narrow = append(NarrowNode.create(value, kind.getBitCount(), NodeView.DEFAULT));
 323         if (kind.isUnsigned()) {
 324             return append(ZeroExtendNode.create(narrow, 32, NodeView.DEFAULT));
 325         } else {
 326             return append(SignExtendNode.create(narrow, 32, NodeView.DEFAULT));
 327         }
 328     }
 329 
 330     /**
 331      * @return true if an explicit exception check should be emitted.
 332      */
 333     default boolean needsExplicitException() {
 334         return false;
 335     }
 336 
 337     /**
 338      * Generates an exception edge for the current bytecode. When {@link #needsExplicitException()}
 339      * returns true, this method should return non-null begin nodes.
 340      *
 341      * @param exceptionKind the type of exception to be created.
 342      * @return a begin node that precedes the actual exception instantiation code.
 343      */
 344     default AbstractBeginNode genExplicitExceptionEdge(@SuppressWarnings("ununsed") BytecodeExceptionKind exceptionKind) {
 345         return null;
 346     }
 347 }
 348 
 349 class GraphBuilderContextUtil {
 350     static <T extends ValueNode> T setStateAfterIfNecessary(GraphBuilderContext b, T value) {
 351         if (value instanceof StateSplit) {
 352             StateSplit stateSplit = (StateSplit) value;
 353             if (stateSplit.stateAfter() == null && (stateSplit.hasSideEffect() || stateSplit instanceof AbstractMergeNode)) {
 354                 b.setStateAfter(stateSplit);
 355             }
 356         }
 357         return value;
 358     }
 359 }