1 /*
  2  * Copyright (c) 2021, 2022, 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.lib.ir_framework.test;
 25 
 26 import compiler.lib.ir_framework.*;
 27 import compiler.lib.ir_framework.Compiler;
 28 import compiler.lib.ir_framework.shared.*;
 29 import jdk.test.lib.Platform;
 30 import jdk.test.lib.Utils;
 31 import sun.hotspot.WhiteBox;
 32 
 33 import java.io.PrintWriter;
 34 import java.io.StringWriter;
 35 import java.lang.annotation.Annotation;
 36 import java.lang.reflect.*;
 37 import java.util.*;
 38 import java.util.stream.Collectors;
 39 import java.util.stream.Stream;
 40 
 41 /**
 42  * This class' main method is called from {@link TestFramework} and represents the so-called "test VM". The class is
 43  * the heart of the framework and is responsible for executing all the specified tests in the test class. It uses the
 44  * Whitebox API and reflection to achieve this task.
 45  */
 46 public class TestVM {
 47     private static final WhiteBox WHITE_BOX;
 48 
 49     static {
 50         try {
 51             WHITE_BOX = WhiteBox.getWhiteBox();
 52         } catch (UnsatisfiedLinkError e) {
 53             System.err.println(System.lineSeparator() + """
 54                                ##########################################################
 55                                 - Did you call a test-related interface method from
 56                                   TestFramework in main() of your test? Make sure to
 57                                   only call setup/run methods and no checks or
 58                                   assertions from main() of your test!
 59                                 - Are you rerunning the test VM (TestVM class)
 60                                   directly after a JTreg run? Make sure to start it
 61                                   from within JTwork/scratch and with the flag
 62                                   -DReproduce=true!
 63                                ##########################################################
 64                                """);
 65             throw e;
 66         }
 67     }
 68 
 69     /**
 70      * The default number of warm-up iterations used to warm up a {@link Test} annotated test method.
 71      * Use {@code -DWarmup=XY} to specify a different default value. An individual warm-up can also be
 72      * set by specifying a {@link Warmup} iteration for a test.
 73      */
 74     public static final int WARMUP_ITERATIONS = Integer.parseInt(System.getProperty("Warmup", "2000"));
 75 
 76     private static final boolean TIERED_COMPILATION = (Boolean)WHITE_BOX.getVMFlag("TieredCompilation");
 77     private static final CompLevel TIERED_COMPILATION_STOP_AT_LEVEL;
 78     private static final boolean CLIENT_VM = Platform.isClient();
 79 
 80     static {
 81         CompLevel level = CompLevel.forValue(((Long)WHITE_BOX.getVMFlag("TieredStopAtLevel")).intValue());
 82         if (CLIENT_VM && level == CompLevel.C2) {
 83             // No C2 available, use C1 level without profiling.
 84             level = CompLevel.C1_SIMPLE;
 85         }
 86         TIERED_COMPILATION_STOP_AT_LEVEL = level;
 87     }
 88     public static final boolean TEST_C1 = (TIERED_COMPILATION && TIERED_COMPILATION_STOP_AT_LEVEL.getValue() < CompLevel.C2.getValue()) || CLIENT_VM;
 89 
 90     static final boolean XCOMP = Platform.isComp();
 91     static final boolean VERBOSE = Boolean.getBoolean("Verbose");
 92     private static final boolean PRINT_TIMES = Boolean.getBoolean("PrintTimes");
 93     public static final boolean USE_COMPILER = WHITE_BOX.getBooleanVMFlag("UseCompiler");
 94     static final boolean EXCLUDE_RANDOM = Boolean.getBoolean("ExcludeRandom");
 95     private static final String TESTLIST = System.getProperty("Test", "");
 96     private static final String EXCLUDELIST = System.getProperty("Exclude", "");
 97     private static final boolean DUMP_REPLAY = Boolean.getBoolean("DumpReplay");
 98     private static final boolean GC_AFTER = Boolean.getBoolean("GCAfter");
 99     private static final boolean SHUFFLE_TESTS = Boolean.parseBoolean(System.getProperty("ShuffleTests", "true"));
100     // Use separate flag as VERIFY_IR could have been set by user but due to other flags it was disabled by flag VM.
101     private static final boolean PRINT_VALID_IR_RULES = Boolean.getBoolean("ShouldDoIRVerification");
102     protected static final long PER_METHOD_TRAP_LIMIT = (Long)WHITE_BOX.getVMFlag("PerMethodTrapLimit");
103     protected static final boolean PROFILE_INTERPRETER = (Boolean)WHITE_BOX.getVMFlag("ProfileInterpreter");
104     private static final boolean FLIP_C1_C2 = Boolean.getBoolean("FlipC1C2");
105     private static final boolean IGNORE_COMPILER_CONTROLS = Boolean.getBoolean("IgnoreCompilerControls");
106 
107     private final HashMap<Method, DeclaredTest> declaredTests = new HashMap<>();
108     private final List<AbstractTest> allTests = new ArrayList<>();
109     private final HashMap<String, Method> testMethodMap = new HashMap<>();
110     private final List<String> excludeList;
111     private final List<String> testList;
112     private Set<Class<?>> helperClasses = null; // Helper classes that contain framework annotations to be processed.
113     private final IREncodingPrinter irMatchRulePrinter;
114     private final Class<?> testClass;
115     private final Map<Executable, CompLevel> forceCompileMap = new HashMap<>();
116 
117     private TestVM(Class<?> testClass) {
118         TestRun.check(testClass != null, "Test class cannot be null");
119         this.testClass = testClass;
120         this.testList = createTestFilterList(TESTLIST, testClass);
121         this.excludeList = createTestFilterList(EXCLUDELIST, testClass);
122 
123         if (PRINT_VALID_IR_RULES) {
124             irMatchRulePrinter = new IREncodingPrinter();
125         } else {
126             irMatchRulePrinter = null;
127         }
128     }
129 
130     /**
131      * Parse "test1,test2,test3" into a list.
132      */
133     private static List<String> createTestFilterList(String list, Class<?> testClass) {
134         List<String> filterList = null;
135         if (!list.isEmpty()) {
136             String classPrefix = testClass.getSimpleName() + ".";
137             filterList = new ArrayList<>(Arrays.asList(list.split(",")));
138             for (int i = filterList.size() - 1; i >= 0; i--) {
139                 String test = filterList.get(i);
140                 if (test.indexOf(".") > 0) {
141                     if (test.startsWith(classPrefix)) {
142                         test = test.substring(classPrefix.length());
143                         filterList.set(i, test);
144                     } else {
145                         filterList.remove(i);
146                     }
147                 }
148             }
149         }
150         return filterList;
151     }
152 
153     /**
154      * Main entry point of the test VM.
155      */
156     public static void main(String[] args) {
157         try {
158             String testClassName = args[0];
159             System.out.println("TestVM main() called - about to run tests in class " + testClassName);
160             Class<?> testClass = getClassObject(testClassName, "test");
161 
162             TestVM framework = new TestVM(testClass);
163             framework.addHelperClasses(args);
164             framework.start();
165         } finally {
166             TestFrameworkSocket.closeClientSocket();
167         }
168     }
169 
170     protected static Class<?> getClassObject(String className, String classType) {
171         try {
172             return Class.forName(className);
173         } catch (Exception e) {
174             throw new TestRunException("Could not find " + classType + " class", e);
175         }
176     }
177 
178     /**
179      * Set up all helper classes and verify they are specified correctly.
180      */
181     private void addHelperClasses(String[] args) {
182         Class<?>[] helperClassesList = getHelperClasses(args);
183         if (helperClassesList != null) {
184             TestRun.check(Arrays.stream(helperClassesList).noneMatch(Objects::isNull), "A Helper class cannot be null");
185             this.helperClasses = new HashSet<>();
186 
187             for (Class<?> helperClass : helperClassesList) {
188                 if (Arrays.stream(testClass.getDeclaredClasses()).anyMatch(c -> c == helperClass)) {
189                     // Nested class of test class is automatically treated as helper class
190                     TestFormat.failNoThrow("Nested " + helperClass + " inside test " + testClass + " is implicitly"
191                                            + " treated as helper class and does not need to be specified as such.");
192                     continue;
193                 }
194                 TestRun.check(!this.helperClasses.contains(helperClass), "Cannot add the same class twice: " + helperClass);
195                 this.helperClasses.add(helperClass);
196             }
197         }
198     }
199 
200     private static Class<?>[] getHelperClasses(String[] args) {
201         if (args.length == 1) {
202             return null;
203         }
204         Class<?>[] helperClasses = new Class<?>[args.length - 1]; // First argument is test class
205         for (int i = 1; i < args.length; i++) {
206             String helperClassName = args[i];
207             helperClasses[i - 1] = getClassObject(helperClassName, "helper");
208         }
209         return helperClasses;
210     }
211 
212     private void checkHelperClass(Class<?> clazz) {
213         checkAnnotationsInClass(clazz, "helper");
214         for (Class<?> c : clazz.getDeclaredClasses()) {
215             checkAnnotationsInClass(c, "nested (and helper)");
216         }
217     }
218 
219     private void checkAnnotationsInClass(Class<?> c, String clazzType) {
220         Method[] methods = c.getDeclaredMethods();
221         for (Method m : methods) {
222             TestFormat.checkNoThrow(getAnnotation(m, Test.class) == null,
223                                     "Cannot use @Test annotation in " + clazzType + " " + c + " at " + m);
224             TestFormat.checkNoThrow(getAnnotation(m, Run.class) == null,
225                                     "Cannot use @Run annotation in " + clazzType + " " + c + " at " + m);
226             TestFormat.checkNoThrow(getAnnotation(m, Check.class) == null,
227                                     "Cannot use @Check annotation in " + clazzType + " " + c + " at " + m);
228         }
229     }
230 
231     /**
232      * Only called by internal tests testing the framework itself. Accessed by reflection. Not exposed to normal users.
233      */
234     private static void runTestsOnSameVM(Class<?> testClass) {
235         if (testClass == null) {
236             StackWalker walker = StackWalker.getInstance(StackWalker.Option.RETAIN_CLASS_REFERENCE);
237             testClass = walker.getCallerClass();
238         }
239         TestVM framework = new TestVM(testClass);
240         framework.start();
241     }
242 
243     /**
244      * Once everything is initialized and set up, start collecting tests and executing them afterwards.
245      */
246     private void start() {
247         setupTests();
248         checkForcedCompilationsCompleted();
249         runTests();
250     }
251 
252     private void setupTests() {
253         for (Class<?> clazz : testClass.getDeclaredClasses()) {
254             checkAnnotationsInClass(clazz, "inner");
255         }
256         if (DUMP_REPLAY) {
257             addReplay();
258         }
259         // Make sure to first setup test methods and make them non-inlineable and only then process compile commands.
260         setupDeclaredTests();
261         processControlAnnotations(testClass);
262         processHelperClasses();
263         setupCheckedAndCustomRunTests();
264 
265         // All remaining tests are simple base tests without check or specific way to run them.
266         addBaseTests();
267         if (PRINT_VALID_IR_RULES) {
268             irMatchRulePrinter.emit();
269         }
270         TestFormat.throwIfAnyFailures();
271         declaredTests.clear();
272         testMethodMap.clear();
273     }
274 
275     private void addBaseTests() {
276         declaredTests.forEach((m, test) -> {
277             if (test.getAttachedMethod() == null) {
278                 try {
279                     Arguments argumentsAnno = getAnnotation(m, Arguments.class);
280                     TestFormat.check(argumentsAnno != null || m.getParameterCount() == 0, "Missing @Arguments annotation to define arguments of " + m);
281                     BaseTest baseTest = new BaseTest(test, shouldExcludeTest(m.getName()));
282                     allTests.add(baseTest);
283                     if (PRINT_VALID_IR_RULES) {
284                         irMatchRulePrinter.emitRuleEncoding(m, baseTest.isSkipped());
285                     }
286                 } catch (TestFormatException e) {
287                     // Failure logged. Continue and report later.
288                 }
289             }
290         });
291     }
292 
293     /**
294      * Check if user wants to exclude this test by checking the -DTest and -DExclude lists.
295      */
296     private boolean shouldExcludeTest(String testName) {
297         boolean hasTestList = testList != null;
298         boolean hasExcludeList = excludeList != null;
299         if (hasTestList) {
300             return !testList.contains(testName) || (hasExcludeList && excludeList.contains(testName));
301         } else if (hasExcludeList) {
302             return excludeList.contains(testName);
303         }
304         return false;
305     }
306 
307     /**
308      * Generate replay compilation files.
309      */
310     private void addReplay() {
311         String directive = "[{ match: \"*.*\", DumpReplay: true }]";
312         TestFramework.check(WHITE_BOX.addCompilerDirective(directive) == 1, "Failed to add DUMP_REPLAY directive");
313     }
314 
315     private void processControlAnnotations(Class<?> clazz) {
316         if (IGNORE_COMPILER_CONTROLS) {
317             return;
318         }
319         // Also apply compile commands to all inner classes of 'clazz'.
320         ArrayList<Class<?>> classes = new ArrayList<>(Arrays.asList(clazz.getDeclaredClasses()));
321         classes.add(clazz);
322         for (Class<?> c : classes) {
323             applyClassAnnotations(c);
324             List<Executable> executables = new ArrayList<>(Arrays.asList(c.getDeclaredMethods()));
325             Collections.addAll(executables, c.getDeclaredConstructors());
326             for (Executable ex : executables) {
327                 checkClassAnnotations(ex);
328                 try {
329                     applyIndependentCompilationCommands(ex);
330                 } catch (TestFormatException e) {
331                     // Failure logged. Continue and report later.
332                 }
333             }
334 
335             // Only force compilation now because above annotations affect inlining
336             for (Executable ex : executables) {
337                 try {
338                     applyForceCompileCommand(ex);
339                 } catch (TestFormatException e) {
340                     // Failure logged. Continue and report later.
341                 }
342             }
343         }
344     }
345 
346     private void applyClassAnnotations(Class<?> c) {
347         ForceCompileClassInitializer anno = getAnnotation(c, ForceCompileClassInitializer.class);
348         if (anno == null) {
349             return;
350         }
351 
352         // Compile class initializer
353         CompLevel level = anno.value();
354         if (level == CompLevel.SKIP || level == CompLevel.WAIT_FOR_COMPILATION) {
355             TestFormat.failNoThrow("Cannot define compilation level SKIP or WAIT_FOR_COMPILATION in " +
356                                    "@ForceCompileClassInitializer at " + c);
357             return;
358         }
359         level = restrictCompLevel(anno.value());
360         if (level != CompLevel.SKIP) {
361             // Make sure class is initialized to avoid compilation bailout of <clinit>
362             getClassObject(c.getName(), "nested"); // calls Class.forName() to initialize 'c'
363             TestFormat.checkNoThrow(WHITE_BOX.enqueueInitializerForCompilation(c, level.getValue()),
364                                     "Failed to enqueue <clinit> of " + c + " for compilation. Did you specify "
365                                     + "@ForceCompileClassInitializer without providing a static class initialization? "
366                                     + "Make sure to provide any form of static initialization or remove the annotation.");
367         }
368     }
369 
370     private void checkClassAnnotations(Executable ex) {
371         TestFormat.checkNoThrow(getAnnotation(ex, ForceCompileClassInitializer.class) == null,
372                                 "@ForceCompileClassInitializer only allowed at classes but not at method " + ex);
373     }
374 
375     /**
376      * Exclude a method from compilation with a compiler randomly. Return the compiler for which the method was made
377      * not compilable.
378      */
379     public static Compiler excludeRandomly(Executable ex) {
380         Compiler compiler = switch (Utils.getRandomInstance().nextInt() % 3) {
381             case 1 -> Compiler.C1;
382             case 2 -> Compiler.C2;
383             default -> Compiler.ANY;
384         };
385         WHITE_BOX.makeMethodNotCompilable(ex, compiler.getValue(), false);
386         WHITE_BOX.makeMethodNotCompilable(ex, compiler.getValue(), true);
387         System.out.println("Excluding from " + compiler.name() + " compilation: " + ex);
388         return compiler;
389     }
390 
391     private void applyIndependentCompilationCommands(Executable ex) {
392         ForceInline forceInlineAnno = getAnnotation(ex, ForceInline.class);
393         DontInline dontInlineAnno = getAnnotation(ex, DontInline.class);
394         ForceCompile forceCompileAnno = getAnnotation(ex, ForceCompile.class);
395         DontCompile dontCompileAnno = getAnnotation(ex, DontCompile.class);
396         checkCompilationCommandAnnotations(ex, forceInlineAnno, dontInlineAnno, forceCompileAnno, dontCompileAnno);
397         // First handle inline annotations
398         if (dontInlineAnno != null) {
399             WHITE_BOX.testSetDontInlineMethod(ex, true);
400         } else if (forceInlineAnno != null) {
401             WHITE_BOX.testSetForceInlineMethod(ex, true);
402         }
403         if (dontCompileAnno != null) {
404             dontCompileWithCompiler(ex, dontCompileAnno.value());
405         }
406         if (EXCLUDE_RANDOM && getAnnotation(ex, Test.class) == null && forceCompileAnno == null && dontCompileAnno == null) {
407             // Randomly exclude helper methods from compilation
408             if (Utils.getRandomInstance().nextBoolean()) {
409                 excludeRandomly(ex);
410             }
411         }
412     }
413 
414     private void checkCompilationCommandAnnotations(Executable ex, ForceInline forceInlineAnno, DontInline dontInlineAnno, ForceCompile forceCompileAnno, DontCompile dontCompileAnno) {
415         Test testAnno = getAnnotation(ex, Test.class);
416         Run runAnno = getAnnotation(ex, Run.class);
417         Check checkAnno = getAnnotation(ex, Check.class);
418         TestFormat.check((testAnno == null && runAnno == null && checkAnno == null) || Stream.of(forceCompileAnno, dontCompileAnno, forceInlineAnno, dontInlineAnno).noneMatch(Objects::nonNull),
419                          "Cannot use explicit compile command annotations (@ForceInline, @DontInline, " +
420                          "@ForceCompile or @DontCompile) together with @Test, @Check or @Run: " + ex + ". Use compLevel in @Test for fine tuning.");
421         if (Stream.of(forceInlineAnno, dontCompileAnno, dontInlineAnno).filter(Objects::nonNull).count() > 1) {
422             // Failure
423             TestFormat.check(dontCompileAnno == null || dontInlineAnno == null,
424                              "@DontInline is implicitely done with @DontCompile annotation at " + ex);
425             TestFormat.fail("Cannot mix @ForceInline, @DontInline and @DontCompile at the same time at " + ex);
426         }
427         TestFormat.check(forceInlineAnno == null || dontInlineAnno == null, "Cannot have @ForceInline and @DontInline at the same time at " + ex);
428         if (forceCompileAnno != null && dontCompileAnno != null) {
429             CompLevel forceCompileLevel = forceCompileAnno.value();
430             Compiler dontCompileCompiler = dontCompileAnno.value();
431             TestFormat.check(dontCompileCompiler != Compiler.ANY,
432                              "Cannot have @DontCompile(Compiler.ANY) and @ForceCompile at the same time at " + ex);
433             TestFormat.check(forceCompileLevel != CompLevel.ANY,
434                              "Cannot have @ForceCompile(CompLevel.ANY) and @DontCompile at the same time at " + ex);
435             TestFormat.check(forceCompileLevel.isNotCompilationLevelOfCompiler(dontCompileCompiler),
436                              "Overlapping compilation level and compiler with @ForceCompile and @DontCompile at " + ex);
437         }
438     }
439 
440     /**
441      * Exlude the method from compilation and make sure it is not inlined.
442      */
443     private void dontCompileAndDontInlineMethod(Method m) {
444         if (!IGNORE_COMPILER_CONTROLS) {
445             WHITE_BOX.makeMethodNotCompilable(m, CompLevel.ANY.getValue(), true);
446             WHITE_BOX.makeMethodNotCompilable(m, CompLevel.ANY.getValue(), false);
447             WHITE_BOX.testSetDontInlineMethod(m, true);
448         }
449     }
450 
451     private void dontCompileWithCompiler(Executable ex, Compiler compiler) {
452         if (VERBOSE) {
453             System.out.println("dontCompileWithCompiler " + ex + " , compiler = " + compiler.name());
454         }
455         WHITE_BOX.makeMethodNotCompilable(ex, compiler.getValue(), true);
456         WHITE_BOX.makeMethodNotCompilable(ex, compiler.getValue(), false);
457         if (compiler == Compiler.ANY) {
458             WHITE_BOX.testSetDontInlineMethod(ex, true);
459         }
460     }
461 
462     private void applyForceCompileCommand(Executable ex) {
463         ForceCompile forceCompileAnno = getAnnotation(ex, ForceCompile.class);
464         if (forceCompileAnno != null) {
465             CompLevel compLevel = forceCompileAnno.value();
466             TestFormat.check(compLevel != CompLevel.SKIP && compLevel != CompLevel.WAIT_FOR_COMPILATION,
467                              "Cannot define compilation level SKIP or WAIT_FOR_COMPILATION in @ForceCompile at " + ex);
468             compLevel = restrictCompLevel(forceCompileAnno.value());
469             if (FLIP_C1_C2) {
470                 compLevel = compLevel.flipCompLevel();
471                 compLevel = restrictCompLevel(compLevel.flipCompLevel());
472             }
473             if (EXCLUDE_RANDOM) {
474                 compLevel = compLevel.excludeCompilationRandomly(ex);
475             }
476             if (compLevel != CompLevel.SKIP) {
477                 enqueueForCompilation(ex, compLevel);
478                 forceCompileMap.put(ex, compLevel);
479             }
480         }
481     }
482 
483     static void enqueueForCompilation(Executable ex, CompLevel requestedCompLevel) {
484         if (TestVM.VERBOSE) {
485             System.out.println("enqueueForCompilation " + ex + ", level = " + requestedCompLevel);
486         }
487         CompLevel compLevel = restrictCompLevel(requestedCompLevel);
488         if (compLevel != CompLevel.SKIP) {
489             WHITE_BOX.enqueueMethodForCompilation(ex, compLevel.getValue());
490         } else {
491             System.out.println("Skipped compilation on level " + requestedCompLevel + " due to VM flags not allowing it.");
492         }
493     }
494 
495     /**
496      * Setup @Test annotated method an add them to the declaredTests map to have a convenient way of accessing them
497      * once setting up a framework test (base  checked, or custom run test).
498      */
499     private void setupDeclaredTests() {
500         for (Method m : testClass.getDeclaredMethods()) {
501             Test testAnno = getAnnotation(m, Test.class);
502             try {
503                 if (testAnno != null) {
504                     addDeclaredTest(m);
505                 } else {
506                     TestFormat.checkNoThrow(!m.isAnnotationPresent(IR.class), "Found @IR annotation on non-@Test method " + m);
507                     TestFormat.checkNoThrow(!m.isAnnotationPresent(Warmup.class) || getAnnotation(m, Run.class) != null,
508                                             "Found @Warmup annotation on non-@Test or non-@Run method " + m);
509                 }
510             } catch (TestFormatException e) {
511                 // Failure logged. Continue and report later.
512             }
513         }
514         TestFormat.checkNoThrow(!declaredTests.isEmpty(), "Did not specify any @Test methods in " + testClass);
515     }
516 
517     private void addDeclaredTest(Method m) {
518         Test testAnno = getAnnotation(m, Test.class);
519         checkTestAnnotations(m, testAnno);
520         Warmup warmup = getAnnotation(m, Warmup.class);
521         int warmupIterations = WARMUP_ITERATIONS;
522         if (warmup != null) {
523             warmupIterations = warmup.value();
524             TestFormat.checkNoThrow(warmupIterations >= 0, "Cannot have negative value for @Warmup at " + m);
525         }
526 
527         if (!IGNORE_COMPILER_CONTROLS) {
528             // Don't inline test methods by default. Do not apply this when -DIgnoreCompilerControls=true is set.
529             WHITE_BOX.testSetDontInlineMethod(m, true);
530         }
531         CompLevel compLevel = restrictCompLevel(testAnno.compLevel());
532         if (FLIP_C1_C2) {
533             compLevel = compLevel.flipCompLevel();
534             compLevel = restrictCompLevel(compLevel.flipCompLevel());
535         }
536         if (EXCLUDE_RANDOM) {
537             compLevel = compLevel.excludeCompilationRandomly(m);
538         }
539         DeclaredTest test = new DeclaredTest(m, ArgumentValue.getArguments(m), compLevel, warmupIterations);
540         declaredTests.put(m, test);
541         testMethodMap.put(m.getName(), m);
542     }
543 
544     private void checkTestAnnotations(Method m, Test testAnno) {
545         TestFormat.check(!testMethodMap.containsKey(m.getName()),
546                          "Cannot overload two @Test methods: " + m + ", " + testMethodMap.get(m.getName()));
547         TestFormat.check(testAnno != null, m + " must be a method with a @Test annotation");
548 
549         Check checkAnno = getAnnotation(m, Check.class);
550         Run runAnno = getAnnotation(m, Run.class);
551         TestFormat.check(checkAnno == null && runAnno == null,
552                          m + " has invalid @Check or @Run annotation while @Test annotation is present.");
553 
554         TestFormat.checkNoThrow(Arrays.stream(m.getParameterTypes()).noneMatch(AbstractInfo.class::isAssignableFrom),
555                                 "Cannot " + AbstractInfo.class + " or any of its subclasses as parameter type at " +
556                                 "@Test method " + m);
557 
558         TestFormat.checkNoThrow(!AbstractInfo.class.isAssignableFrom(m.getReturnType()),
559                                 "Cannot " + AbstractInfo.class + " or any of its subclasses as return type at " +
560                                 "@Test method " + m);
561     }
562 
563 
564     /**
565      * Get the appropriate level as permitted by the test scenario and VM flags.
566      */
567     private static CompLevel restrictCompLevel(CompLevel compLevel) {
568         if (!USE_COMPILER) {
569             return CompLevel.SKIP;
570         }
571         if (compLevel == CompLevel.ANY) {
572             // Use highest available compilation level by default (usually C2).
573             compLevel = TIERED_COMPILATION_STOP_AT_LEVEL;
574         }
575         if (TEST_C1 && compLevel == CompLevel.C2) {
576             return CompLevel.SKIP;
577         }
578         if ((!TIERED_COMPILATION && !CLIENT_VM) && compLevel.getValue() < CompLevel.C2.getValue()) {
579             return CompLevel.SKIP;
580         }
581         if ((TIERED_COMPILATION || CLIENT_VM) && compLevel.getValue() > TIERED_COMPILATION_STOP_AT_LEVEL.getValue()) {
582             return CompLevel.SKIP;
583         }
584         return compLevel;
585     }
586 
587     /**
588      * Verify that the helper classes do not contain illegal framework annotations and then apply the actions as
589      * specified by the different helper class annotations.
590      */
591     private void processHelperClasses() {
592         if (helperClasses != null) {
593             for (Class<?> helperClass : helperClasses) {
594                 // Process the helper classes and apply the explicit compile commands
595                 TestFormat.checkNoThrow(helperClass != testClass,
596                                         "Cannot specify test " + testClass + " as helper class, too.");
597                 checkHelperClass(helperClass);
598                 processControlAnnotations(helperClass);
599             }
600         }
601     }
602 
603     /**
604      * First set up checked (with @Check) and custom run tests (with @Run). All remaining unmatched/unused @Test methods
605      * are treated as base tests and set up as such later.
606      */
607     private void setupCheckedAndCustomRunTests() {
608         for (Method m : testClass.getDeclaredMethods()) {
609             Check checkAnno = getAnnotation(m, Check.class);
610             Run runAnno = getAnnotation(m, Run.class);
611             Arguments argumentsAnno = getAnnotation(m, Arguments.class);
612             try {
613                 TestFormat.check(argumentsAnno == null || (checkAnno == null && runAnno == null),
614                                  "Cannot have @Argument annotation in combination with @Run or @Check at " + m);
615                 if (checkAnno != null) {
616                     addCheckedTest(m, checkAnno, runAnno);
617                 } else if (runAnno != null) {
618                     addCustomRunTest(m, runAnno);
619                 }
620             } catch (TestFormatException e) {
621                 // Failure logged. Continue and report later.
622             }
623         }
624     }
625 
626     /**
627      * Set up a checked test by first verifying the correct format of the @Test and @Check method and then adding it
628      * to the allTests list which keeps track of all framework tests that are eventually executed.
629      */
630     private void addCheckedTest(Method m, Check checkAnno, Run runAnno) {
631         Method testMethod = testMethodMap.get(checkAnno.test());
632         DeclaredTest test = declaredTests.get(testMethod);
633         checkCheckedTest(m, checkAnno, runAnno, testMethod, test);
634         test.setAttachedMethod(m);
635         TestFormat.check(getAnnotation(testMethod, Arguments.class) != null || testMethod.getParameterCount() == 0,
636                          "Missing @Arguments annotation to define arguments of " + testMethod + " required by "
637                          + "checked test " + m);
638         CheckedTest.Parameter parameter = getCheckedTestParameter(m, testMethod);
639         dontCompileAndDontInlineMethod(m);
640         CheckedTest checkedTest = new CheckedTest(test, m, checkAnno, parameter, shouldExcludeTest(testMethod.getName()));
641         allTests.add(checkedTest);
642         if (PRINT_VALID_IR_RULES) {
643             // Only need to emit IR verification information if IR verification is actually performed.
644             irMatchRulePrinter.emitRuleEncoding(testMethod, checkedTest.isSkipped());
645         }
646     }
647 
648     private void checkCheckedTest(Method m, Check checkAnno, Run runAnno, Method testMethod, DeclaredTest test) {
649         TestFormat.check(runAnno == null, m + " has invalid @Run annotation while @Check annotation is present.");
650         TestFormat.check(testMethod != null, "Did not find associated test method \"" + m.getDeclaringClass().getName()
651                                              + "." + checkAnno.test() + "\" for @Check at " + m);
652         TestFormat.check(test != null, "Missing @Test annotation for associated test method " + testMethod + " for @Check at " + m);
653         Method attachedMethod = test.getAttachedMethod();
654         TestFormat.check(attachedMethod == null,
655                          "Cannot use @Test " + testMethod + " for more than one @Run or one @Check method. Found: " + m + ", " + attachedMethod);
656     }
657 
658     /**
659      * Only allow parameters as specified in {@link Check}.
660      */
661     private CheckedTest.Parameter getCheckedTestParameter(Method m, Method testMethod) {
662         boolean firstParameterTestInfo = m.getParameterCount() > 0 && m.getParameterTypes()[0].equals(TestInfo.class);
663         boolean secondParameterTestInfo = m.getParameterCount() > 1 && m.getParameterTypes()[1].equals(TestInfo.class);
664         CheckedTest.Parameter parameter = null;
665         Class<?> testReturnType = testMethod.getReturnType();
666         switch (m.getParameterCount()) {
667             case 0 -> parameter = CheckedTest.Parameter.NONE;
668             case 1 -> {
669                 TestFormat.checkNoThrow(firstParameterTestInfo || m.getParameterTypes()[0] == testReturnType,
670                                         "Single-parameter version of @Check method " + m + " must match return type of @Test " + testMethod);
671                 parameter = firstParameterTestInfo ? CheckedTest.Parameter.TEST_INFO_ONLY : CheckedTest.Parameter.RETURN_ONLY;
672             }
673             case 2 -> {
674                 TestFormat.checkNoThrow(m.getParameterTypes()[0] == testReturnType && secondParameterTestInfo,
675                                         "Two-parameter version of @Check method " + m + " must provide as first parameter the same"
676                                         + " return type as @Test method " + testMethod + " and as second parameter an object of " + TestInfo.class);
677                 parameter = CheckedTest.Parameter.BOTH;
678             }
679             default -> TestFormat.failNoThrow("@Check method " + m + " must provide either a none, single or two-parameter variant.");
680         }
681         return parameter;
682     }
683 
684     /**
685      * Set up a custom run test by first verifying the correct format of the @Test and @Run method and then adding it
686      * to the allTests list which keeps track of all framework tests that are eventually executed.
687      */
688     private void addCustomRunTest(Method m, Run runAnno) {
689         checkRunMethod(m, runAnno);
690         List<DeclaredTest> tests = new ArrayList<>();
691         boolean shouldExcludeTest = true;
692         for (String testName : runAnno.test()) {
693             try {
694                 Method testMethod = testMethodMap.get(testName);
695                 DeclaredTest test = declaredTests.get(testMethod);
696                 checkCustomRunTest(m, testName, testMethod, test, runAnno.mode());
697                 test.setAttachedMethod(m);
698                 tests.add(test);
699                 // Only exclude custom run test if all test methods excluded
700                 shouldExcludeTest &= shouldExcludeTest(testMethod.getName());
701             } catch (TestFormatException e) {
702                 // Logged, continue.
703             }
704         }
705         if (tests.isEmpty()) {
706             return; // There was a format violation. Return.
707         }
708         dontCompileAndDontInlineMethod(m);
709         CustomRunTest customRunTest = new CustomRunTest(m, getAnnotation(m, Warmup.class), runAnno, tests, shouldExcludeTest);
710         allTests.add(customRunTest);
711         if (PRINT_VALID_IR_RULES) {
712             tests.forEach(test -> irMatchRulePrinter.emitRuleEncoding(test.getTestMethod(), customRunTest.isSkipped()));
713         }
714     }
715 
716     /**
717      * Only allow parameters as specified in {@link Run}.
718      */
719     private void checkCustomRunTest(Method m, String testName, Method testMethod, DeclaredTest test, RunMode runMode) {
720         TestFormat.check(testMethod != null, "Did not find associated @Test method \""  + m.getDeclaringClass().getName()
721                                              + "." + testName + "\" specified in @Run at " + m);
722         TestFormat.check(test != null,
723                          "Missing @Test annotation for associated test method " + testName + " for @Run at " + m);
724         Method attachedMethod = test.getAttachedMethod();
725         TestFormat.check(attachedMethod == null,
726                          "Cannot use @Test " + testMethod + " for more than one @Run/@Check method. Found: "
727                          + m + ", " + attachedMethod);
728         TestFormat.check(!test.hasArguments(),
729                          "Cannot use @Arguments at test method " + testMethod + " in combination with @Run method " + m);
730         Warmup warmupAnno = getAnnotation(testMethod, Warmup.class);
731         TestFormat.checkNoThrow(warmupAnno == null,
732                                 "Cannot set @Warmup at @Test method " + testMethod + " when used with its @Run method "
733                                 + m + ". Use @Warmup at @Run method instead.");
734         Test testAnno = getAnnotation(testMethod, Test.class);
735         TestFormat.checkNoThrow(runMode != RunMode.STANDALONE || testAnno.compLevel() == CompLevel.ANY,
736                                 "Setting explicit compilation level for @Test method " + testMethod + " has no effect "
737                                 + "when used with STANDALONE @Run method " + m);
738     }
739 
740     private void checkRunMethod(Method m, Run runAnno) {
741         TestFormat.check(runAnno.test().length > 0, "@Run method " + m + " must specify at least one test method");
742         TestFormat.checkNoThrow(m.getParameterCount() == 0 || (m.getParameterCount() == 1 && m.getParameterTypes()[0].equals(RunInfo.class)),
743                                 "@Run method " + m + " must specify either no parameter or exactly one " + RunInfo.class + " parameter.");
744         Warmup warmupAnno = getAnnotation(m, Warmup.class);
745         TestFormat.checkNoThrow(warmupAnno == null || runAnno.mode() != RunMode.STANDALONE,
746                                 "Cannot set @Warmup at @Run method " + m + " when used with RunMode.STANDALONE. The @Run method is only invoked once.");
747     }
748 
749     private static <T extends Annotation> T getAnnotation(AnnotatedElement element, Class<T> c) {
750         T[] annos =  element.getAnnotationsByType(c);
751         TestFormat.check(annos.length < 2, element + " has duplicated annotations");
752         return Arrays.stream(annos).findFirst().orElse(null);
753     }
754 
755     /**
756      * Ensure that all compilations that were enforced (added to compilation queue) by framework annotations are
757      * completed. Wait if necessary for a short amount of time for their completion.
758      */
759     private void checkForcedCompilationsCompleted() {
760         if (forceCompileMap.isEmpty()) {
761             return;
762         }
763         final long started = System.currentTimeMillis();
764         long elapsed;
765         do {
766             forceCompileMap.entrySet().removeIf(entry -> WHITE_BOX.getMethodCompilationLevel(entry.getKey()) == entry.getValue().getValue());
767             if (forceCompileMap.isEmpty()) {
768                 // All @ForceCompile methods are compiled at the requested level.
769                 return;
770             }
771             // Retry again if not yet compiled.
772             forceCompileMap.forEach(TestVM::enqueueForCompilation);
773             elapsed = System.currentTimeMillis() - started;
774         } while (elapsed < 5000);
775         StringBuilder builder = new StringBuilder();
776         forceCompileMap.forEach((key, value) -> builder.append("- ").append(key).append(" at CompLevel.").append(value)
777                                                        .append(System.lineSeparator()));
778         throw new TestRunException("Could not force compile the following @ForceCompile methods:"
779                                    + System.lineSeparator() + builder.toString());
780     }
781 
782     /**
783      * Once all framework tests are collected, they are run in this method.
784      */
785     private void runTests() {
786         TreeMap<Long, String> durations = (PRINT_TIMES || VERBOSE) ? new TreeMap<>() : null;
787         long startTime = System.nanoTime();
788         List<AbstractTest> testList;
789         boolean testFilterPresent = testFilterPresent();
790         if (testFilterPresent) {
791             // Only run the specified tests by the user filters -DTest and/or -DExclude.
792             testList = allTests.stream().filter(test -> !test.isSkipped()).collect(Collectors.toList());
793             if (testList.isEmpty()) {
794                 // Throw an exception to inform the user about an empty specified test set with -DTest and/or -DExclude
795                 throw new NoTestsRunException();
796             }
797         } else {
798             testList = allTests;
799         }
800 
801         if (SHUFFLE_TESTS) {
802             // Execute tests in random order (execution sequence affects profiling). This is done by default.
803             Collections.shuffle(testList, Utils.getRandomInstance());
804         }
805         StringBuilder builder = new StringBuilder();
806         int failures = 0;
807 
808         // Execute all tests and keep track of each exception that is thrown. These are then reported once all tests
809         // are executing. This prevents a premature exit without running all tests.
810         for (AbstractTest test : testList) {
811             if (VERBOSE) {
812                 System.out.println("Run " + test.toString());
813             }
814             if (testFilterPresent) {
815                 TestFrameworkSocket.write("Run " + test.toString(), TestFrameworkSocket.TESTLIST_TAG, true);
816             }
817             try {
818                 test.run();
819             } catch (TestRunException e) {
820                 StringWriter sw = new StringWriter();
821                 PrintWriter pw = new PrintWriter(sw);
822                 e.printStackTrace(pw);
823                 builder.append(test.toString()).append(":").append(System.lineSeparator()).append(sw.toString())
824                        .append(System.lineSeparator()).append(System.lineSeparator());
825                 failures++;
826             }
827             if (PRINT_TIMES || VERBOSE) {
828                 long endTime = System.nanoTime();
829                 long duration = (endTime - startTime);
830                 durations.put(duration, test.getName());
831                 if (VERBOSE) {
832                     System.out.println("Done " + test.getName() + ": " + duration + " ns = " + (duration / 1000000) + " ms");
833                 }
834             }
835             if (GC_AFTER) {
836                 System.out.println("doing GC");
837                 WHITE_BOX.fullGC();
838             }
839         }
840 
841         // Print execution times
842         if (VERBOSE || PRINT_TIMES) {
843             System.out.println(System.lineSeparator() + System.lineSeparator() + "Test execution times:");
844             for (Map.Entry<Long, String> entry : durations.entrySet()) {
845                 System.out.format("%-10s%15d ns%n", entry.getValue() + ":", entry.getKey());
846             }
847         }
848 
849         if (failures > 0) {
850             // Finally, report all occurred exceptions in a nice format.
851             String msg = System.lineSeparator() + System.lineSeparator() + "Test Failures (" + failures + ")"
852                          + System.lineSeparator() + "----------------" + "-".repeat(String.valueOf(failures).length());
853             throw new TestRunException(msg + System.lineSeparator() + builder.toString());
854         }
855     }
856 
857     private boolean testFilterPresent() {
858         return testList != null || excludeList != null;
859     }
860 
861     enum TriState {
862         Maybe,
863         Yes,
864         No
865     }
866 
867     public static void compile(Method m, CompLevel compLevel) {
868         TestRun.check(compLevel != CompLevel.SKIP && compLevel != CompLevel.WAIT_FOR_COMPILATION,
869                       "Invalid compilation request with level " + compLevel);
870         enqueueForCompilation(m, compLevel);
871     }
872 
873     public static void deoptimize(Method m) {
874         WHITE_BOX.deoptimizeMethod(m);
875     }
876 
877     public static boolean isCompiled(Method m) {
878         return compiledAtLevel(m, CompLevel.ANY) == TriState.Yes;
879     }
880 
881     public static boolean isC1Compiled(Method m) {
882         return compiledByC1(m) == TriState.Yes;
883     }
884 
885     public static boolean isC2Compiled(Method m) {
886         return compiledByC2(m) == TriState.Yes;
887     }
888 
889     public static boolean isCompiledAtLevel(Method m, CompLevel compLevel) {
890         return compiledAtLevel(m, compLevel) == TriState.Yes;
891     }
892 
893     public static void assertDeoptimizedByC1(Method m) {
894         if (notUnstableDeoptAssertion(m, CompLevel.C1_SIMPLE)) {
895             TestRun.check(compiledByC1(m) != TriState.Yes || PER_METHOD_TRAP_LIMIT == 0 || !PROFILE_INTERPRETER,
896                           m + " should have been deoptimized by C1");
897         }
898     }
899 
900     public static void assertDeoptimizedByC2(Method m) {
901         if (notUnstableDeoptAssertion(m, CompLevel.C2)) {
902             TestRun.check(compiledByC2(m) != TriState.Yes || PER_METHOD_TRAP_LIMIT == 0 || !PROFILE_INTERPRETER,
903                           m + " should have been deoptimized by C2");
904         }
905     }
906 
907     /**
908      * Some VM flags could make the deopt assertions unstable.
909      */
910     private static boolean notUnstableDeoptAssertion(Method m, CompLevel level) {
911         return (USE_COMPILER && !XCOMP && !IGNORE_COMPILER_CONTROLS && !TEST_C1 &&
912                 (!EXCLUDE_RANDOM || WHITE_BOX.isMethodCompilable(m, level.getValue(), false)));
913     }
914 
915     public static void assertCompiledByC1(Method m) {
916         TestRun.check(compiledByC1(m) != TriState.No, m + " should have been C1 compiled");
917     }
918 
919     public static void assertCompiledByC2(Method m) {
920         TestRun.check(compiledByC2(m) != TriState.No, m + " should have been C2 compiled");
921     }
922 
923     public static void assertCompiledAtLevel(Method m, CompLevel level) {
924         TestRun.check(compiledAtLevel(m, level) != TriState.No, m + " should have been compiled at level " + level.name());
925     }
926 
927     public static void assertNotCompiled(Method m) {
928         TestRun.check(!isC1Compiled(m), m + " should not have been compiled by C1");
929         TestRun.check(!isC2Compiled(m), m + " should not have been compiled by C2");
930     }
931 
932     public static void assertCompiled(Method m) {
933         TestRun.check(compiledByC1(m) != TriState.No || compiledByC2(m) != TriState.No, m + " should have been compiled");
934     }
935 
936     private static TriState compiledByC1(Method m) {
937         TriState triState = compiledAtLevel(m, CompLevel.C1_SIMPLE);
938         if (triState != TriState.No) {
939             return triState;
940         }
941         triState = compiledAtLevel(m, CompLevel.C1_LIMITED_PROFILE);
942         if (triState != TriState.No) {
943             return triState;
944         }
945         triState = compiledAtLevel(m, CompLevel.C1_FULL_PROFILE);
946         return triState;
947     }
948 
949     private static TriState compiledByC2(Method m) {
950         return compiledAtLevel(m, CompLevel.C2);
951     }
952 
953     private static TriState compiledAtLevel(Method m, CompLevel level) {
954         if (WHITE_BOX.isMethodCompiled(m, false)) {
955             switch (level) {
956                 case C1_SIMPLE, C1_LIMITED_PROFILE, C1_FULL_PROFILE, C2 -> {
957                     if (WHITE_BOX.getMethodCompilationLevel(m, false) == level.getValue()) {
958                         return TriState.Yes;
959                     }
960                 }
961                 case ANY -> {
962                     return TriState.Yes;
963                 }
964                 default -> throw new TestRunException("compiledAtLevel() should not be called with " + level);
965             }
966         }
967         if (!USE_COMPILER || XCOMP || TEST_C1 || IGNORE_COMPILER_CONTROLS || FLIP_C1_C2 ||
968             (EXCLUDE_RANDOM && !WHITE_BOX.isMethodCompilable(m, level.getValue(), false))) {
969             return TriState.Maybe;
970         }
971         return TriState.No;
972     }
973 }