Path: blob/master/src/hotspot/share/compiler/compilationPolicy.cpp
64440 views
/*1* Copyright (c) 2010, 2022, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation.7*8* This code is distributed in the hope that it will be useful, but WITHOUT9* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or10* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License11* version 2 for more details (a copy is included in the LICENSE file that12* accompanied this code).13*14* You should have received a copy of the GNU General Public License version15* 2 along with this work; if not, write to the Free Software Foundation,16* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.17*18* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA19* or visit www.oracle.com if you need additional information or have any20* questions.21*22*/2324#include "precompiled.hpp"25#include "code/scopeDesc.hpp"26#include "compiler/compilationPolicy.hpp"27#include "compiler/compileBroker.hpp"28#include "compiler/compilerOracle.hpp"29#include "memory/resourceArea.hpp"30#include "oops/methodData.hpp"31#include "oops/method.inline.hpp"32#include "oops/oop.inline.hpp"33#include "prims/jvmtiExport.hpp"34#include "runtime/arguments.hpp"35#include "runtime/deoptimization.hpp"36#include "runtime/frame.hpp"37#include "runtime/frame.inline.hpp"38#include "runtime/globals_extension.hpp"39#include "runtime/handles.inline.hpp"40#include "runtime/safepoint.hpp"41#include "runtime/safepointVerifiers.hpp"4243#if INCLUDE_JVMCI44#include "jvmci/jvmci.hpp"45#endif4647#ifdef COMPILER148#include "c1/c1_Compiler.hpp"49#endif5051#ifdef COMPILER252#include "opto/c2compiler.hpp"53#endif5455jlong CompilationPolicy::_start_time = 0;56int CompilationPolicy::_c1_count = 0;57int CompilationPolicy::_c2_count = 0;58double CompilationPolicy::_increase_threshold_at_ratio = 0;5960void compilationPolicy_init() {61CompilationPolicy::initialize();62}6364int CompilationPolicy::compiler_count(CompLevel comp_level) {65if (is_c1_compile(comp_level)) {66return c1_count();67} else if (is_c2_compile(comp_level)) {68return c2_count();69}70return 0;71}7273// Returns true if m must be compiled before executing it74// This is intended to force compiles for methods (usually for75// debugging) that would otherwise be interpreted for some reason.76bool CompilationPolicy::must_be_compiled(const methodHandle& m, int comp_level) {77// Don't allow Xcomp to cause compiles in replay mode78if (ReplayCompiles) return false;7980if (m->has_compiled_code()) return false; // already compiled81if (!can_be_compiled(m, comp_level)) return false;8283return !UseInterpreter || // must compile all methods84(UseCompiler && AlwaysCompileLoopMethods && m->has_loops() && CompileBroker::should_compile_new_jobs()); // eagerly compile loop methods85}8687void CompilationPolicy::compile_if_required(const methodHandle& m, TRAPS) {88if (must_be_compiled(m)) {89// This path is unusual, mostly used by the '-Xcomp' stress test mode.9091if (!THREAD->can_call_java() || THREAD->is_Compiler_thread()) {92// don't force compilation, resolve was on behalf of compiler93return;94}95if (m->method_holder()->is_not_initialized()) {96// 'is_not_initialized' means not only '!is_initialized', but also that97// initialization has not been started yet ('!being_initialized')98// Do not force compilation of methods in uninitialized classes.99// Note that doing this would throw an assert later,100// in CompileBroker::compile_method.101// We sometimes use the link resolver to do reflective lookups102// even before classes are initialized.103return;104}105CompLevel level = initial_compile_level(m);106if (PrintTieredEvents) {107print_event(COMPILE, m(), m(), InvocationEntryBci, level);108}109CompileBroker::compile_method(m, InvocationEntryBci, level, methodHandle(), 0, CompileTask::Reason_MustBeCompiled, THREAD);110}111}112113static inline CompLevel adjust_level_for_compilability_query(CompLevel comp_level) {114if (comp_level == CompLevel_any) {115if (CompilerConfig::is_c1_only()) {116comp_level = CompLevel_simple;117} else if (CompilerConfig::is_c2_or_jvmci_compiler_only()) {118comp_level = CompLevel_full_optimization;119}120}121return comp_level;122}123124// Returns true if m is allowed to be compiled125bool CompilationPolicy::can_be_compiled(const methodHandle& m, int comp_level) {126// allow any levels for WhiteBox127assert(WhiteBoxAPI || comp_level == CompLevel_any || is_compile(comp_level), "illegal compilation level");128129if (m->is_abstract()) return false;130if (DontCompileHugeMethods && m->code_size() > HugeMethodLimit) return false;131132// Math intrinsics should never be compiled as this can lead to133// monotonicity problems because the interpreter will prefer the134// compiled code to the intrinsic version. This can't happen in135// production because the invocation counter can't be incremented136// but we shouldn't expose the system to this problem in testing137// modes.138if (!AbstractInterpreter::can_be_compiled(m)) {139return false;140}141comp_level = adjust_level_for_compilability_query((CompLevel) comp_level);142if (comp_level == CompLevel_any || is_compile(comp_level)) {143return !m->is_not_compilable(comp_level);144}145return false;146}147148// Returns true if m is allowed to be osr compiled149bool CompilationPolicy::can_be_osr_compiled(const methodHandle& m, int comp_level) {150bool result = false;151comp_level = adjust_level_for_compilability_query((CompLevel) comp_level);152if (comp_level == CompLevel_any || is_compile(comp_level)) {153result = !m->is_not_osr_compilable(comp_level);154}155return (result && can_be_compiled(m, comp_level));156}157158bool CompilationPolicy::is_compilation_enabled() {159// NOTE: CompileBroker::should_compile_new_jobs() checks for UseCompiler160return CompileBroker::should_compile_new_jobs();161}162163CompileTask* CompilationPolicy::select_task_helper(CompileQueue* compile_queue) {164// Remove unloaded methods from the queue165for (CompileTask* task = compile_queue->first(); task != NULL; ) {166CompileTask* next = task->next();167if (task->is_unloaded()) {168compile_queue->remove_and_mark_stale(task);169}170task = next;171}172#if INCLUDE_JVMCI173if (UseJVMCICompiler && !BackgroundCompilation) {174/*175* In blocking compilation mode, the CompileBroker will make176* compilations submitted by a JVMCI compiler thread non-blocking. These177* compilations should be scheduled after all blocking compilations178* to service non-compiler related compilations sooner and reduce the179* chance of such compilations timing out.180*/181for (CompileTask* task = compile_queue->first(); task != NULL; task = task->next()) {182if (task->is_blocking()) {183return task;184}185}186}187#endif188return compile_queue->first();189}190191// Simple methods are as good being compiled with C1 as C2.192// Determine if a given method is such a case.193bool CompilationPolicy::is_trivial(const methodHandle& method) {194if (method->is_accessor() ||195method->is_constant_getter()) {196return true;197}198return false;199}200201bool CompilationPolicy::force_comp_at_level_simple(const methodHandle& method) {202if (CompilationModeFlag::quick_internal()) {203#if INCLUDE_JVMCI204if (UseJVMCICompiler) {205AbstractCompiler* comp = CompileBroker::compiler(CompLevel_full_optimization);206if (comp != NULL && comp->is_jvmci() && ((JVMCICompiler*) comp)->force_comp_at_level_simple(method)) {207return true;208}209}210#endif211}212return false;213}214215CompLevel CompilationPolicy::comp_level(Method* method) {216CompiledMethod *nm = method->code();217if (nm != NULL && nm->is_in_use()) {218return (CompLevel)nm->comp_level();219}220return CompLevel_none;221}222223// Call and loop predicates determine whether a transition to a higher224// compilation level should be performed (pointers to predicate functions225// are passed to common()).226// Tier?LoadFeedback is basically a coefficient that determines of227// how many methods per compiler thread can be in the queue before228// the threshold values double.229class LoopPredicate : AllStatic {230public:231static bool apply_scaled(const methodHandle& method, CompLevel cur_level, int i, int b, double scale) {232double threshold_scaling;233if (CompilerOracle::has_option_value(method, CompileCommand::CompileThresholdScaling, threshold_scaling)) {234scale *= threshold_scaling;235}236switch(cur_level) {237case CompLevel_none:238case CompLevel_limited_profile:239return b >= Tier3BackEdgeThreshold * scale;240case CompLevel_full_profile:241return b >= Tier4BackEdgeThreshold * scale;242default:243return true;244}245}246247static bool apply(const methodHandle& method, CompLevel cur_level, int i, int b) {248double k = 1;249switch(cur_level) {250case CompLevel_none:251// Fall through252case CompLevel_limited_profile: {253k = CompilationPolicy::threshold_scale(CompLevel_full_profile, Tier3LoadFeedback);254break;255}256case CompLevel_full_profile: {257k = CompilationPolicy::threshold_scale(CompLevel_full_optimization, Tier4LoadFeedback);258break;259}260default:261return true;262}263return apply_scaled(method, cur_level, i, b, k);264}265};266267class CallPredicate : AllStatic {268public:269static bool apply_scaled(const methodHandle& method, CompLevel cur_level, int i, int b, double scale) {270double threshold_scaling;271if (CompilerOracle::has_option_value(method, CompileCommand::CompileThresholdScaling, threshold_scaling)) {272scale *= threshold_scaling;273}274switch(cur_level) {275case CompLevel_none:276case CompLevel_limited_profile:277return (i >= Tier3InvocationThreshold * scale) ||278(i >= Tier3MinInvocationThreshold * scale && i + b >= Tier3CompileThreshold * scale);279case CompLevel_full_profile:280return (i >= Tier4InvocationThreshold * scale) ||281(i >= Tier4MinInvocationThreshold * scale && i + b >= Tier4CompileThreshold * scale);282default:283return true;284}285}286287static bool apply(const methodHandle& method, CompLevel cur_level, int i, int b) {288double k = 1;289switch(cur_level) {290case CompLevel_none:291case CompLevel_limited_profile: {292k = CompilationPolicy::threshold_scale(CompLevel_full_profile, Tier3LoadFeedback);293break;294}295case CompLevel_full_profile: {296k = CompilationPolicy::threshold_scale(CompLevel_full_optimization, Tier4LoadFeedback);297break;298}299default:300return true;301}302return apply_scaled(method, cur_level, i, b, k);303}304};305306double CompilationPolicy::threshold_scale(CompLevel level, int feedback_k) {307int comp_count = compiler_count(level);308if (comp_count > 0) {309double queue_size = CompileBroker::queue_size(level);310double k = queue_size / (feedback_k * comp_count) + 1;311312// Increase C1 compile threshold when the code cache is filled more313// than specified by IncreaseFirstTierCompileThresholdAt percentage.314// The main intention is to keep enough free space for C2 compiled code315// to achieve peak performance if the code cache is under stress.316if (CompilerConfig::is_tiered() && !CompilationModeFlag::disable_intermediate() && is_c1_compile(level)) {317double current_reverse_free_ratio = CodeCache::reverse_free_ratio();318if (current_reverse_free_ratio > _increase_threshold_at_ratio) {319k *= exp(current_reverse_free_ratio - _increase_threshold_at_ratio);320}321}322return k;323}324return 1;325}326327void CompilationPolicy::print_counters(const char* prefix, const Method* m) {328int invocation_count = m->invocation_count();329int backedge_count = m->backedge_count();330MethodData* mdh = m->method_data();331int mdo_invocations = 0, mdo_backedges = 0;332int mdo_invocations_start = 0, mdo_backedges_start = 0;333if (mdh != NULL) {334mdo_invocations = mdh->invocation_count();335mdo_backedges = mdh->backedge_count();336mdo_invocations_start = mdh->invocation_count_start();337mdo_backedges_start = mdh->backedge_count_start();338}339tty->print(" %stotal=%d,%d %smdo=%d(%d),%d(%d)", prefix,340invocation_count, backedge_count, prefix,341mdo_invocations, mdo_invocations_start,342mdo_backedges, mdo_backedges_start);343tty->print(" %smax levels=%d,%d", prefix,344m->highest_comp_level(), m->highest_osr_comp_level());345}346347// Print an event.348void CompilationPolicy::print_event(EventType type, const Method* m, const Method* im, int bci, CompLevel level) {349bool inlinee_event = m != im;350351ttyLocker tty_lock;352tty->print("%lf: [", os::elapsedTime());353354switch(type) {355case CALL:356tty->print("call");357break;358case LOOP:359tty->print("loop");360break;361case COMPILE:362tty->print("compile");363break;364case REMOVE_FROM_QUEUE:365tty->print("remove-from-queue");366break;367case UPDATE_IN_QUEUE:368tty->print("update-in-queue");369break;370case REPROFILE:371tty->print("reprofile");372break;373case MAKE_NOT_ENTRANT:374tty->print("make-not-entrant");375break;376default:377tty->print("unknown");378}379380tty->print(" level=%d ", level);381382ResourceMark rm;383char *method_name = m->name_and_sig_as_C_string();384tty->print("[%s", method_name);385if (inlinee_event) {386char *inlinee_name = im->name_and_sig_as_C_string();387tty->print(" [%s]] ", inlinee_name);388}389else tty->print("] ");390tty->print("@%d queues=%d,%d", bci, CompileBroker::queue_size(CompLevel_full_profile),391CompileBroker::queue_size(CompLevel_full_optimization));392393tty->print(" rate=");394if (m->prev_time() == 0) tty->print("n/a");395else tty->print("%f", m->rate());396397tty->print(" k=%.2lf,%.2lf", threshold_scale(CompLevel_full_profile, Tier3LoadFeedback),398threshold_scale(CompLevel_full_optimization, Tier4LoadFeedback));399400if (type != COMPILE) {401print_counters("", m);402if (inlinee_event) {403print_counters("inlinee ", im);404}405tty->print(" compilable=");406bool need_comma = false;407if (!m->is_not_compilable(CompLevel_full_profile)) {408tty->print("c1");409need_comma = true;410}411if (!m->is_not_osr_compilable(CompLevel_full_profile)) {412if (need_comma) tty->print(",");413tty->print("c1-osr");414need_comma = true;415}416if (!m->is_not_compilable(CompLevel_full_optimization)) {417if (need_comma) tty->print(",");418tty->print("c2");419need_comma = true;420}421if (!m->is_not_osr_compilable(CompLevel_full_optimization)) {422if (need_comma) tty->print(",");423tty->print("c2-osr");424}425tty->print(" status=");426if (m->queued_for_compilation()) {427tty->print("in-queue");428} else tty->print("idle");429}430tty->print_cr("]");431}432433void CompilationPolicy::initialize() {434if (!CompilerConfig::is_interpreter_only()) {435int count = CICompilerCount;436bool c1_only = CompilerConfig::is_c1_only();437bool c2_only = CompilerConfig::is_c2_or_jvmci_compiler_only();438439#ifdef _LP64440// Turn on ergonomic compiler count selection441if (FLAG_IS_DEFAULT(CICompilerCountPerCPU) && FLAG_IS_DEFAULT(CICompilerCount)) {442FLAG_SET_DEFAULT(CICompilerCountPerCPU, true);443}444if (CICompilerCountPerCPU) {445// Simple log n seems to grow too slowly for tiered, try something faster: log n * log log n446int log_cpu = log2i(os::active_processor_count());447int loglog_cpu = log2i(MAX2(log_cpu, 1));448count = MAX2(log_cpu * loglog_cpu * 3 / 2, 2);449// Make sure there is enough space in the code cache to hold all the compiler buffers450size_t c1_size = 0;451#ifdef COMPILER1452c1_size = Compiler::code_buffer_size();453#endif454size_t c2_size = 0;455#ifdef COMPILER2456c2_size = C2Compiler::initial_code_buffer_size();457#endif458size_t buffer_size = c1_only ? c1_size : (c1_size/3 + 2*c2_size/3);459int max_count = (ReservedCodeCacheSize - (CodeCacheMinimumUseSpace DEBUG_ONLY(* 3))) / (int)buffer_size;460if (count > max_count) {461// Lower the compiler count such that all buffers fit into the code cache462count = MAX2(max_count, c1_only ? 1 : 2);463}464FLAG_SET_ERGO(CICompilerCount, count);465}466#else467// On 32-bit systems, the number of compiler threads is limited to 3.468// On these systems, the virtual address space available to the JVM469// is usually limited to 2-4 GB (the exact value depends on the platform).470// As the compilers (especially C2) can consume a large amount of471// memory, scaling the number of compiler threads with the number of472// available cores can result in the exhaustion of the address space473/// available to the VM and thus cause the VM to crash.474if (FLAG_IS_DEFAULT(CICompilerCount)) {475count = 3;476FLAG_SET_ERGO(CICompilerCount, count);477}478#endif479480if (c1_only) {481// No C2 compiler thread required482set_c1_count(count);483} else if (c2_only) {484set_c2_count(count);485} else {486set_c1_count(MAX2(count / 3, 1));487set_c2_count(MAX2(count - c1_count(), 1));488}489assert(count == c1_count() + c2_count(), "inconsistent compiler thread count");490set_increase_threshold_at_ratio();491}492set_start_time(nanos_to_millis(os::javaTimeNanos()));493}494495496#ifdef ASSERT497bool CompilationPolicy::verify_level(CompLevel level) {498if (TieredCompilation && level > TieredStopAtLevel) {499return false;500}501// Check if there is a compiler to process the requested level502if (!CompilerConfig::is_c1_enabled() && is_c1_compile(level)) {503return false;504}505if (!CompilerConfig::is_c2_or_jvmci_compiler_enabled() && is_c2_compile(level)) {506return false;507}508509// Interpreter level is always valid.510if (level == CompLevel_none) {511return true;512}513if (CompilationModeFlag::normal()) {514return true;515} else if (CompilationModeFlag::quick_only()) {516return level == CompLevel_simple;517} else if (CompilationModeFlag::high_only()) {518return level == CompLevel_full_optimization;519} else if (CompilationModeFlag::high_only_quick_internal()) {520return level == CompLevel_full_optimization || level == CompLevel_simple;521}522return false;523}524#endif525526527CompLevel CompilationPolicy::highest_compile_level() {528CompLevel level = CompLevel_none;529// Setup the maximum level availible for the current compiler configuration.530if (!CompilerConfig::is_interpreter_only()) {531if (CompilerConfig::is_c2_or_jvmci_compiler_enabled()) {532level = CompLevel_full_optimization;533} else if (CompilerConfig::is_c1_enabled()) {534if (CompilerConfig::is_c1_simple_only()) {535level = CompLevel_simple;536} else {537level = CompLevel_full_profile;538}539}540}541// Clamp the maximum level with TieredStopAtLevel.542if (TieredCompilation) {543level = MIN2(level, (CompLevel) TieredStopAtLevel);544}545546// Fix it up if after the clamping it has become invalid.547// Bring it monotonically down depending on the next available level for548// the compilation mode.549if (!CompilationModeFlag::normal()) {550// a) quick_only - levels 2,3,4 are invalid; levels -1,0,1 are valid;551// b) high_only - levels 1,2,3 are invalid; levels -1,0,4 are valid;552// c) high_only_quick_internal - levels 2,3 are invalid; levels -1,0,1,4 are valid.553if (CompilationModeFlag::quick_only()) {554if (level == CompLevel_limited_profile || level == CompLevel_full_profile || level == CompLevel_full_optimization) {555level = CompLevel_simple;556}557} else if (CompilationModeFlag::high_only()) {558if (level == CompLevel_simple || level == CompLevel_limited_profile || level == CompLevel_full_profile) {559level = CompLevel_none;560}561} else if (CompilationModeFlag::high_only_quick_internal()) {562if (level == CompLevel_limited_profile || level == CompLevel_full_profile) {563level = CompLevel_simple;564}565}566}567568assert(verify_level(level), "Invalid highest compilation level: %d", level);569return level;570}571572CompLevel CompilationPolicy::limit_level(CompLevel level) {573level = MIN2(level, highest_compile_level());574assert(verify_level(level), "Invalid compilation level: %d", level);575return level;576}577578CompLevel CompilationPolicy::initial_compile_level(const methodHandle& method) {579CompLevel level = CompLevel_any;580if (CompilationModeFlag::normal()) {581level = CompLevel_full_profile;582} else if (CompilationModeFlag::quick_only()) {583level = CompLevel_simple;584} else if (CompilationModeFlag::high_only()) {585level = CompLevel_full_optimization;586} else if (CompilationModeFlag::high_only_quick_internal()) {587if (force_comp_at_level_simple(method)) {588level = CompLevel_simple;589} else {590level = CompLevel_full_optimization;591}592}593assert(level != CompLevel_any, "Unhandled compilation mode");594return limit_level(level);595}596597// Set carry flags on the counters if necessary598void CompilationPolicy::handle_counter_overflow(const methodHandle& method) {599MethodCounters *mcs = method->method_counters();600if (mcs != NULL) {601mcs->invocation_counter()->set_carry_on_overflow();602mcs->backedge_counter()->set_carry_on_overflow();603}604MethodData* mdo = method->method_data();605if (mdo != NULL) {606mdo->invocation_counter()->set_carry_on_overflow();607mdo->backedge_counter()->set_carry_on_overflow();608}609}610611// Called with the queue locked and with at least one element612CompileTask* CompilationPolicy::select_task(CompileQueue* compile_queue) {613CompileTask *max_blocking_task = NULL;614CompileTask *max_task = NULL;615Method* max_method = NULL;616617jlong t = nanos_to_millis(os::javaTimeNanos());618// Iterate through the queue and find a method with a maximum rate.619for (CompileTask* task = compile_queue->first(); task != NULL;) {620CompileTask* next_task = task->next();621// If a method was unloaded or has been stale for some time, remove it from the queue.622// Blocking tasks and tasks submitted from whitebox API don't become stale623if (task->is_unloaded()) {624compile_queue->remove_and_mark_stale(task);625task = next_task;626continue;627}628Method* method = task->method();629methodHandle mh(Thread::current(), method);630if (task->can_become_stale() && is_stale(t, TieredCompileTaskTimeout, mh) && !is_old(mh)) {631if (PrintTieredEvents) {632print_event(REMOVE_FROM_QUEUE, method, method, task->osr_bci(), (CompLevel) task->comp_level());633}634method->clear_queued_for_compilation();635compile_queue->remove_and_mark_stale(task);636task = next_task;637continue;638}639update_rate(t, mh);640if (max_task == NULL || compare_methods(method, max_method)) {641// Select a method with the highest rate642max_task = task;643max_method = method;644}645646if (task->is_blocking()) {647if (max_blocking_task == NULL || compare_methods(method, max_blocking_task->method())) {648max_blocking_task = task;649}650}651652task = next_task;653}654655if (max_blocking_task != NULL) {656// In blocking compilation mode, the CompileBroker will make657// compilations submitted by a JVMCI compiler thread non-blocking. These658// compilations should be scheduled after all blocking compilations659// to service non-compiler related compilations sooner and reduce the660// chance of such compilations timing out.661max_task = max_blocking_task;662max_method = max_task->method();663}664665methodHandle max_method_h(Thread::current(), max_method);666667if (max_task != NULL && max_task->comp_level() == CompLevel_full_profile && TieredStopAtLevel > CompLevel_full_profile &&668max_method != NULL && is_method_profiled(max_method_h) && !Arguments::is_compiler_only()) {669max_task->set_comp_level(CompLevel_limited_profile);670671if (CompileBroker::compilation_is_complete(max_method_h, max_task->osr_bci(), CompLevel_limited_profile)) {672if (PrintTieredEvents) {673print_event(REMOVE_FROM_QUEUE, max_method, max_method, max_task->osr_bci(), (CompLevel)max_task->comp_level());674}675compile_queue->remove_and_mark_stale(max_task);676max_method->clear_queued_for_compilation();677return NULL;678}679680if (PrintTieredEvents) {681print_event(UPDATE_IN_QUEUE, max_method, max_method, max_task->osr_bci(), (CompLevel)max_task->comp_level());682}683}684685return max_task;686}687688void CompilationPolicy::reprofile(ScopeDesc* trap_scope, bool is_osr) {689for (ScopeDesc* sd = trap_scope;; sd = sd->sender()) {690if (PrintTieredEvents) {691print_event(REPROFILE, sd->method(), sd->method(), InvocationEntryBci, CompLevel_none);692}693MethodData* mdo = sd->method()->method_data();694if (mdo != NULL) {695mdo->reset_start_counters();696}697if (sd->is_top()) break;698}699}700701nmethod* CompilationPolicy::event(const methodHandle& method, const methodHandle& inlinee,702int branch_bci, int bci, CompLevel comp_level, CompiledMethod* nm, TRAPS) {703if (PrintTieredEvents) {704print_event(bci == InvocationEntryBci ? CALL : LOOP, method(), inlinee(), bci, comp_level);705}706707if (comp_level == CompLevel_none &&708JvmtiExport::can_post_interpreter_events() &&709THREAD->is_interp_only_mode()) {710return NULL;711}712if (ReplayCompiles) {713// Don't trigger other compiles in testing mode714return NULL;715}716717handle_counter_overflow(method);718if (method() != inlinee()) {719handle_counter_overflow(inlinee);720}721722if (bci == InvocationEntryBci) {723method_invocation_event(method, inlinee, comp_level, nm, THREAD);724} else {725// method == inlinee if the event originated in the main method726method_back_branch_event(method, inlinee, bci, comp_level, nm, THREAD);727// Check if event led to a higher level OSR compilation728CompLevel expected_comp_level = MIN2(CompLevel_full_optimization, static_cast<CompLevel>(comp_level + 1));729if (!CompilationModeFlag::disable_intermediate() && inlinee->is_not_osr_compilable(expected_comp_level)) {730// It's not possble to reach the expected level so fall back to simple.731expected_comp_level = CompLevel_simple;732}733CompLevel max_osr_level = static_cast<CompLevel>(inlinee->highest_osr_comp_level());734if (max_osr_level >= expected_comp_level) { // fast check to avoid locking in a typical scenario735nmethod* osr_nm = inlinee->lookup_osr_nmethod_for(bci, expected_comp_level, false);736assert(osr_nm == NULL || osr_nm->comp_level() >= expected_comp_level, "lookup_osr_nmethod_for is broken");737if (osr_nm != NULL && osr_nm->comp_level() != comp_level) {738// Perform OSR with new nmethod739return osr_nm;740}741}742}743return NULL;744}745746// Check if the method can be compiled, change level if necessary747void CompilationPolicy::compile(const methodHandle& mh, int bci, CompLevel level, TRAPS) {748assert(verify_level(level), "Invalid compilation level requested: %d", level);749750if (level == CompLevel_none) {751if (mh->has_compiled_code()) {752// Happens when we switch to interpreter to profile.753MutexLocker ml(Compile_lock);754NoSafepointVerifier nsv;755if (mh->has_compiled_code()) {756mh->code()->make_not_used();757}758// Deoptimize immediately (we don't have to wait for a compile).759JavaThread* jt = THREAD;760RegisterMap map(jt, false);761frame fr = jt->last_frame().sender(&map);762Deoptimization::deoptimize_frame(jt, fr.id());763}764return;765}766767if (!CompilationModeFlag::disable_intermediate()) {768// Check if the method can be compiled. If it cannot be compiled with C1, continue profiling769// in the interpreter and then compile with C2 (the transition function will request that,770// see common() ). If the method cannot be compiled with C2 but still can with C1, compile it with771// pure C1.772if ((bci == InvocationEntryBci && !can_be_compiled(mh, level))) {773if (level == CompLevel_full_optimization && can_be_compiled(mh, CompLevel_simple)) {774compile(mh, bci, CompLevel_simple, THREAD);775}776return;777}778if ((bci != InvocationEntryBci && !can_be_osr_compiled(mh, level))) {779if (level == CompLevel_full_optimization && can_be_osr_compiled(mh, CompLevel_simple)) {780nmethod* osr_nm = mh->lookup_osr_nmethod_for(bci, CompLevel_simple, false);781if (osr_nm != NULL && osr_nm->comp_level() > CompLevel_simple) {782// Invalidate the existing OSR nmethod so that a compile at CompLevel_simple is permitted.783osr_nm->make_not_entrant();784}785compile(mh, bci, CompLevel_simple, THREAD);786}787return;788}789}790if (bci != InvocationEntryBci && mh->is_not_osr_compilable(level)) {791return;792}793if (!CompileBroker::compilation_is_in_queue(mh)) {794if (PrintTieredEvents) {795print_event(COMPILE, mh(), mh(), bci, level);796}797int hot_count = (bci == InvocationEntryBci) ? mh->invocation_count() : mh->backedge_count();798update_rate(nanos_to_millis(os::javaTimeNanos()), mh);799CompileBroker::compile_method(mh, bci, level, mh, hot_count, CompileTask::Reason_Tiered, THREAD);800}801}802803// update_rate() is called from select_task() while holding a compile queue lock.804void CompilationPolicy::update_rate(jlong t, const methodHandle& method) {805// Skip update if counters are absent.806// Can't allocate them since we are holding compile queue lock.807if (method->method_counters() == NULL) return;808809if (is_old(method)) {810// We don't remove old methods from the queue,811// so we can just zero the rate.812method->set_rate(0);813return;814}815816// We don't update the rate if we've just came out of a safepoint.817// delta_s is the time since last safepoint in milliseconds.818jlong delta_s = t - SafepointTracing::end_of_last_safepoint_ms();819jlong delta_t = t - (method->prev_time() != 0 ? method->prev_time() : start_time()); // milliseconds since the last measurement820// How many events were there since the last time?821int event_count = method->invocation_count() + method->backedge_count();822int delta_e = event_count - method->prev_event_count();823824// We should be running for at least 1ms.825if (delta_s >= TieredRateUpdateMinTime) {826// And we must've taken the previous point at least 1ms before.827if (delta_t >= TieredRateUpdateMinTime && delta_e > 0) {828method->set_prev_time(t);829method->set_prev_event_count(event_count);830method->set_rate((float)delta_e / (float)delta_t); // Rate is events per millisecond831} else {832if (delta_t > TieredRateUpdateMaxTime && delta_e == 0) {833// If nothing happened for 25ms, zero the rate. Don't modify prev values.834method->set_rate(0);835}836}837}838}839840// Check if this method has been stale for a given number of milliseconds.841// See select_task().842bool CompilationPolicy::is_stale(jlong t, jlong timeout, const methodHandle& method) {843jlong delta_s = t - SafepointTracing::end_of_last_safepoint_ms();844jlong delta_t = t - method->prev_time();845if (delta_t > timeout && delta_s > timeout) {846int event_count = method->invocation_count() + method->backedge_count();847int delta_e = event_count - method->prev_event_count();848// Return true if there were no events.849return delta_e == 0;850}851return false;852}853854// We don't remove old methods from the compile queue even if they have855// very low activity. See select_task().856bool CompilationPolicy::is_old(const methodHandle& method) {857int i = method->invocation_count();858int b = method->backedge_count();859double k = TieredOldPercentage / 100.0;860861return CallPredicate::apply_scaled(method, CompLevel_none, i, b, k) || LoopPredicate::apply_scaled(method, CompLevel_none, i, b, k);862}863864double CompilationPolicy::weight(Method* method) {865return (double)(method->rate() + 1) * (method->invocation_count() + 1) * (method->backedge_count() + 1);866}867868// Apply heuristics and return true if x should be compiled before y869bool CompilationPolicy::compare_methods(Method* x, Method* y) {870if (x->highest_comp_level() > y->highest_comp_level()) {871// recompilation after deopt872return true;873} else874if (x->highest_comp_level() == y->highest_comp_level()) {875if (weight(x) > weight(y)) {876return true;877}878}879return false;880}881882// Is method profiled enough?883bool CompilationPolicy::is_method_profiled(const methodHandle& method) {884MethodData* mdo = method->method_data();885if (mdo != NULL) {886int i = mdo->invocation_count_delta();887int b = mdo->backedge_count_delta();888return CallPredicate::apply_scaled(method, CompLevel_full_profile, i, b, 1);889}890return false;891}892893894// Determine is a method is mature.895bool CompilationPolicy::is_mature(Method* method) {896methodHandle mh(Thread::current(), method);897MethodData* mdo = method->method_data();898if (mdo != NULL) {899int i = mdo->invocation_count();900int b = mdo->backedge_count();901double k = ProfileMaturityPercentage / 100.0;902return CallPredicate::apply_scaled(mh, CompLevel_full_profile, i, b, k) || LoopPredicate::apply_scaled(mh, CompLevel_full_profile, i, b, k);903}904return false;905}906907// If a method is old enough and is still in the interpreter we would want to908// start profiling without waiting for the compiled method to arrive.909// We also take the load on compilers into the account.910bool CompilationPolicy::should_create_mdo(const methodHandle& method, CompLevel cur_level) {911if (cur_level != CompLevel_none || force_comp_at_level_simple(method) || CompilationModeFlag::quick_only() || !ProfileInterpreter) {912return false;913}914if (is_old(method)) {915return true;916}917int i = method->invocation_count();918int b = method->backedge_count();919double k = Tier0ProfilingStartPercentage / 100.0;920921// If the top level compiler is not keeping up, delay profiling.922if (CompileBroker::queue_size(CompLevel_full_optimization) <= Tier0Delay * compiler_count(CompLevel_full_optimization)) {923return CallPredicate::apply_scaled(method, CompLevel_none, i, b, k) || LoopPredicate::apply_scaled(method, CompLevel_none, i, b, k);924}925return false;926}927928// Inlining control: if we're compiling a profiled method with C1 and the callee929// is known to have OSRed in a C2 version, don't inline it.930bool CompilationPolicy::should_not_inline(ciEnv* env, ciMethod* callee) {931CompLevel comp_level = (CompLevel)env->comp_level();932if (comp_level == CompLevel_full_profile ||933comp_level == CompLevel_limited_profile) {934return callee->highest_osr_comp_level() == CompLevel_full_optimization;935}936return false;937}938939// Create MDO if necessary.940void CompilationPolicy::create_mdo(const methodHandle& mh, JavaThread* THREAD) {941if (mh->is_native() ||942mh->is_abstract() ||943mh->is_accessor() ||944mh->is_constant_getter()) {945return;946}947if (mh->method_data() == NULL) {948Method::build_interpreter_method_data(mh, CHECK_AND_CLEAR);949}950if (ProfileInterpreter) {951MethodData* mdo = mh->method_data();952if (mdo != NULL) {953frame last_frame = THREAD->last_frame();954if (last_frame.is_interpreted_frame() && mh == last_frame.interpreter_frame_method()) {955int bci = last_frame.interpreter_frame_bci();956address dp = mdo->bci_to_dp(bci);957last_frame.interpreter_frame_set_mdp(dp);958}959}960}961}962963964965/*966* Method states:967* 0 - interpreter (CompLevel_none)968* 1 - pure C1 (CompLevel_simple)969* 2 - C1 with invocation and backedge counting (CompLevel_limited_profile)970* 3 - C1 with full profiling (CompLevel_full_profile)971* 4 - C2 or Graal (CompLevel_full_optimization)972*973* Common state transition patterns:974* a. 0 -> 3 -> 4.975* The most common path. But note that even in this straightforward case976* profiling can start at level 0 and finish at level 3.977*978* b. 0 -> 2 -> 3 -> 4.979* This case occurs when the load on C2 is deemed too high. So, instead of transitioning980* into state 3 directly and over-profiling while a method is in the C2 queue we transition to981* level 2 and wait until the load on C2 decreases. This path is disabled for OSRs.982*983* c. 0 -> (3->2) -> 4.984* In this case we enqueue a method for compilation at level 3, but the C1 queue is long enough985* to enable the profiling to fully occur at level 0. In this case we change the compilation level986* of the method to 2 while the request is still in-queue, because it'll allow it to run much faster987* without full profiling while c2 is compiling.988*989* d. 0 -> 3 -> 1 or 0 -> 2 -> 1.990* After a method was once compiled with C1 it can be identified as trivial and be compiled to991* level 1. These transition can also occur if a method can't be compiled with C2 but can with C1.992*993* e. 0 -> 4.994* This can happen if a method fails C1 compilation (it will still be profiled in the interpreter)995* or because of a deopt that didn't require reprofiling (compilation won't happen in this case because996* the compiled version already exists).997*998* Note that since state 0 can be reached from any other state via deoptimization different loops999* are possible.1000*1001*/10021003// Common transition function. Given a predicate determines if a method should transition to another level.1004template<typename Predicate>1005CompLevel CompilationPolicy::common(const methodHandle& method, CompLevel cur_level, bool disable_feedback) {1006CompLevel next_level = cur_level;1007int i = method->invocation_count();1008int b = method->backedge_count();10091010if (force_comp_at_level_simple(method)) {1011next_level = CompLevel_simple;1012} else {1013if (is_trivial(method)) {1014next_level = CompilationModeFlag::disable_intermediate() ? CompLevel_full_optimization : CompLevel_simple;1015} else {1016switch(cur_level) {1017default: break;1018case CompLevel_none:1019// If we were at full profile level, would we switch to full opt?1020if (common<Predicate>(method, CompLevel_full_profile, disable_feedback) == CompLevel_full_optimization) {1021next_level = CompLevel_full_optimization;1022} else if (!CompilationModeFlag::disable_intermediate() && Predicate::apply(method, cur_level, i, b)) {1023// C1-generated fully profiled code is about 30% slower than the limited profile1024// code that has only invocation and backedge counters. The observation is that1025// if C2 queue is large enough we can spend too much time in the fully profiled code1026// while waiting for C2 to pick the method from the queue. To alleviate this problem1027// we introduce a feedback on the C2 queue size. If the C2 queue is sufficiently long1028// we choose to compile a limited profiled version and then recompile with full profiling1029// when the load on C2 goes down.1030if (!disable_feedback && CompileBroker::queue_size(CompLevel_full_optimization) >1031Tier3DelayOn * compiler_count(CompLevel_full_optimization)) {1032next_level = CompLevel_limited_profile;1033} else {1034next_level = CompLevel_full_profile;1035}1036}1037break;1038case CompLevel_limited_profile:1039if (is_method_profiled(method)) {1040// Special case: we got here because this method was fully profiled in the interpreter.1041next_level = CompLevel_full_optimization;1042} else {1043MethodData* mdo = method->method_data();1044if (mdo != NULL) {1045if (mdo->would_profile()) {1046if (disable_feedback || (CompileBroker::queue_size(CompLevel_full_optimization) <=1047Tier3DelayOff * compiler_count(CompLevel_full_optimization) &&1048Predicate::apply(method, cur_level, i, b))) {1049next_level = CompLevel_full_profile;1050}1051} else {1052next_level = CompLevel_full_optimization;1053}1054} else {1055// If there is no MDO we need to profile1056if (disable_feedback || (CompileBroker::queue_size(CompLevel_full_optimization) <=1057Tier3DelayOff * compiler_count(CompLevel_full_optimization) &&1058Predicate::apply(method, cur_level, i, b))) {1059next_level = CompLevel_full_profile;1060}1061}1062}1063break;1064case CompLevel_full_profile:1065{1066MethodData* mdo = method->method_data();1067if (mdo != NULL) {1068if (mdo->would_profile() || CompilationModeFlag::disable_intermediate()) {1069int mdo_i = mdo->invocation_count_delta();1070int mdo_b = mdo->backedge_count_delta();1071if (Predicate::apply(method, cur_level, mdo_i, mdo_b)) {1072next_level = CompLevel_full_optimization;1073}1074} else {1075next_level = CompLevel_full_optimization;1076}1077}1078}1079break;1080}1081}1082}1083return (next_level != cur_level) ? limit_level(next_level) : next_level;1084}1085108610871088// Determine if a method should be compiled with a normal entry point at a different level.1089CompLevel CompilationPolicy::call_event(const methodHandle& method, CompLevel cur_level, Thread* thread) {1090CompLevel osr_level = MIN2((CompLevel) method->highest_osr_comp_level(), common<LoopPredicate>(method, cur_level, true));1091CompLevel next_level = common<CallPredicate>(method, cur_level, is_old(method));10921093// If OSR method level is greater than the regular method level, the levels should be1094// equalized by raising the regular method level in order to avoid OSRs during each1095// invocation of the method.1096if (osr_level == CompLevel_full_optimization && cur_level == CompLevel_full_profile) {1097MethodData* mdo = method->method_data();1098guarantee(mdo != NULL, "MDO should not be NULL");1099if (mdo->invocation_count() >= 1) {1100next_level = CompLevel_full_optimization;1101}1102} else {1103next_level = MAX2(osr_level, next_level);1104}1105return next_level;1106}11071108// Determine if we should do an OSR compilation of a given method.1109CompLevel CompilationPolicy::loop_event(const methodHandle& method, CompLevel cur_level, Thread* thread) {1110CompLevel next_level = common<LoopPredicate>(method, cur_level, true);1111if (cur_level == CompLevel_none) {1112// If there is a live OSR method that means that we deopted to the interpreter1113// for the transition.1114CompLevel osr_level = MIN2((CompLevel)method->highest_osr_comp_level(), next_level);1115if (osr_level > CompLevel_none) {1116return osr_level;1117}1118}1119return next_level;1120}11211122// Handle the invocation event.1123void CompilationPolicy::method_invocation_event(const methodHandle& mh, const methodHandle& imh,1124CompLevel level, CompiledMethod* nm, TRAPS) {1125if (should_create_mdo(mh, level)) {1126create_mdo(mh, THREAD);1127}1128CompLevel next_level = call_event(mh, level, THREAD);1129if (next_level != level) {1130if (is_compilation_enabled() && !CompileBroker::compilation_is_in_queue(mh)) {1131compile(mh, InvocationEntryBci, next_level, THREAD);1132}1133}1134}11351136// Handle the back branch event. Notice that we can compile the method1137// with a regular entry from here.1138void CompilationPolicy::method_back_branch_event(const methodHandle& mh, const methodHandle& imh,1139int bci, CompLevel level, CompiledMethod* nm, TRAPS) {1140if (should_create_mdo(mh, level)) {1141create_mdo(mh, THREAD);1142}1143// Check if MDO should be created for the inlined method1144if (should_create_mdo(imh, level)) {1145create_mdo(imh, THREAD);1146}11471148if (is_compilation_enabled()) {1149CompLevel next_osr_level = loop_event(imh, level, THREAD);1150CompLevel max_osr_level = (CompLevel)imh->highest_osr_comp_level();1151// At the very least compile the OSR version1152if (!CompileBroker::compilation_is_in_queue(imh) && (next_osr_level != level)) {1153compile(imh, bci, next_osr_level, CHECK);1154}11551156// Use loop event as an opportunity to also check if there's been1157// enough calls.1158CompLevel cur_level, next_level;1159if (mh() != imh()) { // If there is an enclosing method1160{1161guarantee(nm != NULL, "Should have nmethod here");1162cur_level = comp_level(mh());1163next_level = call_event(mh, cur_level, THREAD);11641165if (max_osr_level == CompLevel_full_optimization) {1166// The inlinee OSRed to full opt, we need to modify the enclosing method to avoid deopts1167bool make_not_entrant = false;1168if (nm->is_osr_method()) {1169// This is an osr method, just make it not entrant and recompile later if needed1170make_not_entrant = true;1171} else {1172if (next_level != CompLevel_full_optimization) {1173// next_level is not full opt, so we need to recompile the1174// enclosing method without the inlinee1175cur_level = CompLevel_none;1176make_not_entrant = true;1177}1178}1179if (make_not_entrant) {1180if (PrintTieredEvents) {1181int osr_bci = nm->is_osr_method() ? nm->osr_entry_bci() : InvocationEntryBci;1182print_event(MAKE_NOT_ENTRANT, mh(), mh(), osr_bci, level);1183}1184nm->make_not_entrant();1185}1186}1187// Fix up next_level if necessary to avoid deopts1188if (next_level == CompLevel_limited_profile && max_osr_level == CompLevel_full_profile) {1189next_level = CompLevel_full_profile;1190}1191if (cur_level != next_level) {1192if (!CompileBroker::compilation_is_in_queue(mh)) {1193compile(mh, InvocationEntryBci, next_level, THREAD);1194}1195}1196}1197} else {1198cur_level = comp_level(mh());1199next_level = call_event(mh, cur_level, THREAD);1200if (next_level != cur_level) {1201if (!CompileBroker::compilation_is_in_queue(mh)) {1202compile(mh, InvocationEntryBci, next_level, THREAD);1203}1204}1205}1206}1207}1208120912101211