1 /*
   2  * Copyright (c) 2017, 2019, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  */
  23 
  24 package compiler.valhalla.valuetypes;
  25 
  26 import compiler.whitebox.CompilerWhiteBoxTest;
  27 import jdk.test.lib.Asserts;
  28 import jdk.test.lib.management.InputArguments;
  29 import jdk.test.lib.Platform;
  30 import jdk.test.lib.process.ProcessTools;
  31 import jdk.test.lib.process.OutputAnalyzer;
  32 import jdk.test.lib.Utils;
  33 import sun.hotspot.WhiteBox;
  34 
  35 import java.lang.annotation.Retention;
  36 import java.lang.annotation.RetentionPolicy;
  37 import java.lang.annotation.Repeatable;
  38 import java.lang.invoke.*;
  39 import java.lang.reflect.Method;
  40 import java.util.ArrayList;
  41 import java.util.Arrays;
  42 import java.util.Hashtable;
  43 import java.util.LinkedHashMap;
  44 import java.util.List;
  45 import java.util.Map;
  46 import java.util.regex.Matcher;
  47 import java.util.regex.Pattern;
  48 import java.util.TreeMap;
  49 
  50 // Mark method as test
  51 @Retention(RetentionPolicy.RUNTIME)
  52 @Repeatable(Tests.class)
  53 @interface Test {
  54     // Regular expression used to match forbidden IR nodes
  55     // in the C2 IR emitted for this test.
  56     String failOn() default "";
  57     // Regular expressions used to match and count IR nodes.
  58     String[] match() default { };
  59     int[] matchCount() default { };
  60     int compLevel() default ValueTypeTest.COMP_LEVEL_ANY;
  61     int valid() default ValueTypeTest.AllFlags;
  62 }
  63 
  64 @Retention(RetentionPolicy.RUNTIME)
  65 @interface Tests {
  66     Test[] value();
  67 }
  68 
  69 // Force method inlining during compilation
  70 @Retention(RetentionPolicy.RUNTIME)
  71 @interface ForceInline { }
  72 
  73 // Prevent method inlining during compilation
  74 @Retention(RetentionPolicy.RUNTIME)
  75 @interface DontInline { }
  76 
  77 // Prevent method compilation
  78 @Retention(RetentionPolicy.RUNTIME)
  79 @interface DontCompile { }
  80 
  81 // Force method compilation
  82 @Retention(RetentionPolicy.RUNTIME)
  83 @interface ForceCompile {
  84     int compLevel() default ValueTypeTest.COMP_LEVEL_ANY;
  85 }
  86 
  87 // Number of warmup iterations
  88 @Retention(RetentionPolicy.RUNTIME)
  89 @interface Warmup {
  90     int value();
  91 }
  92 
  93 // Do not enqueue the test method for compilation immediately after warmup loops have finished. Instead
  94 // let the test method be compiled with on-stack-replacement.
  95 @Retention(RetentionPolicy.RUNTIME)
  96 @interface OSRCompileOnly {}
  97 
  98 // Skip this test temporarily for C1 testing
  99 @Retention(RetentionPolicy.RUNTIME)
 100 @interface TempSkipForC1 {
 101     String reason() default "";
 102 }
 103 
 104 public abstract class ValueTypeTest {
 105     protected static final WhiteBox WHITE_BOX = WhiteBox.getWhiteBox();
 106 
 107     // Currently C1 is disabled by default. To test C1, run "jtreg -vmoptions:-XX:+EnableValhallaC1 -vmoptions:-XX:TieredStopAtLevel=1".
 108     // This forces C1 to be use for all methods that are compiled, @Test(compLevel=?) setting.
 109     static final boolean TEST_C1 = (Boolean)WHITE_BOX.getVMFlag("EnableValhallaC1");
 110 
 111     // Should we execute tests that assume (ValueType[] <: Object[])?
 112     static final boolean ENABLE_VALUE_ARRAY_COVARIANCE = Boolean.getBoolean("ValueArrayCovariance");
 113 
 114     // Random test values
 115     public static final int  rI = Utils.getRandomInstance().nextInt() % 1000;
 116     public static final long rL = Utils.getRandomInstance().nextLong() % 1000;
 117 
 118     // User defined settings
 119     protected static final boolean XCOMP = Platform.isComp();
 120     private static final boolean PRINT_GRAPH = true;
 121     protected static final boolean VERBOSE = Boolean.parseBoolean(System.getProperty("Verbose", "false"));
 122     private static final boolean PRINT_TIMES = Boolean.parseBoolean(System.getProperty("PrintTimes", "false"));
 123     private static       boolean VERIFY_IR = Boolean.parseBoolean(System.getProperty("VerifyIR", "true")) && !TEST_C1 && !XCOMP;
 124     private static final boolean VERIFY_VM = Boolean.parseBoolean(System.getProperty("VerifyVM", "false"));
 125     private static final String SCENARIOS = System.getProperty("Scenarios", "");
 126     private static final String TESTLIST = System.getProperty("Testlist", "");
 127     private static final String EXCLUDELIST = System.getProperty("Exclude", "");
 128     private static final int WARMUP = Integer.parseInt(System.getProperty("Warmup", "251"));
 129     private static final boolean DUMP_REPLAY = Boolean.parseBoolean(System.getProperty("DumpReplay", "false"));
 130     protected static final boolean FLIP_C1_C2 = Boolean.parseBoolean(System.getProperty("FlipC1C2", "false"));
 131 
 132     // "jtreg -DXcomp=true" runs all the scenarios with -Xcomp. This is faster than "jtreg -javaoptions:-Xcomp".
 133     protected static final boolean RUN_SCENARIOS_WITH_XCOMP = Boolean.parseBoolean(System.getProperty("Xcomp", "false"));
 134 
 135     // Pre-defined settings
 136     private static final String[] defaultFlags = {
 137         "-XX:-BackgroundCompilation", "-XX:CICompilerCount=1",
 138         "-XX:CompileCommand=quiet",
 139         "-XX:CompileCommand=compileonly,java.lang.invoke.*::*",
 140         "-XX:CompileCommand=compileonly,java.lang.Long::sum",
 141         "-XX:CompileCommand=compileonly,java.lang.Object::<init>",
 142         "-XX:CompileCommand=inline,compiler.valhalla.valuetypes.MyValue*::<init>",
 143         "-XX:CompileCommand=compileonly,compiler.valhalla.valuetypes.*::*"};
 144     private static final String[] printFlags = {
 145         "-XX:+PrintCompilation", "-XX:+PrintIdeal", "-XX:+UnlockDiagnosticVMOptions", "-XX:+PrintOptoAssembly"};
 146     private static final String[] verifyFlags = {
 147         "-XX:+VerifyOops", "-XX:+VerifyStack", "-XX:+VerifyLastFrame", "-XX:+VerifyBeforeGC", "-XX:+VerifyAfterGC",
 148         "-XX:+VerifyDuringGC", "-XX:+VerifyAdapterSharing"};
 149 
 150     protected static final int ValueTypePassFieldsAsArgsOn = 0x1;
 151     protected static final int ValueTypePassFieldsAsArgsOff = 0x2;
 152     protected static final int ValueTypeArrayFlattenOn = 0x4;
 153     protected static final int ValueTypeArrayFlattenOff = 0x8;
 154     protected static final int ValueTypeReturnedAsFieldsOn = 0x10;
 155     protected static final int ValueTypeReturnedAsFieldsOff = 0x20;
 156     protected static final int AlwaysIncrementalInlineOn = 0x40;
 157     protected static final int AlwaysIncrementalInlineOff = 0x80;
 158     protected static final int G1GCOn = 0x100;
 159     protected static final int G1GCOff = 0x200;
 160     static final int AllFlags = ValueTypePassFieldsAsArgsOn | ValueTypePassFieldsAsArgsOff | ValueTypeArrayFlattenOn | ValueTypeArrayFlattenOff | ValueTypeReturnedAsFieldsOn;
 161     protected static final boolean ValueTypePassFieldsAsArgs = (Boolean)WHITE_BOX.getVMFlag("ValueTypePassFieldsAsArgs");
 162     protected static final boolean ValueTypeArrayFlatten = (WHITE_BOX.getIntxVMFlag("ValueArrayElemMaxFlatSize") == -1); // FIXME - fix this if default of ValueArrayElemMaxFlatSize is changed
 163     protected static final boolean ValueTypeReturnedAsFields = (Boolean)WHITE_BOX.getVMFlag("ValueTypeReturnedAsFields");
 164     protected static final boolean AlwaysIncrementalInline = (Boolean)WHITE_BOX.getVMFlag("AlwaysIncrementalInline");
 165     protected static final boolean G1GC = (Boolean)WHITE_BOX.getVMFlag("UseG1GC");
 166     protected static final long TieredStopAtLevel = (Long)WHITE_BOX.getVMFlag("TieredStopAtLevel");
 167     protected static final boolean VerifyOops = (Boolean)WHITE_BOX.getVMFlag("VerifyOops");
 168     protected static final int COMP_LEVEL_ANY               = -2;
 169     protected static final int COMP_LEVEL_ALL               = -2;
 170     protected static final int COMP_LEVEL_AOT               = -1;
 171     protected static final int COMP_LEVEL_NONE              =  0;
 172     protected static final int COMP_LEVEL_SIMPLE            =  1;     // C1
 173     protected static final int COMP_LEVEL_LIMITED_PROFILE   =  2;     // C1, invocation & backedge counters
 174     protected static final int COMP_LEVEL_FULL_PROFILE      =  3;     // C1, invocation & backedge counters + mdo
 175     protected static final int COMP_LEVEL_FULL_OPTIMIZATION =  4;     // C2 or JVMCI
 176 
 177     protected static final Hashtable<String, Method> tests = new Hashtable<String, Method>();
 178     protected static final boolean USE_COMPILER = WHITE_BOX.getBooleanVMFlag("UseCompiler");
 179     protected static final boolean PRINT_IDEAL  = WHITE_BOX.getBooleanVMFlag("PrintIdeal");
 180 
 181     // Regular expressions used to match nodes in the PrintIdeal output
 182     protected static final String START = "(\\d+\\t(.*";
 183     protected static final String MID = ".*)+\\t===.*";
 184     protected static final String END = ")|";
 185     protected static final String ALLOC  = "(.*precise klass compiler/valhalla/valuetypes/MyValue.*\\R(.*(nop|spill).*\\R)*.*_new_instance_Java" + END;
 186     protected static final String ALLOCA = "(.*precise klass \\[Lcompiler/valhalla/valuetypes/MyValue.*\\R(.*(nop|spill).*\\R)*.*_new_array_Java" + END;
 187     protected static final String LOAD   = START + "Load(B|S|I|L|F|D|P|N)" + MID + "@compiler/valhalla/valuetypes/MyValue.*" + END;
 188     protected static final String LOADK  = START + "LoadK" + MID + END;
 189     protected static final String STORE  = START + "Store(B|C|S|I|L|F|D|P|N)" + MID + "@compiler/valhalla/valuetypes/MyValue.*" + END;
 190     protected static final String LOOP   = START + "Loop" + MID + "" + END;
 191     protected static final String COUNTEDLOOP = START + "CountedLoop\\b" + MID + "" + END;
 192     protected static final String TRAP   = START + "CallStaticJava" + MID + "uncommon_trap.*(unstable_if|predicate)" + END;
 193     protected static final String RETURN = START + "Return" + MID + "returns" + END;
 194     protected static final String LINKTOSTATIC = START + "CallStaticJava" + MID + "linkToStatic" + END;
 195     protected static final String NPE = START + "CallStaticJava" + MID + "null_check" + END;
 196     protected static final String CALL = START + "CallStaticJava" + MID + END;
 197     protected static final String STOREVALUETYPEFIELDS = START + "CallStaticJava" + MID + "store_value_type_fields" + END;
 198     protected static final String SCOBJ = "(.*# ScObj.*" + END;
 199 
 200     public static String[] concat(String prefix[], String... extra) {
 201         ArrayList<String> list = new ArrayList<String>();
 202         if (prefix != null) {
 203             for (String s : prefix) {
 204                 list.add(s);
 205             }
 206         }
 207         if (extra != null) {
 208             for (String s : extra) {
 209                 list.add(s);
 210             }
 211         }
 212 
 213         return list.toArray(new String[list.size()]);
 214     }
 215 
 216     /**
 217      * Override getNumScenarios and getVMParameters if you want to run with more than
 218      * the 6 built-in scenarios
 219      */
 220     public int getNumScenarios() {
 221         return 6;
 222     }
 223 
 224     /**
 225      * VM paramaters for the 5 built-in test scenarios. If your test needs to append
 226      * extra parameters for (some of) these scenarios, override getExtraVMParameters().
 227      */
 228     public String[] getVMParameters(int scenario) {
 229         switch (scenario) {
 230         case 0: return new String[] {
 231                 "-XX:+AlwaysIncrementalInline",
 232                 "-XX:ValueArrayElemMaxFlatOops=-1",
 233                 "-XX:ValueArrayElemMaxFlatSize=-1",
 234                 "-XX:ValueFieldMaxFlatSize=-1",
 235                 "-XX:+ValueTypePassFieldsAsArgs",
 236                 "-XX:+ValueTypeReturnedAsFields"};
 237         case 1: return new String[] {
 238                 "-XX:-UseCompressedOops",
 239                 "-XX:ValueArrayElemMaxFlatOops=-1",
 240                 "-XX:ValueArrayElemMaxFlatSize=-1",
 241                 "-XX:ValueFieldMaxFlatSize=-1",
 242                 "-XX:-ValueTypePassFieldsAsArgs",
 243                 "-XX:-ValueTypeReturnedAsFields"};
 244         case 2: return new String[] {
 245                 "-DVerifyIR=false",
 246                 "-XX:-UseCompressedOops",
 247                 "-XX:ValueArrayElemMaxFlatOops=0",
 248                 "-XX:ValueArrayElemMaxFlatSize=0",
 249                 "-XX:ValueFieldMaxFlatSize=0",
 250                 "-XX:+ValueTypePassFieldsAsArgs",
 251                 "-XX:+ValueTypeReturnedAsFields",
 252                 "-XX:+StressValueTypeReturnedAsFields"};
 253         case 3: return new String[] {
 254                 "-DVerifyIR=false",
 255                 "-XX:+AlwaysIncrementalInline",
 256                 "-XX:-ValueTypePassFieldsAsArgs",
 257                 "-XX:-ValueTypeReturnedAsFields"};
 258         case 4: return new String[] {
 259                 "-DVerifyIR=false",
 260                 "-XX:ValueArrayElemMaxFlatOops=-1",
 261                 "-XX:ValueArrayElemMaxFlatSize=-1",
 262                 "-XX:ValueFieldMaxFlatSize=0",
 263                 "-XX:+ValueTypePassFieldsAsArgs",
 264                 "-XX:-ValueTypeReturnedAsFields"};
 265         case 5: return new String[] {
 266                 "-XX:+AlwaysIncrementalInline",
 267                 "-XX:ValueArrayElemMaxFlatOops=-1",
 268                 "-XX:ValueArrayElemMaxFlatSize=-1",
 269                 "-XX:ValueFieldMaxFlatSize=-1",
 270                 "-XX:-ValueTypePassFieldsAsArgs",
 271                 "-XX:-ValueTypeReturnedAsFields"};
 272         }
 273 
 274         return null;
 275     }
 276 
 277     /**
 278      * Override this method to provide extra parameters for selected scenarios
 279      */
 280     public String[] getExtraVMParameters(int scenario) {
 281         return null;
 282     }
 283 
 284     public static void main(String[] args) throws Throwable {
 285         if (args.length != 1) {
 286             throw new RuntimeException("Usage: @run main/othervm/timeout=120 -Xbootclasspath/a:." +
 287                                        " -XX:+IgnoreUnrecognizedVMOptions -XX:+UnlockDiagnosticVMOptions" +
 288                                        " -XX:+UnlockExperimentalVMOptions -XX:+WhiteBoxAPI" +
 289                                        " compiler.valhalla.valuetypes.ValueTypeTest <YourTestMainClass>");
 290         }
 291         String testMainClassName = args[0];
 292         Class testMainClass = Class.forName(testMainClassName);
 293         ValueTypeTest test = (ValueTypeTest)testMainClass.newInstance();
 294         List<String> scenarios = null;
 295         if (!SCENARIOS.isEmpty()) {
 296            scenarios = Arrays.asList(SCENARIOS.split(","));
 297         }
 298         for (int i=0; i<test.getNumScenarios(); i++) {
 299             if (scenarios == null || scenarios.contains(Integer.toString(i))) {
 300                 System.out.println("Scenario #" + i + " -------- ");
 301                 String[] cmds = InputArguments.getVmInputArgs();
 302                 if (RUN_SCENARIOS_WITH_XCOMP) {
 303                     cmds = concat(cmds, "-Xcomp");
 304                 }
 305                 cmds = concat(cmds, test.getVMParameters(i));
 306                 cmds = concat(cmds, test.getExtraVMParameters(i));
 307                 cmds = concat(cmds, testMainClassName);
 308 
 309                 OutputAnalyzer oa = ProcessTools.executeTestJvm(cmds);
 310                 String output = oa.getOutput();
 311                 oa.shouldHaveExitValue(0);
 312                 System.out.println(output);
 313             } else {
 314                 System.out.println("Scenario #" + i + " is skipped due to -Dscenarios=" + SCENARIOS);
 315             }
 316         }
 317     }
 318 
 319     // To exclude test cases, use -DExclude=<case1>,<case2>,...
 320     // Each case can be just the method name, or can be <class>.<method>. The latter form is useful
 321     // when you are running several tests at the same time.
 322     //
 323     // jtreg -DExclude=test12 TestArrays.java
 324     // jtreg -DExclude=test34 TestLWorld.java
 325     // -- or --
 326     // jtreg -DExclude=TestArrays.test12,TestLWorld.test34 TestArrays.java TestLWorld.java
 327     //
 328     private List<String> buildExcludeList() {
 329         List<String> exclude = null;
 330         String classPrefix = getClass().getSimpleName() + ".";
 331         if (!EXCLUDELIST.isEmpty()) {
 332             exclude = new ArrayList(Arrays.asList(EXCLUDELIST.split(",")));
 333             for (int i = exclude.size() - 1; i >= 0; i--) {
 334                 String ex = exclude.get(i);
 335                 if (ex.indexOf(".") > 0) {
 336                     if (ex.startsWith(classPrefix)) {
 337                         ex = ex.substring(classPrefix.length());
 338                         exclude.set(i, ex);
 339                     } else {
 340                         exclude.remove(i);
 341                     }
 342                 }
 343             }
 344         }
 345         return exclude;
 346     }
 347 
 348     protected ValueTypeTest() {
 349         List<String> list = null;
 350         if (!TESTLIST.isEmpty()) {
 351            list = Arrays.asList(TESTLIST.split(","));
 352         }
 353         List<String> exclude = buildExcludeList();
 354 
 355         // Gather all test methods and put them in Hashtable
 356         for (Method m : getClass().getDeclaredMethods()) {
 357             Test[] annos = m.getAnnotationsByType(Test.class);
 358             if (annos.length != 0 &&
 359                 ((list == null || list.contains(m.getName())) && (exclude == null || !exclude.contains(m.getName())))) {
 360                 tests.put(getClass().getSimpleName() + "::" + m.getName(), m);
 361             }
 362         }
 363     }
 364 
 365     protected void run(String[] args, Class<?>... classes) throws Throwable {
 366         if (args.length == 0) {
 367             // Spawn a new VM instance
 368             execute_vm();
 369         } else {
 370             // Execute tests in the VM spawned by the above code.
 371             Asserts.assertTrue(args.length == 1 && args[0].equals("run"), "must be");
 372             run(classes);
 373         }
 374     }
 375 
 376     private void execute_vm() throws Throwable {
 377         Asserts.assertFalse(tests.isEmpty(), "no tests to execute");
 378         String[] vmInputArgs = InputArguments.getVmInputArgs();
 379         for (String arg : vmInputArgs) {
 380             if (arg.startsWith("-XX:CompileThreshold")) {
 381                 // Disable IR verification if non-default CompileThreshold is set
 382                 VERIFY_IR = false;
 383             }
 384             if (arg.startsWith("-XX:+EnableValhallaC1")) {
 385                 // Disable IR verification if C1 is used (FIXME!)
 386                 VERIFY_IR = false;
 387             }
 388         }
 389         // Each VM is launched with flags in this order, so the later ones can override the earlier one:
 390         //     defaultFlags
 391         //     VERIFY_IR/VERIFY_VM flags specified below
 392         //     vmInputArgs, which consists of:
 393         //        @run options
 394         //        getVMParameters()
 395         //        getExtraVMParameters()
 396         String cmds[] = defaultFlags;
 397         if (VERIFY_IR) {
 398             // Add print flags for IR verification
 399             cmds = concat(cmds, printFlags);
 400             // Always trap for exception throwing to not confuse IR verification
 401             cmds = concat(cmds, "-XX:-OmitStackTraceInFastThrow");
 402         }
 403         if (VERIFY_VM) {
 404             cmds = concat(cmds, verifyFlags);
 405         }
 406         cmds = concat(cmds, vmInputArgs);
 407 
 408         // Run tests in own process and verify output
 409         cmds = concat(cmds, getClass().getName(), "run");
 410         OutputAnalyzer oa = ProcessTools.executeTestJvm(cmds);
 411         // If ideal graph printing is enabled/supported, verify output
 412         String output = oa.getOutput();
 413         oa.shouldHaveExitValue(0);
 414         if (VERIFY_IR) {
 415             if (output.contains("PrintIdeal enabled")) {
 416                 parseOutput(output);
 417             } else {
 418                 System.out.println(output);
 419                 System.out.println("WARNING: IR verification failed! Running with -Xint, -Xcomp or release build?");
 420             }
 421         }
 422     }
 423 
 424     private void parseOutput(String output) throws Exception {
 425         Pattern comp_re = Pattern.compile("\\n\\s+\\d+\\s+\\d+\\s+(%| )(s| )(!| )b(n| )\\s+\\S+\\.(?<name>[^.]+::\\S+)\\s+(?<osr>@ \\d+\\s+)?[(]\\d+ bytes[)]\\n");
 426         Matcher m = comp_re.matcher(output);
 427         Map<String,String> compilations = new LinkedHashMap<>();
 428         int prev = 0;
 429         String methodName = null;
 430         while (m.find()) {
 431             if (prev == 0) {
 432                 // Print header
 433                 System.out.print(output.substring(0, m.start()+1));
 434             } else if (methodName != null) {
 435                 compilations.put(methodName, output.substring(prev, m.start()+1));
 436             }
 437             if (m.group("osr") != null) {
 438                 methodName = null;
 439             } else {
 440                 methodName = m.group("name");
 441             }
 442             prev = m.end();
 443         }
 444         if (prev == 0) {
 445             // Print header
 446             System.out.print(output);
 447         } else if (methodName != null) {
 448             compilations.put(methodName, output.substring(prev));
 449         }
 450         // Iterate over compilation output
 451         for (String testName : compilations.keySet()) {
 452             Method test = tests.get(testName);
 453             if (test == null) {
 454                 // Skip helper methods
 455                 continue;
 456             }
 457             String graph = compilations.get(testName);
 458             if (PRINT_GRAPH) {
 459                 System.out.println("\nGraph for " + testName + "\n" + graph);
 460             }
 461             // Parse graph using regular expressions to determine if it contains forbidden nodes
 462             Test[] annos = test.getAnnotationsByType(Test.class);
 463             Test anno = null;
 464             for (Test a : annos) {
 465                 if ((a.valid() & ValueTypePassFieldsAsArgsOn) != 0 && ValueTypePassFieldsAsArgs) {
 466                     assert anno == null;
 467                     anno = a;
 468                 } else if ((a.valid() & ValueTypePassFieldsAsArgsOff) != 0 && !ValueTypePassFieldsAsArgs) {
 469                     assert anno == null;
 470                     anno = a;
 471                 } else if ((a.valid() & ValueTypeArrayFlattenOn) != 0 && ValueTypeArrayFlatten) {
 472                     assert anno == null;
 473                     anno = a;
 474                 } else if ((a.valid() & ValueTypeArrayFlattenOff) != 0 && !ValueTypeArrayFlatten) {
 475                     assert anno == null;
 476                     anno = a;
 477                 } else if ((a.valid() & ValueTypeReturnedAsFieldsOn) != 0 && ValueTypeReturnedAsFields) {
 478                     assert anno == null;
 479                     anno = a;
 480                 } else if ((a.valid() & ValueTypeReturnedAsFieldsOff) != 0 && !ValueTypeReturnedAsFields) {
 481                     assert anno == null;
 482                     anno = a;
 483                 } else if ((a.valid() & AlwaysIncrementalInlineOn) != 0 && AlwaysIncrementalInline) {
 484                     assert anno == null;
 485                     anno = a;
 486                 } else if ((a.valid() & AlwaysIncrementalInlineOff) != 0 && !AlwaysIncrementalInline) {
 487                     assert anno == null;
 488                     anno = a;
 489                 } else if ((a.valid() & G1GCOn) != 0 && G1GC) {
 490                     assert anno == null;
 491                     anno = a;
 492                 } else if ((a.valid() & G1GCOff) != 0 && !G1GC) {
 493                     assert anno == null;
 494                     anno = a;
 495                 }
 496             }
 497             assert anno != null;
 498             String regexFail = anno.failOn();
 499             if (!regexFail.isEmpty()) {
 500                 Pattern pattern = Pattern.compile(regexFail.substring(0, regexFail.length()-1));
 501                 Matcher matcher = pattern.matcher(graph);
 502                 boolean found = matcher.find();
 503                 Asserts.assertFalse(found, "Graph for '" + testName + "' contains forbidden node:\n" + (found ? matcher.group() : ""));
 504             }
 505             String[] regexMatch = anno.match();
 506             int[] matchCount = anno.matchCount();
 507             for (int i = 0; i < regexMatch.length; ++i) {
 508                 Pattern pattern = Pattern.compile(regexMatch[i].substring(0, regexMatch[i].length()-1));
 509                 Matcher matcher = pattern.matcher(graph);
 510                 int count = 0;
 511                 String nodes = "";
 512                 while (matcher.find()) {
 513                     count++;
 514                     nodes += matcher.group() + "\n";
 515                 }
 516                 if (matchCount[i] < 0) {
 517                     Asserts.assertLTE(Math.abs(matchCount[i]), count, "Graph for '" + testName + "' contains different number of match nodes:\n" + nodes);
 518                 } else {
 519                     Asserts.assertEQ(matchCount[i], count, "Graph for '" + testName + "' contains different number of match nodes:\n" + nodes);
 520                 }
 521             }
 522             tests.remove(testName);
 523             System.out.println(testName + " passed");
 524         }
 525         // Check if all tests were compiled
 526         if (tests.size() != 0) {
 527             for (String name : tests.keySet()) {
 528                 System.out.println("Test '" + name + "' not compiled!");
 529             }
 530             throw new RuntimeException("Not all tests were compiled");
 531         }
 532     }
 533 
 534     private void setup(Class<?> clazz) {
 535         if (XCOMP) {
 536             // Don't control compilation if -Xcomp is enabled
 537             return;
 538         }
 539         if (DUMP_REPLAY) {
 540             // Generate replay compilation files
 541             String directive = "[{ match: \"*.*\", DumpReplay: true }]";
 542             if (WHITE_BOX.addCompilerDirective(directive) != 1) {
 543                 throw new RuntimeException("Failed to add compiler directive");
 544             }
 545         }
 546 
 547         Method[] methods = clazz.getDeclaredMethods();
 548         for (Method m : methods) {
 549             if (m.isAnnotationPresent(Test.class)) {
 550                 // Don't inline tests
 551                 WHITE_BOX.testSetDontInlineMethod(m, true);
 552             }
 553             if (m.isAnnotationPresent(DontCompile.class)) {
 554                 WHITE_BOX.makeMethodNotCompilable(m, COMP_LEVEL_ANY, true);
 555                 WHITE_BOX.makeMethodNotCompilable(m, COMP_LEVEL_ANY, false);
 556                 WHITE_BOX.testSetDontInlineMethod(m, true);
 557             } else if (m.isAnnotationPresent(ForceCompile.class)) {
 558                 int compLevel = getCompLevel(m.getAnnotation(ForceCompile.class));
 559                 WHITE_BOX.enqueueMethodForCompilation(m, compLevel);
 560             }
 561             if (m.isAnnotationPresent(ForceInline.class)) {
 562                 WHITE_BOX.testSetForceInlineMethod(m, true);
 563             } else if (m.isAnnotationPresent(DontInline.class)) {
 564                 WHITE_BOX.testSetDontInlineMethod(m, true);
 565             }
 566         }
 567 
 568         // Compile class initializers
 569         int compLevel = getCompLevel(null);
 570         WHITE_BOX.enqueueInitializerForCompilation(clazz, compLevel);
 571     }
 572 
 573     private void run(Class<?>... classes) throws Exception {
 574         if (USE_COMPILER && PRINT_IDEAL && !XCOMP) {
 575             System.out.println("PrintIdeal enabled");
 576         }
 577         System.out.format("rI = %d, rL = %d\n", rI, rL);
 578 
 579         setup(getClass());
 580         for (Class<?> clazz : classes) {
 581             setup(clazz);
 582         }
 583 
 584         // Execute tests
 585         TreeMap<Long, String> durations = (PRINT_TIMES || VERBOSE) ? new TreeMap<Long, String>() : null;
 586         for (Method test : tests.values()) {
 587             if (VERBOSE) {
 588                 System.out.println("Starting " + test.getName());
 589             }
 590             TempSkipForC1 c1skip = test.getAnnotation(TempSkipForC1.class);
 591             if (TEST_C1 && c1skip != null) {
 592                 System.out.println("Skipped " + test.getName() + " for C1 testing: " + c1skip.reason());
 593                 continue;
 594             }
 595             long startTime = System.nanoTime();
 596             Method verifier = getClass().getMethod(test.getName() + "_verifier", boolean.class);
 597             // Warmup using verifier method
 598             Warmup anno = test.getAnnotation(Warmup.class);
 599             int warmup = anno == null ? WARMUP : anno.value();
 600             for (int i = 0; i < warmup; ++i) {
 601                 verifier.invoke(this, true);
 602             }
 603             boolean osrOnly = (test.getAnnotation(OSRCompileOnly.class) != null);
 604 
 605             // C1 generates a lot of code when VerifyOops is enabled and may run out of space (for a small
 606             // number of test cases).
 607             boolean maybeCodeBufferOverflow = (TEST_C1 && VerifyOops);
 608 
 609             if (!osrOnly) {
 610                 int compLevel = getCompLevel(test.getAnnotation(Test.class));
 611                 // Trigger compilation
 612                 WHITE_BOX.enqueueMethodForCompilation(test, compLevel);
 613                 if (maybeCodeBufferOverflow && !WHITE_BOX.isMethodCompiled(test, false)) {
 614                   // Let's disable VerifyOops temporarily and retry.
 615                   WHITE_BOX.setBooleanVMFlag("VerifyOops", false);
 616                   WHITE_BOX.clearMethodState(test);
 617                   WHITE_BOX.enqueueMethodForCompilation(test, compLevel);
 618                   WHITE_BOX.setBooleanVMFlag("VerifyOops", true);
 619                 }
 620                 Asserts.assertTrue(!USE_COMPILER || WHITE_BOX.isMethodCompiled(test, false), test + " not compiled");
 621             }
 622             // Check result
 623             verifier.invoke(this, false);
 624             if (osrOnly && !maybeCodeBufferOverflow) {
 625                 Asserts.assertTrue(!USE_COMPILER || WHITE_BOX.isMethodCompiled(test, false), test + " not compiled");
 626             }
 627             if (PRINT_TIMES || VERBOSE) {
 628                 long endTime = System.nanoTime();
 629                 long duration = (endTime - startTime);
 630                 durations.put(duration, test.getName());
 631                 if (VERBOSE) {
 632                     System.out.println("Done " + test.getName() + ": " + duration + "ns");
 633                 }
 634             }
 635         }
 636 
 637         // Print execution times
 638         if (PRINT_TIMES) {
 639           System.out.println("\n\nTest execution times:");
 640           for (Map.Entry<Long, String> entry : durations.entrySet()) {
 641               System.out.format("%-10s%15d ns\n", entry.getValue() + ":", entry.getKey());
 642           }
 643         }
 644     }
 645 
 646     // Choose the appropriate compilation level for a method, according to the given annotation.
 647     //
 648     // Currently, if TEST_C1 is true, we always use COMP_LEVEL_SIMPLE. Otherwise, if the
 649     // compLevel is unspecified, the default is COMP_LEVEL_FULL_OPTIMIZATION.
 650     int getCompLevel(Object annotation) {
 651         if (TEST_C1 && !(this instanceof TestCallingConventionC1)) {
 652             return COMP_LEVEL_SIMPLE;
 653         }
 654         int compLevel;
 655         if (annotation == null) {
 656             compLevel = COMP_LEVEL_ANY;
 657         } else if (annotation instanceof Test) {
 658             compLevel = ((Test)annotation).compLevel();
 659         } else {
 660             compLevel = ((ForceCompile)annotation).compLevel();
 661         }
 662         if (compLevel == COMP_LEVEL_ANY) {
 663             compLevel = COMP_LEVEL_FULL_OPTIMIZATION;
 664         }
 665         if (FLIP_C1_C2) {
 666             // Effectively treat all (compLevel = C1) as (compLevel = C2), and
 667             //                       (compLevel = C2) as (compLevel = C1).
 668             if (compLevel == COMP_LEVEL_SIMPLE) {
 669                 compLevel = COMP_LEVEL_FULL_OPTIMIZATION;
 670             } else if (compLevel == COMP_LEVEL_FULL_OPTIMIZATION) {
 671                 compLevel = COMP_LEVEL_SIMPLE;
 672             }
 673         }
 674         if (!TEST_C1 && compLevel < COMP_LEVEL_FULL_OPTIMIZATION) {
 675             compLevel = COMP_LEVEL_FULL_OPTIMIZATION;
 676         }
 677         if (compLevel > (int)TieredStopAtLevel) {
 678             compLevel = (int)TieredStopAtLevel;
 679         }
 680         return compLevel;
 681     }
 682 }