1 /*
   2  * Copyright (c) 2011, 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.hotspot.phases;
  26 
  27 import static org.graalvm.compiler.phases.common.DeadCodeEliminationPhase.Optionality.Required;
  28 
  29 import org.graalvm.compiler.core.common.PermanentBailoutException;
  30 import org.graalvm.compiler.core.common.cfg.Loop;
  31 import org.graalvm.compiler.core.common.type.ObjectStamp;
  32 import org.graalvm.compiler.core.common.type.Stamp;
  33 import org.graalvm.compiler.debug.CounterKey;
  34 import org.graalvm.compiler.debug.DebugCloseable;
  35 import org.graalvm.compiler.debug.DebugContext;
  36 import org.graalvm.compiler.debug.GraalError;
  37 import org.graalvm.compiler.graph.Node;
  38 import org.graalvm.compiler.graph.iterators.NodeIterable;
  39 import org.graalvm.compiler.loop.LoopEx;
  40 import org.graalvm.compiler.loop.LoopsData;
  41 import org.graalvm.compiler.loop.phases.LoopTransformations;
  42 import org.graalvm.compiler.nodeinfo.InputType;
  43 import org.graalvm.compiler.nodeinfo.Verbosity;
  44 import org.graalvm.compiler.nodes.AbstractBeginNode;
  45 import org.graalvm.compiler.nodes.EntryMarkerNode;
  46 import org.graalvm.compiler.nodes.EntryProxyNode;
  47 import org.graalvm.compiler.nodes.FixedGuardNode;
  48 import org.graalvm.compiler.nodes.FixedNode;
  49 import org.graalvm.compiler.nodes.FrameState;
  50 import org.graalvm.compiler.nodes.LogicNode;
  51 import org.graalvm.compiler.nodes.LoopBeginNode;
  52 import org.graalvm.compiler.nodes.NodeView;
  53 import org.graalvm.compiler.nodes.ParameterNode;
  54 import org.graalvm.compiler.nodes.PiNode;
  55 import org.graalvm.compiler.nodes.StartNode;
  56 import org.graalvm.compiler.nodes.StructuredGraph;
  57 import org.graalvm.compiler.nodes.ValueNode;
  58 import org.graalvm.compiler.nodes.cfg.Block;
  59 import org.graalvm.compiler.nodes.extended.OSRLocalNode;
  60 import org.graalvm.compiler.nodes.extended.OSRLockNode;
  61 import org.graalvm.compiler.nodes.extended.OSRMonitorEnterNode;
  62 import org.graalvm.compiler.nodes.extended.OSRStartNode;
  63 import org.graalvm.compiler.nodes.java.AccessMonitorNode;
  64 import org.graalvm.compiler.nodes.java.InstanceOfNode;
  65 import org.graalvm.compiler.nodes.java.MonitorEnterNode;
  66 import org.graalvm.compiler.nodes.java.MonitorExitNode;
  67 import org.graalvm.compiler.nodes.java.MonitorIdNode;
  68 import org.graalvm.compiler.nodes.util.GraphUtil;
  69 import org.graalvm.compiler.options.Option;
  70 import org.graalvm.compiler.options.OptionKey;
  71 import org.graalvm.compiler.options.OptionType;
  72 import org.graalvm.compiler.options.OptionValues;
  73 import org.graalvm.compiler.phases.Phase;
  74 import org.graalvm.compiler.phases.common.DeadCodeEliminationPhase;
  75 import org.graalvm.compiler.serviceprovider.SpeculationReasonGroup;
  76 
  77 import jdk.vm.ci.meta.DeoptimizationAction;
  78 import jdk.vm.ci.meta.DeoptimizationReason;
  79 import jdk.vm.ci.meta.JavaKind;
  80 import jdk.vm.ci.meta.SpeculationLog;
  81 import jdk.vm.ci.meta.SpeculationLog.SpeculationReason;
  82 import jdk.vm.ci.runtime.JVMCICompiler;
  83 
  84 public class OnStackReplacementPhase extends Phase {
  85 
  86     public static class Options {
  87         // @formatter:off
  88         @Option(help = "Deoptimize OSR compiled code when the OSR entry loop is finished " +
  89                        "if there is no mature profile available for the rest of the method.", type = OptionType.Debug)
  90         public static final OptionKey<Boolean> DeoptAfterOSR = new OptionKey<>(true);
  91         @Option(help = "Support OSR compilations with locks. If DeoptAfterOSR is true we can per definition not have " +
  92                        "unbalanced enter/exits mappings. If DeoptAfterOSR is false insert artificial monitor enters after " +
  93                        "the OSRStart to have balanced enter/exits in the graph.", type = OptionType.Debug)
  94         public static final OptionKey<Boolean> SupportOSRWithLocks = new OptionKey<>(true);
  95         // @formatter:on
  96     }
  97 
  98     private static final CounterKey OsrWithLocksCount = DebugContext.counter("OSRWithLocks");
  99 
 100     private static boolean supportOSRWithLocks(OptionValues options) {
 101         return Options.SupportOSRWithLocks.getValue(options);
 102     }
 103 
 104     private static final SpeculationReasonGroup OSR_LOCAL_SPECULATIONS = new SpeculationReasonGroup("OSRLocal", int.class, Stamp.class, int.class);
 105 
 106     @Override
 107     @SuppressWarnings("try")
 108     protected void run(StructuredGraph graph) {
 109         DebugContext debug = graph.getDebug();
 110         if (graph.getEntryBCI() == JVMCICompiler.INVOCATION_ENTRY_BCI) {
 111             // This happens during inlining in a OSR method, because the same phase plan will be
 112             // used.
 113             assert graph.getNodes(EntryMarkerNode.TYPE).isEmpty();
 114             return;
 115         }
 116         debug.dump(DebugContext.DETAILED_LEVEL, graph, "OnStackReplacement initial at bci %d", graph.getEntryBCI());
 117 
 118         EntryMarkerNode osr;
 119         int maxIterations = -1;
 120         int iterations = 0;
 121 
 122         final EntryMarkerNode originalOSRNode = getEntryMarker(graph);
 123         final LoopBeginNode originalOSRLoop = osrLoop(originalOSRNode);
 124         final boolean currentOSRWithLocks = osrWithLocks(originalOSRNode);
 125 
 126         if (originalOSRLoop == null) {
 127             /*
 128              * OSR with Locks: We do not have an OSR loop for the original OSR bci. Therefore we
 129              * cannot decide where to deopt and which framestate will be used. In the worst case the
 130              * framestate of the OSR entry would be used.
 131              */
 132             throw new PermanentBailoutException("OSR compilation without OSR entry loop.");
 133         }
 134 
 135         if (!supportOSRWithLocks(graph.getOptions()) && currentOSRWithLocks) {
 136             throw new PermanentBailoutException("OSR with locks disabled.");
 137         }
 138 
 139         do {
 140             osr = getEntryMarker(graph);
 141             LoopsData loops = new LoopsData(graph);
 142             // Find the loop that contains the EntryMarker
 143             Loop<Block> l = loops.getCFG().getNodeToBlock().get(osr).getLoop();
 144             if (l == null) {
 145                 break;
 146             }
 147 
 148             iterations++;
 149             if (maxIterations == -1) {
 150                 maxIterations = l.getDepth();
 151             } else if (iterations > maxIterations) {
 152                 throw GraalError.shouldNotReachHere();
 153             }
 154             // Peel the outermost loop first
 155             while (l.getParent() != null) {
 156                 l = l.getParent();
 157             }
 158 
 159             LoopEx loop = loops.loop(l);
 160             loop.loopBegin().markOsrLoop();
 161             LoopTransformations.peel(loop);
 162             osr.replaceAtUsages(InputType.Guard, AbstractBeginNode.prevBegin((FixedNode) osr.predecessor()));
 163             for (Node usage : osr.usages().snapshot()) {
 164                 EntryProxyNode proxy = (EntryProxyNode) usage;
 165                 proxy.replaceAndDelete(proxy.value());
 166             }
 167             GraphUtil.removeFixedWithUnusedInputs(osr);
 168             debug.dump(DebugContext.DETAILED_LEVEL, graph, "OnStackReplacement loop peeling result");
 169         } while (true);
 170 
 171         StartNode start = graph.start();
 172         FrameState osrState = osr.stateAfter();
 173         OSRStartNode osrStart;
 174         try (DebugCloseable context = osr.withNodeSourcePosition()) {
 175             osr.setStateAfter(null);
 176             osrStart = graph.add(new OSRStartNode());
 177             FixedNode next = osr.next();
 178             osr.setNext(null);
 179             osrStart.setNext(next);
 180             graph.setStart(osrStart);
 181             osrStart.setStateAfter(osrState);
 182 
 183             debug.dump(DebugContext.DETAILED_LEVEL, graph, "OnStackReplacement after setting OSR start");
 184             final int localsSize = osrState.localsSize();
 185             final int locksSize = osrState.locksSize();
 186 
 187             for (int i = 0; i < localsSize + locksSize; i++) {
 188                 ValueNode value;
 189                 if (i >= localsSize) {
 190                     value = osrState.lockAt(i - localsSize);
 191                 } else {
 192                     value = osrState.localAt(i);
 193                 }
 194                 if (value instanceof EntryProxyNode) {
 195                     EntryProxyNode proxy = (EntryProxyNode) value;
 196                     /*
 197                      * We need to drop the stamp since the types we see during OSR may be too
 198                      * precise (if a branch was not parsed for example). In cases when this is
 199                      * possible, we insert a guard and narrow the OSRLocal stamp at its usages.
 200                      */
 201                     Stamp narrowedStamp = proxy.value().stamp(NodeView.DEFAULT);
 202                     Stamp unrestrictedStamp = proxy.stamp(NodeView.DEFAULT).unrestricted();
 203                     ValueNode osrLocal;
 204                     if (i >= localsSize) {
 205                         osrLocal = graph.addOrUnique(new OSRLockNode(i - localsSize, unrestrictedStamp));
 206                     } else {
 207                         osrLocal = graph.addOrUnique(new OSRLocalNode(i, unrestrictedStamp));
 208                     }
 209                     // Speculate on the OSRLocal stamps that could be more precise.
 210                     SpeculationReason reason = OSR_LOCAL_SPECULATIONS.createSpeculationReason(osrState.bci, narrowedStamp, i);
 211                     if (graph.getSpeculationLog().maySpeculate(reason) && osrLocal instanceof OSRLocalNode && value.getStackKind().equals(JavaKind.Object) && !narrowedStamp.isUnrestricted()) {
 212                         // Add guard.
 213                         LogicNode check = graph.addOrUniqueWithInputs(InstanceOfNode.createHelper((ObjectStamp) narrowedStamp, osrLocal, null, null));
 214                         SpeculationLog.Speculation constant = graph.getSpeculationLog().speculate(reason);
 215                         FixedGuardNode guard = graph.add(new FixedGuardNode(check, DeoptimizationReason.OptimizedTypeCheckViolated, DeoptimizationAction.InvalidateRecompile, constant, false));
 216                         graph.addAfterFixed(osrStart, guard);
 217 
 218                         // Replace with a more specific type at usages.
 219                         // We know that we are at the root,
 220                         // so we need to replace the proxy in the state.
 221                         proxy.replaceAtMatchingUsages(osrLocal, n -> n == osrState);
 222                         osrLocal = graph.addOrUnique(new PiNode(osrLocal, narrowedStamp, guard));
 223                     }
 224                     proxy.replaceAndDelete(osrLocal);
 225                 } else {
 226                     assert value == null || value instanceof OSRLocalNode;
 227                 }
 228             }
 229 
 230             osr.replaceAtUsages(InputType.Guard, osrStart);
 231         }
 232         debug.dump(DebugContext.DETAILED_LEVEL, graph, "OnStackReplacement after replacing entry proxies");
 233         GraphUtil.killCFG(start);
 234         debug.dump(DebugContext.DETAILED_LEVEL, graph, "OnStackReplacement result");
 235         new DeadCodeEliminationPhase(Required).apply(graph);
 236 
 237         if (currentOSRWithLocks) {
 238             OsrWithLocksCount.increment(debug);
 239             try (DebugCloseable context = osrStart.withNodeSourcePosition()) {
 240                 for (int i = osrState.monitorIdCount() - 1; i >= 0; --i) {
 241                     MonitorIdNode id = osrState.monitorIdAt(i);
 242                     ValueNode lockedObject = osrState.lockAt(i);
 243                     OSRMonitorEnterNode osrMonitorEnter = graph.add(new OSRMonitorEnterNode(lockedObject, id));
 244                     for (Node usage : id.usages()) {
 245                         if (usage instanceof AccessMonitorNode) {
 246                             AccessMonitorNode access = (AccessMonitorNode) usage;
 247                             access.setObject(lockedObject);
 248                         }
 249                     }
 250                     FixedNode oldNext = osrStart.next();
 251                     oldNext.replaceAtPredecessor(null);
 252                     osrMonitorEnter.setNext(oldNext);
 253                     osrStart.setNext(osrMonitorEnter);
 254                 }
 255             }
 256 
 257             debug.dump(DebugContext.DETAILED_LEVEL, graph, "After inserting OSR monitor enters");
 258             /*
 259              * Ensure balanced monitorenter - monitorexit
 260              *
 261              * Ensure that there is no monitor exit without a monitor enter in the graph. If there
 262              * is one this can only be done by bytecode as we have the monitor enter before the OSR
 263              * loop but the exit in a path of the loop that must be under a condition, else it will
 264              * throw an IllegalStateException anyway in the 2.iteration
 265              */
 266             for (MonitorExitNode exit : graph.getNodes(MonitorExitNode.TYPE)) {
 267                 MonitorIdNode id = exit.getMonitorId();
 268                 if (id.usages().filter(MonitorEnterNode.class).count() != 1) {
 269                     throw new PermanentBailoutException("Unbalanced monitor enter-exit in OSR compilation with locks. Object is locked before the loop but released inside the loop.");
 270                 }
 271             }
 272         }
 273         debug.dump(DebugContext.DETAILED_LEVEL, graph, "OnStackReplacement result");
 274         new DeadCodeEliminationPhase(Required).apply(graph);
 275         /*
 276          * There must not be any parameter nodes left after OSR compilation.
 277          */
 278         assert graph.getNodes(ParameterNode.TYPE).count() == 0 : "OSR Compilation contains references to parameters.";
 279     }
 280 
 281     private static EntryMarkerNode getEntryMarker(StructuredGraph graph) {
 282         NodeIterable<EntryMarkerNode> osrNodes = graph.getNodes(EntryMarkerNode.TYPE);
 283         EntryMarkerNode osr = osrNodes.first();
 284         if (osr == null) {
 285             throw new PermanentBailoutException("No OnStackReplacementNode generated");
 286         }
 287         if (osrNodes.count() > 1) {
 288             throw new GraalError("Multiple OnStackReplacementNodes generated");
 289         }
 290         if (osr.stateAfter().stackSize() != 0) {
 291             throw new PermanentBailoutException("OSR with stack entries not supported: %s", osr.stateAfter().toString(Verbosity.Debugger));
 292         }
 293         return osr;
 294     }
 295 
 296     private static LoopBeginNode osrLoop(EntryMarkerNode osr) {
 297         // Check that there is an OSR loop for the OSR begin
 298         LoopsData loops = new LoopsData(osr.graph());
 299         Loop<Block> l = loops.getCFG().getNodeToBlock().get(osr).getLoop();
 300         if (l == null) {
 301             return null;
 302         }
 303         return (LoopBeginNode) l.getHeader().getBeginNode();
 304     }
 305 
 306     private static boolean osrWithLocks(EntryMarkerNode osr) {
 307         return osr.stateAfter().locksSize() != 0;
 308     }
 309 
 310     @Override
 311     public float codeSizeIncrease() {
 312         return 5.0f;
 313     }
 314 }