001/* 002 * Copyright (c) 2011, 2015, Oracle and/or its affiliates. All rights reserved. 003 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 004 * 005 * This code is free software; you can redistribute it and/or modify it 006 * under the terms of the GNU General Public License version 2 only, as 007 * published by the Free Software Foundation. 008 * 009 * This code is distributed in the hope that it will be useful, but WITHOUT 010 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 011 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 012 * version 2 for more details (a copy is included in the LICENSE file that 013 * accompanied this code). 014 * 015 * You should have received a copy of the GNU General Public License version 016 * 2 along with this work; if not, write to the Free Software Foundation, 017 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 018 * 019 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 020 * or visit www.oracle.com if you need additional information or have any 021 * questions. 022 */ 023package com.oracle.graal.compiler.test; 024 025import static com.oracle.graal.compiler.GraalCompiler.*; 026import static com.oracle.graal.nodes.ConstantNode.*; 027import static jdk.internal.jvmci.code.CodeUtil.*; 028import static jdk.internal.jvmci.compiler.Compiler.*; 029 030import java.lang.reflect.*; 031import java.util.*; 032import java.util.concurrent.atomic.*; 033import java.util.function.*; 034 035import org.junit.*; 036import org.junit.internal.AssumptionViolatedException; 037 038import com.oracle.graal.api.directives.*; 039import com.oracle.graal.api.replacements.*; 040import com.oracle.graal.api.runtime.*; 041import com.oracle.graal.compiler.*; 042import com.oracle.graal.compiler.target.*; 043import com.oracle.graal.graph.*; 044import com.oracle.graal.graphbuilderconf.*; 045import com.oracle.graal.graphbuilderconf.GraphBuilderConfiguration.*; 046import com.oracle.graal.java.*; 047import com.oracle.graal.lir.asm.*; 048import com.oracle.graal.lir.phases.*; 049import com.oracle.graal.nodeinfo.*; 050import com.oracle.graal.nodes.*; 051import com.oracle.graal.nodes.StructuredGraph.*; 052import com.oracle.graal.nodes.cfg.*; 053import com.oracle.graal.nodes.spi.*; 054import com.oracle.graal.nodes.virtual.*; 055import com.oracle.graal.phases.*; 056import com.oracle.graal.phases.common.*; 057import com.oracle.graal.phases.schedule.*; 058import com.oracle.graal.phases.schedule.SchedulePhase.*; 059import com.oracle.graal.phases.tiers.*; 060import com.oracle.graal.phases.util.*; 061import com.oracle.graal.runtime.*; 062import com.oracle.graal.test.*; 063 064import jdk.internal.jvmci.code.*; 065import jdk.internal.jvmci.code.CallingConvention.Type; 066import jdk.internal.jvmci.common.*; 067import com.oracle.graal.debug.*; 068import com.oracle.graal.debug.Debug.*; 069 070import jdk.internal.jvmci.meta.*; 071import jdk.internal.jvmci.options.*; 072 073/** 074 * Base class for Graal compiler unit tests. 075 * <p> 076 * White box tests for Graal compiler transformations use this pattern: 077 * <ol> 078 * <li>Create a graph by {@linkplain #parseEager(String, AllowAssumptions) parsing} a method.</li> 079 * <li>Manually modify the graph (e.g. replace a parameter node with a constant).</li> 080 * <li>Apply a transformation to the graph.</li> 081 * <li>Assert that the transformed graph is equal to an expected graph.</li> 082 * </ol> 083 * <p> 084 * See {@link InvokeHintsTest} as an example of a white box test. 085 * <p> 086 * Black box tests use the {@link #test(String, Object...)} or 087 * {@link #testN(int, String, Object...)} to execute some method in the interpreter and compare its 088 * result against that produced by a Graal compiled version of the method. 089 * <p> 090 * These tests will be run by the {@code mx unittest} command. 091 */ 092public abstract class GraalCompilerTest extends GraalTest { 093 094 private final Providers providers; 095 private final Backend backend; 096 private final DerivedOptionValue<Suites> suites; 097 private final DerivedOptionValue<LIRSuites> lirSuites; 098 099 /** 100 * Can be overridden by unit tests to verify properties of the graph. 101 * 102 * @param graph the graph at the end of HighTier 103 */ 104 protected boolean checkHighTierGraph(StructuredGraph graph) { 105 return true; 106 } 107 108 /** 109 * Can be overridden by unit tests to verify properties of the graph. 110 * 111 * @param graph the graph at the end of MidTier 112 */ 113 protected boolean checkMidTierGraph(StructuredGraph graph) { 114 return true; 115 } 116 117 /** 118 * Can be overridden by unit tests to verify properties of the graph. 119 * 120 * @param graph the graph at the end of LowTier 121 */ 122 protected boolean checkLowTierGraph(StructuredGraph graph) { 123 return true; 124 } 125 126 protected static void breakpoint() { 127 } 128 129 @SuppressWarnings("unused") 130 protected static void breakpoint(int arg0) { 131 } 132 133 protected Suites createSuites() { 134 Suites ret = backend.getSuites().createSuites(); 135 ListIterator<BasePhase<? super HighTierContext>> iter = ret.getHighTier().findPhase(ConvertDeoptimizeToGuardPhase.class); 136 PhaseSuite.findNextPhase(iter, CanonicalizerPhase.class); 137 iter.add(new Phase("ComputeLoopFrequenciesPhase") { 138 139 @Override 140 protected void run(StructuredGraph graph) { 141 ComputeLoopFrequenciesClosure.compute(graph); 142 } 143 }); 144 ret.getHighTier().appendPhase(new Phase("CheckGraphPhase") { 145 146 @Override 147 protected void run(StructuredGraph graph) { 148 assert checkHighTierGraph(graph) : "failed HighTier graph check"; 149 } 150 }); 151 ret.getMidTier().appendPhase(new Phase("CheckGraphPhase") { 152 153 @Override 154 protected void run(StructuredGraph graph) { 155 assert checkMidTierGraph(graph) : "failed MidTier graph check"; 156 } 157 }); 158 ret.getLowTier().appendPhase(new Phase("CheckGraphPhase") { 159 160 @Override 161 protected void run(StructuredGraph graph) { 162 assert checkLowTierGraph(graph) : "failed LowTier graph check"; 163 } 164 }); 165 return ret; 166 } 167 168 protected LIRSuites createLIRSuites() { 169 LIRSuites ret = backend.getSuites().createLIRSuites(); 170 return ret; 171 } 172 173 public GraalCompilerTest() { 174 this.backend = Graal.getRequiredCapability(RuntimeProvider.class).getHostBackend(); 175 this.providers = getBackend().getProviders(); 176 this.suites = new DerivedOptionValue<>(this::createSuites); 177 this.lirSuites = new DerivedOptionValue<>(this::createLIRSuites); 178 } 179 180 /** 181 * Set up a test for a non-default backend. The test should check (via {@link #getBackend()} ) 182 * whether the desired backend is available. 183 * 184 * @param arch the name of the desired backend architecture 185 */ 186 public GraalCompilerTest(Class<? extends Architecture> arch) { 187 RuntimeProvider runtime = Graal.getRequiredCapability(RuntimeProvider.class); 188 Backend b = runtime.getBackend(arch); 189 if (b != null) { 190 this.backend = b; 191 } else { 192 // Fall back to the default/host backend 193 this.backend = runtime.getHostBackend(); 194 } 195 this.providers = backend.getProviders(); 196 this.suites = new DerivedOptionValue<>(this::createSuites); 197 this.lirSuites = new DerivedOptionValue<>(this::createLIRSuites); 198 } 199 200 @BeforeClass 201 public static void initializeDebugging() { 202 DebugEnvironment.initialize(System.out); 203 } 204 205 private Scope debugScope; 206 207 @Before 208 public void beforeTest() { 209 assert debugScope == null; 210 debugScope = Debug.scope(getClass()); 211 } 212 213 @After 214 public void afterTest() { 215 if (debugScope != null) { 216 debugScope.close(); 217 } 218 debugScope = null; 219 } 220 221 protected void assertEquals(StructuredGraph expected, StructuredGraph graph) { 222 assertEquals(expected, graph, false, true); 223 } 224 225 protected int countUnusedConstants(StructuredGraph graph) { 226 int total = 0; 227 for (ConstantNode node : getConstantNodes(graph)) { 228 if (node.hasNoUsages()) { 229 total++; 230 } 231 } 232 return total; 233 } 234 235 protected int getNodeCountExcludingUnusedConstants(StructuredGraph graph) { 236 return graph.getNodeCount() - countUnusedConstants(graph); 237 } 238 239 protected void assertEquals(StructuredGraph expected, StructuredGraph graph, boolean excludeVirtual, boolean checkConstants) { 240 String expectedString = getCanonicalGraphString(expected, excludeVirtual, checkConstants); 241 String actualString = getCanonicalGraphString(graph, excludeVirtual, checkConstants); 242 String mismatchString = compareGraphStrings(expected, expectedString, graph, actualString); 243 244 if (!excludeVirtual && getNodeCountExcludingUnusedConstants(expected) != getNodeCountExcludingUnusedConstants(graph)) { 245 Debug.dump(expected, "Node count not matching - expected"); 246 Debug.dump(graph, "Node count not matching - actual"); 247 Assert.fail("Graphs do not have the same number of nodes: " + expected.getNodeCount() + " vs. " + graph.getNodeCount() + "\n" + mismatchString); 248 } 249 if (!expectedString.equals(actualString)) { 250 Debug.dump(expected, "mismatching graphs - expected"); 251 Debug.dump(graph, "mismatching graphs - actual"); 252 Assert.fail(mismatchString); 253 } 254 } 255 256 private static String compareGraphStrings(StructuredGraph expectedGraph, String expectedString, StructuredGraph actualGraph, String actualString) { 257 if (!expectedString.equals(actualString)) { 258 String[] expectedLines = expectedString.split("\n"); 259 String[] actualLines = actualString.split("\n"); 260 int diffIndex = -1; 261 int limit = Math.min(actualLines.length, expectedLines.length); 262 String marker = " <<<"; 263 for (int i = 0; i < limit; i++) { 264 if (!expectedLines[i].equals(actualLines[i])) { 265 diffIndex = i; 266 break; 267 } 268 } 269 if (diffIndex == -1) { 270 // Prefix is the same so add some space after the prefix 271 diffIndex = limit; 272 if (actualLines.length == limit) { 273 actualLines = Arrays.copyOf(actualLines, limit + 1); 274 actualLines[diffIndex] = ""; 275 } else { 276 assert expectedLines.length == limit; 277 expectedLines = Arrays.copyOf(expectedLines, limit + 1); 278 expectedLines[diffIndex] = ""; 279 } 280 } 281 // Place a marker next to the first line that differs 282 expectedLines[diffIndex] = expectedLines[diffIndex] + marker; 283 actualLines[diffIndex] = actualLines[diffIndex] + marker; 284 String ediff = String.join("\n", expectedLines); 285 String adiff = String.join("\n", actualLines); 286 return "mismatch in graphs:\n========= expected (" + expectedGraph + ") =========\n" + ediff + "\n\n========= actual (" + actualGraph + ") =========\n" + adiff; 287 } else { 288 return "mismatch in graphs"; 289 } 290 } 291 292 protected void assertConstantReturn(StructuredGraph graph, int value) { 293 String graphString = getCanonicalGraphString(graph, false, true); 294 Assert.assertEquals("unexpected number of ReturnNodes: " + graphString, graph.getNodes(ReturnNode.TYPE).count(), 1); 295 ValueNode result = graph.getNodes(ReturnNode.TYPE).first().result(); 296 Assert.assertTrue("unexpected ReturnNode result node: " + graphString, result.isConstant()); 297 Assert.assertEquals("unexpected ReturnNode result kind: " + graphString, result.asJavaConstant().getKind(), Kind.Int); 298 Assert.assertEquals("unexpected ReturnNode result: " + graphString, result.asJavaConstant().asInt(), value); 299 } 300 301 protected static String getCanonicalGraphString(StructuredGraph graph, boolean excludeVirtual, boolean checkConstants) { 302 SchedulePhase schedule = new SchedulePhase(SchedulingStrategy.EARLIEST); 303 schedule.apply(graph); 304 305 NodeMap<Integer> canonicalId = graph.createNodeMap(); 306 int nextId = 0; 307 308 List<String> constantsLines = new ArrayList<>(); 309 310 StringBuilder result = new StringBuilder(); 311 for (Block block : schedule.getCFG().getBlocks()) { 312 result.append("Block " + block + " "); 313 if (block == schedule.getCFG().getStartBlock()) { 314 result.append("* "); 315 } 316 result.append("-> "); 317 for (Block succ : block.getSuccessors()) { 318 result.append(succ + " "); 319 } 320 result.append("\n"); 321 for (Node node : schedule.getBlockToNodesMap().get(block)) { 322 if (node instanceof ValueNode && node.isAlive()) { 323 if (!excludeVirtual || !(node instanceof VirtualObjectNode || node instanceof ProxyNode || node instanceof InfopointNode)) { 324 if (node instanceof ConstantNode) { 325 String name = checkConstants ? node.toString(Verbosity.Name) : node.getClass().getSimpleName(); 326 String str = name + (excludeVirtual ? "\n" : " (" + node.getUsageCount() + ")\n"); 327 constantsLines.add(str); 328 } else { 329 int id; 330 if (canonicalId.get(node) != null) { 331 id = canonicalId.get(node); 332 } else { 333 id = nextId++; 334 canonicalId.set(node, id); 335 } 336 String name = node.getClass().getSimpleName(); 337 String str = " " + id + "|" + name + (excludeVirtual ? "\n" : " (" + node.getUsageCount() + ")\n"); 338 result.append(str); 339 } 340 } 341 } 342 } 343 } 344 345 StringBuilder constantsLinesResult = new StringBuilder(); 346 constantsLinesResult.append(constantsLines.size() + " constants:\n"); 347 Collections.sort(constantsLines); 348 for (String s : constantsLines) { 349 constantsLinesResult.append(s); 350 constantsLinesResult.append("\n"); 351 } 352 353 return constantsLines.toString() + result.toString(); 354 } 355 356 protected Backend getBackend() { 357 return backend; 358 } 359 360 protected Suites getSuites() { 361 return suites.getValue(); 362 } 363 364 protected LIRSuites getLIRSuites() { 365 return lirSuites.getValue(); 366 } 367 368 protected Providers getProviders() { 369 return providers; 370 } 371 372 protected HighTierContext getDefaultHighTierContext() { 373 return new HighTierContext(getProviders(), getDefaultGraphBuilderSuite(), OptimisticOptimizations.ALL); 374 } 375 376 protected SnippetReflectionProvider getSnippetReflection() { 377 return Graal.getRequiredCapability(SnippetReflectionProvider.class); 378 } 379 380 protected TargetDescription getTarget() { 381 return getProviders().getCodeCache().getTarget(); 382 } 383 384 protected CodeCacheProvider getCodeCache() { 385 return getProviders().getCodeCache(); 386 } 387 388 protected ConstantReflectionProvider getConstantReflection() { 389 return getProviders().getConstantReflection(); 390 } 391 392 protected MetaAccessProvider getMetaAccess() { 393 return getProviders().getMetaAccess(); 394 } 395 396 protected LoweringProvider getLowerer() { 397 return getProviders().getLowerer(); 398 } 399 400 private static AtomicInteger compilationId = new AtomicInteger(); 401 402 protected void testN(int n, final String name, final Object... args) { 403 final List<Throwable> errors = new ArrayList<>(n); 404 Thread[] threads = new Thread[n]; 405 for (int i = 0; i < n; i++) { 406 Thread t = new Thread(i + ":" + name) { 407 408 @Override 409 public void run() { 410 try { 411 test(name, args); 412 } catch (Throwable e) { 413 errors.add(e); 414 } 415 } 416 }; 417 threads[i] = t; 418 t.start(); 419 } 420 for (int i = 0; i < n; i++) { 421 try { 422 threads[i].join(); 423 } catch (InterruptedException e) { 424 errors.add(e); 425 } 426 } 427 if (!errors.isEmpty()) { 428 throw new MultiCauseAssertionError(errors.size() + " failures", errors.toArray(new Throwable[errors.size()])); 429 } 430 } 431 432 protected Object referenceInvoke(ResolvedJavaMethod method, Object receiver, Object... args) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException { 433 return invoke(method, receiver, args); 434 } 435 436 protected static class Result { 437 438 public final Object returnValue; 439 public final Throwable exception; 440 441 public Result(Object returnValue, Throwable exception) { 442 this.returnValue = returnValue; 443 this.exception = exception; 444 } 445 446 @Override 447 public String toString() { 448 return exception == null ? returnValue == null ? "null" : returnValue.toString() : "!" + exception; 449 } 450 } 451 452 /** 453 * Called before a test is executed. 454 */ 455 protected void before(@SuppressWarnings("unused") ResolvedJavaMethod method) { 456 } 457 458 /** 459 * Called after a test is executed. 460 */ 461 protected void after() { 462 } 463 464 protected Result executeExpected(ResolvedJavaMethod method, Object receiver, Object... args) { 465 before(method); 466 try { 467 // This gives us both the expected return value as well as ensuring that the method to 468 // be compiled is fully resolved 469 return new Result(referenceInvoke(method, receiver, args), null); 470 } catch (InvocationTargetException e) { 471 return new Result(null, e.getTargetException()); 472 } catch (Exception e) { 473 throw new RuntimeException(e); 474 } finally { 475 after(); 476 } 477 } 478 479 protected Result executeActual(ResolvedJavaMethod method, Object receiver, Object... args) { 480 before(method); 481 Object[] executeArgs = argsWithReceiver(receiver, args); 482 483 checkArgs(method, executeArgs); 484 485 InstalledCode compiledMethod = getCode(method); 486 try { 487 return new Result(compiledMethod.executeVarargs(executeArgs), null); 488 } catch (Throwable e) { 489 return new Result(null, e); 490 } finally { 491 after(); 492 } 493 } 494 495 protected void checkArgs(ResolvedJavaMethod method, Object[] args) { 496 JavaType[] sig = method.toParameterTypes(); 497 Assert.assertEquals(sig.length, args.length); 498 for (int i = 0; i < args.length; i++) { 499 JavaType javaType = sig[i]; 500 Kind kind = javaType.getKind(); 501 Object arg = args[i]; 502 if (kind == Kind.Object) { 503 if (arg != null && javaType instanceof ResolvedJavaType) { 504 ResolvedJavaType resolvedJavaType = (ResolvedJavaType) javaType; 505 Assert.assertTrue(resolvedJavaType + " from " + getMetaAccess().lookupJavaType(arg.getClass()), resolvedJavaType.isAssignableFrom(getMetaAccess().lookupJavaType(arg.getClass()))); 506 } 507 } else { 508 Assert.assertNotNull(arg); 509 Assert.assertEquals(kind.toBoxedJavaClass(), arg.getClass()); 510 } 511 } 512 } 513 514 /** 515 * Prepends a non-null receiver argument to a given list or args. 516 * 517 * @param receiver the receiver argument to prepend if it is non-null 518 */ 519 protected Object[] argsWithReceiver(Object receiver, Object... args) { 520 Object[] executeArgs; 521 if (receiver == null) { 522 executeArgs = args; 523 } else { 524 executeArgs = new Object[args.length + 1]; 525 executeArgs[0] = receiver; 526 for (int i = 0; i < args.length; i++) { 527 executeArgs[i + 1] = args[i]; 528 } 529 } 530 return applyArgSuppliers(executeArgs); 531 } 532 533 protected void test(String name, Object... args) { 534 try { 535 ResolvedJavaMethod method = getResolvedJavaMethod(name); 536 Object receiver = method.isStatic() ? null : this; 537 test(method, receiver, args); 538 } catch (AssumptionViolatedException e) { 539 // Suppress so that subsequent calls to this method within the 540 // same Junit @Test annotated method can proceed. 541 } 542 } 543 544 /** 545 * Type denoting a lambda that supplies a fresh value each time it is called. This is useful 546 * when supplying an argument to {@link GraalCompilerTest#test(String, Object...)} where the 547 * test modifies the state of the argument (e.g., updates a field). 548 */ 549 @FunctionalInterface 550 public interface ArgSupplier extends Supplier<Object> { 551 } 552 553 /** 554 * Convenience method for using an {@link ArgSupplier} lambda in a varargs list. 555 */ 556 public static Object supply(ArgSupplier supplier) { 557 return supplier; 558 } 559 560 protected void test(ResolvedJavaMethod method, Object receiver, Object... args) { 561 Result expect = executeExpected(method, receiver, args); 562 if (getCodeCache() == null) { 563 return; 564 } 565 testAgainstExpected(method, expect, receiver, args); 566 } 567 568 /** 569 * Process a given set of arguments, converting any {@link ArgSupplier} argument to the argument 570 * it supplies. 571 */ 572 protected Object[] applyArgSuppliers(Object... args) { 573 Object[] res = args; 574 for (int i = 0; i < args.length; i++) { 575 if (args[i] instanceof ArgSupplier) { 576 if (res == args) { 577 res = args.clone(); 578 } 579 res[i] = ((ArgSupplier) args[i]).get(); 580 } 581 } 582 return res; 583 } 584 585 protected void testAgainstExpected(ResolvedJavaMethod method, Result expect, Object receiver, Object... args) { 586 testAgainstExpected(method, expect, Collections.<DeoptimizationReason> emptySet(), receiver, args); 587 } 588 589 protected Result executeActualCheckDeopt(ResolvedJavaMethod method, Set<DeoptimizationReason> shouldNotDeopt, Object receiver, Object... args) { 590 Map<DeoptimizationReason, Integer> deoptCounts = new EnumMap<>(DeoptimizationReason.class); 591 ProfilingInfo profile = method.getProfilingInfo(); 592 for (DeoptimizationReason reason : shouldNotDeopt) { 593 deoptCounts.put(reason, profile.getDeoptimizationCount(reason)); 594 } 595 Result actual = executeActual(method, receiver, args); 596 profile = method.getProfilingInfo(); // profile can change after execution 597 for (DeoptimizationReason reason : shouldNotDeopt) { 598 Assert.assertEquals((int) deoptCounts.get(reason), profile.getDeoptimizationCount(reason)); 599 } 600 return actual; 601 } 602 603 protected void assertEquals(Result expect, Result actual) { 604 if (expect.exception != null) { 605 Assert.assertTrue("expected " + expect.exception, actual.exception != null); 606 Assert.assertEquals("Exception class", expect.exception.getClass(), actual.exception.getClass()); 607 Assert.assertEquals("Exception message", expect.exception.getMessage(), actual.exception.getMessage()); 608 } else { 609 if (actual.exception != null) { 610 actual.exception.printStackTrace(); 611 Assert.fail("expected " + expect.returnValue + " but got an exception"); 612 } 613 assertDeepEquals(expect.returnValue, actual.returnValue); 614 } 615 } 616 617 protected void testAgainstExpected(ResolvedJavaMethod method, Result expect, Set<DeoptimizationReason> shouldNotDeopt, Object receiver, Object... args) { 618 Result actual = executeActualCheckDeopt(method, shouldNotDeopt, receiver, args); 619 assertEquals(expect, actual); 620 } 621 622 private Map<ResolvedJavaMethod, InstalledCode> cache = new HashMap<>(); 623 624 /** 625 * Gets installed code for a given method, compiling it first if necessary. The graph is parsed 626 * {@link #parseEager(ResolvedJavaMethod, AllowAssumptions) eagerly}. 627 */ 628 protected InstalledCode getCode(ResolvedJavaMethod method) { 629 return getCode(method, null); 630 } 631 632 /** 633 * Gets installed code for a given method, compiling it first if necessary. 634 * 635 * @param installedCodeOwner the method the compiled code will be associated with when installed 636 * @param graph the graph to be compiled. If null, a graph will be obtained from 637 * {@code installedCodeOwner} via {@link #parseForCompile(ResolvedJavaMethod)}. 638 */ 639 protected InstalledCode getCode(ResolvedJavaMethod installedCodeOwner, StructuredGraph graph) { 640 return getCode(installedCodeOwner, graph, false); 641 } 642 643 /** 644 * Gets installed code for a given method and graph, compiling it first if necessary. 645 * 646 * @param installedCodeOwner the method the compiled code will be associated with when installed 647 * @param graph the graph to be compiled. If null, a graph will be obtained from 648 * {@code installedCodeOwner} via {@link #parseForCompile(ResolvedJavaMethod)}. 649 * @param forceCompile specifies whether to ignore any previous code cached for the (method, 650 * key) pair 651 */ 652 protected InstalledCode getCode(final ResolvedJavaMethod installedCodeOwner, StructuredGraph graph, boolean forceCompile) { 653 if (!forceCompile) { 654 InstalledCode cached = cache.get(installedCodeOwner); 655 if (cached != null) { 656 if (cached.isValid()) { 657 return cached; 658 } 659 } 660 } 661 662 final int id = compilationId.incrementAndGet(); 663 664 InstalledCode installedCode = null; 665 try (AllocSpy spy = AllocSpy.open(installedCodeOwner); Scope ds = Debug.scope("Compiling", new DebugDumpScope(String.valueOf(id), true))) { 666 final boolean printCompilation = PrintCompilation.getValue() && !TTY.isSuppressed(); 667 if (printCompilation) { 668 TTY.println(String.format("@%-6d Graal %-70s %-45s %-50s ...", id, installedCodeOwner.getDeclaringClass().getName(), installedCodeOwner.getName(), installedCodeOwner.getSignature())); 669 } 670 long start = System.currentTimeMillis(); 671 CompilationResult compResult = compile(installedCodeOwner, graph); 672 if (printCompilation) { 673 TTY.println(String.format("@%-6d Graal %-70s %-45s %-50s | %4dms %5dB", id, "", "", "", System.currentTimeMillis() - start, compResult.getTargetCodeSize())); 674 } 675 676 try (Scope s = Debug.scope("CodeInstall", getCodeCache(), installedCodeOwner)) { 677 installedCode = addMethod(installedCodeOwner, compResult); 678 if (installedCode == null) { 679 throw new JVMCIError("Could not install code for " + installedCodeOwner.format("%H.%n(%p)")); 680 } 681 } catch (Throwable e) { 682 throw Debug.handle(e); 683 } 684 } catch (Throwable e) { 685 throw Debug.handle(e); 686 } 687 688 if (!forceCompile) { 689 cache.put(installedCodeOwner, installedCode); 690 } 691 return installedCode; 692 } 693 694 /** 695 * Used to produce a graph for a method about to be compiled by 696 * {@link #compile(ResolvedJavaMethod, StructuredGraph)} if the second parameter to that method 697 * is null. 698 * 699 * The default implementation in {@link GraalCompilerTest} is to call 700 * {@link #parseEager(ResolvedJavaMethod, AllowAssumptions)}. 701 */ 702 protected StructuredGraph parseForCompile(ResolvedJavaMethod method) { 703 return parseEager(method, AllowAssumptions.YES); 704 } 705 706 /** 707 * Compiles a given method. 708 * 709 * @param installedCodeOwner the method the compiled code will be associated with when installed 710 * @param graph the graph to be compiled for {@code installedCodeOwner}. If null, a graph will 711 * be obtained from {@code installedCodeOwner} via 712 * {@link #parseForCompile(ResolvedJavaMethod)}. 713 */ 714 protected CompilationResult compile(ResolvedJavaMethod installedCodeOwner, StructuredGraph graph) { 715 StructuredGraph graphToCompile = graph == null ? parseForCompile(installedCodeOwner) : graph; 716 lastCompiledGraph = graphToCompile; 717 CallingConvention cc = getCallingConvention(getCodeCache(), Type.JavaCallee, graphToCompile.method(), false); 718 Request<CompilationResult> request = new Request<>(graphToCompile, cc, installedCodeOwner, getProviders(), getBackend(), getCodeCache().getTarget(), getDefaultGraphBuilderSuite(), 719 OptimisticOptimizations.ALL, getProfilingInfo(graphToCompile), getSuites(), getLIRSuites(), new CompilationResult(), CompilationResultBuilderFactory.Default); 720 return GraalCompiler.compile(request); 721 } 722 723 protected StructuredGraph lastCompiledGraph; 724 725 protected SpeculationLog getSpeculationLog() { 726 return null; 727 } 728 729 protected InstalledCode addMethod(final ResolvedJavaMethod method, final CompilationResult compResult) { 730 return getCodeCache().addMethod(method, compResult, null, null); 731 } 732 733 private final Map<ResolvedJavaMethod, Method> methodMap = new HashMap<>(); 734 735 /** 736 * Converts a reflection {@link Method} to a {@link ResolvedJavaMethod}. 737 */ 738 protected ResolvedJavaMethod asResolvedJavaMethod(Method method) { 739 ResolvedJavaMethod javaMethod = getMetaAccess().lookupJavaMethod(method); 740 methodMap.put(javaMethod, method); 741 return javaMethod; 742 } 743 744 protected ResolvedJavaMethod getResolvedJavaMethod(String methodName) { 745 return asResolvedJavaMethod(getMethod(methodName)); 746 } 747 748 protected ResolvedJavaMethod getResolvedJavaMethod(Class<?> clazz, String methodName) { 749 return asResolvedJavaMethod(getMethod(clazz, methodName)); 750 } 751 752 protected ResolvedJavaMethod getResolvedJavaMethod(Class<?> clazz, String methodName, Class<?>... parameterTypes) { 753 return asResolvedJavaMethod(getMethod(clazz, methodName, parameterTypes)); 754 } 755 756 /** 757 * Gets the reflection {@link Method} from which a given {@link ResolvedJavaMethod} was created 758 * or null if {@code javaMethod} does not correspond to a reflection method. 759 */ 760 protected Method lookupMethod(ResolvedJavaMethod javaMethod) { 761 return methodMap.get(javaMethod); 762 } 763 764 protected Object invoke(ResolvedJavaMethod javaMethod, Object receiver, Object... args) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException { 765 Method method = lookupMethod(javaMethod); 766 Assert.assertTrue(method != null); 767 if (!method.isAccessible()) { 768 method.setAccessible(true); 769 } 770 return method.invoke(receiver, applyArgSuppliers(args)); 771 } 772 773 /** 774 * Parses a Java method in {@linkplain GraphBuilderConfiguration#getDefault default} mode to 775 * produce a graph. 776 * 777 * @param methodName the name of the method in {@code this.getClass()} to be parsed 778 */ 779 protected StructuredGraph parseProfiled(String methodName, AllowAssumptions allowAssumptions) { 780 return parseProfiled(getResolvedJavaMethod(methodName), allowAssumptions); 781 } 782 783 /** 784 * Parses a Java method in {@linkplain GraphBuilderConfiguration#getDefault default} mode to 785 * produce a graph. 786 */ 787 protected StructuredGraph parseProfiled(ResolvedJavaMethod m, AllowAssumptions allowAssumptions) { 788 return parse1(m, getDefaultGraphBuilderSuite(), allowAssumptions); 789 } 790 791 /** 792 * Parses a Java method in {@linkplain GraphBuilderConfiguration#getEagerDefault eager} mode to 793 * produce a graph. 794 * 795 * @param methodName the name of the method in {@code this.getClass()} to be parsed 796 */ 797 protected StructuredGraph parseEager(String methodName, AllowAssumptions allowAssumptions) { 798 return parseEager(getResolvedJavaMethod(methodName), allowAssumptions); 799 } 800 801 /** 802 * Parses a Java method in {@linkplain GraphBuilderConfiguration#getEagerDefault eager} mode to 803 * produce a graph. 804 */ 805 protected StructuredGraph parseEager(ResolvedJavaMethod m, AllowAssumptions allowAssumptions) { 806 return parse1(m, getCustomGraphBuilderSuite(GraphBuilderConfiguration.getEagerDefault(getDefaultGraphBuilderPlugins())), allowAssumptions); 807 } 808 809 /** 810 * Parses a Java method in {@linkplain GraphBuilderConfiguration#getFullDebugDefault full debug} 811 * mode to produce a graph. 812 */ 813 protected StructuredGraph parseDebug(ResolvedJavaMethod m, AllowAssumptions allowAssumptions) { 814 return parse1(m, getCustomGraphBuilderSuite(GraphBuilderConfiguration.getFullDebugDefault(getDefaultGraphBuilderPlugins())), allowAssumptions); 815 } 816 817 private StructuredGraph parse1(ResolvedJavaMethod javaMethod, PhaseSuite<HighTierContext> graphBuilderSuite, AllowAssumptions allowAssumptions) { 818 assert javaMethod.getAnnotation(Test.class) == null : "shouldn't parse method with @Test annotation: " + javaMethod; 819 try (Scope ds = Debug.scope("Parsing", javaMethod)) { 820 StructuredGraph graph = new StructuredGraph(javaMethod, allowAssumptions, getSpeculationLog()); 821 graphBuilderSuite.apply(graph, getDefaultHighTierContext()); 822 return graph; 823 } catch (Throwable e) { 824 throw Debug.handle(e); 825 } 826 } 827 828 protected Plugins getDefaultGraphBuilderPlugins() { 829 PhaseSuite<HighTierContext> suite = backend.getSuites().getDefaultGraphBuilderSuite(); 830 Plugins defaultPlugins = ((GraphBuilderPhase) suite.findPhase(GraphBuilderPhase.class).previous()).getGraphBuilderConfig().getPlugins(); 831 // defensive copying 832 return new Plugins(defaultPlugins); 833 } 834 835 protected PhaseSuite<HighTierContext> getDefaultGraphBuilderSuite() { 836 // defensive copying 837 return backend.getSuites().getDefaultGraphBuilderSuite().copy(); 838 } 839 840 protected PhaseSuite<HighTierContext> getCustomGraphBuilderSuite(GraphBuilderConfiguration gbConf) { 841 PhaseSuite<HighTierContext> suite = getDefaultGraphBuilderSuite(); 842 ListIterator<BasePhase<? super HighTierContext>> iterator = suite.findPhase(GraphBuilderPhase.class); 843 GraphBuilderConfiguration gbConfCopy = editGraphBuilderConfiguration(gbConf.copy()); 844 iterator.remove(); 845 iterator.add(new GraphBuilderPhase(gbConfCopy)); 846 return suite; 847 } 848 849 protected GraphBuilderConfiguration editGraphBuilderConfiguration(GraphBuilderConfiguration conf) { 850 InvocationPlugins invocationPlugins = conf.getPlugins().getInvocationPlugins(); 851 invocationPlugins.register(new InvocationPlugin() { 852 public boolean apply(GraphBuilderContext b, ResolvedJavaMethod targetMethod, Receiver receiver) { 853 b.add(new BreakpointNode()); 854 return true; 855 } 856 }, GraalCompilerTest.class, "breakpoint"); 857 invocationPlugins.register(new InvocationPlugin() { 858 public boolean apply(GraphBuilderContext b, ResolvedJavaMethod targetMethod, Receiver receiver, ValueNode arg0) { 859 b.add(new BreakpointNode(arg0)); 860 return true; 861 } 862 }, GraalCompilerTest.class, "breakpoint", int.class); 863 return conf; 864 } 865 866 protected Replacements getReplacements() { 867 return getProviders().getReplacements(); 868 } 869 870 /** 871 * Inject a probability for a branch condition into the profiling information of this test case. 872 * 873 * @param p the probability that cond is true 874 * @param cond the condition of the branch 875 * @return cond 876 */ 877 protected static boolean branchProbability(double p, boolean cond) { 878 return GraalDirectives.injectBranchProbability(p, cond); 879 } 880 881 /** 882 * Inject an iteration count for a loop condition into the profiling information of this test 883 * case. 884 * 885 * @param i the iteration count of the loop 886 * @param cond the condition of the loop 887 * @return cond 888 */ 889 protected static boolean iterationCount(double i, boolean cond) { 890 return GraalDirectives.injectIterationCount(i, cond); 891 } 892 893 /** 894 * Test if the current test runs on the given platform. The name must match the name given in 895 * the {@link Architecture#getName()}. 896 * 897 * @param name The name to test 898 * @return true if we run on the architecture given by name 899 */ 900 protected boolean isArchitecture(String name) { 901 return name.equals(backend.getTarget().arch.getName()); 902 } 903}