Path: blob/master/src/hotspot/share/compiler/compileBroker.cpp
64440 views
/*1* Copyright (c) 1999, 2021, 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 "jvm.h"26#include "classfile/javaClasses.hpp"27#include "classfile/symbolTable.hpp"28#include "classfile/vmClasses.hpp"29#include "classfile/vmSymbols.hpp"30#include "code/codeCache.hpp"31#include "code/codeHeapState.hpp"32#include "code/dependencyContext.hpp"33#include "compiler/compilationPolicy.hpp"34#include "compiler/compileBroker.hpp"35#include "compiler/compileLog.hpp"36#include "compiler/compilerEvent.hpp"37#include "compiler/compilerOracle.hpp"38#include "compiler/directivesParser.hpp"39#include "interpreter/linkResolver.hpp"40#include "jfr/jfrEvents.hpp"41#include "logging/log.hpp"42#include "logging/logStream.hpp"43#include "memory/allocation.inline.hpp"44#include "memory/resourceArea.hpp"45#include "memory/universe.hpp"46#include "oops/methodData.hpp"47#include "oops/method.inline.hpp"48#include "oops/oop.inline.hpp"49#include "prims/jvmtiExport.hpp"50#include "prims/nativeLookup.hpp"51#include "prims/whitebox.hpp"52#include "runtime/atomic.hpp"53#include "runtime/escapeBarrier.hpp"54#include "runtime/globals_extension.hpp"55#include "runtime/handles.inline.hpp"56#include "runtime/init.hpp"57#include "runtime/interfaceSupport.inline.hpp"58#include "runtime/java.hpp"59#include "runtime/javaCalls.hpp"60#include "runtime/jniHandles.inline.hpp"61#include "runtime/os.hpp"62#include "runtime/perfData.hpp"63#include "runtime/safepointVerifiers.hpp"64#include "runtime/sharedRuntime.hpp"65#include "runtime/sweeper.hpp"66#include "runtime/threadSMR.hpp"67#include "runtime/timerTrace.hpp"68#include "runtime/vframe.inline.hpp"69#include "utilities/debug.hpp"70#include "utilities/dtrace.hpp"71#include "utilities/events.hpp"72#include "utilities/formatBuffer.hpp"73#include "utilities/macros.hpp"74#ifdef COMPILER175#include "c1/c1_Compiler.hpp"76#endif77#if INCLUDE_JVMCI78#include "jvmci/jvmciEnv.hpp"79#include "jvmci/jvmciRuntime.hpp"80#endif81#ifdef COMPILER282#include "opto/c2compiler.hpp"83#endif8485#ifdef DTRACE_ENABLED8687// Only bother with this argument setup if dtrace is available8889#define DTRACE_METHOD_COMPILE_BEGIN_PROBE(method, comp_name) \90{ \91Symbol* klass_name = (method)->klass_name(); \92Symbol* name = (method)->name(); \93Symbol* signature = (method)->signature(); \94HOTSPOT_METHOD_COMPILE_BEGIN( \95(char *) comp_name, strlen(comp_name), \96(char *) klass_name->bytes(), klass_name->utf8_length(), \97(char *) name->bytes(), name->utf8_length(), \98(char *) signature->bytes(), signature->utf8_length()); \99}100101#define DTRACE_METHOD_COMPILE_END_PROBE(method, comp_name, success) \102{ \103Symbol* klass_name = (method)->klass_name(); \104Symbol* name = (method)->name(); \105Symbol* signature = (method)->signature(); \106HOTSPOT_METHOD_COMPILE_END( \107(char *) comp_name, strlen(comp_name), \108(char *) klass_name->bytes(), klass_name->utf8_length(), \109(char *) name->bytes(), name->utf8_length(), \110(char *) signature->bytes(), signature->utf8_length(), (success)); \111}112113#else // ndef DTRACE_ENABLED114115#define DTRACE_METHOD_COMPILE_BEGIN_PROBE(method, comp_name)116#define DTRACE_METHOD_COMPILE_END_PROBE(method, comp_name, success)117118#endif // ndef DTRACE_ENABLED119120bool CompileBroker::_initialized = false;121volatile bool CompileBroker::_should_block = false;122volatile int CompileBroker::_print_compilation_warning = 0;123volatile jint CompileBroker::_should_compile_new_jobs = run_compilation;124125// The installed compiler(s)126AbstractCompiler* CompileBroker::_compilers[2];127128// The maximum numbers of compiler threads to be determined during startup.129int CompileBroker::_c1_count = 0;130int CompileBroker::_c2_count = 0;131132// An array of compiler names as Java String objects133jobject* CompileBroker::_compiler1_objects = NULL;134jobject* CompileBroker::_compiler2_objects = NULL;135136CompileLog** CompileBroker::_compiler1_logs = NULL;137CompileLog** CompileBroker::_compiler2_logs = NULL;138139// These counters are used to assign an unique ID to each compilation.140volatile jint CompileBroker::_compilation_id = 0;141volatile jint CompileBroker::_osr_compilation_id = 0;142143// Performance counters144PerfCounter* CompileBroker::_perf_total_compilation = NULL;145PerfCounter* CompileBroker::_perf_osr_compilation = NULL;146PerfCounter* CompileBroker::_perf_standard_compilation = NULL;147148PerfCounter* CompileBroker::_perf_total_bailout_count = NULL;149PerfCounter* CompileBroker::_perf_total_invalidated_count = NULL;150PerfCounter* CompileBroker::_perf_total_compile_count = NULL;151PerfCounter* CompileBroker::_perf_total_osr_compile_count = NULL;152PerfCounter* CompileBroker::_perf_total_standard_compile_count = NULL;153154PerfCounter* CompileBroker::_perf_sum_osr_bytes_compiled = NULL;155PerfCounter* CompileBroker::_perf_sum_standard_bytes_compiled = NULL;156PerfCounter* CompileBroker::_perf_sum_nmethod_size = NULL;157PerfCounter* CompileBroker::_perf_sum_nmethod_code_size = NULL;158159PerfStringVariable* CompileBroker::_perf_last_method = NULL;160PerfStringVariable* CompileBroker::_perf_last_failed_method = NULL;161PerfStringVariable* CompileBroker::_perf_last_invalidated_method = NULL;162PerfVariable* CompileBroker::_perf_last_compile_type = NULL;163PerfVariable* CompileBroker::_perf_last_compile_size = NULL;164PerfVariable* CompileBroker::_perf_last_failed_type = NULL;165PerfVariable* CompileBroker::_perf_last_invalidated_type = NULL;166167// Timers and counters for generating statistics168elapsedTimer CompileBroker::_t_total_compilation;169elapsedTimer CompileBroker::_t_osr_compilation;170elapsedTimer CompileBroker::_t_standard_compilation;171elapsedTimer CompileBroker::_t_invalidated_compilation;172elapsedTimer CompileBroker::_t_bailedout_compilation;173174int CompileBroker::_total_bailout_count = 0;175int CompileBroker::_total_invalidated_count = 0;176int CompileBroker::_total_compile_count = 0;177int CompileBroker::_total_osr_compile_count = 0;178int CompileBroker::_total_standard_compile_count = 0;179int CompileBroker::_total_compiler_stopped_count = 0;180int CompileBroker::_total_compiler_restarted_count = 0;181182int CompileBroker::_sum_osr_bytes_compiled = 0;183int CompileBroker::_sum_standard_bytes_compiled = 0;184int CompileBroker::_sum_nmethod_size = 0;185int CompileBroker::_sum_nmethod_code_size = 0;186187long CompileBroker::_peak_compilation_time = 0;188189CompilerStatistics CompileBroker::_stats_per_level[CompLevel_full_optimization];190191CompileQueue* CompileBroker::_c2_compile_queue = NULL;192CompileQueue* CompileBroker::_c1_compile_queue = NULL;193194195196class CompilationLog : public StringEventLog {197public:198CompilationLog() : StringEventLog("Compilation events", "jit") {199}200201void log_compile(JavaThread* thread, CompileTask* task) {202StringLogMessage lm;203stringStream sstr(lm.buffer(), lm.size());204// msg.time_stamp().update_to(tty->time_stamp().ticks());205task->print(&sstr, NULL, true, false);206log(thread, "%s", (const char*)lm);207}208209void log_nmethod(JavaThread* thread, nmethod* nm) {210log(thread, "nmethod %d%s " INTPTR_FORMAT " code [" INTPTR_FORMAT ", " INTPTR_FORMAT "]",211nm->compile_id(), nm->is_osr_method() ? "%" : "",212p2i(nm), p2i(nm->code_begin()), p2i(nm->code_end()));213}214215void log_failure(JavaThread* thread, CompileTask* task, const char* reason, const char* retry_message) {216StringLogMessage lm;217lm.print("%4d COMPILE SKIPPED: %s", task->compile_id(), reason);218if (retry_message != NULL) {219lm.append(" (%s)", retry_message);220}221lm.print("\n");222log(thread, "%s", (const char*)lm);223}224225void log_metaspace_failure(const char* reason) {226// Note: This method can be called from non-Java/compiler threads to227// log the global metaspace failure that might affect profiling.228ResourceMark rm;229StringLogMessage lm;230lm.print("%4d COMPILE PROFILING SKIPPED: %s", -1, reason);231lm.print("\n");232log(Thread::current(), "%s", (const char*)lm);233}234};235236static CompilationLog* _compilation_log = NULL;237238bool compileBroker_init() {239if (LogEvents) {240_compilation_log = new CompilationLog();241}242243// init directives stack, adding default directive244DirectivesStack::init();245246if (DirectivesParser::has_file()) {247return DirectivesParser::parse_from_flag();248} else if (CompilerDirectivesPrint) {249// Print default directive even when no other was added250DirectivesStack::print(tty);251}252253return true;254}255256CompileTaskWrapper::CompileTaskWrapper(CompileTask* task) {257CompilerThread* thread = CompilerThread::current();258thread->set_task(task);259CompileLog* log = thread->log();260if (log != NULL && !task->is_unloaded()) task->log_task_start(log);261}262263CompileTaskWrapper::~CompileTaskWrapper() {264CompilerThread* thread = CompilerThread::current();265CompileTask* task = thread->task();266CompileLog* log = thread->log();267if (log != NULL && !task->is_unloaded()) task->log_task_done(log);268thread->set_task(NULL);269task->set_code_handle(NULL);270thread->set_env(NULL);271if (task->is_blocking()) {272bool free_task = false;273{274MutexLocker notifier(thread, task->lock());275task->mark_complete();276#if INCLUDE_JVMCI277if (CompileBroker::compiler(task->comp_level())->is_jvmci()) {278if (!task->has_waiter()) {279// The waiting thread timed out and thus did not free the task.280free_task = true;281}282task->set_blocking_jvmci_compile_state(NULL);283}284#endif285if (!free_task) {286// Notify the waiting thread that the compilation has completed287// so that it can free the task.288task->lock()->notify_all();289}290}291if (free_task) {292// The task can only be freed once the task lock is released.293CompileTask::free(task);294}295} else {296task->mark_complete();297298// By convention, the compiling thread is responsible for299// recycling a non-blocking CompileTask.300CompileTask::free(task);301}302}303304/**305* Check if a CompilerThread can be removed and update count if requested.306*/307bool CompileBroker::can_remove(CompilerThread *ct, bool do_it) {308assert(UseDynamicNumberOfCompilerThreads, "or shouldn't be here");309if (!ReduceNumberOfCompilerThreads) return false;310311AbstractCompiler *compiler = ct->compiler();312int compiler_count = compiler->num_compiler_threads();313bool c1 = compiler->is_c1();314315// Keep at least 1 compiler thread of each type.316if (compiler_count < 2) return false;317318// Keep thread alive for at least some time.319if (ct->idle_time_millis() < (c1 ? 500 : 100)) return false;320321#if INCLUDE_JVMCI322if (compiler->is_jvmci()) {323// Handles for JVMCI thread objects may get released concurrently.324if (do_it) {325assert(CompileThread_lock->owner() == ct, "must be holding lock");326} else {327// Skip check if it's the last thread and let caller check again.328return true;329}330}331#endif332333// We only allow the last compiler thread of each type to get removed.334jobject last_compiler = c1 ? compiler1_object(compiler_count - 1)335: compiler2_object(compiler_count - 1);336if (ct->threadObj() == JNIHandles::resolve_non_null(last_compiler)) {337if (do_it) {338assert_locked_or_safepoint(CompileThread_lock); // Update must be consistent.339compiler->set_num_compiler_threads(compiler_count - 1);340#if INCLUDE_JVMCI341if (compiler->is_jvmci()) {342// Old j.l.Thread object can die when no longer referenced elsewhere.343JNIHandles::destroy_global(compiler2_object(compiler_count - 1));344_compiler2_objects[compiler_count - 1] = NULL;345}346#endif347}348return true;349}350return false;351}352353/**354* Add a CompileTask to a CompileQueue.355*/356void CompileQueue::add(CompileTask* task) {357assert(MethodCompileQueue_lock->owned_by_self(), "must own lock");358359task->set_next(NULL);360task->set_prev(NULL);361362if (_last == NULL) {363// The compile queue is empty.364assert(_first == NULL, "queue is empty");365_first = task;366_last = task;367} else {368// Append the task to the queue.369assert(_last->next() == NULL, "not last");370_last->set_next(task);371task->set_prev(_last);372_last = task;373}374++_size;375376// Mark the method as being in the compile queue.377task->method()->set_queued_for_compilation();378379if (CIPrintCompileQueue) {380print_tty();381}382383if (LogCompilation && xtty != NULL) {384task->log_task_queued();385}386387// Notify CompilerThreads that a task is available.388MethodCompileQueue_lock->notify_all();389}390391/**392* Empties compilation queue by putting all compilation tasks onto393* a freelist. Furthermore, the method wakes up all threads that are394* waiting on a compilation task to finish. This can happen if background395* compilation is disabled.396*/397void CompileQueue::free_all() {398MutexLocker mu(MethodCompileQueue_lock);399CompileTask* next = _first;400401// Iterate over all tasks in the compile queue402while (next != NULL) {403CompileTask* current = next;404next = current->next();405{406// Wake up thread that blocks on the compile task.407MutexLocker ct_lock(current->lock());408current->lock()->notify();409}410// Put the task back on the freelist.411CompileTask::free(current);412}413_first = NULL;414_last = NULL;415416// Wake up all threads that block on the queue.417MethodCompileQueue_lock->notify_all();418}419420/**421* Get the next CompileTask from a CompileQueue422*/423CompileTask* CompileQueue::get() {424// save methods from RedefineClasses across safepoint425// across MethodCompileQueue_lock below.426methodHandle save_method;427methodHandle save_hot_method;428429MonitorLocker locker(MethodCompileQueue_lock);430// If _first is NULL we have no more compile jobs. There are two reasons for431// having no compile jobs: First, we compiled everything we wanted. Second,432// we ran out of code cache so compilation has been disabled. In the latter433// case we perform code cache sweeps to free memory such that we can re-enable434// compilation.435while (_first == NULL) {436// Exit loop if compilation is disabled forever437if (CompileBroker::is_compilation_disabled_forever()) {438return NULL;439}440441// If there are no compilation tasks and we can compile new jobs442// (i.e., there is enough free space in the code cache) there is443// no need to invoke the sweeper. As a result, the hotness of methods444// remains unchanged. This behavior is desired, since we want to keep445// the stable state, i.e., we do not want to evict methods from the446// code cache if it is unnecessary.447// We need a timed wait here, since compiler threads can exit if compilation448// is disabled forever. We use 5 seconds wait time; the exiting of compiler threads449// is not critical and we do not want idle compiler threads to wake up too often.450locker.wait(5*1000);451452if (UseDynamicNumberOfCompilerThreads && _first == NULL) {453// Still nothing to compile. Give caller a chance to stop this thread.454if (CompileBroker::can_remove(CompilerThread::current(), false)) return NULL;455}456}457458if (CompileBroker::is_compilation_disabled_forever()) {459return NULL;460}461462CompileTask* task;463{464NoSafepointVerifier nsv;465task = CompilationPolicy::select_task(this);466if (task != NULL) {467task = task->select_for_compilation();468}469}470471if (task != NULL) {472// Save method pointers across unlock safepoint. The task is removed from473// the compilation queue, which is walked during RedefineClasses.474Thread* thread = Thread::current();475save_method = methodHandle(thread, task->method());476save_hot_method = methodHandle(thread, task->hot_method());477478remove(task);479}480purge_stale_tasks(); // may temporarily release MCQ lock481return task;482}483484// Clean & deallocate stale compile tasks.485// Temporarily releases MethodCompileQueue lock.486void CompileQueue::purge_stale_tasks() {487assert(MethodCompileQueue_lock->owned_by_self(), "must own lock");488if (_first_stale != NULL) {489// Stale tasks are purged when MCQ lock is released,490// but _first_stale updates are protected by MCQ lock.491// Once task processing starts and MCQ lock is released,492// other compiler threads can reuse _first_stale.493CompileTask* head = _first_stale;494_first_stale = NULL;495{496MutexUnlocker ul(MethodCompileQueue_lock);497for (CompileTask* task = head; task != NULL; ) {498CompileTask* next_task = task->next();499CompileTaskWrapper ctw(task); // Frees the task500task->set_failure_reason("stale task");501task = next_task;502}503}504}505}506507void CompileQueue::remove(CompileTask* task) {508assert(MethodCompileQueue_lock->owned_by_self(), "must own lock");509if (task->prev() != NULL) {510task->prev()->set_next(task->next());511} else {512// max is the first element513assert(task == _first, "Sanity");514_first = task->next();515}516517if (task->next() != NULL) {518task->next()->set_prev(task->prev());519} else {520// max is the last element521assert(task == _last, "Sanity");522_last = task->prev();523}524--_size;525}526527void CompileQueue::remove_and_mark_stale(CompileTask* task) {528assert(MethodCompileQueue_lock->owned_by_self(), "must own lock");529remove(task);530531// Enqueue the task for reclamation (should be done outside MCQ lock)532task->set_next(_first_stale);533task->set_prev(NULL);534_first_stale = task;535}536537// methods in the compile queue need to be marked as used on the stack538// so that they don't get reclaimed by Redefine Classes539void CompileQueue::mark_on_stack() {540CompileTask* task = _first;541while (task != NULL) {542task->mark_on_stack();543task = task->next();544}545}546547548CompileQueue* CompileBroker::compile_queue(int comp_level) {549if (is_c2_compile(comp_level)) return _c2_compile_queue;550if (is_c1_compile(comp_level)) return _c1_compile_queue;551return NULL;552}553554void CompileBroker::print_compile_queues(outputStream* st) {555st->print_cr("Current compiles: ");556557char buf[2000];558int buflen = sizeof(buf);559Threads::print_threads_compiling(st, buf, buflen, /* short_form = */ true);560561st->cr();562if (_c1_compile_queue != NULL) {563_c1_compile_queue->print(st);564}565if (_c2_compile_queue != NULL) {566_c2_compile_queue->print(st);567}568}569570void CompileQueue::print(outputStream* st) {571assert_locked_or_safepoint(MethodCompileQueue_lock);572st->print_cr("%s:", name());573CompileTask* task = _first;574if (task == NULL) {575st->print_cr("Empty");576} else {577while (task != NULL) {578task->print(st, NULL, true, true);579task = task->next();580}581}582st->cr();583}584585void CompileQueue::print_tty() {586ResourceMark rm;587stringStream ss;588// Dump the compile queue into a buffer before locking the tty589print(&ss);590{591ttyLocker ttyl;592tty->print("%s", ss.as_string());593}594}595596CompilerCounters::CompilerCounters() {597_current_method[0] = '\0';598_compile_type = CompileBroker::no_compile;599}600601#if INCLUDE_JFR && COMPILER2_OR_JVMCI602// It appends new compiler phase names to growable array phase_names(a new CompilerPhaseType mapping603// in compiler/compilerEvent.cpp) and registers it with its serializer.604//605// c2 uses explicit CompilerPhaseType idToPhase mapping in opto/phasetype.hpp,606// so if c2 is used, it should be always registered first.607// This function is called during vm initialization.608void register_jfr_phasetype_serializer(CompilerType compiler_type) {609ResourceMark rm;610static bool first_registration = true;611if (compiler_type == compiler_jvmci) {612CompilerEvent::PhaseEvent::get_phase_id("NOT_A_PHASE_NAME", false, false, false);613first_registration = false;614#ifdef COMPILER2615} else if (compiler_type == compiler_c2) {616assert(first_registration, "invariant"); // c2 must be registered first.617GrowableArray<const char*>* c2_phase_names = new GrowableArray<const char*>(PHASE_NUM_TYPES);618for (int i = 0; i < PHASE_NUM_TYPES; i++) {619const char* phase_name = CompilerPhaseTypeHelper::to_string((CompilerPhaseType) i);620CompilerEvent::PhaseEvent::get_phase_id(phase_name, false, false, false);621}622first_registration = false;623#endif // COMPILER2624}625}626#endif // INCLUDE_JFR && COMPILER2_OR_JVMCI627628// ------------------------------------------------------------------629// CompileBroker::compilation_init630//631// Initialize the Compilation object632void CompileBroker::compilation_init_phase1(JavaThread* THREAD) {633// No need to initialize compilation system if we do not use it.634if (!UseCompiler) {635return;636}637// Set the interface to the current compiler(s).638_c1_count = CompilationPolicy::c1_count();639_c2_count = CompilationPolicy::c2_count();640641#if INCLUDE_JVMCI642if (EnableJVMCI) {643// This is creating a JVMCICompiler singleton.644JVMCICompiler* jvmci = new JVMCICompiler();645646if (UseJVMCICompiler) {647_compilers[1] = jvmci;648if (FLAG_IS_DEFAULT(JVMCIThreads)) {649if (BootstrapJVMCI) {650// JVMCI will bootstrap so give it more threads651_c2_count = MIN2(32, os::active_processor_count());652}653} else {654_c2_count = JVMCIThreads;655}656if (FLAG_IS_DEFAULT(JVMCIHostThreads)) {657} else {658#ifdef COMPILER1659_c1_count = JVMCIHostThreads;660#endif // COMPILER1661}662}663}664#endif // INCLUDE_JVMCI665666#ifdef COMPILER1667if (_c1_count > 0) {668_compilers[0] = new Compiler();669}670#endif // COMPILER1671672#ifdef COMPILER2673if (true JVMCI_ONLY( && !UseJVMCICompiler)) {674if (_c2_count > 0) {675_compilers[1] = new C2Compiler();676// Register c2 first as c2 CompilerPhaseType idToPhase mapping is explicit.677// idToPhase mapping for c2 is in opto/phasetype.hpp678JFR_ONLY(register_jfr_phasetype_serializer(compiler_c2);)679}680}681#endif // COMPILER2682683#if INCLUDE_JVMCI684// Register after c2 registration.685// JVMCI CompilerPhaseType idToPhase mapping is dynamic.686if (EnableJVMCI) {687JFR_ONLY(register_jfr_phasetype_serializer(compiler_jvmci);)688}689#endif // INCLUDE_JVMCI690691// Start the compiler thread(s) and the sweeper thread692init_compiler_sweeper_threads();693// totalTime performance counter is always created as it is required694// by the implementation of java.lang.management.CompilationMXBean.695{696// Ensure OOM leads to vm_exit_during_initialization.697EXCEPTION_MARK;698_perf_total_compilation =699PerfDataManager::create_counter(JAVA_CI, "totalTime",700PerfData::U_Ticks, CHECK);701}702703if (UsePerfData) {704705EXCEPTION_MARK;706707// create the jvmstat performance counters708_perf_osr_compilation =709PerfDataManager::create_counter(SUN_CI, "osrTime",710PerfData::U_Ticks, CHECK);711712_perf_standard_compilation =713PerfDataManager::create_counter(SUN_CI, "standardTime",714PerfData::U_Ticks, CHECK);715716_perf_total_bailout_count =717PerfDataManager::create_counter(SUN_CI, "totalBailouts",718PerfData::U_Events, CHECK);719720_perf_total_invalidated_count =721PerfDataManager::create_counter(SUN_CI, "totalInvalidates",722PerfData::U_Events, CHECK);723724_perf_total_compile_count =725PerfDataManager::create_counter(SUN_CI, "totalCompiles",726PerfData::U_Events, CHECK);727_perf_total_osr_compile_count =728PerfDataManager::create_counter(SUN_CI, "osrCompiles",729PerfData::U_Events, CHECK);730731_perf_total_standard_compile_count =732PerfDataManager::create_counter(SUN_CI, "standardCompiles",733PerfData::U_Events, CHECK);734735_perf_sum_osr_bytes_compiled =736PerfDataManager::create_counter(SUN_CI, "osrBytes",737PerfData::U_Bytes, CHECK);738739_perf_sum_standard_bytes_compiled =740PerfDataManager::create_counter(SUN_CI, "standardBytes",741PerfData::U_Bytes, CHECK);742743_perf_sum_nmethod_size =744PerfDataManager::create_counter(SUN_CI, "nmethodSize",745PerfData::U_Bytes, CHECK);746747_perf_sum_nmethod_code_size =748PerfDataManager::create_counter(SUN_CI, "nmethodCodeSize",749PerfData::U_Bytes, CHECK);750751_perf_last_method =752PerfDataManager::create_string_variable(SUN_CI, "lastMethod",753CompilerCounters::cmname_buffer_length,754"", CHECK);755756_perf_last_failed_method =757PerfDataManager::create_string_variable(SUN_CI, "lastFailedMethod",758CompilerCounters::cmname_buffer_length,759"", CHECK);760761_perf_last_invalidated_method =762PerfDataManager::create_string_variable(SUN_CI, "lastInvalidatedMethod",763CompilerCounters::cmname_buffer_length,764"", CHECK);765766_perf_last_compile_type =767PerfDataManager::create_variable(SUN_CI, "lastType",768PerfData::U_None,769(jlong)CompileBroker::no_compile,770CHECK);771772_perf_last_compile_size =773PerfDataManager::create_variable(SUN_CI, "lastSize",774PerfData::U_Bytes,775(jlong)CompileBroker::no_compile,776CHECK);777778779_perf_last_failed_type =780PerfDataManager::create_variable(SUN_CI, "lastFailedType",781PerfData::U_None,782(jlong)CompileBroker::no_compile,783CHECK);784785_perf_last_invalidated_type =786PerfDataManager::create_variable(SUN_CI, "lastInvalidatedType",787PerfData::U_None,788(jlong)CompileBroker::no_compile,789CHECK);790}791}792793// Completes compiler initialization. Compilation requests submitted794// prior to this will be silently ignored.795void CompileBroker::compilation_init_phase2() {796_initialized = true;797}798799Handle CompileBroker::create_thread_oop(const char* name, TRAPS) {800Handle string = java_lang_String::create_from_str(name, CHECK_NH);801Handle thread_group(THREAD, Universe::system_thread_group());802return JavaCalls::construct_new_instance(803vmClasses::Thread_klass(),804vmSymbols::threadgroup_string_void_signature(),805thread_group,806string,807CHECK_NH);808}809810#if defined(ASSERT) && COMPILER2_OR_JVMCI811// Stress testing. Dedicated threads revert optimizations based on escape analysis concurrently to812// the running java application. Configured with vm options DeoptimizeObjectsALot*.813class DeoptimizeObjectsALotThread : public JavaThread {814815static void deopt_objs_alot_thread_entry(JavaThread* thread, TRAPS);816void deoptimize_objects_alot_loop_single();817void deoptimize_objects_alot_loop_all();818819public:820DeoptimizeObjectsALotThread() : JavaThread(&deopt_objs_alot_thread_entry) { }821822bool is_hidden_from_external_view() const { return true; }823};824825// Entry for DeoptimizeObjectsALotThread. The threads are started in826// CompileBroker::init_compiler_sweeper_threads() iff DeoptimizeObjectsALot is enabled827void DeoptimizeObjectsALotThread::deopt_objs_alot_thread_entry(JavaThread* thread, TRAPS) {828DeoptimizeObjectsALotThread* dt = ((DeoptimizeObjectsALotThread*) thread);829bool enter_single_loop;830{831MonitorLocker ml(dt, EscapeBarrier_lock, Mutex::_no_safepoint_check_flag);832static int single_thread_count = 0;833enter_single_loop = single_thread_count++ < DeoptimizeObjectsALotThreadCountSingle;834}835if (enter_single_loop) {836dt->deoptimize_objects_alot_loop_single();837} else {838dt->deoptimize_objects_alot_loop_all();839}840}841842// Execute EscapeBarriers in an endless loop to revert optimizations based on escape analysis. Each843// barrier targets a single thread which is selected round robin.844void DeoptimizeObjectsALotThread::deoptimize_objects_alot_loop_single() {845HandleMark hm(this);846while (true) {847for (JavaThreadIteratorWithHandle jtiwh; JavaThread *deoptee_thread = jtiwh.next(); ) {848{ // Begin new scope for escape barrier849HandleMarkCleaner hmc(this);850ResourceMark rm(this);851EscapeBarrier eb(true, this, deoptee_thread);852eb.deoptimize_objects(100);853}854// Now sleep after the escape barriers destructor resumed deoptee_thread.855sleep(DeoptimizeObjectsALotInterval);856}857}858}859860// Execute EscapeBarriers in an endless loop to revert optimizations based on escape analysis. Each861// barrier targets all java threads in the vm at once.862void DeoptimizeObjectsALotThread::deoptimize_objects_alot_loop_all() {863HandleMark hm(this);864while (true) {865{ // Begin new scope for escape barrier866HandleMarkCleaner hmc(this);867ResourceMark rm(this);868EscapeBarrier eb(true, this);869eb.deoptimize_objects_all_threads();870}871// Now sleep after the escape barriers destructor resumed the java threads.872sleep(DeoptimizeObjectsALotInterval);873}874}875#endif // defined(ASSERT) && COMPILER2_OR_JVMCI876877878JavaThread* CompileBroker::make_thread(ThreadType type, jobject thread_handle, CompileQueue* queue, AbstractCompiler* comp, JavaThread* THREAD) {879JavaThread* new_thread = NULL;880{881MutexLocker mu(THREAD, Threads_lock);882switch (type) {883case compiler_t:884assert(comp != NULL, "Compiler instance missing.");885if (!InjectCompilerCreationFailure || comp->num_compiler_threads() == 0) {886CompilerCounters* counters = new CompilerCounters();887new_thread = new CompilerThread(queue, counters);888}889break;890case sweeper_t:891new_thread = new CodeCacheSweeperThread();892break;893#if defined(ASSERT) && COMPILER2_OR_JVMCI894case deoptimizer_t:895new_thread = new DeoptimizeObjectsALotThread();896break;897#endif // ASSERT898default:899ShouldNotReachHere();900}901902// At this point the new CompilerThread data-races with this startup903// thread (which I believe is the primoridal thread and NOT the VM904// thread). This means Java bytecodes being executed at startup can905// queue compile jobs which will run at whatever default priority the906// newly created CompilerThread runs at.907908909// At this point it may be possible that no osthread was created for the910// JavaThread due to lack of memory. We would have to throw an exception911// in that case. However, since this must work and we do not allow912// exceptions anyway, check and abort if this fails. But first release the913// lock.914915if (new_thread != NULL && new_thread->osthread() != NULL) {916917java_lang_Thread::set_thread(JNIHandles::resolve_non_null(thread_handle), new_thread);918919// Note that this only sets the JavaThread _priority field, which by920// definition is limited to Java priorities and not OS priorities.921// The os-priority is set in the CompilerThread startup code itself922923java_lang_Thread::set_priority(JNIHandles::resolve_non_null(thread_handle), NearMaxPriority);924925// Note that we cannot call os::set_priority because it expects Java926// priorities and we are *explicitly* using OS priorities so that it's927// possible to set the compiler thread priority higher than any Java928// thread.929930int native_prio = CompilerThreadPriority;931if (native_prio == -1) {932if (UseCriticalCompilerThreadPriority) {933native_prio = os::java_to_os_priority[CriticalPriority];934} else {935native_prio = os::java_to_os_priority[NearMaxPriority];936}937}938os::set_native_priority(new_thread, native_prio);939940java_lang_Thread::set_daemon(JNIHandles::resolve_non_null(thread_handle));941942new_thread->set_threadObj(JNIHandles::resolve_non_null(thread_handle));943if (type == compiler_t) {944CompilerThread::cast(new_thread)->set_compiler(comp);945}946Threads::add(new_thread);947Thread::start(new_thread);948}949}950951// First release lock before aborting VM.952if (new_thread == NULL || new_thread->osthread() == NULL) {953if (UseDynamicNumberOfCompilerThreads && type == compiler_t && comp->num_compiler_threads() > 0) {954if (new_thread != NULL) {955new_thread->smr_delete();956}957return NULL;958}959vm_exit_during_initialization("java.lang.OutOfMemoryError",960os::native_thread_creation_failed_msg());961}962963// Let go of Threads_lock before yielding964os::naked_yield(); // make sure that the compiler thread is started early (especially helpful on SOLARIS)965966return new_thread;967}968969970void CompileBroker::init_compiler_sweeper_threads() {971NMethodSweeper::set_sweep_threshold_bytes(static_cast<size_t>(SweeperThreshold * ReservedCodeCacheSize / 100.0));972log_info(codecache, sweep)("Sweeper threshold: " SIZE_FORMAT " bytes", NMethodSweeper::sweep_threshold_bytes());973974// Ensure any exceptions lead to vm_exit_during_initialization.975EXCEPTION_MARK;976#if !defined(ZERO)977assert(_c2_count > 0 || _c1_count > 0, "No compilers?");978#endif // !ZERO979// Initialize the compilation queue980if (_c2_count > 0) {981const char* name = JVMCI_ONLY(UseJVMCICompiler ? "JVMCI compile queue" :) "C2 compile queue";982_c2_compile_queue = new CompileQueue(name);983_compiler2_objects = NEW_C_HEAP_ARRAY(jobject, _c2_count, mtCompiler);984_compiler2_logs = NEW_C_HEAP_ARRAY(CompileLog*, _c2_count, mtCompiler);985}986if (_c1_count > 0) {987_c1_compile_queue = new CompileQueue("C1 compile queue");988_compiler1_objects = NEW_C_HEAP_ARRAY(jobject, _c1_count, mtCompiler);989_compiler1_logs = NEW_C_HEAP_ARRAY(CompileLog*, _c1_count, mtCompiler);990}991992char name_buffer[256];993994for (int i = 0; i < _c2_count; i++) {995jobject thread_handle = NULL;996// Create all j.l.Thread objects for C1 and C2 threads here, but only one997// for JVMCI compiler which can create further ones on demand.998JVMCI_ONLY(if (!UseJVMCICompiler || !UseDynamicNumberOfCompilerThreads || i == 0) {)999// Create a name for our thread.1000sprintf(name_buffer, "%s CompilerThread%d", _compilers[1]->name(), i);1001Handle thread_oop = create_thread_oop(name_buffer, CHECK);1002thread_handle = JNIHandles::make_global(thread_oop);1003JVMCI_ONLY(})1004_compiler2_objects[i] = thread_handle;1005_compiler2_logs[i] = NULL;10061007if (!UseDynamicNumberOfCompilerThreads || i == 0) {1008JavaThread *ct = make_thread(compiler_t, thread_handle, _c2_compile_queue, _compilers[1], THREAD);1009assert(ct != NULL, "should have been handled for initial thread");1010_compilers[1]->set_num_compiler_threads(i + 1);1011if (TraceCompilerThreads) {1012ResourceMark rm;1013ThreadsListHandle tlh; // get_thread_name() depends on the TLH.1014assert(tlh.includes(ct), "ct=" INTPTR_FORMAT " exited unexpectedly.", p2i(ct));1015tty->print_cr("Added initial compiler thread %s", ct->get_thread_name());1016}1017}1018}10191020for (int i = 0; i < _c1_count; i++) {1021// Create a name for our thread.1022sprintf(name_buffer, "C1 CompilerThread%d", i);1023Handle thread_oop = create_thread_oop(name_buffer, CHECK);1024jobject thread_handle = JNIHandles::make_global(thread_oop);1025_compiler1_objects[i] = thread_handle;1026_compiler1_logs[i] = NULL;10271028if (!UseDynamicNumberOfCompilerThreads || i == 0) {1029JavaThread *ct = make_thread(compiler_t, thread_handle, _c1_compile_queue, _compilers[0], THREAD);1030assert(ct != NULL, "should have been handled for initial thread");1031_compilers[0]->set_num_compiler_threads(i + 1);1032if (TraceCompilerThreads) {1033ResourceMark rm;1034ThreadsListHandle tlh; // get_thread_name() depends on the TLH.1035assert(tlh.includes(ct), "ct=" INTPTR_FORMAT " exited unexpectedly.", p2i(ct));1036tty->print_cr("Added initial compiler thread %s", ct->get_thread_name());1037}1038}1039}10401041if (UsePerfData) {1042PerfDataManager::create_constant(SUN_CI, "threads", PerfData::U_Bytes, _c1_count + _c2_count, CHECK);1043}10441045if (MethodFlushing) {1046// Initialize the sweeper thread1047Handle thread_oop = create_thread_oop("Sweeper thread", CHECK);1048jobject thread_handle = JNIHandles::make_local(THREAD, thread_oop());1049make_thread(sweeper_t, thread_handle, NULL, NULL, THREAD);1050}10511052#if defined(ASSERT) && COMPILER2_OR_JVMCI1053if (DeoptimizeObjectsALot) {1054// Initialize and start the object deoptimizer threads1055const int total_count = DeoptimizeObjectsALotThreadCountSingle + DeoptimizeObjectsALotThreadCountAll;1056for (int count = 0; count < total_count; count++) {1057Handle thread_oop = create_thread_oop("Deoptimize objects a lot single mode", CHECK);1058jobject thread_handle = JNIHandles::make_local(THREAD, thread_oop());1059make_thread(deoptimizer_t, thread_handle, NULL, NULL, THREAD);1060}1061}1062#endif // defined(ASSERT) && COMPILER2_OR_JVMCI1063}10641065void CompileBroker::possibly_add_compiler_threads(JavaThread* THREAD) {10661067julong available_memory = os::available_memory();1068// If SegmentedCodeCache is off, both values refer to the single heap (with type CodeBlobType::All).1069size_t available_cc_np = CodeCache::unallocated_capacity(CodeBlobType::MethodNonProfiled),1070available_cc_p = CodeCache::unallocated_capacity(CodeBlobType::MethodProfiled);10711072// Only do attempt to start additional threads if the lock is free.1073if (!CompileThread_lock->try_lock()) return;10741075if (_c2_compile_queue != NULL) {1076int old_c2_count = _compilers[1]->num_compiler_threads();1077int new_c2_count = MIN4(_c2_count,1078_c2_compile_queue->size() / 2,1079(int)(available_memory / (200*M)),1080(int)(available_cc_np / (128*K)));10811082for (int i = old_c2_count; i < new_c2_count; i++) {1083#if INCLUDE_JVMCI1084if (UseJVMCICompiler) {1085// Native compiler threads as used in C1/C2 can reuse the j.l.Thread1086// objects as their existence is completely hidden from the rest of1087// the VM (and those compiler threads can't call Java code to do the1088// creation anyway). For JVMCI we have to create new j.l.Thread objects1089// as they are visible and we can see unexpected thread lifecycle1090// transitions if we bind them to new JavaThreads.1091if (!THREAD->can_call_java()) break;1092char name_buffer[256];1093sprintf(name_buffer, "%s CompilerThread%d", _compilers[1]->name(), i);1094Handle thread_oop;1095{1096// We have to give up the lock temporarily for the Java calls.1097MutexUnlocker mu(CompileThread_lock);1098thread_oop = create_thread_oop(name_buffer, THREAD);1099}1100if (HAS_PENDING_EXCEPTION) {1101if (TraceCompilerThreads) {1102ResourceMark rm;1103tty->print_cr("JVMCI compiler thread creation failed:");1104PENDING_EXCEPTION->print();1105}1106CLEAR_PENDING_EXCEPTION;1107break;1108}1109// Check if another thread has beaten us during the Java calls.1110if (_compilers[1]->num_compiler_threads() != i) break;1111jobject thread_handle = JNIHandles::make_global(thread_oop);1112assert(compiler2_object(i) == NULL, "Old one must be released!");1113_compiler2_objects[i] = thread_handle;1114}1115#endif1116JavaThread *ct = make_thread(compiler_t, compiler2_object(i), _c2_compile_queue, _compilers[1], THREAD);1117if (ct == NULL) break;1118_compilers[1]->set_num_compiler_threads(i + 1);1119if (TraceCompilerThreads) {1120ResourceMark rm;1121ThreadsListHandle tlh; // get_thread_name() depends on the TLH.1122assert(tlh.includes(ct), "ct=" INTPTR_FORMAT " exited unexpectedly.", p2i(ct));1123tty->print_cr("Added compiler thread %s (available memory: %dMB, available non-profiled code cache: %dMB)",1124ct->get_thread_name(), (int)(available_memory/M), (int)(available_cc_np/M));1125}1126}1127}11281129if (_c1_compile_queue != NULL) {1130int old_c1_count = _compilers[0]->num_compiler_threads();1131int new_c1_count = MIN4(_c1_count,1132_c1_compile_queue->size() / 4,1133(int)(available_memory / (100*M)),1134(int)(available_cc_p / (128*K)));11351136for (int i = old_c1_count; i < new_c1_count; i++) {1137JavaThread *ct = make_thread(compiler_t, compiler1_object(i), _c1_compile_queue, _compilers[0], THREAD);1138if (ct == NULL) break;1139_compilers[0]->set_num_compiler_threads(i + 1);1140if (TraceCompilerThreads) {1141ResourceMark rm;1142ThreadsListHandle tlh; // get_thread_name() depends on the TLH.1143assert(tlh.includes(ct), "ct=" INTPTR_FORMAT " exited unexpectedly.", p2i(ct));1144tty->print_cr("Added compiler thread %s (available memory: %dMB, available profiled code cache: %dMB)",1145ct->get_thread_name(), (int)(available_memory/M), (int)(available_cc_p/M));1146}1147}1148}11491150CompileThread_lock->unlock();1151}115211531154/**1155* Set the methods on the stack as on_stack so that redefine classes doesn't1156* reclaim them. This method is executed at a safepoint.1157*/1158void CompileBroker::mark_on_stack() {1159assert(SafepointSynchronize::is_at_safepoint(), "sanity check");1160// Since we are at a safepoint, we do not need a lock to access1161// the compile queues.1162if (_c2_compile_queue != NULL) {1163_c2_compile_queue->mark_on_stack();1164}1165if (_c1_compile_queue != NULL) {1166_c1_compile_queue->mark_on_stack();1167}1168}11691170// ------------------------------------------------------------------1171// CompileBroker::compile_method1172//1173// Request compilation of a method.1174void CompileBroker::compile_method_base(const methodHandle& method,1175int osr_bci,1176int comp_level,1177const methodHandle& hot_method,1178int hot_count,1179CompileTask::CompileReason compile_reason,1180bool blocking,1181Thread* thread) {1182guarantee(!method->is_abstract(), "cannot compile abstract methods");1183assert(method->method_holder()->is_instance_klass(),1184"sanity check");1185assert(!method->method_holder()->is_not_initialized(),1186"method holder must be initialized");1187assert(!method->is_method_handle_intrinsic(), "do not enqueue these guys");11881189if (CIPrintRequests) {1190tty->print("request: ");1191method->print_short_name(tty);1192if (osr_bci != InvocationEntryBci) {1193tty->print(" osr_bci: %d", osr_bci);1194}1195tty->print(" level: %d comment: %s count: %d", comp_level, CompileTask::reason_name(compile_reason), hot_count);1196if (!hot_method.is_null()) {1197tty->print(" hot: ");1198if (hot_method() != method()) {1199hot_method->print_short_name(tty);1200} else {1201tty->print("yes");1202}1203}1204tty->cr();1205}12061207// A request has been made for compilation. Before we do any1208// real work, check to see if the method has been compiled1209// in the meantime with a definitive result.1210if (compilation_is_complete(method, osr_bci, comp_level)) {1211return;1212}12131214#ifndef PRODUCT1215if (osr_bci != -1 && !FLAG_IS_DEFAULT(OSROnlyBCI)) {1216if ((OSROnlyBCI > 0) ? (OSROnlyBCI != osr_bci) : (-OSROnlyBCI == osr_bci)) {1217// Positive OSROnlyBCI means only compile that bci. Negative means don't compile that BCI.1218return;1219}1220}1221#endif12221223// If this method is already in the compile queue, then1224// we do not block the current thread.1225if (compilation_is_in_queue(method)) {1226// We may want to decay our counter a bit here to prevent1227// multiple denied requests for compilation. This is an1228// open compilation policy issue. Note: The other possibility,1229// in the case that this is a blocking compile request, is to have1230// all subsequent blocking requesters wait for completion of1231// ongoing compiles. Note that in this case we'll need a protocol1232// for freeing the associated compile tasks. [Or we could have1233// a single static monitor on which all these waiters sleep.]1234return;1235}12361237// Tiered policy requires MethodCounters to exist before adding a method to1238// the queue. Create if we don't have them yet.1239method->get_method_counters(thread);12401241// Outputs from the following MutexLocker block:1242CompileTask* task = NULL;1243CompileQueue* queue = compile_queue(comp_level);12441245// Acquire our lock.1246{1247MutexLocker locker(thread, MethodCompileQueue_lock);12481249// Make sure the method has not slipped into the queues since1250// last we checked; note that those checks were "fast bail-outs".1251// Here we need to be more careful, see 14012000 below.1252if (compilation_is_in_queue(method)) {1253return;1254}12551256// We need to check again to see if the compilation has1257// completed. A previous compilation may have registered1258// some result.1259if (compilation_is_complete(method, osr_bci, comp_level)) {1260return;1261}12621263// We now know that this compilation is not pending, complete,1264// or prohibited. Assign a compile_id to this compilation1265// and check to see if it is in our [Start..Stop) range.1266int compile_id = assign_compile_id(method, osr_bci);1267if (compile_id == 0) {1268// The compilation falls outside the allowed range.1269return;1270}12711272#if INCLUDE_JVMCI1273if (UseJVMCICompiler && blocking) {1274// Don't allow blocking compiles for requests triggered by JVMCI.1275if (thread->is_Compiler_thread()) {1276blocking = false;1277}12781279if (!UseJVMCINativeLibrary) {1280// Don't allow blocking compiles if inside a class initializer or while performing class loading1281vframeStream vfst(thread->as_Java_thread());1282for (; !vfst.at_end(); vfst.next()) {1283if (vfst.method()->is_static_initializer() ||1284(vfst.method()->method_holder()->is_subclass_of(vmClasses::ClassLoader_klass()) &&1285vfst.method()->name() == vmSymbols::loadClass_name())) {1286blocking = false;1287break;1288}1289}1290}12911292// Don't allow blocking compilation requests to JVMCI1293// if JVMCI itself is not yet initialized1294if (!JVMCI::is_compiler_initialized() && compiler(comp_level)->is_jvmci()) {1295blocking = false;1296}12971298// Don't allow blocking compilation requests if we are in JVMCIRuntime::shutdown1299// to avoid deadlock between compiler thread(s) and threads run at shutdown1300// such as the DestroyJavaVM thread.1301if (JVMCI::in_shutdown()) {1302blocking = false;1303}1304}1305#endif // INCLUDE_JVMCI13061307// We will enter the compilation in the queue.1308// 14012000: Note that this sets the queued_for_compile bits in1309// the target method. We can now reason that a method cannot be1310// queued for compilation more than once, as follows:1311// Before a thread queues a task for compilation, it first acquires1312// the compile queue lock, then checks if the method's queued bits1313// are set or it has already been compiled. Thus there can not be two1314// instances of a compilation task for the same method on the1315// compilation queue. Consider now the case where the compilation1316// thread has already removed a task for that method from the queue1317// and is in the midst of compiling it. In this case, the1318// queued_for_compile bits must be set in the method (and these1319// will be visible to the current thread, since the bits were set1320// under protection of the compile queue lock, which we hold now.1321// When the compilation completes, the compiler thread first sets1322// the compilation result and then clears the queued_for_compile1323// bits. Neither of these actions are protected by a barrier (or done1324// under the protection of a lock), so the only guarantee we have1325// (on machines with TSO (Total Store Order)) is that these values1326// will update in that order. As a result, the only combinations of1327// these bits that the current thread will see are, in temporal order:1328// <RESULT, QUEUE> :1329// <0, 1> : in compile queue, but not yet compiled1330// <1, 1> : compiled but queue bit not cleared1331// <1, 0> : compiled and queue bit cleared1332// Because we first check the queue bits then check the result bits,1333// we are assured that we cannot introduce a duplicate task.1334// Note that if we did the tests in the reverse order (i.e. check1335// result then check queued bit), we could get the result bit before1336// the compilation completed, and the queue bit after the compilation1337// completed, and end up introducing a "duplicate" (redundant) task.1338// In that case, the compiler thread should first check if a method1339// has already been compiled before trying to compile it.1340// NOTE: in the event that there are multiple compiler threads and1341// there is de-optimization/recompilation, things will get hairy,1342// and in that case it's best to protect both the testing (here) of1343// these bits, and their updating (here and elsewhere) under a1344// common lock.1345task = create_compile_task(queue,1346compile_id, method,1347osr_bci, comp_level,1348hot_method, hot_count, compile_reason,1349blocking);1350}13511352if (blocking) {1353wait_for_completion(task);1354}1355}13561357nmethod* CompileBroker::compile_method(const methodHandle& method, int osr_bci,1358int comp_level,1359const methodHandle& hot_method, int hot_count,1360CompileTask::CompileReason compile_reason,1361TRAPS) {1362// Do nothing if compilebroker is not initalized or compiles are submitted on level none1363if (!_initialized || comp_level == CompLevel_none) {1364return NULL;1365}13661367AbstractCompiler *comp = CompileBroker::compiler(comp_level);1368assert(comp != NULL, "Ensure we have a compiler");13691370DirectiveSet* directive = DirectivesStack::getMatchingDirective(method, comp);1371// CompileBroker::compile_method can trap and can have pending aysnc exception.1372nmethod* nm = CompileBroker::compile_method(method, osr_bci, comp_level, hot_method, hot_count, compile_reason, directive, THREAD);1373DirectivesStack::release(directive);1374return nm;1375}13761377nmethod* CompileBroker::compile_method(const methodHandle& method, int osr_bci,1378int comp_level,1379const methodHandle& hot_method, int hot_count,1380CompileTask::CompileReason compile_reason,1381DirectiveSet* directive,1382TRAPS) {13831384// make sure arguments make sense1385assert(method->method_holder()->is_instance_klass(), "not an instance method");1386assert(osr_bci == InvocationEntryBci || (0 <= osr_bci && osr_bci < method->code_size()), "bci out of range");1387assert(!method->is_abstract() && (osr_bci == InvocationEntryBci || !method->is_native()), "cannot compile abstract/native methods");1388assert(!method->method_holder()->is_not_initialized(), "method holder must be initialized");1389// return quickly if possible13901391// lock, make sure that the compilation1392// isn't prohibited in a straightforward way.1393AbstractCompiler* comp = CompileBroker::compiler(comp_level);1394if (comp == NULL || compilation_is_prohibited(method, osr_bci, comp_level, directive->ExcludeOption)) {1395return NULL;1396}13971398#if INCLUDE_JVMCI1399if (comp->is_jvmci() && !JVMCI::can_initialize_JVMCI()) {1400return NULL;1401}1402#endif14031404if (osr_bci == InvocationEntryBci) {1405// standard compilation1406CompiledMethod* method_code = method->code();1407if (method_code != NULL && method_code->is_nmethod()) {1408if (compilation_is_complete(method, osr_bci, comp_level)) {1409return (nmethod*) method_code;1410}1411}1412if (method->is_not_compilable(comp_level)) {1413return NULL;1414}1415} else {1416// osr compilation1417// We accept a higher level osr method1418nmethod* nm = method->lookup_osr_nmethod_for(osr_bci, comp_level, false);1419if (nm != NULL) return nm;1420if (method->is_not_osr_compilable(comp_level)) return NULL;1421}14221423assert(!HAS_PENDING_EXCEPTION, "No exception should be present");1424// some prerequisites that are compiler specific1425if (comp->is_c2()) {1426method->constants()->resolve_string_constants(CHECK_AND_CLEAR_NONASYNC_NULL);1427// Resolve all classes seen in the signature of the method1428// we are compiling.1429Method::load_signature_classes(method, CHECK_AND_CLEAR_NONASYNC_NULL);1430}14311432// If the method is native, do the lookup in the thread requesting1433// the compilation. Native lookups can load code, which is not1434// permitted during compilation.1435//1436// Note: A native method implies non-osr compilation which is1437// checked with an assertion at the entry of this method.1438if (method->is_native() && !method->is_method_handle_intrinsic()) {1439address adr = NativeLookup::lookup(method, THREAD);1440if (HAS_PENDING_EXCEPTION) {1441// In case of an exception looking up the method, we just forget1442// about it. The interpreter will kick-in and throw the exception.1443method->set_not_compilable("NativeLookup::lookup failed"); // implies is_not_osr_compilable()1444CLEAR_PENDING_EXCEPTION;1445return NULL;1446}1447assert(method->has_native_function(), "must have native code by now");1448}14491450// RedefineClasses() has replaced this method; just return1451if (method->is_old()) {1452return NULL;1453}14541455// JVMTI -- post_compile_event requires jmethod_id() that may require1456// a lock the compiling thread can not acquire. Prefetch it here.1457if (JvmtiExport::should_post_compiled_method_load()) {1458method->jmethod_id();1459}14601461// do the compilation1462if (method->is_native()) {1463if (!PreferInterpreterNativeStubs || method->is_method_handle_intrinsic()) {1464#if defined(X86) && !defined(ZERO)1465// The following native methods:1466//1467// java.lang.Float.intBitsToFloat1468// java.lang.Float.floatToRawIntBits1469// java.lang.Double.longBitsToDouble1470// java.lang.Double.doubleToRawLongBits1471//1472// are called through the interpreter even if interpreter native stubs1473// are not preferred (i.e., calling through adapter handlers is preferred).1474// The reason is that on x86_32 signaling NaNs (sNaNs) are not preserved1475// if the version of the methods from the native libraries is called.1476// As the interpreter and the C2-intrinsified version of the methods preserves1477// sNaNs, that would result in an inconsistent way of handling of sNaNs.1478if ((UseSSE >= 1 &&1479(method->intrinsic_id() == vmIntrinsics::_intBitsToFloat ||1480method->intrinsic_id() == vmIntrinsics::_floatToRawIntBits)) ||1481(UseSSE >= 2 &&1482(method->intrinsic_id() == vmIntrinsics::_longBitsToDouble ||1483method->intrinsic_id() == vmIntrinsics::_doubleToRawLongBits))) {1484return NULL;1485}1486#endif // X86 && !ZERO14871488// To properly handle the appendix argument for out-of-line calls we are using a small trampoline that1489// pops off the appendix argument and jumps to the target (see gen_special_dispatch in SharedRuntime).1490//1491// Since normal compiled-to-compiled calls are not able to handle such a thing we MUST generate an adapter1492// in this case. If we can't generate one and use it we can not execute the out-of-line method handle calls.1493AdapterHandlerLibrary::create_native_wrapper(method);1494} else {1495return NULL;1496}1497} else {1498// If the compiler is shut off due to code cache getting full1499// fail out now so blocking compiles dont hang the java thread1500if (!should_compile_new_jobs()) {1501return NULL;1502}1503bool is_blocking = !directive->BackgroundCompilationOption || ReplayCompiles;1504compile_method_base(method, osr_bci, comp_level, hot_method, hot_count, compile_reason, is_blocking, THREAD);1505}15061507// return requested nmethod1508// We accept a higher level osr method1509if (osr_bci == InvocationEntryBci) {1510CompiledMethod* code = method->code();1511if (code == NULL) {1512return (nmethod*) code;1513} else {1514return code->as_nmethod_or_null();1515}1516}1517return method->lookup_osr_nmethod_for(osr_bci, comp_level, false);1518}151915201521// ------------------------------------------------------------------1522// CompileBroker::compilation_is_complete1523//1524// See if compilation of this method is already complete.1525bool CompileBroker::compilation_is_complete(const methodHandle& method,1526int osr_bci,1527int comp_level) {1528bool is_osr = (osr_bci != standard_entry_bci);1529if (is_osr) {1530if (method->is_not_osr_compilable(comp_level)) {1531return true;1532} else {1533nmethod* result = method->lookup_osr_nmethod_for(osr_bci, comp_level, true);1534return (result != NULL);1535}1536} else {1537if (method->is_not_compilable(comp_level)) {1538return true;1539} else {1540CompiledMethod* result = method->code();1541if (result == NULL) return false;1542return comp_level == result->comp_level();1543}1544}1545}154615471548/**1549* See if this compilation is already requested.1550*1551* Implementation note: there is only a single "is in queue" bit1552* for each method. This means that the check below is overly1553* conservative in the sense that an osr compilation in the queue1554* will block a normal compilation from entering the queue (and vice1555* versa). This can be remedied by a full queue search to disambiguate1556* cases. If it is deemed profitable, this may be done.1557*/1558bool CompileBroker::compilation_is_in_queue(const methodHandle& method) {1559return method->queued_for_compilation();1560}15611562// ------------------------------------------------------------------1563// CompileBroker::compilation_is_prohibited1564//1565// See if this compilation is not allowed.1566bool CompileBroker::compilation_is_prohibited(const methodHandle& method, int osr_bci, int comp_level, bool excluded) {1567bool is_native = method->is_native();1568// Some compilers may not support the compilation of natives.1569AbstractCompiler *comp = compiler(comp_level);1570if (is_native && (!CICompileNatives || comp == NULL)) {1571method->set_not_compilable_quietly("native methods not supported", comp_level);1572return true;1573}15741575bool is_osr = (osr_bci != standard_entry_bci);1576// Some compilers may not support on stack replacement.1577if (is_osr && (!CICompileOSR || comp == NULL)) {1578method->set_not_osr_compilable("OSR not supported", comp_level);1579return true;1580}15811582// The method may be explicitly excluded by the user.1583double scale;1584if (excluded || (CompilerOracle::has_option_value(method, CompileCommand::CompileThresholdScaling, scale) && scale == 0)) {1585bool quietly = CompilerOracle::be_quiet();1586if (PrintCompilation && !quietly) {1587// This does not happen quietly...1588ResourceMark rm;1589tty->print("### Excluding %s:%s",1590method->is_native() ? "generation of native wrapper" : "compile",1591(method->is_static() ? " static" : ""));1592method->print_short_name(tty);1593tty->cr();1594}1595method->set_not_compilable("excluded by CompileCommand", comp_level, !quietly);1596}15971598return false;1599}16001601/**1602* Generate serialized IDs for compilation requests. If certain debugging flags are used1603* and the ID is not within the specified range, the method is not compiled and 0 is returned.1604* The function also allows to generate separate compilation IDs for OSR compilations.1605*/1606int CompileBroker::assign_compile_id(const methodHandle& method, int osr_bci) {1607#ifdef ASSERT1608bool is_osr = (osr_bci != standard_entry_bci);1609int id;1610if (method->is_native()) {1611assert(!is_osr, "can't be osr");1612// Adapters, native wrappers and method handle intrinsics1613// should be generated always.1614return Atomic::add(&_compilation_id, 1);1615} else if (CICountOSR && is_osr) {1616id = Atomic::add(&_osr_compilation_id, 1);1617if (CIStartOSR <= id && id < CIStopOSR) {1618return id;1619}1620} else {1621id = Atomic::add(&_compilation_id, 1);1622if (CIStart <= id && id < CIStop) {1623return id;1624}1625}16261627// Method was not in the appropriate compilation range.1628method->set_not_compilable_quietly("Not in requested compile id range");1629return 0;1630#else1631// CICountOSR is a develop flag and set to 'false' by default. In a product built,1632// only _compilation_id is incremented.1633return Atomic::add(&_compilation_id, 1);1634#endif1635}16361637// ------------------------------------------------------------------1638// CompileBroker::assign_compile_id_unlocked1639//1640// Public wrapper for assign_compile_id that acquires the needed locks1641uint CompileBroker::assign_compile_id_unlocked(Thread* thread, const methodHandle& method, int osr_bci) {1642MutexLocker locker(thread, MethodCompileQueue_lock);1643return assign_compile_id(method, osr_bci);1644}16451646// ------------------------------------------------------------------1647// CompileBroker::create_compile_task1648//1649// Create a CompileTask object representing the current request for1650// compilation. Add this task to the queue.1651CompileTask* CompileBroker::create_compile_task(CompileQueue* queue,1652int compile_id,1653const methodHandle& method,1654int osr_bci,1655int comp_level,1656const methodHandle& hot_method,1657int hot_count,1658CompileTask::CompileReason compile_reason,1659bool blocking) {1660CompileTask* new_task = CompileTask::allocate();1661new_task->initialize(compile_id, method, osr_bci, comp_level,1662hot_method, hot_count, compile_reason,1663blocking);1664queue->add(new_task);1665return new_task;1666}16671668#if INCLUDE_JVMCI1669// The number of milliseconds to wait before checking if1670// JVMCI compilation has made progress.1671static const long JVMCI_COMPILATION_PROGRESS_WAIT_TIMESLICE = 1000;16721673// The number of JVMCI compilation progress checks that must fail1674// before unblocking a thread waiting for a blocking compilation.1675static const int JVMCI_COMPILATION_PROGRESS_WAIT_ATTEMPTS = 10;16761677/**1678* Waits for a JVMCI compiler to complete a given task. This thread1679* waits until either the task completes or it sees no JVMCI compilation1680* progress for N consecutive milliseconds where N is1681* JVMCI_COMPILATION_PROGRESS_WAIT_TIMESLICE *1682* JVMCI_COMPILATION_PROGRESS_WAIT_ATTEMPTS.1683*1684* @return true if this thread needs to free/recycle the task1685*/1686bool CompileBroker::wait_for_jvmci_completion(JVMCICompiler* jvmci, CompileTask* task, JavaThread* thread) {1687assert(UseJVMCICompiler, "sanity");1688MonitorLocker ml(thread, task->lock());1689int progress_wait_attempts = 0;1690jint thread_jvmci_compilation_ticks = 0;1691jint global_jvmci_compilation_ticks = jvmci->global_compilation_ticks();1692while (!task->is_complete() && !is_compilation_disabled_forever() &&1693ml.wait(JVMCI_COMPILATION_PROGRESS_WAIT_TIMESLICE)) {1694JVMCICompileState* jvmci_compile_state = task->blocking_jvmci_compile_state();16951696bool progress;1697if (jvmci_compile_state != NULL) {1698jint ticks = jvmci_compile_state->compilation_ticks();1699progress = (ticks - thread_jvmci_compilation_ticks) != 0;1700JVMCI_event_1("waiting on compilation %d [ticks=%d]", task->compile_id(), ticks);1701thread_jvmci_compilation_ticks = ticks;1702} else {1703// Still waiting on JVMCI compiler queue. This thread may be holding a lock1704// that all JVMCI compiler threads are blocked on. We use the global JVMCI1705// compilation ticks to determine whether JVMCI compilation1706// is still making progress through the JVMCI compiler queue.1707jint ticks = jvmci->global_compilation_ticks();1708progress = (ticks - global_jvmci_compilation_ticks) != 0;1709JVMCI_event_1("waiting on compilation %d to be queued [ticks=%d]", task->compile_id(), ticks);1710global_jvmci_compilation_ticks = ticks;1711}17121713if (!progress) {1714if (++progress_wait_attempts == JVMCI_COMPILATION_PROGRESS_WAIT_ATTEMPTS) {1715if (PrintCompilation) {1716task->print(tty, "wait for blocking compilation timed out");1717}1718JVMCI_event_1("waiting on compilation %d timed out", task->compile_id());1719break;1720}1721} else {1722progress_wait_attempts = 0;1723}1724}1725task->clear_waiter();1726return task->is_complete();1727}1728#endif17291730/**1731* Wait for the compilation task to complete.1732*/1733void CompileBroker::wait_for_completion(CompileTask* task) {1734if (CIPrintCompileQueue) {1735ttyLocker ttyl;1736tty->print_cr("BLOCKING FOR COMPILE");1737}17381739assert(task->is_blocking(), "can only wait on blocking task");17401741JavaThread* thread = JavaThread::current();17421743methodHandle method(thread, task->method());1744bool free_task;1745#if INCLUDE_JVMCI1746AbstractCompiler* comp = compiler(task->comp_level());1747if (comp->is_jvmci() && !task->should_wait_for_compilation()) {1748// It may return before compilation is completed.1749free_task = wait_for_jvmci_completion((JVMCICompiler*) comp, task, thread);1750} else1751#endif1752{1753MonitorLocker ml(thread, task->lock());1754free_task = true;1755while (!task->is_complete() && !is_compilation_disabled_forever()) {1756ml.wait();1757}1758}17591760if (free_task) {1761if (is_compilation_disabled_forever()) {1762CompileTask::free(task);1763return;1764}17651766// It is harmless to check this status without the lock, because1767// completion is a stable property (until the task object is recycled).1768assert(task->is_complete(), "Compilation should have completed");1769assert(task->code_handle() == NULL, "must be reset");17701771// By convention, the waiter is responsible for recycling a1772// blocking CompileTask. Since there is only one waiter ever1773// waiting on a CompileTask, we know that no one else will1774// be using this CompileTask; we can free it.1775CompileTask::free(task);1776}1777}17781779/**1780* Initialize compiler thread(s) + compiler object(s). The postcondition1781* of this function is that the compiler runtimes are initialized and that1782* compiler threads can start compiling.1783*/1784bool CompileBroker::init_compiler_runtime() {1785CompilerThread* thread = CompilerThread::current();1786AbstractCompiler* comp = thread->compiler();1787// Final sanity check - the compiler object must exist1788guarantee(comp != NULL, "Compiler object must exist");17891790{1791// Must switch to native to allocate ci_env1792ThreadToNativeFromVM ttn(thread);1793ciEnv ci_env((CompileTask*)NULL);1794// Cache Jvmti state1795ci_env.cache_jvmti_state();1796// Cache DTrace flags1797ci_env.cache_dtrace_flags();17981799// Switch back to VM state to do compiler initialization1800ThreadInVMfromNative tv(thread);18011802// Perform per-thread and global initializations1803comp->initialize();1804}18051806if (comp->is_failed()) {1807disable_compilation_forever();1808// If compiler initialization failed, no compiler thread that is specific to a1809// particular compiler runtime will ever start to compile methods.1810shutdown_compiler_runtime(comp, thread);1811return false;1812}18131814// C1 specific check1815if (comp->is_c1() && (thread->get_buffer_blob() == NULL)) {1816warning("Initialization of %s thread failed (no space to run compilers)", thread->name());1817return false;1818}18191820return true;1821}18221823/**1824* If C1 and/or C2 initialization failed, we shut down all compilation.1825* We do this to keep things simple. This can be changed if it ever turns1826* out to be a problem.1827*/1828void CompileBroker::shutdown_compiler_runtime(AbstractCompiler* comp, CompilerThread* thread) {1829// Free buffer blob, if allocated1830if (thread->get_buffer_blob() != NULL) {1831MutexLocker mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);1832CodeCache::free(thread->get_buffer_blob());1833}18341835if (comp->should_perform_shutdown()) {1836// There are two reasons for shutting down the compiler1837// 1) compiler runtime initialization failed1838// 2) The code cache is full and the following flag is set: -XX:-UseCodeCacheFlushing1839warning("%s initialization failed. Shutting down all compilers", comp->name());18401841// Only one thread per compiler runtime object enters here1842// Set state to shut down1843comp->set_shut_down();18441845// Delete all queued compilation tasks to make compiler threads exit faster.1846if (_c1_compile_queue != NULL) {1847_c1_compile_queue->free_all();1848}18491850if (_c2_compile_queue != NULL) {1851_c2_compile_queue->free_all();1852}18531854// Set flags so that we continue execution with using interpreter only.1855UseCompiler = false;1856UseInterpreter = true;18571858// We could delete compiler runtimes also. However, there are references to1859// the compiler runtime(s) (e.g., nmethod::is_compiled_by_c1()) which then1860// fail. This can be done later if necessary.1861}1862}18631864/**1865* Helper function to create new or reuse old CompileLog.1866*/1867CompileLog* CompileBroker::get_log(CompilerThread* ct) {1868if (!LogCompilation) return NULL;18691870AbstractCompiler *compiler = ct->compiler();1871bool c1 = compiler->is_c1();1872jobject* compiler_objects = c1 ? _compiler1_objects : _compiler2_objects;1873assert(compiler_objects != NULL, "must be initialized at this point");1874CompileLog** logs = c1 ? _compiler1_logs : _compiler2_logs;1875assert(logs != NULL, "must be initialized at this point");1876int count = c1 ? _c1_count : _c2_count;18771878// Find Compiler number by its threadObj.1879oop compiler_obj = ct->threadObj();1880int compiler_number = 0;1881bool found = false;1882for (; compiler_number < count; compiler_number++) {1883if (JNIHandles::resolve_non_null(compiler_objects[compiler_number]) == compiler_obj) {1884found = true;1885break;1886}1887}1888assert(found, "Compiler must exist at this point");18891890// Determine pointer for this thread's log.1891CompileLog** log_ptr = &logs[compiler_number];18921893// Return old one if it exists.1894CompileLog* log = *log_ptr;1895if (log != NULL) {1896ct->init_log(log);1897return log;1898}18991900// Create a new one and remember it.1901init_compiler_thread_log();1902log = ct->log();1903*log_ptr = log;1904return log;1905}19061907// ------------------------------------------------------------------1908// CompileBroker::compiler_thread_loop1909//1910// The main loop run by a CompilerThread.1911void CompileBroker::compiler_thread_loop() {1912CompilerThread* thread = CompilerThread::current();1913CompileQueue* queue = thread->queue();1914// For the thread that initializes the ciObjectFactory1915// this resource mark holds all the shared objects1916ResourceMark rm;19171918// First thread to get here will initialize the compiler interface19191920{1921ASSERT_IN_VM;1922MutexLocker only_one (thread, CompileThread_lock);1923if (!ciObjectFactory::is_initialized()) {1924ciObjectFactory::initialize();1925}1926}19271928// Open a log.1929CompileLog* log = get_log(thread);1930if (log != NULL) {1931log->begin_elem("start_compile_thread name='%s' thread='" UINTX_FORMAT "' process='%d'",1932thread->name(),1933os::current_thread_id(),1934os::current_process_id());1935log->stamp();1936log->end_elem();1937}19381939// If compiler thread/runtime initialization fails, exit the compiler thread1940if (!init_compiler_runtime()) {1941return;1942}19431944thread->start_idle_timer();19451946// Poll for new compilation tasks as long as the JVM runs. Compilation1947// should only be disabled if something went wrong while initializing the1948// compiler runtimes. This, in turn, should not happen. The only known case1949// when compiler runtime initialization fails is if there is not enough free1950// space in the code cache to generate the necessary stubs, etc.1951while (!is_compilation_disabled_forever()) {1952// We need this HandleMark to avoid leaking VM handles.1953HandleMark hm(thread);19541955CompileTask* task = queue->get();1956if (task == NULL) {1957if (UseDynamicNumberOfCompilerThreads) {1958// Access compiler_count under lock to enforce consistency.1959MutexLocker only_one(CompileThread_lock);1960if (can_remove(thread, true)) {1961if (TraceCompilerThreads) {1962tty->print_cr("Removing compiler thread %s after " JLONG_FORMAT " ms idle time",1963thread->name(), thread->idle_time_millis());1964}1965// Free buffer blob, if allocated1966if (thread->get_buffer_blob() != NULL) {1967MutexLocker mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);1968CodeCache::free(thread->get_buffer_blob());1969}1970return; // Stop this thread.1971}1972}1973} else {1974// Assign the task to the current thread. Mark this compilation1975// thread as active for the profiler.1976// CompileTaskWrapper also keeps the Method* from being deallocated if redefinition1977// occurs after fetching the compile task off the queue.1978CompileTaskWrapper ctw(task);1979nmethodLocker result_handle; // (handle for the nmethod produced by this task)1980task->set_code_handle(&result_handle);1981methodHandle method(thread, task->method());19821983// Never compile a method if breakpoints are present in it1984if (method()->number_of_breakpoints() == 0) {1985// Compile the method.1986if ((UseCompiler || AlwaysCompileLoopMethods) && CompileBroker::should_compile_new_jobs()) {1987invoke_compiler_on_method(task);1988thread->start_idle_timer();1989} else {1990// After compilation is disabled, remove remaining methods from queue1991method->clear_queued_for_compilation();1992task->set_failure_reason("compilation is disabled");1993}1994} else {1995task->set_failure_reason("breakpoints are present");1996}19971998if (UseDynamicNumberOfCompilerThreads) {1999possibly_add_compiler_threads(thread);2000assert(!thread->has_pending_exception(), "should have been handled");2001}2002}2003}20042005// Shut down compiler runtime2006shutdown_compiler_runtime(thread->compiler(), thread);2007}20082009// ------------------------------------------------------------------2010// CompileBroker::init_compiler_thread_log2011//2012// Set up state required by +LogCompilation.2013void CompileBroker::init_compiler_thread_log() {2014CompilerThread* thread = CompilerThread::current();2015char file_name[4*K];2016FILE* fp = NULL;2017intx thread_id = os::current_thread_id();2018for (int try_temp_dir = 1; try_temp_dir >= 0; try_temp_dir--) {2019const char* dir = (try_temp_dir ? os::get_temp_directory() : NULL);2020if (dir == NULL) {2021jio_snprintf(file_name, sizeof(file_name), "hs_c" UINTX_FORMAT "_pid%u.log",2022thread_id, os::current_process_id());2023} else {2024jio_snprintf(file_name, sizeof(file_name),2025"%s%shs_c" UINTX_FORMAT "_pid%u.log", dir,2026os::file_separator(), thread_id, os::current_process_id());2027}20282029fp = fopen(file_name, "wt");2030if (fp != NULL) {2031if (LogCompilation && Verbose) {2032tty->print_cr("Opening compilation log %s", file_name);2033}2034CompileLog* log = new(ResourceObj::C_HEAP, mtCompiler) CompileLog(file_name, fp, thread_id);2035if (log == NULL) {2036fclose(fp);2037return;2038}2039thread->init_log(log);20402041if (xtty != NULL) {2042ttyLocker ttyl;2043// Record any per thread log files2044xtty->elem("thread_logfile thread='" INTX_FORMAT "' filename='%s'", thread_id, file_name);2045}2046return;2047}2048}2049warning("Cannot open log file: %s", file_name);2050}20512052void CompileBroker::log_metaspace_failure() {2053const char* message = "some methods may not be compiled because metaspace "2054"is out of memory";2055if (_compilation_log != NULL) {2056_compilation_log->log_metaspace_failure(message);2057}2058if (PrintCompilation) {2059tty->print_cr("COMPILE PROFILING SKIPPED: %s", message);2060}2061}206220632064// ------------------------------------------------------------------2065// CompileBroker::set_should_block2066//2067// Set _should_block.2068// Call this from the VM, with Threads_lock held and a safepoint requested.2069void CompileBroker::set_should_block() {2070assert(Threads_lock->owner() == Thread::current(), "must have threads lock");2071assert(SafepointSynchronize::is_at_safepoint(), "must be at a safepoint already");2072#ifndef PRODUCT2073if (PrintCompilation && (Verbose || WizardMode))2074tty->print_cr("notifying compiler thread pool to block");2075#endif2076_should_block = true;2077}20782079// ------------------------------------------------------------------2080// CompileBroker::maybe_block2081//2082// Call this from the compiler at convenient points, to poll for _should_block.2083void CompileBroker::maybe_block() {2084if (_should_block) {2085#ifndef PRODUCT2086if (PrintCompilation && (Verbose || WizardMode))2087tty->print_cr("compiler thread " INTPTR_FORMAT " poll detects block request", p2i(Thread::current()));2088#endif2089ThreadInVMfromNative tivfn(JavaThread::current());2090}2091}20922093// wrapper for CodeCache::print_summary()2094static void codecache_print(bool detailed)2095{2096ResourceMark rm;2097stringStream s;2098// Dump code cache into a buffer before locking the tty,2099{2100MutexLocker mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);2101CodeCache::print_summary(&s, detailed);2102}2103ttyLocker ttyl;2104tty->print("%s", s.as_string());2105}21062107// wrapper for CodeCache::print_summary() using outputStream2108static void codecache_print(outputStream* out, bool detailed) {2109ResourceMark rm;2110stringStream s;21112112// Dump code cache into a buffer2113{2114MutexLocker mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);2115CodeCache::print_summary(&s, detailed);2116}21172118char* remaining_log = s.as_string();2119while (*remaining_log != '\0') {2120char* eol = strchr(remaining_log, '\n');2121if (eol == NULL) {2122out->print_cr("%s", remaining_log);2123remaining_log = remaining_log + strlen(remaining_log);2124} else {2125*eol = '\0';2126out->print_cr("%s", remaining_log);2127remaining_log = eol + 1;2128}2129}2130}21312132void CompileBroker::post_compile(CompilerThread* thread, CompileTask* task, bool success, ciEnv* ci_env,2133int compilable, const char* failure_reason) {2134if (success) {2135task->mark_success();2136if (ci_env != NULL) {2137task->set_num_inlined_bytecodes(ci_env->num_inlined_bytecodes());2138}2139if (_compilation_log != NULL) {2140nmethod* code = task->code();2141if (code != NULL) {2142_compilation_log->log_nmethod(thread, code);2143}2144}2145} else if (AbortVMOnCompilationFailure) {2146if (compilable == ciEnv::MethodCompilable_not_at_tier) {2147fatal("Not compilable at tier %d: %s", task->comp_level(), failure_reason);2148}2149if (compilable == ciEnv::MethodCompilable_never) {2150fatal("Never compilable: %s", failure_reason);2151}2152}2153// simulate crash during compilation2154assert(task->compile_id() != CICrashAt, "just as planned");2155}21562157static void post_compilation_event(EventCompilation& event, CompileTask* task) {2158assert(task != NULL, "invariant");2159CompilerEvent::CompilationEvent::post(event,2160task->compile_id(),2161task->compiler()->type(),2162task->method(),2163task->comp_level(),2164task->is_success(),2165task->osr_bci() != CompileBroker::standard_entry_bci,2166(task->code() == NULL) ? 0 : task->code()->total_size(),2167task->num_inlined_bytecodes());2168}21692170int DirectivesStack::_depth = 0;2171CompilerDirectives* DirectivesStack::_top = NULL;2172CompilerDirectives* DirectivesStack::_bottom = NULL;21732174// ------------------------------------------------------------------2175// CompileBroker::invoke_compiler_on_method2176//2177// Compile a method.2178//2179void CompileBroker::invoke_compiler_on_method(CompileTask* task) {2180task->print_ul();2181if (PrintCompilation) {2182ResourceMark rm;2183task->print_tty();2184}2185elapsedTimer time;21862187CompilerThread* thread = CompilerThread::current();2188ResourceMark rm(thread);21892190if (LogEvents) {2191_compilation_log->log_compile(thread, task);2192}21932194// Common flags.2195uint compile_id = task->compile_id();2196int osr_bci = task->osr_bci();2197bool is_osr = (osr_bci != standard_entry_bci);2198bool should_log = (thread->log() != NULL);2199bool should_break = false;2200const int task_level = task->comp_level();2201AbstractCompiler* comp = task->compiler();22022203DirectiveSet* directive;2204{2205// create the handle inside it's own block so it can't2206// accidentally be referenced once the thread transitions to2207// native. The NoHandleMark before the transition should catch2208// any cases where this occurs in the future.2209methodHandle method(thread, task->method());2210assert(!method->is_native(), "no longer compile natives");22112212// Look up matching directives2213directive = DirectivesStack::getMatchingDirective(method, comp);22142215// Update compile information when using perfdata.2216if (UsePerfData) {2217update_compile_perf_data(thread, method, is_osr);2218}22192220DTRACE_METHOD_COMPILE_BEGIN_PROBE(method, compiler_name(task_level));2221}22222223should_break = directive->BreakAtCompileOption || task->check_break_at_flags();2224if (should_log && !directive->LogOption) {2225should_log = false;2226}22272228// Allocate a new set of JNI handles.2229push_jni_handle_block();2230Method* target_handle = task->method();2231int compilable = ciEnv::MethodCompilable;2232const char* failure_reason = NULL;2233bool failure_reason_on_C_heap = false;2234const char* retry_message = NULL;22352236#if INCLUDE_JVMCI2237if (UseJVMCICompiler && comp != NULL && comp->is_jvmci()) {2238JVMCICompiler* jvmci = (JVMCICompiler*) comp;22392240TraceTime t1("compilation", &time);2241EventCompilation event;2242JVMCICompileState compile_state(task, jvmci);2243JVMCIRuntime *runtime = NULL;22442245if (JVMCI::in_shutdown()) {2246failure_reason = "in JVMCI shutdown";2247retry_message = "not retryable";2248compilable = ciEnv::MethodCompilable_never;2249} else if (compile_state.target_method_is_old()) {2250// Skip redefined methods2251failure_reason = "redefined method";2252retry_message = "not retryable";2253compilable = ciEnv::MethodCompilable_never;2254} else {2255JVMCIEnv env(thread, &compile_state, __FILE__, __LINE__);2256methodHandle method(thread, target_handle);2257runtime = env.runtime();2258runtime->compile_method(&env, jvmci, method, osr_bci);22592260failure_reason = compile_state.failure_reason();2261failure_reason_on_C_heap = compile_state.failure_reason_on_C_heap();2262if (!compile_state.retryable()) {2263retry_message = "not retryable";2264compilable = ciEnv::MethodCompilable_not_at_tier;2265}2266if (task->code() == NULL) {2267assert(failure_reason != NULL, "must specify failure_reason");2268}2269}2270post_compile(thread, task, task->code() != NULL, NULL, compilable, failure_reason);2271if (event.should_commit()) {2272post_compilation_event(event, task);2273}22742275} else2276#endif // INCLUDE_JVMCI2277{2278NoHandleMark nhm;2279ThreadToNativeFromVM ttn(thread);22802281ciEnv ci_env(task);2282if (should_break) {2283ci_env.set_break_at_compile(true);2284}2285if (should_log) {2286ci_env.set_log(thread->log());2287}2288assert(thread->env() == &ci_env, "set by ci_env");2289// The thread-env() field is cleared in ~CompileTaskWrapper.22902291// Cache Jvmti state2292bool method_is_old = ci_env.cache_jvmti_state();22932294// Skip redefined methods2295if (method_is_old) {2296ci_env.record_method_not_compilable("redefined method", true);2297}22982299// Cache DTrace flags2300ci_env.cache_dtrace_flags();23012302ciMethod* target = ci_env.get_method_from_handle(target_handle);23032304TraceTime t1("compilation", &time);2305EventCompilation event;23062307if (comp == NULL) {2308ci_env.record_method_not_compilable("no compiler");2309} else if (!ci_env.failing()) {2310if (WhiteBoxAPI && WhiteBox::compilation_locked) {2311MonitorLocker locker(Compilation_lock, Mutex::_no_safepoint_check_flag);2312while (WhiteBox::compilation_locked) {2313locker.wait();2314}2315}2316comp->compile_method(&ci_env, target, osr_bci, true, directive);23172318/* Repeat compilation without installing code for profiling purposes */2319int repeat_compilation_count = directive->RepeatCompilationOption;2320while (repeat_compilation_count > 0) {2321ResourceMark rm(thread);2322task->print_ul("NO CODE INSTALLED");2323comp->compile_method(&ci_env, target, osr_bci, false, directive);2324repeat_compilation_count--;2325}2326}23272328if (!ci_env.failing() && task->code() == NULL) {2329//assert(false, "compiler should always document failure");2330// The compiler elected, without comment, not to register a result.2331// Do not attempt further compilations of this method.2332ci_env.record_method_not_compilable("compile failed");2333}23342335// Copy this bit to the enclosing block:2336compilable = ci_env.compilable();23372338if (ci_env.failing()) {2339failure_reason = ci_env.failure_reason();2340retry_message = ci_env.retry_message();2341ci_env.report_failure(failure_reason);2342}23432344post_compile(thread, task, !ci_env.failing(), &ci_env, compilable, failure_reason);2345if (event.should_commit()) {2346post_compilation_event(event, task);2347}2348}2349// Remove the JNI handle block after the ciEnv destructor has run in2350// the previous block.2351pop_jni_handle_block();23522353if (failure_reason != NULL) {2354task->set_failure_reason(failure_reason, failure_reason_on_C_heap);2355if (_compilation_log != NULL) {2356_compilation_log->log_failure(thread, task, failure_reason, retry_message);2357}2358if (PrintCompilation) {2359FormatBufferResource msg = retry_message != NULL ?2360FormatBufferResource("COMPILE SKIPPED: %s (%s)", failure_reason, retry_message) :2361FormatBufferResource("COMPILE SKIPPED: %s", failure_reason);2362task->print(tty, msg);2363}2364}23652366methodHandle method(thread, task->method());23672368DTRACE_METHOD_COMPILE_END_PROBE(method, compiler_name(task_level), task->is_success());23692370collect_statistics(thread, time, task);23712372nmethod* nm = task->code();2373if (nm != NULL) {2374nm->maybe_print_nmethod(directive);2375}2376DirectivesStack::release(directive);23772378if (PrintCompilation && PrintCompilation2) {2379tty->print("%7d ", (int) tty->time_stamp().milliseconds()); // print timestamp2380tty->print("%4d ", compile_id); // print compilation number2381tty->print("%s ", (is_osr ? "%" : " "));2382if (task->code() != NULL) {2383tty->print("size: %d(%d) ", task->code()->total_size(), task->code()->insts_size());2384}2385tty->print_cr("time: %d inlined: %d bytes", (int)time.milliseconds(), task->num_inlined_bytecodes());2386}23872388Log(compilation, codecache) log;2389if (log.is_debug()) {2390LogStream ls(log.debug());2391codecache_print(&ls, /* detailed= */ false);2392}2393if (PrintCodeCacheOnCompilation) {2394codecache_print(/* detailed= */ false);2395}2396// Disable compilation, if required.2397switch (compilable) {2398case ciEnv::MethodCompilable_never:2399if (is_osr)2400method->set_not_osr_compilable_quietly("MethodCompilable_never");2401else2402method->set_not_compilable_quietly("MethodCompilable_never");2403break;2404case ciEnv::MethodCompilable_not_at_tier:2405if (is_osr)2406method->set_not_osr_compilable_quietly("MethodCompilable_not_at_tier", task_level);2407else2408method->set_not_compilable_quietly("MethodCompilable_not_at_tier", task_level);2409break;2410}24112412// Note that the queued_for_compilation bits are cleared without2413// protection of a mutex. [They were set by the requester thread,2414// when adding the task to the compile queue -- at which time the2415// compile queue lock was held. Subsequently, we acquired the compile2416// queue lock to get this task off the compile queue; thus (to belabour2417// the point somewhat) our clearing of the bits must be occurring2418// only after the setting of the bits. See also 14012000 above.2419method->clear_queued_for_compilation();2420}24212422/**2423* The CodeCache is full. Print warning and disable compilation.2424* Schedule code cache cleaning so compilation can continue later.2425* This function needs to be called only from CodeCache::allocate(),2426* since we currently handle a full code cache uniformly.2427*/2428void CompileBroker::handle_full_code_cache(int code_blob_type) {2429UseInterpreter = true;2430if (UseCompiler || AlwaysCompileLoopMethods ) {2431if (xtty != NULL) {2432ResourceMark rm;2433stringStream s;2434// Dump code cache state into a buffer before locking the tty,2435// because log_state() will use locks causing lock conflicts.2436CodeCache::log_state(&s);2437// Lock to prevent tearing2438ttyLocker ttyl;2439xtty->begin_elem("code_cache_full");2440xtty->print("%s", s.as_string());2441xtty->stamp();2442xtty->end_elem();2443}24442445#ifndef PRODUCT2446if (ExitOnFullCodeCache) {2447codecache_print(/* detailed= */ true);2448before_exit(JavaThread::current());2449exit_globals(); // will delete tty2450vm_direct_exit(1);2451}2452#endif2453if (UseCodeCacheFlushing) {2454// Since code cache is full, immediately stop new compiles2455if (CompileBroker::set_should_compile_new_jobs(CompileBroker::stop_compilation)) {2456NMethodSweeper::log_sweep("disable_compiler");2457}2458} else {2459disable_compilation_forever();2460}24612462CodeCache::report_codemem_full(code_blob_type, should_print_compiler_warning());2463}2464}24652466// ------------------------------------------------------------------2467// CompileBroker::update_compile_perf_data2468//2469// Record this compilation for debugging purposes.2470void CompileBroker::update_compile_perf_data(CompilerThread* thread, const methodHandle& method, bool is_osr) {2471ResourceMark rm;2472char* method_name = method->name()->as_C_string();2473char current_method[CompilerCounters::cmname_buffer_length];2474size_t maxLen = CompilerCounters::cmname_buffer_length;24752476const char* class_name = method->method_holder()->name()->as_C_string();24772478size_t s1len = strlen(class_name);2479size_t s2len = strlen(method_name);24802481// check if we need to truncate the string2482if (s1len + s2len + 2 > maxLen) {24832484// the strategy is to lop off the leading characters of the2485// class name and the trailing characters of the method name.24862487if (s2len + 2 > maxLen) {2488// lop of the entire class name string, let snprintf handle2489// truncation of the method name.2490class_name += s1len; // null string2491}2492else {2493// lop off the extra characters from the front of the class name2494class_name += ((s1len + s2len + 2) - maxLen);2495}2496}24972498jio_snprintf(current_method, maxLen, "%s %s", class_name, method_name);24992500int last_compile_type = normal_compile;2501if (CICountOSR && is_osr) {2502last_compile_type = osr_compile;2503}25042505CompilerCounters* counters = thread->counters();2506counters->set_current_method(current_method);2507counters->set_compile_type((jlong) last_compile_type);2508}25092510// ------------------------------------------------------------------2511// CompileBroker::push_jni_handle_block2512//2513// Push on a new block of JNI handles.2514void CompileBroker::push_jni_handle_block() {2515JavaThread* thread = JavaThread::current();25162517// Allocate a new block for JNI handles.2518// Inlined code from jni_PushLocalFrame()2519JNIHandleBlock* java_handles = thread->active_handles();2520JNIHandleBlock* compile_handles = JNIHandleBlock::allocate_block(thread);2521assert(compile_handles != NULL && java_handles != NULL, "should not be NULL");2522compile_handles->set_pop_frame_link(java_handles); // make sure java handles get gc'd.2523thread->set_active_handles(compile_handles);2524}252525262527// ------------------------------------------------------------------2528// CompileBroker::pop_jni_handle_block2529//2530// Pop off the current block of JNI handles.2531void CompileBroker::pop_jni_handle_block() {2532JavaThread* thread = JavaThread::current();25332534// Release our JNI handle block2535JNIHandleBlock* compile_handles = thread->active_handles();2536JNIHandleBlock* java_handles = compile_handles->pop_frame_link();2537thread->set_active_handles(java_handles);2538compile_handles->set_pop_frame_link(NULL);2539JNIHandleBlock::release_block(compile_handles, thread); // may block2540}25412542// ------------------------------------------------------------------2543// CompileBroker::collect_statistics2544//2545// Collect statistics about the compilation.25462547void CompileBroker::collect_statistics(CompilerThread* thread, elapsedTimer time, CompileTask* task) {2548bool success = task->is_success();2549methodHandle method (thread, task->method());2550uint compile_id = task->compile_id();2551bool is_osr = (task->osr_bci() != standard_entry_bci);2552const int comp_level = task->comp_level();2553nmethod* code = task->code();2554CompilerCounters* counters = thread->counters();25552556assert(code == NULL || code->is_locked_by_vm(), "will survive the MutexLocker");2557MutexLocker locker(CompileStatistics_lock);25582559// _perf variables are production performance counters which are2560// updated regardless of the setting of the CITime and CITimeEach flags2561//25622563// account all time, including bailouts and failures in this counter;2564// C1 and C2 counters are counting both successful and unsuccessful compiles2565_t_total_compilation.add(time);25662567if (!success) {2568_total_bailout_count++;2569if (UsePerfData) {2570_perf_last_failed_method->set_value(counters->current_method());2571_perf_last_failed_type->set_value(counters->compile_type());2572_perf_total_bailout_count->inc();2573}2574_t_bailedout_compilation.add(time);2575} else if (code == NULL) {2576if (UsePerfData) {2577_perf_last_invalidated_method->set_value(counters->current_method());2578_perf_last_invalidated_type->set_value(counters->compile_type());2579_perf_total_invalidated_count->inc();2580}2581_total_invalidated_count++;2582_t_invalidated_compilation.add(time);2583} else {2584// Compilation succeeded25852586// update compilation ticks - used by the implementation of2587// java.lang.management.CompilationMXBean2588_perf_total_compilation->inc(time.ticks());2589_peak_compilation_time = time.milliseconds() > _peak_compilation_time ? time.milliseconds() : _peak_compilation_time;25902591if (CITime) {2592int bytes_compiled = method->code_size() + task->num_inlined_bytecodes();2593if (is_osr) {2594_t_osr_compilation.add(time);2595_sum_osr_bytes_compiled += bytes_compiled;2596} else {2597_t_standard_compilation.add(time);2598_sum_standard_bytes_compiled += method->code_size() + task->num_inlined_bytecodes();2599}26002601// Collect statistic per compilation level2602if (comp_level > CompLevel_none && comp_level <= CompLevel_full_optimization) {2603CompilerStatistics* stats = &_stats_per_level[comp_level-1];2604if (is_osr) {2605stats->_osr.update(time, bytes_compiled);2606} else {2607stats->_standard.update(time, bytes_compiled);2608}2609stats->_nmethods_size += code->total_size();2610stats->_nmethods_code_size += code->insts_size();2611} else {2612assert(false, "CompilerStatistics object does not exist for compilation level %d", comp_level);2613}26142615// Collect statistic per compiler2616AbstractCompiler* comp = compiler(comp_level);2617if (comp) {2618CompilerStatistics* stats = comp->stats();2619if (is_osr) {2620stats->_osr.update(time, bytes_compiled);2621} else {2622stats->_standard.update(time, bytes_compiled);2623}2624stats->_nmethods_size += code->total_size();2625stats->_nmethods_code_size += code->insts_size();2626} else { // if (!comp)2627assert(false, "Compiler object must exist");2628}2629}26302631if (UsePerfData) {2632// save the name of the last method compiled2633_perf_last_method->set_value(counters->current_method());2634_perf_last_compile_type->set_value(counters->compile_type());2635_perf_last_compile_size->set_value(method->code_size() +2636task->num_inlined_bytecodes());2637if (is_osr) {2638_perf_osr_compilation->inc(time.ticks());2639_perf_sum_osr_bytes_compiled->inc(method->code_size() + task->num_inlined_bytecodes());2640} else {2641_perf_standard_compilation->inc(time.ticks());2642_perf_sum_standard_bytes_compiled->inc(method->code_size() + task->num_inlined_bytecodes());2643}2644}26452646if (CITimeEach) {2647double compile_time = time.seconds();2648double bytes_per_sec = compile_time == 0.0 ? 0.0 : (double)(method->code_size() + task->num_inlined_bytecodes()) / compile_time;2649tty->print_cr("%3d seconds: %6.3f bytes/sec : %f (bytes %d + %d inlined)",2650compile_id, compile_time, bytes_per_sec, method->code_size(), task->num_inlined_bytecodes());2651}26522653// Collect counts of successful compilations2654_sum_nmethod_size += code->total_size();2655_sum_nmethod_code_size += code->insts_size();2656_total_compile_count++;26572658if (UsePerfData) {2659_perf_sum_nmethod_size->inc( code->total_size());2660_perf_sum_nmethod_code_size->inc(code->insts_size());2661_perf_total_compile_count->inc();2662}26632664if (is_osr) {2665if (UsePerfData) _perf_total_osr_compile_count->inc();2666_total_osr_compile_count++;2667} else {2668if (UsePerfData) _perf_total_standard_compile_count->inc();2669_total_standard_compile_count++;2670}2671}2672// set the current method for the thread to null2673if (UsePerfData) counters->set_current_method("");2674}26752676const char* CompileBroker::compiler_name(int comp_level) {2677AbstractCompiler *comp = CompileBroker::compiler(comp_level);2678if (comp == NULL) {2679return "no compiler";2680} else {2681return (comp->name());2682}2683}26842685jlong CompileBroker::total_compilation_ticks() {2686return _perf_total_compilation != NULL ? _perf_total_compilation->get_value() : 0;2687}26882689void CompileBroker::print_times(const char* name, CompilerStatistics* stats) {2690tty->print_cr(" %s {speed: %6.3f bytes/s; standard: %6.3f s, %d bytes, %d methods; osr: %6.3f s, %d bytes, %d methods; nmethods_size: %d bytes; nmethods_code_size: %d bytes}",2691name, stats->bytes_per_second(),2692stats->_standard._time.seconds(), stats->_standard._bytes, stats->_standard._count,2693stats->_osr._time.seconds(), stats->_osr._bytes, stats->_osr._count,2694stats->_nmethods_size, stats->_nmethods_code_size);2695}26962697void CompileBroker::print_times(bool per_compiler, bool aggregate) {2698if (per_compiler) {2699if (aggregate) {2700tty->cr();2701tty->print_cr("Individual compiler times (for compiled methods only)");2702tty->print_cr("------------------------------------------------");2703tty->cr();2704}2705for (unsigned int i = 0; i < sizeof(_compilers) / sizeof(AbstractCompiler*); i++) {2706AbstractCompiler* comp = _compilers[i];2707if (comp != NULL) {2708print_times(comp->name(), comp->stats());2709}2710}2711if (aggregate) {2712tty->cr();2713tty->print_cr("Individual compilation Tier times (for compiled methods only)");2714tty->print_cr("------------------------------------------------");2715tty->cr();2716}2717char tier_name[256];2718for (int tier = CompLevel_simple; tier <= CompilationPolicy::highest_compile_level(); tier++) {2719CompilerStatistics* stats = &_stats_per_level[tier-1];2720sprintf(tier_name, "Tier%d", tier);2721print_times(tier_name, stats);2722}2723}27242725if (!aggregate) {2726return;2727}27282729elapsedTimer standard_compilation = CompileBroker::_t_standard_compilation;2730elapsedTimer osr_compilation = CompileBroker::_t_osr_compilation;2731elapsedTimer total_compilation = CompileBroker::_t_total_compilation;27322733int standard_bytes_compiled = CompileBroker::_sum_standard_bytes_compiled;2734int osr_bytes_compiled = CompileBroker::_sum_osr_bytes_compiled;27352736int standard_compile_count = CompileBroker::_total_standard_compile_count;2737int osr_compile_count = CompileBroker::_total_osr_compile_count;2738int total_compile_count = CompileBroker::_total_compile_count;2739int total_bailout_count = CompileBroker::_total_bailout_count;2740int total_invalidated_count = CompileBroker::_total_invalidated_count;27412742int nmethods_size = CompileBroker::_sum_nmethod_code_size;2743int nmethods_code_size = CompileBroker::_sum_nmethod_size;27442745tty->cr();2746tty->print_cr("Accumulated compiler times");2747tty->print_cr("----------------------------------------------------------");2748//00000000001111111111222222222233333333334444444444555555555566666666662749//01234567890123456789012345678901234567890123456789012345678901234567892750tty->print_cr(" Total compilation time : %7.3f s", total_compilation.seconds());2751tty->print_cr(" Standard compilation : %7.3f s, Average : %2.3f s",2752standard_compilation.seconds(),2753standard_compile_count == 0 ? 0.0 : standard_compilation.seconds() / standard_compile_count);2754tty->print_cr(" Bailed out compilation : %7.3f s, Average : %2.3f s",2755CompileBroker::_t_bailedout_compilation.seconds(),2756total_bailout_count == 0 ? 0.0 : CompileBroker::_t_bailedout_compilation.seconds() / total_bailout_count);2757tty->print_cr(" On stack replacement : %7.3f s, Average : %2.3f s",2758osr_compilation.seconds(),2759osr_compile_count == 0 ? 0.0 : osr_compilation.seconds() / osr_compile_count);2760tty->print_cr(" Invalidated : %7.3f s, Average : %2.3f s",2761CompileBroker::_t_invalidated_compilation.seconds(),2762total_invalidated_count == 0 ? 0.0 : CompileBroker::_t_invalidated_compilation.seconds() / total_invalidated_count);27632764AbstractCompiler *comp = compiler(CompLevel_simple);2765if (comp != NULL) {2766tty->cr();2767comp->print_timers();2768}2769comp = compiler(CompLevel_full_optimization);2770if (comp != NULL) {2771tty->cr();2772comp->print_timers();2773}2774#if INCLUDE_JVMCI2775if (EnableJVMCI) {2776tty->cr();2777JVMCICompiler::print_hosted_timers();2778}2779#endif27802781tty->cr();2782tty->print_cr(" Total compiled methods : %8d methods", total_compile_count);2783tty->print_cr(" Standard compilation : %8d methods", standard_compile_count);2784tty->print_cr(" On stack replacement : %8d methods", osr_compile_count);2785int tcb = osr_bytes_compiled + standard_bytes_compiled;2786tty->print_cr(" Total compiled bytecodes : %8d bytes", tcb);2787tty->print_cr(" Standard compilation : %8d bytes", standard_bytes_compiled);2788tty->print_cr(" On stack replacement : %8d bytes", osr_bytes_compiled);2789double tcs = total_compilation.seconds();2790int bps = tcs == 0.0 ? 0 : (int)(tcb / tcs);2791tty->print_cr(" Average compilation speed : %8d bytes/s", bps);2792tty->cr();2793tty->print_cr(" nmethod code size : %8d bytes", nmethods_code_size);2794tty->print_cr(" nmethod total size : %8d bytes", nmethods_size);2795}27962797// Print general/accumulated JIT information.2798void CompileBroker::print_info(outputStream *out) {2799if (out == NULL) out = tty;2800out->cr();2801out->print_cr("======================");2802out->print_cr(" General JIT info ");2803out->print_cr("======================");2804out->cr();2805out->print_cr(" JIT is : %7s", should_compile_new_jobs() ? "on" : "off");2806out->print_cr(" Compiler threads : %7d", (int)CICompilerCount);2807out->cr();2808out->print_cr("CodeCache overview");2809out->print_cr("--------------------------------------------------------");2810out->cr();2811out->print_cr(" Reserved size : " SIZE_FORMAT_W(7) " KB", CodeCache::max_capacity() / K);2812out->print_cr(" Committed size : " SIZE_FORMAT_W(7) " KB", CodeCache::capacity() / K);2813out->print_cr(" Unallocated capacity : " SIZE_FORMAT_W(7) " KB", CodeCache::unallocated_capacity() / K);2814out->cr();28152816out->cr();2817out->print_cr("CodeCache cleaning overview");2818out->print_cr("--------------------------------------------------------");2819out->cr();2820NMethodSweeper::print(out);2821out->print_cr("--------------------------------------------------------");2822out->cr();2823}28242825// Note: tty_lock must not be held upon entry to this function.2826// Print functions called from herein do "micro-locking" on tty_lock.2827// That's a tradeoff which keeps together important blocks of output.2828// At the same time, continuous tty_lock hold time is kept in check,2829// preventing concurrently printing threads from stalling a long time.2830void CompileBroker::print_heapinfo(outputStream* out, const char* function, size_t granularity) {2831TimeStamp ts_total;2832TimeStamp ts_global;2833TimeStamp ts;28342835bool allFun = !strcmp(function, "all");2836bool aggregate = !strcmp(function, "aggregate") || !strcmp(function, "analyze") || allFun;2837bool usedSpace = !strcmp(function, "UsedSpace") || allFun;2838bool freeSpace = !strcmp(function, "FreeSpace") || allFun;2839bool methodCount = !strcmp(function, "MethodCount") || allFun;2840bool methodSpace = !strcmp(function, "MethodSpace") || allFun;2841bool methodAge = !strcmp(function, "MethodAge") || allFun;2842bool methodNames = !strcmp(function, "MethodNames") || allFun;2843bool discard = !strcmp(function, "discard") || allFun;28442845if (out == NULL) {2846out = tty;2847}28482849if (!(aggregate || usedSpace || freeSpace || methodCount || methodSpace || methodAge || methodNames || discard)) {2850out->print_cr("\n__ CodeHeapStateAnalytics: Function %s is not supported", function);2851out->cr();2852return;2853}28542855ts_total.update(); // record starting point28562857if (aggregate) {2858print_info(out);2859}28602861// We hold the CodeHeapStateAnalytics_lock all the time, from here until we leave this function.2862// That prevents other threads from destroying (making inconsistent) our view on the CodeHeap.2863// When we request individual parts of the analysis via the jcmd interface, it is possible2864// that in between another thread (another jcmd user or the vm running into CodeCache OOM)2865// updated the aggregated data. We will then see a modified, but again consistent, view2866// on the CodeHeap. That's a tolerable tradeoff we have to accept because we can't hold2867// a lock across user interaction.28682869// We should definitely acquire this lock before acquiring Compile_lock and CodeCache_lock.2870// CodeHeapStateAnalytics_lock may be held by a concurrent thread for a long time,2871// leading to an unnecessarily long hold time of the other locks we acquired before.2872ts.update(); // record starting point2873MutexLocker mu0(CodeHeapStateAnalytics_lock, Mutex::_safepoint_check_flag);2874out->print_cr("\n__ CodeHeapStateAnalytics lock wait took %10.3f seconds _________\n", ts.seconds());28752876// Holding the CodeCache_lock protects from concurrent alterations of the CodeCache.2877// Unfortunately, such protection is not sufficient:2878// When a new nmethod is created via ciEnv::register_method(), the2879// Compile_lock is taken first. After some initializations,2880// nmethod::new_nmethod() takes over, grabbing the CodeCache_lock2881// immediately (after finalizing the oop references). To lock out concurrent2882// modifiers, we have to grab both locks as well in the described sequence.2883//2884// If we serve an "allFun" call, it is beneficial to hold CodeCache_lock and Compile_lock2885// for the entire duration of aggregation and printing. That makes sure we see2886// a consistent picture and do not run into issues caused by concurrent alterations.2887bool should_take_Compile_lock = !SafepointSynchronize::is_at_safepoint() &&2888!Compile_lock->owned_by_self();2889bool should_take_CodeCache_lock = !SafepointSynchronize::is_at_safepoint() &&2890!CodeCache_lock->owned_by_self();2891Mutex* global_lock_1 = allFun ? (should_take_Compile_lock ? Compile_lock : NULL) : NULL;2892Monitor* global_lock_2 = allFun ? (should_take_CodeCache_lock ? CodeCache_lock : NULL) : NULL;2893Mutex* function_lock_1 = allFun ? NULL : (should_take_Compile_lock ? Compile_lock : NULL);2894Monitor* function_lock_2 = allFun ? NULL : (should_take_CodeCache_lock ? CodeCache_lock : NULL);2895ts_global.update(); // record starting point2896MutexLocker mu1(global_lock_1, Mutex::_safepoint_check_flag);2897MutexLocker mu2(global_lock_2, Mutex::_no_safepoint_check_flag);2898if ((global_lock_1 != NULL) || (global_lock_2 != NULL)) {2899out->print_cr("\n__ Compile & CodeCache (global) lock wait took %10.3f seconds _________\n", ts_global.seconds());2900ts_global.update(); // record starting point2901}29022903if (aggregate) {2904ts.update(); // record starting point2905MutexLocker mu11(function_lock_1, Mutex::_safepoint_check_flag);2906MutexLocker mu22(function_lock_2, Mutex::_no_safepoint_check_flag);2907if ((function_lock_1 != NULL) || (function_lock_1 != NULL)) {2908out->print_cr("\n__ Compile & CodeCache (function) lock wait took %10.3f seconds _________\n", ts.seconds());2909}29102911ts.update(); // record starting point2912CodeCache::aggregate(out, granularity);2913if ((function_lock_1 != NULL) || (function_lock_1 != NULL)) {2914out->print_cr("\n__ Compile & CodeCache (function) lock hold took %10.3f seconds _________\n", ts.seconds());2915}2916}29172918if (usedSpace) CodeCache::print_usedSpace(out);2919if (freeSpace) CodeCache::print_freeSpace(out);2920if (methodCount) CodeCache::print_count(out);2921if (methodSpace) CodeCache::print_space(out);2922if (methodAge) CodeCache::print_age(out);2923if (methodNames) {2924if (allFun) {2925// print_names() can only be used safely if the locks have been continuously held2926// since aggregation begin. That is true only for function "all".2927CodeCache::print_names(out);2928} else {2929out->print_cr("\nCodeHeapStateAnalytics: Function 'MethodNames' is only available as part of function 'all'");2930}2931}2932if (discard) CodeCache::discard(out);29332934if ((global_lock_1 != NULL) || (global_lock_2 != NULL)) {2935out->print_cr("\n__ Compile & CodeCache (global) lock hold took %10.3f seconds _________\n", ts_global.seconds());2936}2937out->print_cr("\n__ CodeHeapStateAnalytics total duration %10.3f seconds _________\n", ts_total.seconds());2938}293929402941