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.core.test;
  26 
  27 import static java.lang.reflect.Modifier.isStatic;
  28 import static jdk.vm.ci.runtime.JVMCICompiler.INVOCATION_ENTRY_BCI;
  29 import static org.graalvm.compiler.nodes.ConstantNode.getConstantNodes;
  30 import static org.graalvm.compiler.nodes.graphbuilderconf.InlineInvokePlugin.InlineInfo.DO_NOT_INLINE_NO_EXCEPTION;
  31 import static org.graalvm.compiler.nodes.graphbuilderconf.InlineInvokePlugin.InlineInfo.DO_NOT_INLINE_WITH_EXCEPTION;
  32 
  33 import java.lang.annotation.ElementType;
  34 import java.lang.annotation.Retention;
  35 import java.lang.annotation.RetentionPolicy;
  36 import java.lang.annotation.Target;
  37 import java.lang.reflect.Constructor;
  38 import java.lang.reflect.Executable;
  39 import java.lang.reflect.InvocationTargetException;
  40 import java.lang.reflect.Method;
  41 import java.util.ArrayList;
  42 import java.util.Arrays;
  43 import java.util.Collection;
  44 import java.util.Collections;
  45 import java.util.EnumMap;
  46 import java.util.List;
  47 import java.util.ListIterator;
  48 import java.util.Map;
  49 import java.util.Set;
  50 import java.util.concurrent.ConcurrentHashMap;
  51 import java.util.function.Supplier;
  52 
  53 import org.graalvm.compiler.api.directives.GraalDirectives;
  54 import org.graalvm.compiler.api.replacements.SnippetReflectionProvider;
  55 import org.graalvm.compiler.api.test.Graal;
  56 import org.graalvm.compiler.code.CompilationResult;
  57 import org.graalvm.compiler.core.CompilationPrinter;
  58 import org.graalvm.compiler.core.GraalCompiler;
  59 import org.graalvm.compiler.core.GraalCompiler.Request;
  60 import org.graalvm.compiler.core.common.CompilationIdentifier;
  61 import org.graalvm.compiler.core.common.type.StampFactory;
  62 import org.graalvm.compiler.core.target.Backend;
  63 import org.graalvm.compiler.debug.DebugContext;
  64 import org.graalvm.compiler.debug.DebugDumpHandler;
  65 import org.graalvm.compiler.debug.DebugDumpScope;
  66 import org.graalvm.compiler.debug.DebugHandlersFactory;
  67 import org.graalvm.compiler.debug.GraalError;
  68 import org.graalvm.compiler.debug.TTY;
  69 import org.graalvm.compiler.graph.Node;
  70 import org.graalvm.compiler.graph.NodeClass;
  71 import org.graalvm.compiler.graph.NodeMap;
  72 import org.graalvm.compiler.java.BytecodeParser;
  73 import org.graalvm.compiler.java.ComputeLoopFrequenciesClosure;
  74 import org.graalvm.compiler.java.GraphBuilderPhase;
  75 import org.graalvm.compiler.lir.asm.CompilationResultBuilderFactory;
  76 import org.graalvm.compiler.lir.phases.LIRSuites;
  77 import org.graalvm.compiler.nodeinfo.NodeInfo;
  78 import org.graalvm.compiler.nodeinfo.NodeSize;
  79 import org.graalvm.compiler.nodeinfo.Verbosity;
  80 import org.graalvm.compiler.nodes.BreakpointNode;
  81 import org.graalvm.compiler.nodes.Cancellable;
  82 import org.graalvm.compiler.nodes.ConstantNode;
  83 import org.graalvm.compiler.nodes.FixedWithNextNode;
  84 import org.graalvm.compiler.nodes.FrameState;
  85 import org.graalvm.compiler.nodes.FullInfopointNode;
  86 import org.graalvm.compiler.nodes.Invoke;
  87 import org.graalvm.compiler.nodes.InvokeNode;
  88 import org.graalvm.compiler.nodes.InvokeWithExceptionNode;
  89 import org.graalvm.compiler.nodes.ParameterNode;
  90 import org.graalvm.compiler.nodes.ProxyNode;
  91 import org.graalvm.compiler.nodes.ReturnNode;
  92 import org.graalvm.compiler.nodes.StructuredGraph;
  93 import org.graalvm.compiler.nodes.StructuredGraph.AllowAssumptions;
  94 import org.graalvm.compiler.nodes.StructuredGraph.Builder;
  95 import org.graalvm.compiler.nodes.StructuredGraph.ScheduleResult;
  96 import org.graalvm.compiler.nodes.ValueNode;
  97 import org.graalvm.compiler.nodes.cfg.Block;
  98 import org.graalvm.compiler.nodes.graphbuilderconf.GraphBuilderConfiguration;
  99 import org.graalvm.compiler.nodes.graphbuilderconf.GraphBuilderConfiguration.Plugins;
 100 import org.graalvm.compiler.nodes.graphbuilderconf.GraphBuilderContext;
 101 import org.graalvm.compiler.nodes.graphbuilderconf.InlineInvokePlugin;
 102 import org.graalvm.compiler.nodes.graphbuilderconf.InvocationPlugin;
 103 import org.graalvm.compiler.nodes.graphbuilderconf.InvocationPlugins;
 104 import org.graalvm.compiler.nodes.java.AccessFieldNode;
 105 import org.graalvm.compiler.nodes.spi.LoweringProvider;
 106 import org.graalvm.compiler.nodes.spi.Replacements;
 107 import org.graalvm.compiler.nodes.virtual.VirtualObjectNode;
 108 import org.graalvm.compiler.options.OptionValues;
 109 import org.graalvm.compiler.phases.BasePhase;
 110 import org.graalvm.compiler.phases.OptimisticOptimizations;
 111 import org.graalvm.compiler.phases.Phase;
 112 import org.graalvm.compiler.phases.PhaseSuite;
 113 import org.graalvm.compiler.phases.common.CanonicalizerPhase;
 114 import org.graalvm.compiler.loop.phases.ConvertDeoptimizeToGuardPhase;
 115 import org.graalvm.compiler.phases.common.inlining.InliningPhase;
 116 import org.graalvm.compiler.phases.common.inlining.info.InlineInfo;
 117 import org.graalvm.compiler.phases.common.inlining.policy.GreedyInliningPolicy;
 118 import org.graalvm.compiler.phases.schedule.SchedulePhase;
 119 import org.graalvm.compiler.phases.schedule.SchedulePhase.SchedulingStrategy;
 120 import org.graalvm.compiler.phases.tiers.HighTierContext;
 121 import org.graalvm.compiler.phases.tiers.MidTierContext;
 122 import org.graalvm.compiler.phases.tiers.Suites;
 123 import org.graalvm.compiler.phases.tiers.TargetProvider;
 124 import org.graalvm.compiler.phases.util.Providers;
 125 import org.graalvm.compiler.printer.GraalDebugHandlersFactory;
 126 import org.graalvm.compiler.runtime.RuntimeProvider;
 127 import org.graalvm.compiler.test.AddExports;
 128 import org.graalvm.compiler.test.GraalTest;
 129 import org.graalvm.compiler.test.JLModule;
 130 import org.junit.After;
 131 import org.junit.Assert;
 132 import org.junit.Test;
 133 import org.junit.internal.AssumptionViolatedException;
 134 
 135 import jdk.vm.ci.code.Architecture;
 136 import jdk.vm.ci.code.BailoutException;
 137 import jdk.vm.ci.code.CodeCacheProvider;
 138 import jdk.vm.ci.code.InstalledCode;
 139 import jdk.vm.ci.code.TargetDescription;
 140 import jdk.vm.ci.meta.Assumptions.Assumption;
 141 import jdk.vm.ci.meta.ConstantReflectionProvider;
 142 import jdk.vm.ci.meta.DeoptimizationReason;
 143 import jdk.vm.ci.meta.JavaConstant;
 144 import jdk.vm.ci.meta.JavaKind;
 145 import jdk.vm.ci.meta.JavaType;
 146 import jdk.vm.ci.meta.MetaAccessProvider;
 147 import jdk.vm.ci.meta.ProfilingInfo;
 148 import jdk.vm.ci.meta.ResolvedJavaMethod;
 149 import jdk.vm.ci.meta.ResolvedJavaType;
 150 import jdk.vm.ci.meta.SpeculationLog;
 151 
 152 /**
 153  * Base class for Graal compiler unit tests.
 154  * <p>
 155  * White box tests for Graal compiler transformations use this pattern:
 156  * <ol>
 157  * <li>Create a graph by {@linkplain #parseEager parsing} a method.</li>
 158  * <li>Manually modify the graph (e.g. replace a parameter node with a constant).</li>
 159  * <li>Apply a transformation to the graph.</li>
 160  * <li>Assert that the transformed graph is equal to an expected graph.</li>
 161  * </ol>
 162  * <p>
 163  * See {@link InvokeHintsTest} as an example of a white box test.
 164  * <p>
 165  * Black box tests use the {@link #test(String, Object...)} or
 166  * {@link #testN(int, String, Object...)} to execute some method in the interpreter and compare its
 167  * result against that produced by a Graal compiled version of the method.
 168  * <p>
 169  * These tests will be run by the {@code mx unittest} command.
 170  */
 171 @AddExports({"java.base/jdk.internal.org.objectweb.asm", "java.base/jdk.internal.org.objectweb.asm.tree"})
 172 public abstract class GraalCompilerTest extends GraalTest {
 173 
 174     /**
 175      * Gets the initial option values provided by the Graal runtime. These are option values
 176      * typically parsed from the command line.
 177      */
 178     public static OptionValues getInitialOptions() {
 179         return Graal.getRequiredCapability(OptionValues.class);
 180     }
 181 
 182     private static final int BAILOUT_RETRY_LIMIT = 1;
 183     private final Providers providers;
 184     private final Backend backend;
 185 
 186     /**
 187      * Representative class for the {@code java.base} module.
 188      */
 189     public static final Class<?> JAVA_BASE = Class.class;
 190 
 191     /**
 192      * Exports the package named {@code packageName} declared in {@code moduleMember}'s module to
 193      * this object's module. This must be called before accessing packages that are no longer public
 194      * as of JDK 9.
 195      */
 196     protected final void exportPackage(Class<?> moduleMember, String packageName) {
 197         if (!Java8OrEarlier) {
 198             JLModule.exportPackageTo(moduleMember, packageName, getClass());
 199         }
 200     }
 201 
 202     /**
 203      * Denotes a test method that must be inlined by the {@link BytecodeParser}.
 204      */
 205     @Target({ElementType.METHOD, ElementType.CONSTRUCTOR})
 206     @Retention(RetentionPolicy.RUNTIME)
 207     public @interface BytecodeParserForceInline {
 208     }
 209 
 210     /**
 211      * Denotes a test method that must never be inlined by the {@link BytecodeParser}.
 212      */
 213     @Retention(RetentionPolicy.RUNTIME)
 214     @Target({ElementType.METHOD, ElementType.CONSTRUCTOR})
 215     public @interface BytecodeParserNeverInline {
 216         /**
 217          * Specifies if the call should be implemented with {@link InvokeWithExceptionNode} instead
 218          * of {@link InvokeNode}.
 219          */
 220         boolean invokeWithException() default false;
 221     }
 222 
 223     /**
 224      * Can be overridden by unit tests to verify properties of the graph.
 225      *
 226      * @param graph the graph at the end of HighTier
 227      */
 228     protected boolean checkHighTierGraph(StructuredGraph graph) {
 229         return true;
 230     }
 231 
 232     /**
 233      * Can be overridden by unit tests to verify properties of the graph.
 234      *
 235      * @param graph the graph at the end of MidTier
 236      */
 237     protected boolean checkMidTierGraph(StructuredGraph graph) {
 238         return true;
 239     }
 240 
 241     /**
 242      * Can be overridden by unit tests to verify properties of the graph.
 243      *
 244      * @param graph the graph at the end of LowTier
 245      */
 246     protected boolean checkLowTierGraph(StructuredGraph graph) {
 247         return true;
 248     }
 249 
 250     protected static void breakpoint() {
 251     }
 252 
 253     @SuppressWarnings("unused")
 254     protected static void breakpoint(int arg0) {
 255     }
 256 
 257     protected static void shouldBeOptimizedAway() {
 258     }
 259 
 260     protected Suites createSuites(OptionValues opts) {
 261         Suites ret = backend.getSuites().getDefaultSuites(opts).copy();
 262         ListIterator<BasePhase<? super HighTierContext>> iter = ret.getHighTier().findPhase(ConvertDeoptimizeToGuardPhase.class, true);
 263         if (iter == null) {
 264             /*
 265              * in the economy configuration, we don't have the ConvertDeoptimizeToGuard phase, so we
 266              * just select the first CanonicalizerPhase in HighTier
 267              */
 268             iter = ret.getHighTier().findPhase(CanonicalizerPhase.class);
 269         }
 270         iter.add(new Phase() {
 271 
 272             @Override
 273             protected void run(StructuredGraph graph) {
 274                 ComputeLoopFrequenciesClosure.compute(graph);
 275             }
 276 
 277             @Override
 278             public float codeSizeIncrease() {
 279                 return NodeSize.IGNORE_SIZE_CONTRACT_FACTOR;
 280             }
 281 
 282             @Override
 283             protected CharSequence getName() {
 284                 return "ComputeLoopFrequenciesPhase";
 285             }
 286         });
 287         ret.getHighTier().appendPhase(new Phase() {
 288 
 289             @Override
 290             protected void run(StructuredGraph graph) {
 291                 assert checkHighTierGraph(graph) : "failed HighTier graph check";
 292             }
 293 
 294             @Override
 295             public float codeSizeIncrease() {
 296                 return NodeSize.IGNORE_SIZE_CONTRACT_FACTOR;
 297             }
 298 
 299             @Override
 300             protected CharSequence getName() {
 301                 return "CheckGraphPhase";
 302             }
 303         });
 304         ret.getMidTier().appendPhase(new Phase() {
 305 
 306             @Override
 307             protected void run(StructuredGraph graph) {
 308                 assert checkMidTierGraph(graph) : "failed MidTier graph check";
 309             }
 310 
 311             @Override
 312             public float codeSizeIncrease() {
 313                 return NodeSize.IGNORE_SIZE_CONTRACT_FACTOR;
 314             }
 315 
 316             @Override
 317             protected CharSequence getName() {
 318                 return "CheckGraphPhase";
 319             }
 320         });
 321         ret.getLowTier().appendPhase(new Phase() {
 322 
 323             @Override
 324             protected void run(StructuredGraph graph) {
 325                 assert checkLowTierGraph(graph) : "failed LowTier graph check";
 326             }
 327 
 328             @Override
 329             public float codeSizeIncrease() {
 330                 return NodeSize.IGNORE_SIZE_CONTRACT_FACTOR;
 331             }
 332 
 333             @Override
 334             protected CharSequence getName() {
 335                 return "CheckGraphPhase";
 336             }
 337         });
 338         return ret;
 339     }
 340 
 341     protected LIRSuites createLIRSuites(OptionValues opts) {
 342         LIRSuites ret = backend.getSuites().getDefaultLIRSuites(opts).copy();
 343         return ret;
 344     }
 345 
 346     public GraalCompilerTest() {
 347         this.backend = Graal.getRequiredCapability(RuntimeProvider.class).getHostBackend();
 348         this.providers = getBackend().getProviders();
 349     }
 350 
 351     /**
 352      * Set up a test for a non-default backend. The test should check (via {@link #getBackend()} )
 353      * whether the desired backend is available.
 354      *
 355      * @param arch the name of the desired backend architecture
 356      */
 357     public GraalCompilerTest(Class<? extends Architecture> arch) {
 358         RuntimeProvider runtime = Graal.getRequiredCapability(RuntimeProvider.class);
 359         Backend b = runtime.getBackend(arch);
 360         if (b != null) {
 361             this.backend = b;
 362         } else {
 363             // Fall back to the default/host backend
 364             this.backend = runtime.getHostBackend();
 365         }
 366         this.providers = backend.getProviders();
 367     }
 368 
 369     /**
 370      * Set up a test for a non-default backend.
 371      *
 372      * @param backend the desired backend
 373      */
 374     public GraalCompilerTest(Backend backend) {
 375         this.backend = backend;
 376         this.providers = backend.getProviders();
 377     }
 378 
 379     @Override
 380     @After
 381     public void afterTest() {
 382         if (invocationPluginExtensions != null) {
 383             synchronized (this) {
 384                 if (invocationPluginExtensions != null) {
 385                     extendedInvocationPlugins.removeTestPlugins(invocationPluginExtensions);
 386                     extendedInvocationPlugins = null;
 387                     invocationPluginExtensions = null;
 388                 }
 389             }
 390         }
 391         super.afterTest();
 392     }
 393 
 394     /**
 395      * Gets a {@link DebugContext} object corresponding to {@code options}, creating a new one if
 396      * none currently exists. Debug contexts created by this method will have their
 397      * {@link DebugDumpHandler}s closed in {@link #afterTest()}.
 398      */
 399     protected DebugContext getDebugContext() {
 400         return getDebugContext(getInitialOptions(), null, null);
 401     }
 402 
 403     @Override
 404     protected Collection<DebugHandlersFactory> getDebugHandlersFactories() {
 405         return Collections.singletonList(new GraalDebugHandlersFactory(getSnippetReflection()));
 406     }
 407 
 408     protected void assertEquals(StructuredGraph expected, StructuredGraph graph) {
 409         assertEquals(expected, graph, false, true);
 410     }
 411 
 412     protected int countUnusedConstants(StructuredGraph graph) {
 413         int total = 0;
 414         for (ConstantNode node : getConstantNodes(graph)) {
 415             if (node.hasNoUsages()) {
 416                 total++;
 417             }
 418         }
 419         return total;
 420     }
 421 
 422     protected int getNodeCountExcludingUnusedConstants(StructuredGraph graph) {
 423         return graph.getNodeCount() - countUnusedConstants(graph);
 424     }
 425 
 426     protected void assertEquals(StructuredGraph expected, StructuredGraph graph, boolean excludeVirtual, boolean checkConstants) {
 427         String expectedString = getCanonicalGraphString(expected, excludeVirtual, checkConstants);
 428         String actualString = getCanonicalGraphString(graph, excludeVirtual, checkConstants);
 429         String mismatchString = compareGraphStrings(expected, expectedString, graph, actualString);
 430 
 431         if (!excludeVirtual && getNodeCountExcludingUnusedConstants(expected) != getNodeCountExcludingUnusedConstants(graph)) {
 432             expected.getDebug().dump(DebugContext.BASIC_LEVEL, expected, "Node count not matching - expected");
 433             graph.getDebug().dump(DebugContext.BASIC_LEVEL, graph, "Node count not matching - actual");
 434             Assert.fail("Graphs do not have the same number of nodes: " + expected.getNodeCount() + " vs. " + graph.getNodeCount() + "\n" + mismatchString);
 435         }
 436         if (!expectedString.equals(actualString)) {
 437             expected.getDebug().dump(DebugContext.BASIC_LEVEL, expected, "mismatching graphs - expected");
 438             graph.getDebug().dump(DebugContext.BASIC_LEVEL, graph, "mismatching graphs - actual");
 439             Assert.fail(mismatchString);
 440         }
 441     }
 442 
 443     private static String compareGraphStrings(StructuredGraph expectedGraph, String expectedString, StructuredGraph actualGraph, String actualString) {
 444         if (!expectedString.equals(actualString)) {
 445             String[] expectedLines = expectedString.split("\n");
 446             String[] actualLines = actualString.split("\n");
 447             int diffIndex = -1;
 448             int limit = Math.min(actualLines.length, expectedLines.length);
 449             String marker = " <<<";
 450             for (int i = 0; i < limit; i++) {
 451                 if (!expectedLines[i].equals(actualLines[i])) {
 452                     diffIndex = i;
 453                     break;
 454                 }
 455             }
 456             if (diffIndex == -1) {
 457                 // Prefix is the same so add some space after the prefix
 458                 diffIndex = limit;
 459                 if (actualLines.length == limit) {
 460                     actualLines = Arrays.copyOf(actualLines, limit + 1);
 461                     actualLines[diffIndex] = "";
 462                 } else {
 463                     assert expectedLines.length == limit;
 464                     expectedLines = Arrays.copyOf(expectedLines, limit + 1);
 465                     expectedLines[diffIndex] = "";
 466                 }
 467             }
 468             // Place a marker next to the first line that differs
 469             expectedLines[diffIndex] = expectedLines[diffIndex] + marker;
 470             actualLines[diffIndex] = actualLines[diffIndex] + marker;
 471             String ediff = String.join("\n", expectedLines);
 472             String adiff = String.join("\n", actualLines);
 473             return "mismatch in graphs:\n========= expected (" + expectedGraph + ") =========\n" + ediff + "\n\n========= actual (" + actualGraph + ") =========\n" + adiff;
 474         } else {
 475             return "mismatch in graphs";
 476         }
 477     }
 478 
 479     protected void assertOptimizedAway(StructuredGraph g) {
 480         Assert.assertEquals(0, g.getNodes().filter(NotOptimizedNode.class).count());
 481     }
 482 
 483     protected void assertConstantReturn(StructuredGraph graph, int value) {
 484         String graphString = getCanonicalGraphString(graph, false, true);
 485         Assert.assertEquals("unexpected number of ReturnNodes: " + graphString, graph.getNodes(ReturnNode.TYPE).count(), 1);
 486         ValueNode result = graph.getNodes(ReturnNode.TYPE).first().result();
 487         Assert.assertTrue("unexpected ReturnNode result node: " + graphString, result.isConstant());
 488         Assert.assertEquals("unexpected ReturnNode result kind: " + graphString, result.asJavaConstant().getJavaKind(), JavaKind.Int);
 489         Assert.assertEquals("unexpected ReturnNode result: " + graphString, result.asJavaConstant().asInt(), value);
 490     }
 491 
 492     protected static String getCanonicalGraphString(StructuredGraph graph, boolean excludeVirtual, boolean checkConstants) {
 493         SchedulePhase schedule = new SchedulePhase(SchedulingStrategy.EARLIEST);
 494         schedule.apply(graph);
 495         ScheduleResult scheduleResult = graph.getLastSchedule();
 496 
 497         NodeMap<Integer> canonicalId = graph.createNodeMap();
 498         int nextId = 0;
 499 
 500         List<String> constantsLines = new ArrayList<>();
 501 
 502         StringBuilder result = new StringBuilder();
 503         for (Block block : scheduleResult.getCFG().getBlocks()) {
 504             result.append("Block ").append(block).append(' ');
 505             if (block == scheduleResult.getCFG().getStartBlock()) {
 506                 result.append("* ");
 507             }
 508             result.append("-> ");
 509             for (Block succ : block.getSuccessors()) {
 510                 result.append(succ).append(' ');
 511             }
 512             result.append('\n');
 513             for (Node node : scheduleResult.getBlockToNodesMap().get(block)) {
 514                 if (node instanceof ValueNode && node.isAlive()) {
 515                     if (!excludeVirtual || !(node instanceof VirtualObjectNode || node instanceof ProxyNode || node instanceof FullInfopointNode || node instanceof ParameterNode)) {
 516                         if (node instanceof ConstantNode) {
 517                             String name = checkConstants ? node.toString(Verbosity.Name) : node.getClass().getSimpleName();
 518                             if (excludeVirtual) {
 519                                 constantsLines.add(name);
 520                             } else {
 521                                 constantsLines.add(name + "    (" + filteredUsageCount(node) + ")");
 522                             }
 523                         } else {
 524                             int id;
 525                             if (canonicalId.get(node) != null) {
 526                                 id = canonicalId.get(node);
 527                             } else {
 528                                 id = nextId++;
 529                                 canonicalId.set(node, id);
 530                             }
 531                             String name = node.getClass().getSimpleName();
 532                             result.append("  ").append(id).append('|').append(name);
 533                             if (node instanceof AccessFieldNode) {
 534                                 result.append('#');
 535                                 result.append(((AccessFieldNode) node).field());
 536                             }
 537                             if (!excludeVirtual) {
 538                                 result.append("    (");
 539                                 result.append(filteredUsageCount(node));
 540                                 result.append(')');
 541                             }
 542                             result.append('\n');
 543                         }
 544                     }
 545                 }
 546             }
 547         }
 548 
 549         StringBuilder constantsLinesResult = new StringBuilder();
 550         constantsLinesResult.append(constantsLines.size()).append(" constants:\n");
 551         Collections.sort(constantsLines);
 552         for (String s : constantsLines) {
 553             constantsLinesResult.append(s);
 554             constantsLinesResult.append('\n');
 555         }
 556 
 557         return constantsLinesResult.toString() + result.toString();
 558     }
 559 
 560     /**
 561      * @return usage count excluding {@link FrameState} usages
 562      */
 563     private static int filteredUsageCount(Node node) {
 564         return node.usages().filter(n -> !(n instanceof FrameState)).count();
 565     }
 566 
 567     /**
 568      * @param graph
 569      * @return a scheduled textual dump of {@code graph} .
 570      */
 571     protected static String getScheduledGraphString(StructuredGraph graph) {
 572         SchedulePhase schedule = new SchedulePhase(SchedulingStrategy.EARLIEST_WITH_GUARD_ORDER);
 573         schedule.apply(graph);
 574         ScheduleResult scheduleResult = graph.getLastSchedule();
 575 
 576         StringBuilder result = new StringBuilder();
 577         Block[] blocks = scheduleResult.getCFG().getBlocks();
 578         for (Block block : blocks) {
 579             result.append("Block ").append(block).append(' ');
 580             if (block == scheduleResult.getCFG().getStartBlock()) {
 581                 result.append("* ");
 582             }
 583             result.append("-> ");
 584             for (Block succ : block.getSuccessors()) {
 585                 result.append(succ).append(' ');
 586             }
 587             result.append('\n');
 588             for (Node node : scheduleResult.getBlockToNodesMap().get(block)) {
 589                 result.append(String.format("%1S\n", node));
 590             }
 591         }
 592         return result.toString();
 593     }
 594 
 595     protected Backend getBackend() {
 596         return backend;
 597     }
 598 
 599     protected final Providers getProviders() {
 600         return providers;
 601     }
 602 
 603     protected HighTierContext getDefaultHighTierContext() {
 604         return new HighTierContext(getProviders(), getDefaultGraphBuilderSuite(), getOptimisticOptimizations());
 605     }
 606 
 607     protected MidTierContext getDefaultMidTierContext() {
 608         return new MidTierContext(getProviders(), getTargetProvider(), getOptimisticOptimizations(), null);
 609     }
 610 
 611     protected SnippetReflectionProvider getSnippetReflection() {
 612         return Graal.getRequiredCapability(SnippetReflectionProvider.class);
 613     }
 614 
 615     protected TargetDescription getTarget() {
 616         return getTargetProvider().getTarget();
 617     }
 618 
 619     protected TargetProvider getTargetProvider() {
 620         return getBackend();
 621     }
 622 
 623     protected CodeCacheProvider getCodeCache() {
 624         return getProviders().getCodeCache();
 625     }
 626 
 627     protected ConstantReflectionProvider getConstantReflection() {
 628         return getProviders().getConstantReflection();
 629     }
 630 
 631     protected MetaAccessProvider getMetaAccess() {
 632         return getProviders().getMetaAccess();
 633     }
 634 
 635     protected LoweringProvider getLowerer() {
 636         return getProviders().getLowerer();
 637     }
 638 
 639     protected final BasePhase<HighTierContext> createInliningPhase() {
 640         return createInliningPhase(new CanonicalizerPhase());
 641     }
 642 
 643     protected BasePhase<HighTierContext> createInliningPhase(CanonicalizerPhase canonicalizer) {
 644         return createInliningPhase(null, canonicalizer);
 645     }
 646 
 647     static class GreedyTestInliningPolicy extends GreedyInliningPolicy {
 648         GreedyTestInliningPolicy(Map<Invoke, Double> hints) {
 649             super(hints);
 650         }
 651 
 652         @Override
 653         protected int previousLowLevelGraphSize(InlineInfo info) {
 654             // Ignore previous compiles for tests
 655             return 0;
 656         }
 657     }
 658 
 659     protected BasePhase<HighTierContext> createInliningPhase(Map<Invoke, Double> hints, CanonicalizerPhase canonicalizer) {
 660         return new InliningPhase(new GreedyTestInliningPolicy(hints), canonicalizer);
 661     }
 662 
 663     protected CompilationIdentifier getCompilationId(ResolvedJavaMethod method) {
 664         return getBackend().getCompilationIdentifier(method);
 665     }
 666 
 667     protected CompilationIdentifier getOrCreateCompilationId(final ResolvedJavaMethod installedCodeOwner, StructuredGraph graph) {
 668         if (graph != null) {
 669             return graph.compilationId();
 670         }
 671         return getCompilationId(installedCodeOwner);
 672     }
 673 
 674     protected void testN(int n, final String name, final Object... args) {
 675         final List<Throwable> errors = new ArrayList<>(n);
 676         Thread[] threads = new Thread[n];
 677         for (int i = 0; i < n; i++) {
 678             Thread t = new Thread(i + ":" + name) {
 679 
 680                 @Override
 681                 public void run() {
 682                     try {
 683                         test(name, args);
 684                     } catch (Throwable e) {
 685                         errors.add(e);
 686                     }
 687                 }
 688             };
 689             threads[i] = t;
 690             t.start();
 691         }
 692         for (int i = 0; i < n; i++) {
 693             try {
 694                 threads[i].join();
 695             } catch (InterruptedException e) {
 696                 errors.add(e);
 697             }
 698         }
 699         if (!errors.isEmpty()) {
 700             throw new MultiCauseAssertionError(errors.size() + " failures", errors.toArray(new Throwable[errors.size()]));
 701         }
 702     }
 703 
 704     protected Object referenceInvoke(ResolvedJavaMethod method, Object receiver, Object... args)
 705                     throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, InstantiationException {
 706         return invoke(method, receiver, args);
 707     }
 708 
 709     public static class Result {
 710 
 711         public final Object returnValue;
 712         public final Throwable exception;
 713 
 714         public Result(Object returnValue, Throwable exception) {
 715             this.returnValue = returnValue;
 716             this.exception = exception;
 717         }
 718 
 719         @Override
 720         public String toString() {
 721             return exception == null ? returnValue == null ? "null" : returnValue.toString() : "!" + exception;
 722         }
 723     }
 724 
 725     /**
 726      * Called before a test is executed.
 727      */
 728     protected void before(@SuppressWarnings("unused") ResolvedJavaMethod method) {
 729     }
 730 
 731     /**
 732      * Called after a test is executed.
 733      */
 734     protected void after() {
 735     }
 736 
 737     protected Result executeExpected(ResolvedJavaMethod method, Object receiver, Object... args) {
 738         before(method);
 739         try {
 740             // This gives us both the expected return value as well as ensuring that the method to
 741             // be compiled is fully resolved
 742             return new Result(referenceInvoke(method, receiver, args), null);
 743         } catch (InvocationTargetException e) {
 744             return new Result(null, e.getTargetException());
 745         } catch (Exception e) {
 746             throw new RuntimeException(e);
 747         } finally {
 748             after();
 749         }
 750     }
 751 
 752     protected Result executeActual(ResolvedJavaMethod method, Object receiver, Object... args) {
 753         return executeActual(getInitialOptions(), method, receiver, args);
 754     }
 755 
 756     protected Result executeActual(OptionValues options, ResolvedJavaMethod method, Object receiver, Object... args) {
 757         before(method);
 758         Object[] executeArgs = argsWithReceiver(receiver, args);
 759 
 760         checkArgs(method, executeArgs);
 761 
 762         InstalledCode compiledMethod = getCode(method, options);
 763         try {
 764             return new Result(compiledMethod.executeVarargs(executeArgs), null);
 765         } catch (Throwable e) {
 766             return new Result(null, e);
 767         } finally {
 768             after();
 769         }
 770     }
 771 
 772     protected void checkArgs(ResolvedJavaMethod method, Object[] args) {
 773         JavaType[] sig = method.toParameterTypes();
 774         Assert.assertEquals(sig.length, args.length);
 775         for (int i = 0; i < args.length; i++) {
 776             JavaType javaType = sig[i];
 777             JavaKind kind = javaType.getJavaKind();
 778             Object arg = args[i];
 779             if (kind == JavaKind.Object) {
 780                 if (arg != null && javaType instanceof ResolvedJavaType) {
 781                     ResolvedJavaType resolvedJavaType = (ResolvedJavaType) javaType;
 782                     Assert.assertTrue(resolvedJavaType + " from " + getMetaAccess().lookupJavaType(arg.getClass()), resolvedJavaType.isAssignableFrom(getMetaAccess().lookupJavaType(arg.getClass())));
 783                 }
 784             } else {
 785                 Assert.assertNotNull(arg);
 786                 Assert.assertEquals(kind.toBoxedJavaClass(), arg.getClass());
 787             }
 788         }
 789     }
 790 
 791     /**
 792      * Prepends a non-null receiver argument to a given list or args.
 793      *
 794      * @param receiver the receiver argument to prepend if it is non-null
 795      */
 796     protected Object[] argsWithReceiver(Object receiver, Object... args) {
 797         Object[] executeArgs;
 798         if (receiver == null) {
 799             executeArgs = args;
 800         } else {
 801             executeArgs = new Object[args.length + 1];
 802             executeArgs[0] = receiver;
 803             for (int i = 0; i < args.length; i++) {
 804                 executeArgs[i + 1] = args[i];
 805             }
 806         }
 807         return applyArgSuppliers(executeArgs);
 808     }
 809 
 810     protected final Result test(String name, Object... args) {
 811         return test(getInitialOptions(), name, args);
 812     }
 813 
 814     protected final Result test(OptionValues options, String name, Object... args) {
 815         try {
 816             ResolvedJavaMethod method = getResolvedJavaMethod(name);
 817             Object receiver = method.isStatic() ? null : this;
 818             return test(options, method, receiver, args);
 819         } catch (AssumptionViolatedException e) {
 820             // Suppress so that subsequent calls to this method within the
 821             // same Junit @Test annotated method can proceed.
 822             return null;
 823         }
 824     }
 825 
 826     /**
 827      * Type denoting a lambda that supplies a fresh value each time it is called. This is useful
 828      * when supplying an argument to {@link GraalCompilerTest#test(String, Object...)} where the
 829      * test modifies the state of the argument (e.g., updates a field).
 830      */
 831     @FunctionalInterface
 832     public interface ArgSupplier extends Supplier<Object> {
 833     }
 834 
 835     /**
 836      * Convenience method for using an {@link ArgSupplier} lambda in a varargs list.
 837      */
 838     public static Object supply(ArgSupplier supplier) {
 839         return supplier;
 840     }
 841 
 842     protected Result test(ResolvedJavaMethod method, Object receiver, Object... args) {
 843         return test(getInitialOptions(), method, receiver, args);
 844     }
 845 
 846     protected Result test(OptionValues options, ResolvedJavaMethod method, Object receiver, Object... args) {
 847         Result expect = executeExpected(method, receiver, args);
 848         if (getCodeCache() != null) {
 849             testAgainstExpected(options, method, expect, receiver, args);
 850         }
 851         return expect;
 852     }
 853 
 854     /**
 855      * Process a given set of arguments, converting any {@link ArgSupplier} argument to the argument
 856      * it supplies.
 857      */
 858     protected Object[] applyArgSuppliers(Object... args) {
 859         Object[] res = args;
 860         for (int i = 0; i < args.length; i++) {
 861             if (args[i] instanceof ArgSupplier) {
 862                 if (res == args) {
 863                     res = args.clone();
 864                 }
 865                 res[i] = ((ArgSupplier) args[i]).get();
 866             }
 867         }
 868         return res;
 869     }
 870 
 871     protected final void testAgainstExpected(ResolvedJavaMethod method, Result expect, Object receiver, Object... args) {
 872         testAgainstExpected(getInitialOptions(), method, expect, Collections.<DeoptimizationReason> emptySet(), receiver, args);
 873     }
 874 
 875     protected void testAgainstExpected(ResolvedJavaMethod method, Result expect, Set<DeoptimizationReason> shouldNotDeopt, Object receiver, Object... args) {
 876         testAgainstExpected(getInitialOptions(), method, expect, shouldNotDeopt, receiver, args);
 877     }
 878 
 879     protected final void testAgainstExpected(OptionValues options, ResolvedJavaMethod method, Result expect, Object receiver, Object... args) {
 880         testAgainstExpected(options, method, expect, Collections.<DeoptimizationReason> emptySet(), receiver, args);
 881     }
 882 
 883     protected void testAgainstExpected(OptionValues options, ResolvedJavaMethod method, Result expect, Set<DeoptimizationReason> shouldNotDeopt, Object receiver, Object... args) {
 884         Result actual = executeActualCheckDeopt(options, method, shouldNotDeopt, receiver, args);
 885         assertEquals(expect, actual);
 886     }
 887 
 888     protected Result executeActualCheckDeopt(OptionValues options, ResolvedJavaMethod method, Set<DeoptimizationReason> shouldNotDeopt, Object receiver, Object... args) {
 889         Map<DeoptimizationReason, Integer> deoptCounts = new EnumMap<>(DeoptimizationReason.class);
 890         ProfilingInfo profile = method.getProfilingInfo();
 891         for (DeoptimizationReason reason : shouldNotDeopt) {
 892             deoptCounts.put(reason, profile.getDeoptimizationCount(reason));
 893         }
 894         Result actual = executeActual(options, method, receiver, args);
 895         profile = method.getProfilingInfo(); // profile can change after execution
 896         for (DeoptimizationReason reason : shouldNotDeopt) {
 897             Assert.assertEquals("wrong number of deopt counts for " + reason, (int) deoptCounts.get(reason), profile.getDeoptimizationCount(reason));
 898         }
 899         return actual;
 900     }
 901 
 902     private static final List<Class<?>> C2_OMIT_STACK_TRACE_IN_FAST_THROW_EXCEPTIONS = Arrays.asList(
 903                     ArithmeticException.class,
 904                     ArrayIndexOutOfBoundsException.class,
 905                     ArrayStoreException.class,
 906                     ClassCastException.class,
 907                     NullPointerException.class);
 908 
 909     protected void assertEquals(Result expect, Result actual) {
 910         if (expect.exception != null) {
 911             Assert.assertTrue("expected " + expect.exception, actual.exception != null);
 912             Assert.assertEquals("Exception class", expect.exception.getClass(), actual.exception.getClass());
 913             // C2 can optimize out the stack trace and message in some cases
 914             if (expect.exception.getMessage() != null || !C2_OMIT_STACK_TRACE_IN_FAST_THROW_EXCEPTIONS.contains(expect.exception.getClass())) {
 915                 Assert.assertEquals("Exception message", expect.exception.getMessage(), actual.exception.getMessage());
 916             }
 917         } else {
 918             if (actual.exception != null) {
 919                 throw new AssertionError("expected " + expect.returnValue + " but got an exception", actual.exception);
 920             }
 921             assertDeepEquals(expect.returnValue, actual.returnValue);
 922         }
 923     }
 924 
 925     private Map<ResolvedJavaMethod, InstalledCode> cache = new ConcurrentHashMap<>();
 926 
 927     /**
 928      * Gets installed code for a given method, compiling it first if necessary. The graph is parsed
 929      * {@link #parseEager eagerly}.
 930      */
 931     protected final InstalledCode getCode(ResolvedJavaMethod method) {
 932         return getCode(method, null, false, false, getInitialOptions());
 933     }
 934 
 935     protected final InstalledCode getCode(ResolvedJavaMethod method, OptionValues options) {
 936         return getCode(method, null, false, false, options);
 937     }
 938 
 939     /**
 940      * Gets installed code for a given method, compiling it first if necessary.
 941      *
 942      * @param installedCodeOwner the method the compiled code will be associated with when installed
 943      * @param graph the graph to be compiled. If null, a graph will be obtained from
 944      *            {@code installedCodeOwner} via {@link #parseForCompile(ResolvedJavaMethod)}.
 945      */
 946     protected final InstalledCode getCode(ResolvedJavaMethod installedCodeOwner, StructuredGraph graph) {
 947         return getCode(installedCodeOwner, graph, false, false, graph == null ? getInitialOptions() : graph.getOptions());
 948     }
 949 
 950     /**
 951      * Gets installed code for a given method and graph, compiling it first if necessary.
 952      *
 953      * @param installedCodeOwner the method the compiled code will be associated with when installed
 954      * @param graph the graph to be compiled. If null, a graph will be obtained from
 955      *            {@code installedCodeOwner} via {@link #parseForCompile(ResolvedJavaMethod)}.
 956      * @param forceCompile specifies whether to ignore any previous code cached for the (method,
 957      *            key) pair
 958      */
 959     protected final InstalledCode getCode(final ResolvedJavaMethod installedCodeOwner, StructuredGraph graph, boolean forceCompile) {
 960         return getCode(installedCodeOwner, graph, forceCompile, false, graph == null ? getInitialOptions() : graph.getOptions());
 961     }
 962 
 963     /**
 964      * Gets installed code for a given method and graph, compiling it first if necessary.
 965      *
 966      * @param installedCodeOwner the method the compiled code will be associated with when installed
 967      * @param graph the graph to be compiled. If null, a graph will be obtained from
 968      *            {@code installedCodeOwner} via {@link #parseForCompile(ResolvedJavaMethod)}.
 969      * @param forceCompile specifies whether to ignore any previous code cached for the (method,
 970      *            key) pair
 971      * @param installAsDefault specifies whether to install as the default implementation
 972      * @param options the options that will be used in {@link #parseForCompile(ResolvedJavaMethod)}
 973      */
 974     @SuppressWarnings("try")
 975     protected InstalledCode getCode(final ResolvedJavaMethod installedCodeOwner, StructuredGraph graph, boolean forceCompile, boolean installAsDefault, OptionValues options) {
 976         boolean useCache = !forceCompile && getArgumentToBind() == null;
 977         if (useCache && graph == null) {
 978             InstalledCode cached = cache.get(installedCodeOwner);
 979             if (cached != null) {
 980                 if (cached.isValid()) {
 981                     return cached;
 982                 }
 983             }
 984         }
 985         // loop for retrying compilation
 986         for (int retry = 0; retry <= BAILOUT_RETRY_LIMIT; retry++) {
 987             final CompilationIdentifier id = getOrCreateCompilationId(installedCodeOwner, graph);
 988 
 989             InstalledCode installedCode = null;
 990             StructuredGraph graphToCompile = graph == null ? parseForCompile(installedCodeOwner, id, options) : graph;
 991             DebugContext debug = graphToCompile.getDebug();
 992 
 993             try (AllocSpy spy = AllocSpy.open(installedCodeOwner); DebugContext.Scope ds = debug.scope("Compiling", new DebugDumpScope(id.toString(CompilationIdentifier.Verbosity.ID), true))) {
 994                 CompilationPrinter printer = CompilationPrinter.begin(options, id, installedCodeOwner, INVOCATION_ENTRY_BCI);
 995                 CompilationResult compResult = compile(installedCodeOwner, graphToCompile, new CompilationResult(graphToCompile.compilationId()), id, options);
 996                 printer.finish(compResult);
 997 
 998                 try (DebugContext.Scope s = debug.scope("CodeInstall", getCodeCache(), installedCodeOwner, compResult);
 999                                 DebugContext.Activation a = debug.activate()) {
1000                     try {
1001                         if (installAsDefault) {
1002                             installedCode = addDefaultMethod(debug, installedCodeOwner, compResult);
1003                         } else {
1004                             installedCode = addMethod(debug, installedCodeOwner, compResult);
1005                         }
1006                         if (installedCode == null) {
1007                             throw new GraalError("Could not install code for " + installedCodeOwner.format("%H.%n(%p)"));
1008                         }
1009                     } catch (BailoutException e) {
1010                         if (retry < BAILOUT_RETRY_LIMIT && graph == null && !e.isPermanent()) {
1011                             // retry (if there is no predefined graph)
1012                             TTY.println(String.format("Restart compilation %s (%s) due to a non-permanent bailout!", installedCodeOwner, id));
1013                             continue;
1014                         }
1015                         throw e;
1016                     }
1017                 } catch (Throwable e) {
1018                     throw debug.handle(e);
1019                 }
1020             } catch (Throwable e) {
1021                 throw debug.handle(e);
1022             }
1023 
1024             if (useCache) {
1025                 cache.put(installedCodeOwner, installedCode);
1026             }
1027             return installedCode;
1028         }
1029         throw GraalError.shouldNotReachHere();
1030     }
1031 
1032     /**
1033      * Used to produce a graph for a method about to be compiled by
1034      * {@link #compile(ResolvedJavaMethod, StructuredGraph)} if the second parameter to that method
1035      * is null.
1036      *
1037      * The default implementation in {@link GraalCompilerTest} is to call {@link #parseEager}.
1038      */
1039     protected StructuredGraph parseForCompile(ResolvedJavaMethod method, OptionValues options) {
1040         return parseEager(method, AllowAssumptions.YES, getCompilationId(method), options);
1041     }
1042 
1043     protected final StructuredGraph parseForCompile(ResolvedJavaMethod method, DebugContext debug) {
1044         return parseEager(method, AllowAssumptions.YES, debug);
1045     }
1046 
1047     protected final StructuredGraph parseForCompile(ResolvedJavaMethod method) {
1048         return parseEager(method, AllowAssumptions.YES, getCompilationId(method), getInitialOptions());
1049     }
1050 
1051     protected StructuredGraph parseForCompile(ResolvedJavaMethod method, CompilationIdentifier compilationId, OptionValues options) {
1052         return parseEager(method, AllowAssumptions.YES, compilationId, options);
1053     }
1054 
1055     /**
1056      * Compiles a given method.
1057      *
1058      * @param installedCodeOwner the method the compiled code will be associated with when installed
1059      * @param graph the graph to be compiled for {@code installedCodeOwner}. If null, a graph will
1060      *            be obtained from {@code installedCodeOwner} via
1061      *            {@link #parseForCompile(ResolvedJavaMethod)}.
1062      */
1063     protected final CompilationResult compile(ResolvedJavaMethod installedCodeOwner, StructuredGraph graph) {
1064         OptionValues options = graph == null ? getInitialOptions() : graph.getOptions();
1065         CompilationIdentifier compilationId = getOrCreateCompilationId(installedCodeOwner, graph);
1066         return compile(installedCodeOwner, graph, new CompilationResult(compilationId), compilationId, options);
1067     }
1068 
1069     protected final CompilationResult compile(ResolvedJavaMethod installedCodeOwner, StructuredGraph graph, CompilationIdentifier compilationId) {
1070         OptionValues options = graph == null ? getInitialOptions() : graph.getOptions();
1071         return compile(installedCodeOwner, graph, new CompilationResult(compilationId), compilationId, options);
1072     }
1073 
1074     protected final CompilationResult compile(ResolvedJavaMethod installedCodeOwner, StructuredGraph graph, OptionValues options) {
1075         assert graph == null || graph.getOptions() == options;
1076         CompilationIdentifier compilationId = getOrCreateCompilationId(installedCodeOwner, graph);
1077         return compile(installedCodeOwner, graph, new CompilationResult(compilationId), compilationId, options);
1078     }
1079 
1080     protected OptimisticOptimizations getOptimisticOptimizations() {
1081         return OptimisticOptimizations.ALL;
1082     }
1083 
1084     /**
1085      * Compiles a given method.
1086      *
1087      * @param installedCodeOwner the method the compiled code will be associated with when installed
1088      * @param graph the graph to be compiled for {@code installedCodeOwner}. If null, a graph will
1089      *            be obtained from {@code installedCodeOwner} via
1090      *            {@link #parseForCompile(ResolvedJavaMethod)}.
1091      * @param compilationId
1092      */
1093     @SuppressWarnings("try")
1094     protected CompilationResult compile(ResolvedJavaMethod installedCodeOwner, StructuredGraph graph, CompilationResult compilationResult, CompilationIdentifier compilationId, OptionValues options) {
1095         StructuredGraph graphToCompile = graph == null ? parseForCompile(installedCodeOwner, compilationId, options) : graph;
1096         lastCompiledGraph = graphToCompile;
1097         DebugContext debug = graphToCompile.getDebug();
1098         try (DebugContext.Scope s = debug.scope("Compile", graphToCompile)) {
1099             assert options != null;
1100             Request<CompilationResult> request = new Request<>(graphToCompile, installedCodeOwner, getProviders(), getBackend(), getDefaultGraphBuilderSuite(), getOptimisticOptimizations(),
1101                             graphToCompile.getProfilingInfo(), createSuites(options), createLIRSuites(options), compilationResult, CompilationResultBuilderFactory.Default, true);
1102             return GraalCompiler.compile(request);
1103         } catch (Throwable e) {
1104             throw debug.handle(e);
1105         }
1106     }
1107 
1108     protected StructuredGraph getFinalGraph(String method) {
1109         return getFinalGraph(getResolvedJavaMethod(method));
1110     }
1111 
1112     protected StructuredGraph getFinalGraph(ResolvedJavaMethod method) {
1113         StructuredGraph graph = parseForCompile(method);
1114         applyFrontEnd(graph);
1115         return graph;
1116     }
1117 
1118     protected void applyFrontEnd(StructuredGraph graph) {
1119         GraalCompiler.emitFrontEnd(getProviders(), getBackend(), graph, getDefaultGraphBuilderSuite(), getOptimisticOptimizations(), graph.getProfilingInfo(), createSuites(graph.getOptions()));
1120     }
1121 
1122     protected StructuredGraph lastCompiledGraph;
1123 
1124     protected SpeculationLog getSpeculationLog() {
1125         return null;
1126     }
1127 
1128     protected InstalledCode addMethod(DebugContext debug, final ResolvedJavaMethod method, final CompilationResult compilationResult) {
1129         return backend.addInstalledCode(debug, method, null, compilationResult);
1130     }
1131 
1132     protected InstalledCode addDefaultMethod(DebugContext debug, final ResolvedJavaMethod method, final CompilationResult compilationResult) {
1133         return backend.createDefaultInstalledCode(debug, method, compilationResult);
1134     }
1135 
1136     private final Map<ResolvedJavaMethod, Executable> methodMap = new ConcurrentHashMap<>();
1137 
1138     /**
1139      * Converts a reflection {@link Method} to a {@link ResolvedJavaMethod}.
1140      */
1141     protected ResolvedJavaMethod asResolvedJavaMethod(Executable method) {
1142         ResolvedJavaMethod javaMethod = getMetaAccess().lookupJavaMethod(method);
1143         methodMap.put(javaMethod, method);
1144         return javaMethod;
1145     }
1146 
1147     protected ResolvedJavaMethod getResolvedJavaMethod(String methodName) {
1148         return asResolvedJavaMethod(getMethod(methodName));
1149     }
1150 
1151     protected ResolvedJavaMethod getResolvedJavaMethod(Class<?> clazz, String methodName) {
1152         return asResolvedJavaMethod(getMethod(clazz, methodName));
1153     }
1154 
1155     protected ResolvedJavaMethod getResolvedJavaMethod(Class<?> clazz, String methodName, Class<?>... parameterTypes) {
1156         return asResolvedJavaMethod(getMethod(clazz, methodName, parameterTypes));
1157     }
1158 
1159     /**
1160      * Gets the reflection {@link Method} from which a given {@link ResolvedJavaMethod} was created
1161      * or null if {@code javaMethod} does not correspond to a reflection method.
1162      */
1163     protected Executable lookupMethod(ResolvedJavaMethod javaMethod) {
1164         return methodMap.get(javaMethod);
1165     }
1166 
1167     @SuppressWarnings("deprecation")
1168     protected Object invoke(ResolvedJavaMethod javaMethod, Object receiver, Object... args) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, InstantiationException {
1169         Executable method = lookupMethod(javaMethod);
1170         Assert.assertTrue(method != null);
1171         if (!method.isAccessible()) {
1172             method.setAccessible(true);
1173         }
1174         if (method instanceof Method) {
1175             return ((Method) method).invoke(receiver, applyArgSuppliers(args));
1176         }
1177         assert receiver == null : "no receiver for constructor invokes";
1178         return ((Constructor<?>) method).newInstance(applyArgSuppliers(args));
1179     }
1180 
1181     /**
1182      * Parses a Java method in {@linkplain GraphBuilderConfiguration#getDefault default} mode to
1183      * produce a graph.
1184      *
1185      * @param methodName the name of the method in {@code this.getClass()} to be parsed
1186      * @param allowAssumptions specifies if {@link Assumption}s can be made compiling the graph
1187      */
1188     protected final StructuredGraph parseProfiled(String methodName, AllowAssumptions allowAssumptions) {
1189         ResolvedJavaMethod method = getResolvedJavaMethod(methodName);
1190         return parse(builder(method, allowAssumptions), getDefaultGraphBuilderSuite());
1191     }
1192 
1193     /**
1194      * Parses a Java method in {@linkplain GraphBuilderConfiguration#getDefault default} mode to
1195      * produce a graph.
1196      *
1197      * @param method the method to be parsed
1198      * @param allowAssumptions specifies if {@link Assumption}s can be made compiling the graph
1199      */
1200     protected final StructuredGraph parseProfiled(ResolvedJavaMethod method, AllowAssumptions allowAssumptions) {
1201         return parse(builder(method, allowAssumptions), getDefaultGraphBuilderSuite());
1202     }
1203 
1204     /**
1205      * Parses a Java method with {@linkplain GraphBuilderConfiguration#withEagerResolving(boolean)}
1206      * set to true to produce a graph.
1207      *
1208      * @param methodName the name of the method in {@code this.getClass()} to be parsed
1209      * @param allowAssumptions specifies if {@link Assumption}s can be made compiling the graph
1210      */
1211     protected final StructuredGraph parseEager(String methodName, AllowAssumptions allowAssumptions) {
1212         ResolvedJavaMethod method = getResolvedJavaMethod(methodName);
1213         return parse(builder(method, allowAssumptions), getEagerGraphBuilderSuite());
1214     }
1215 
1216     /**
1217      * Parses a Java method with {@linkplain GraphBuilderConfiguration#withEagerResolving(boolean)}
1218      * set to true to produce a graph.
1219      *
1220      * @param methodName the name of the method in {@code this.getClass()} to be parsed
1221      * @param allowAssumptions specifies if {@link Assumption}s can be made compiling the graph
1222      * @param options the option values to be used when compiling the graph
1223      */
1224     protected final StructuredGraph parseEager(String methodName, AllowAssumptions allowAssumptions, OptionValues options) {
1225         ResolvedJavaMethod method = getResolvedJavaMethod(methodName);
1226         return parse(builder(method, allowAssumptions, options), getEagerGraphBuilderSuite());
1227     }
1228 
1229     protected final StructuredGraph parseEager(String methodName, AllowAssumptions allowAssumptions, DebugContext debug) {
1230         ResolvedJavaMethod method = getResolvedJavaMethod(methodName);
1231         return parse(builder(method, allowAssumptions, debug), getEagerGraphBuilderSuite());
1232     }
1233 
1234     /**
1235      * Parses a Java method with {@linkplain GraphBuilderConfiguration#withEagerResolving(boolean)}
1236      * set to true to produce a graph.
1237      *
1238      * @param method the method to be parsed
1239      * @param allowAssumptions specifies if {@link Assumption}s can be made compiling the graph
1240      */
1241     protected final StructuredGraph parseEager(ResolvedJavaMethod method, AllowAssumptions allowAssumptions) {
1242         return parse(builder(method, allowAssumptions), getEagerGraphBuilderSuite());
1243     }
1244 
1245     protected final StructuredGraph parseEager(ResolvedJavaMethod method, AllowAssumptions allowAssumptions, DebugContext debug) {
1246         return parse(builder(method, allowAssumptions, debug), getEagerGraphBuilderSuite());
1247     }
1248 
1249     /**
1250      * Parses a Java method with {@linkplain GraphBuilderConfiguration#withEagerResolving(boolean)}
1251      * set to true to produce a graph.
1252      *
1253      * @param method the method to be parsed
1254      * @param allowAssumptions specifies if {@link Assumption}s can be made compiling the graph
1255      * @param options the option values to be used when compiling the graph
1256      */
1257     protected final StructuredGraph parseEager(ResolvedJavaMethod method, AllowAssumptions allowAssumptions, OptionValues options) {
1258         return parse(builder(method, allowAssumptions, options), getEagerGraphBuilderSuite());
1259     }
1260 
1261     /**
1262      * Parses a Java method with {@linkplain GraphBuilderConfiguration#withEagerResolving(boolean)}
1263      * set to true to produce a graph.
1264      *
1265      * @param method the method to be parsed
1266      * @param allowAssumptions specifies if {@link Assumption}s can be made compiling the graph
1267      * @param compilationId the compilation identifier to be associated with the graph
1268      * @param options the option values to be used when compiling the graph
1269      */
1270     protected final StructuredGraph parseEager(ResolvedJavaMethod method, AllowAssumptions allowAssumptions, CompilationIdentifier compilationId, OptionValues options) {
1271         return parse(builder(method, allowAssumptions, compilationId, options), getEagerGraphBuilderSuite());
1272     }
1273 
1274     protected final Builder builder(ResolvedJavaMethod method, AllowAssumptions allowAssumptions, DebugContext debug) {
1275         OptionValues options = debug.getOptions();
1276         return new Builder(options, debug, allowAssumptions).method(method).compilationId(getCompilationId(method));
1277     }
1278 
1279     protected final Builder builder(ResolvedJavaMethod method, AllowAssumptions allowAssumptions) {
1280         OptionValues options = getInitialOptions();
1281         return new Builder(options, getDebugContext(options, null, method), allowAssumptions).method(method).compilationId(getCompilationId(method));
1282     }
1283 
1284     protected final Builder builder(ResolvedJavaMethod method, AllowAssumptions allowAssumptions, CompilationIdentifier compilationId, OptionValues options) {
1285         return new Builder(options, getDebugContext(options, compilationId.toString(CompilationIdentifier.Verbosity.ID), method), allowAssumptions).method(method).compilationId(compilationId);
1286     }
1287 
1288     protected final Builder builder(ResolvedJavaMethod method, AllowAssumptions allowAssumptions, OptionValues options) {
1289         return new Builder(options, getDebugContext(options, null, method), allowAssumptions).method(method).compilationId(getCompilationId(method));
1290     }
1291 
1292     protected PhaseSuite<HighTierContext> getDebugGraphBuilderSuite() {
1293         return getCustomGraphBuilderSuite(GraphBuilderConfiguration.getDefault(getDefaultGraphBuilderPlugins()).withFullInfopoints(true));
1294     }
1295 
1296     @SuppressWarnings("try")
1297     protected StructuredGraph parse(StructuredGraph.Builder builder, PhaseSuite<HighTierContext> graphBuilderSuite) {
1298         ResolvedJavaMethod javaMethod = builder.getMethod();
1299         builder.speculationLog(getSpeculationLog());
1300         if (builder.getCancellable() == null) {
1301             builder.cancellable(getCancellable(javaMethod));
1302         }
1303         assert javaMethod.getAnnotation(Test.class) == null : "shouldn't parse method with @Test annotation: " + javaMethod;
1304         StructuredGraph graph = builder.build();
1305         DebugContext debug = graph.getDebug();
1306         try (DebugContext.Scope ds = debug.scope("Parsing", javaMethod, graph)) {
1307             graphBuilderSuite.apply(graph, getDefaultHighTierContext());
1308             Object[] args = getArgumentToBind();
1309             if (args != null) {
1310                 bindArguments(graph, args);
1311             }
1312             return graph;
1313         } catch (Throwable e) {
1314             throw debug.handle(e);
1315         }
1316     }
1317 
1318     protected void bindArguments(StructuredGraph graph, Object[] argsToBind) {
1319         ResolvedJavaMethod m = graph.method();
1320         Object receiver = isStatic(m.getModifiers()) ? null : this;
1321         Object[] args = argsWithReceiver(receiver, argsToBind);
1322         JavaType[] parameterTypes = m.toParameterTypes();
1323         assert parameterTypes.length == args.length;
1324         for (ParameterNode param : graph.getNodes(ParameterNode.TYPE)) {
1325             JavaConstant c = getSnippetReflection().forBoxed(parameterTypes[param.index()].getJavaKind(), args[param.index()]);
1326             ConstantNode replacement = ConstantNode.forConstant(c, getMetaAccess(), graph);
1327             param.replaceAtUsages(replacement);
1328         }
1329     }
1330 
1331     protected Object[] getArgumentToBind() {
1332         return null;
1333     }
1334 
1335     protected PhaseSuite<HighTierContext> getEagerGraphBuilderSuite() {
1336         return getCustomGraphBuilderSuite(GraphBuilderConfiguration.getDefault(getDefaultGraphBuilderPlugins()).withEagerResolving(true).withUnresolvedIsError(true));
1337     }
1338 
1339     /**
1340      * Gets the cancellable that should be associated with a graph being created by any of the
1341      * {@code parse...()} methods.
1342      *
1343      * @param method the method being parsed into a graph
1344      */
1345     protected Cancellable getCancellable(ResolvedJavaMethod method) {
1346         return null;
1347     }
1348 
1349     protected Plugins getDefaultGraphBuilderPlugins() {
1350         PhaseSuite<HighTierContext> suite = backend.getSuites().getDefaultGraphBuilderSuite();
1351         Plugins defaultPlugins = ((GraphBuilderPhase) suite.findPhase(GraphBuilderPhase.class).previous()).getGraphBuilderConfig().getPlugins();
1352         // defensive copying
1353         return new Plugins(defaultPlugins);
1354     }
1355 
1356     protected PhaseSuite<HighTierContext> getDefaultGraphBuilderSuite() {
1357         // defensive copying
1358         return backend.getSuites().getDefaultGraphBuilderSuite().copy();
1359     }
1360 
1361     /**
1362      * Registers extra invocation plugins for this test. The extra plugins are removed in the
1363      * {@link #afterTest()} method.
1364      *
1365      * Subclasses overriding this method should always call the same method on the super class in
1366      * case it wants to register plugins.
1367      *
1368      * @param invocationPlugins
1369      */
1370     protected void registerInvocationPlugins(InvocationPlugins invocationPlugins) {
1371         invocationPlugins.register(new InvocationPlugin() {
1372             @Override
1373             public boolean apply(GraphBuilderContext b, ResolvedJavaMethod targetMethod, Receiver receiver) {
1374                 b.add(new BreakpointNode());
1375                 return true;
1376             }
1377         }, GraalCompilerTest.class, "breakpoint");
1378         invocationPlugins.register(new InvocationPlugin() {
1379             @Override
1380             public boolean apply(GraphBuilderContext b, ResolvedJavaMethod targetMethod, Receiver receiver, ValueNode arg0) {
1381                 b.add(new BreakpointNode(arg0));
1382                 return true;
1383             }
1384         }, GraalCompilerTest.class, "breakpoint", int.class);
1385         invocationPlugins.register(new InvocationPlugin() {
1386             @Override
1387             public boolean apply(GraphBuilderContext b, ResolvedJavaMethod targetMethod, Receiver receiver) {
1388                 b.add(new NotOptimizedNode());
1389                 return true;
1390             }
1391         }, GraalCompilerTest.class, "shouldBeOptimizedAway");
1392     }
1393 
1394     /**
1395      * The {@link #testN(int, String, Object...)} method means multiple threads trying to initialize
1396      * this field.
1397      */
1398     private volatile InvocationPlugins invocationPluginExtensions;
1399 
1400     private InvocationPlugins extendedInvocationPlugins;
1401 
1402     protected PhaseSuite<HighTierContext> getCustomGraphBuilderSuite(GraphBuilderConfiguration gbConf) {
1403         PhaseSuite<HighTierContext> suite = getDefaultGraphBuilderSuite();
1404         ListIterator<BasePhase<? super HighTierContext>> iterator = suite.findPhase(GraphBuilderPhase.class);
1405         initializeInvocationPluginExtensions();
1406         GraphBuilderConfiguration gbConfCopy = editGraphBuilderConfiguration(gbConf.copy());
1407         iterator.remove();
1408         iterator.add(new GraphBuilderPhase(gbConfCopy));
1409         return suite;
1410     }
1411 
1412     private void initializeInvocationPluginExtensions() {
1413         if (invocationPluginExtensions == null) {
1414             synchronized (this) {
1415                 if (invocationPluginExtensions == null) {
1416                     InvocationPlugins invocationPlugins = new InvocationPlugins();
1417                     registerInvocationPlugins(invocationPlugins);
1418                     extendedInvocationPlugins = getReplacements().getGraphBuilderPlugins().getInvocationPlugins();
1419                     extendedInvocationPlugins.addTestPlugins(invocationPlugins, null);
1420                     invocationPluginExtensions = invocationPlugins;
1421                 }
1422             }
1423         }
1424     }
1425 
1426     protected GraphBuilderConfiguration editGraphBuilderConfiguration(GraphBuilderConfiguration conf) {
1427         conf.getPlugins().prependInlineInvokePlugin(new InlineInvokePlugin() {
1428 
1429             @Override
1430             public InlineInfo shouldInlineInvoke(GraphBuilderContext b, ResolvedJavaMethod method, ValueNode[] args) {
1431                 BytecodeParserNeverInline neverInline = method.getAnnotation(BytecodeParserNeverInline.class);
1432                 if (neverInline != null) {
1433                     return neverInline.invokeWithException() ? DO_NOT_INLINE_WITH_EXCEPTION : DO_NOT_INLINE_NO_EXCEPTION;
1434                 }
1435                 if (method.getAnnotation(BytecodeParserForceInline.class) != null) {
1436                     return InlineInfo.createStandardInlineInfo(method);
1437                 }
1438                 return bytecodeParserShouldInlineInvoke(b, method, args);
1439             }
1440         });
1441         return conf;
1442     }
1443 
1444     /**
1445      * Supplements {@link BytecodeParserForceInline} and {@link BytecodeParserNeverInline} in terms
1446      * of allowing a test to influence the inlining decision made during bytecode parsing.
1447      *
1448      * @see InlineInvokePlugin#shouldInlineInvoke(GraphBuilderContext, ResolvedJavaMethod,
1449      *      ValueNode[])
1450      */
1451     @SuppressWarnings("unused")
1452     protected InlineInvokePlugin.InlineInfo bytecodeParserShouldInlineInvoke(GraphBuilderContext b, ResolvedJavaMethod method, ValueNode[] args) {
1453         return null;
1454     }
1455 
1456     @NodeInfo
1457     public static class NotOptimizedNode extends FixedWithNextNode {
1458         private static final NodeClass<NotOptimizedNode> TYPE = NodeClass.create(NotOptimizedNode.class);
1459 
1460         protected NotOptimizedNode() {
1461             super(TYPE, StampFactory.forVoid());
1462         }
1463 
1464     }
1465 
1466     protected Replacements getReplacements() {
1467         return getProviders().getReplacements();
1468     }
1469 
1470     /**
1471      * Inject a probability for a branch condition into the profiling information of this test case.
1472      *
1473      * @param p the probability that cond is true
1474      * @param cond the condition of the branch
1475      * @return cond
1476      */
1477     protected static boolean branchProbability(double p, boolean cond) {
1478         return GraalDirectives.injectBranchProbability(p, cond);
1479     }
1480 
1481     /**
1482      * Inject an iteration count for a loop condition into the profiling information of this test
1483      * case.
1484      *
1485      * @param i the iteration count of the loop
1486      * @param cond the condition of the loop
1487      * @return cond
1488      */
1489     protected static boolean iterationCount(double i, boolean cond) {
1490         return GraalDirectives.injectIterationCount(i, cond);
1491     }
1492 
1493     /**
1494      * Test if the current test runs on the given platform. The name must match the name given in
1495      * the {@link Architecture#getName()}.
1496      *
1497      * @param name The name to test
1498      * @return true if we run on the architecture given by name
1499      */
1500     protected boolean isArchitecture(String name) {
1501         return name.equals(backend.getTarget().arch.getName());
1502     }
1503 }