CompilerWhiteBoxTest.java 18.4 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
/*
 * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
 */

24 25
import com.sun.management.HotSpotDiagnosticMXBean;
import com.sun.management.VMOption;
26 27 28
import sun.hotspot.WhiteBox;
import sun.management.ManagementFactoryHelper;

29 30
import java.lang.reflect.Constructor;
import java.lang.reflect.Executable;
31
import java.lang.reflect.Method;
32 33
import java.util.Objects;
import java.util.concurrent.Callable;
34

35 36 37
/**
 * Abstract class for WhiteBox testing of JIT.
 *
38 39 40
 * @author igor.ignatyev@oracle.com
 */
public abstract class CompilerWhiteBoxTest {
41 42 43 44
    /** {@code CompLevel::CompLevel_none} -- Interpreter */
    protected static int COMP_LEVEL_NONE = 0;
    /** {@code CompLevel::CompLevel_any}, {@code CompLevel::CompLevel_all} */
    protected static int COMP_LEVEL_ANY = -1;
45 46
    /** {@code CompLevel::CompLevel_simple} -- C1 */
    protected static int COMP_LEVEL_SIMPLE = 1;
47 48 49 50
    /** {@code CompLevel::CompLevel_limited_profile} -- C1, invocation & backedge counters */
    protected static int COMP_LEVEL_LIMITED_PROFILE = 2;
    /** {@code CompLevel::CompLevel_full_profile} -- C1, invocation & backedge counters + mdo */
    protected static int COMP_LEVEL_FULL_PROFILE = 3;
51 52
    /** {@code CompLevel::CompLevel_full_optimization} -- C2 or Shark */
    protected static int COMP_LEVEL_FULL_OPTIMIZATION = 4;
53 54
    /** Maximal value for CompLeveL */
    protected static int COMP_LEVEL_MAX = COMP_LEVEL_FULL_OPTIMIZATION;
55

56
    /** Instance of WhiteBox */
57
    protected static final WhiteBox WHITE_BOX = WhiteBox.getWhiteBox();
58
    /** Value of {@code -XX:CompileThreshold} */
59 60
    protected static final int COMPILE_THRESHOLD
            = Integer.parseInt(getVMOption("CompileThreshold", "10000"));
61
    /** Value of {@code -XX:BackgroundCompilation} */
62 63
    protected static final boolean BACKGROUND_COMPILATION
            = Boolean.valueOf(getVMOption("BackgroundCompilation", "true"));
64
    /** Value of {@code -XX:TieredCompilation} */
65 66
    protected static final boolean TIERED_COMPILATION
            = Boolean.valueOf(getVMOption("TieredCompilation", "false"));
67 68 69
    /** Value of {@code -XX:TieredStopAtLevel} */
    protected static final int TIERED_STOP_AT_LEVEL
            = Integer.parseInt(getVMOption("TieredStopAtLevel", "0"));
70 71 72
    /** Flag for verbose output, true if {@code -Dverbose} specified */
    protected static final boolean IS_VERBOSE
            = System.getProperty("verbose") != null;
73 74 75 76
    /** count of invocation to triger compilation */
    protected static final int THRESHOLD;
    /** count of invocation to triger OSR compilation */
    protected static final long BACKEDGE_THRESHOLD;
77 78 79
    /** Value of {@code java.vm.info} (interpreted|mixed|comp mode) */
    protected static final String MODE
            = System.getProperty("java.vm.info");
80 81 82 83 84 85 86 87 88 89 90

    static {
        if (TIERED_COMPILATION) {
            THRESHOLD = 150000;
            BACKEDGE_THRESHOLD = 0xFFFFFFFFL;
        } else {
            THRESHOLD = COMPILE_THRESHOLD;
            BACKEDGE_THRESHOLD = COMPILE_THRESHOLD * Long.parseLong(getVMOption(
                    "OnStackReplacePercentage"));
        }
    }
91

92 93 94 95 96 97 98
    /**
     * Returns value of VM option.
     *
     * @param name option's name
     * @return value of option or {@code null}, if option doesn't exist
     * @throws NullPointerException if name is null
     */
99
    protected static String getVMOption(String name) {
100
        Objects.requireNonNull(name);
101 102
        HotSpotDiagnosticMXBean diagnostic
                = ManagementFactoryHelper.getDiagnosticMXBean();
103 104 105 106 107 108 109
        VMOption tmp;
        try {
            tmp = diagnostic.getVMOption(name);
        } catch (IllegalArgumentException e) {
            tmp = null;
        }
        return (tmp == null ? null : tmp.getValue());
110 111
    }

112 113 114 115 116 117 118 119 120
    /**
     * Returns value of VM option or default value.
     *
     * @param name         option's name
     * @param defaultValue default value
     * @return value of option or {@code defaultValue}, if option doesn't exist
     * @throws NullPointerException if name is null
     * @see #getVMOption(String)
     */
121 122
    protected static String getVMOption(String name, String defaultValue) {
        String result = getVMOption(name);
123 124 125
        return result == null ? defaultValue : result;
    }

126 127 128 129 130 131 132 133 134 135 136
    /** copy of is_c1_compile(int) from utilities/globalDefinitions.hpp */
    protected static boolean isC1Compile(int compLevel) {
        return (compLevel > COMP_LEVEL_NONE)
                && (compLevel < COMP_LEVEL_FULL_OPTIMIZATION);
    }

    /** copy of is_c2_compile(int) from utilities/globalDefinitions.hpp */
    protected static boolean isC2Compile(int compLevel) {
        return compLevel == COMP_LEVEL_FULL_OPTIMIZATION;
    }

137 138
    /** tested method */
    protected final Executable method;
139
    protected final TestCase testCase;
140 141 142 143 144 145 146 147 148 149

    /**
     * Constructor.
     *
     * @param testCase object, that contains tested method and way to invoke it.
     */
    protected CompilerWhiteBoxTest(TestCase testCase) {
        Objects.requireNonNull(testCase);
        System.out.println("TEST CASE:" + testCase.name());
        method = testCase.executable;
150
        this.testCase = testCase;
151 152 153 154 155 156 157 158 159 160 161 162
    }

    /**
     * Template method for testing. Prints tested method's info before
     * {@linkplain #test()} and after {@linkplain #test()} or on thrown
     * exception.
     *
     * @throws RuntimeException if method {@linkplain #test()} throws any
     *                          exception
     * @see #test()
     */
    protected final void runTest() {
163 164 165 166 167 168
        if (ManagementFactoryHelper.getCompilationMXBean() == null) {
            System.err.println(
                    "Warning: test is not applicable in interpreted mode");
            return;
        }
        System.out.println("at test's start:");
169
        printInfo();
170 171 172 173
        try {
            test();
        } catch (Exception e) {
            System.out.printf("on exception '%s':", e.getMessage());
174
            printInfo();
175
            e.printStackTrace();
176 177 178
            if (e instanceof RuntimeException) {
                throw (RuntimeException) e;
            }
179 180 181
            throw new RuntimeException(e);
        }
        System.out.println("at test's end:");
182
        printInfo();
183 184
    }

185 186 187 188 189 190 191 192
    /**
     * Checks, that {@linkplain #method} is not compiled.
     *
     * @throws RuntimeException if {@linkplain #method} is in compiler queue or
     *                          is compiled, or if {@linkplain #method} has zero
     *                          compilation level.
     */
    protected final void checkNotCompiled() {
193 194 195
        if (WHITE_BOX.isMethodQueuedForCompilation(method)) {
            throw new RuntimeException(method + " must not be in queue");
        }
196
        if (WHITE_BOX.isMethodCompiled(method, false)) {
197 198
            throw new RuntimeException(method + " must be not compiled");
        }
199
        if (WHITE_BOX.getMethodCompilationLevel(method, false) != 0) {
200 201
            throw new RuntimeException(method + " comp_level must be == 0");
        }
202 203 204 205 206 207
        if (WHITE_BOX.isMethodCompiled(method, true)) {
            throw new RuntimeException(method + " must be not osr_compiled");
        }
        if (WHITE_BOX.getMethodCompilationLevel(method, true) != 0) {
            throw new RuntimeException(method + " osr_comp_level must be == 0");
        }
208
   }
209

210 211 212 213 214 215 216 217
    /**
     * Checks, that {@linkplain #method} is compiled.
     *
     * @throws RuntimeException if {@linkplain #method} isn't in compiler queue
     *                          and isn't compiled, or if {@linkplain #method}
     *                          has nonzero compilation level
     */
    protected final void checkCompiled() {
218
        final long start = System.currentTimeMillis();
219
        waitBackgroundCompilation();
220 221 222 223 224
        if (WHITE_BOX.isMethodQueuedForCompilation(method)) {
            System.err.printf("Warning: %s is still in queue after %dms%n",
                    method, System.currentTimeMillis() - start);
            return;
        }
225 226 227
        if (!WHITE_BOX.isMethodCompiled(method, testCase.isOsr)) {
            throw new RuntimeException(method + " must be "
                    + (testCase.isOsr ? "osr_" : "") + "compiled");
228
        }
229 230 231 232 233 234 235 236 237 238 239
        if (WHITE_BOX.getMethodCompilationLevel(method, testCase.isOsr) == 0) {
            throw new RuntimeException(method
                    + (testCase.isOsr ? " osr_" : " ")
                    + "comp_level must be != 0");
        }
    }

    protected final void deoptimize() {
        WHITE_BOX.deoptimizeMethod(method, testCase.isOsr);
        if (testCase.isOsr) {
            WHITE_BOX.deoptimizeMethod(method, false);
240 241 242
        }
    }

243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264
    protected final int getCompLevel() {
        return WHITE_BOX.getMethodCompilationLevel(method, testCase.isOsr);
    }

    protected final boolean isCompilable() {
        return WHITE_BOX.isMethodCompilable(method, COMP_LEVEL_ANY,
                testCase.isOsr);
    }

    protected final boolean isCompilable(int compLevel) {
        return WHITE_BOX.isMethodCompilable(method, compLevel, testCase.isOsr);
    }

    protected final void makeNotCompilable() {
        WHITE_BOX.makeMethodNotCompilable(method, COMP_LEVEL_ANY,
                testCase.isOsr);
    }

    protected final void makeNotCompilable(int compLevel) {
        WHITE_BOX.makeMethodNotCompilable(method, compLevel, testCase.isOsr);
    }

265 266 267 268
    /**
     * Waits for completion of background compilation of {@linkplain #method}.
     */
    protected final void waitBackgroundCompilation() {
269 270 271
        if (!BACKGROUND_COMPILATION) {
            return;
        }
272
        final Object obj = new Object();
273 274 275 276 277 278 279
        for (int i = 0; i < 10
                && WHITE_BOX.isMethodQueuedForCompilation(method); ++i) {
            synchronized (obj) {
                try {
                    obj.wait(1000);
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
280 281 282 283 284
                }
            }
        }
    }

285 286 287 288
    /**
     * Prints information about {@linkplain #method}.
     */
    protected final void printInfo() {
289 290
        System.out.printf("%n%s:%n", method);
        System.out.printf("\tcompilable:\t%b%n",
291
                WHITE_BOX.isMethodCompilable(method, COMP_LEVEL_ANY, false));
292
        System.out.printf("\tcompiled:\t%b%n",
293
                WHITE_BOX.isMethodCompiled(method, false));
294
        System.out.printf("\tcomp_level:\t%d%n",
295 296 297 298 299 300 301 302
                WHITE_BOX.getMethodCompilationLevel(method, false));
        System.out.printf("\tosr_compilable:\t%b%n",
                WHITE_BOX.isMethodCompilable(method, COMP_LEVEL_ANY, true));
        System.out.printf("\tosr_compiled:\t%b%n",
                WHITE_BOX.isMethodCompiled(method, true));
        System.out.printf("\tosr_comp_level:\t%d%n",
                WHITE_BOX.getMethodCompilationLevel(method, true));
         System.out.printf("\tin_queue:\t%b%n",
303 304 305 306 307
                WHITE_BOX.isMethodQueuedForCompilation(method));
        System.out.printf("compile_queues_size:\t%d%n%n",
                WHITE_BOX.getCompileQueuesSize());
    }

308 309 310
    /**
     * Executes testing.
     */
311 312
    protected abstract void test() throws Exception;

313 314
    /**
     * Tries to trigger compilation of {@linkplain #method} by call
315
     * {@linkplain #testCase.callable} enough times.
316 317 318 319
     *
     * @return accumulated result
     * @see #compile(int)
     */
320
    protected final int compile() {
321 322 323 324 325
        if (testCase.isOsr) {
            return compile(1);
        } else {
            return compile(THRESHOLD);
        }
326 327
    }

328 329
    /**
     * Tries to trigger compilation of {@linkplain #method} by call
330
     * {@linkplain #testCase.callable} specified times.
331 332 333 334
     *
     * @param count invocation count
     * @return accumulated result
     */
335
    protected final int compile(int count) {
336
        int result = 0;
337
        Integer tmp;
338
        for (int i = 0; i < count; ++i) {
339
            try {
340
                tmp = testCase.callable.call();
341 342 343 344
            } catch (Exception e) {
                tmp = null;
            }
            result += tmp == null ? 0 : tmp;
345
        }
346 347 348
        if (IS_VERBOSE) {
            System.out.println("method was invoked " + count + " times");
        }
349 350
        return result;
    }
351
}
352

353 354 355 356 357
/**
 * Utility structure containing tested method and object to invoke it.
 */
enum TestCase {
    /** constructor test case */
358
    CONSTRUCTOR_TEST(Helper.CONSTRUCTOR, Helper.CONSTRUCTOR_CALLABLE, false),
359
    /** method test case */
360
    METOD_TEST(Helper.METHOD, Helper.METHOD_CALLABLE, false),
361
    /** static method test case */
362 363 364 365 366 367 368 369 370
    STATIC_TEST(Helper.STATIC, Helper.STATIC_CALLABLE, false),

    /** OSR constructor test case */
    OSR_CONSTRUCTOR_TEST(Helper.OSR_CONSTRUCTOR,
            Helper.OSR_CONSTRUCTOR_CALLABLE, true),
     /** OSR method test case */
    OSR_METOD_TEST(Helper.OSR_METHOD, Helper.OSR_METHOD_CALLABLE, true),
    /** OSR static method test case */
    OSR_STATIC_TEST(Helper.OSR_STATIC, Helper.OSR_STATIC_CALLABLE, true);
371 372 373 374 375

    /** tested method */
    final Executable executable;
    /** object to invoke {@linkplain #executable} */
    final Callable<Integer> callable;
376 377
   /** flag for OSR test case */
    final boolean isOsr;
378

379 380
    private TestCase(Executable executable, Callable<Integer> callable,
            boolean isOsr) {
381 382
        this.executable = executable;
        this.callable = callable;
383
        this.isOsr = isOsr;
384 385 386
    }

    private static class Helper {
387

388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413
        private static final Callable<Integer> CONSTRUCTOR_CALLABLE
                = new Callable<Integer>() {
            @Override
            public Integer call() throws Exception {
                return new Helper(1337).hashCode();
            }
        };

        private static final Callable<Integer> METHOD_CALLABLE
                = new Callable<Integer>() {
            private final Helper helper = new Helper();

            @Override
            public Integer call() throws Exception {
                return helper.method();
            }
        };

        private static final Callable<Integer> STATIC_CALLABLE
                = new Callable<Integer>() {
            @Override
            public Integer call() throws Exception {
                return staticMethod();
            }
        };

414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440
        private static final Callable<Integer> OSR_CONSTRUCTOR_CALLABLE
                = new Callable<Integer>() {
            @Override
            public Integer call() throws Exception {
                return new Helper(null).hashCode();
            }
        };

        private static final Callable<Integer> OSR_METHOD_CALLABLE
                = new Callable<Integer>() {
            private final Helper helper = new Helper();

            @Override
            public Integer call() throws Exception {
                return helper.osrMethod();
            }
        };

        private static final Callable<Integer> OSR_STATIC_CALLABLE
                = new Callable<Integer>() {
            @Override
            public Integer call() throws Exception {
                return osrStaticMethod();
            }
        };


441
        private static final Constructor CONSTRUCTOR;
442
        private static final Constructor OSR_CONSTRUCTOR;
443 444
        private static final Method METHOD;
        private static final Method STATIC;
445 446
        private static final Method OSR_METHOD;
        private static final Method OSR_STATIC;
447 448 449 450 451 452 453 454 455

        static {
            try {
                CONSTRUCTOR = Helper.class.getDeclaredConstructor(int.class);
            } catch (NoSuchMethodException | SecurityException e) {
                throw new RuntimeException(
                        "exception on getting method Helper.<init>(int)", e);
            }
            try {
456 457
                OSR_CONSTRUCTOR = Helper.class.getDeclaredConstructor(
                        Object.class);
458 459
            } catch (NoSuchMethodException | SecurityException e) {
                throw new RuntimeException(
460
                        "exception on getting method Helper.<init>(Object)", e);
461
            }
462 463 464 465 466 467 468
            METHOD = getMethod("method");
            STATIC = getMethod("staticMethod");
            OSR_METHOD = getMethod("osrMethod");
            OSR_STATIC = getMethod("osrStaticMethod");
        }

        private static Method getMethod(String name) {
469
            try {
470
                return Helper.class.getDeclaredMethod(name);
471 472
            } catch (NoSuchMethodException | SecurityException e) {
                throw new RuntimeException(
473
                        "exception on getting method Helper." + name, e);
474
            }
475

476 477 478 479 480 481 482 483 484 485
        }

        private static int staticMethod() {
            return 1138;
        }

        private int method() {
            return 42;
        }

486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501
        private static int osrStaticMethod() {
            int result = 0;
            for (long i = 0; i < CompilerWhiteBoxTest.BACKEDGE_THRESHOLD; ++i) {
                result += staticMethod();
            }
            return result;
        }

        private int osrMethod() {
            int result = 0;
            for (long i = 0; i < CompilerWhiteBoxTest.BACKEDGE_THRESHOLD; ++i) {
                result += method();
            }
            return result;
        }

502 503
        private final int x;

504
        // for method and OSR method test case
505 506 507 508
        public Helper() {
            x = 0;
        }

509 510 511 512 513 514 515 516 517 518
        // for OSR constructor test case
        private Helper(Object o) {
            int result = 0;
            for (long i = 0; i < CompilerWhiteBoxTest.BACKEDGE_THRESHOLD; ++i) {
                result += method();
            }
            x = result;
        }

        // for constructor test case
519 520 521 522 523 524 525 526
        private Helper(int x) {
            this.x = x;
        }

        @Override
        public int hashCode() {
            return x;
        }
527 528
    }
}