Path: blob/master/src/hotspot/share/compiler/compileBroker.cpp
40930 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) {226ResourceMark rm;227StringLogMessage lm;228lm.print("%4d COMPILE PROFILING SKIPPED: %s", -1, reason);229lm.print("\n");230log(JavaThread::current(), "%s", (const char*)lm);231}232};233234static CompilationLog* _compilation_log = NULL;235236bool compileBroker_init() {237if (LogEvents) {238_compilation_log = new CompilationLog();239}240241// init directives stack, adding default directive242DirectivesStack::init();243244if (DirectivesParser::has_file()) {245return DirectivesParser::parse_from_flag();246} else if (CompilerDirectivesPrint) {247// Print default directive even when no other was added248DirectivesStack::print(tty);249}250251return true;252}253254CompileTaskWrapper::CompileTaskWrapper(CompileTask* task) {255CompilerThread* thread = CompilerThread::current();256thread->set_task(task);257CompileLog* log = thread->log();258if (log != NULL && !task->is_unloaded()) task->log_task_start(log);259}260261CompileTaskWrapper::~CompileTaskWrapper() {262CompilerThread* thread = CompilerThread::current();263CompileTask* task = thread->task();264CompileLog* log = thread->log();265if (log != NULL && !task->is_unloaded()) task->log_task_done(log);266thread->set_task(NULL);267task->set_code_handle(NULL);268thread->set_env(NULL);269if (task->is_blocking()) {270bool free_task = false;271{272MutexLocker notifier(thread, task->lock());273task->mark_complete();274#if INCLUDE_JVMCI275if (CompileBroker::compiler(task->comp_level())->is_jvmci()) {276if (!task->has_waiter()) {277// The waiting thread timed out and thus did not free the task.278free_task = true;279}280task->set_blocking_jvmci_compile_state(NULL);281}282#endif283if (!free_task) {284// Notify the waiting thread that the compilation has completed285// so that it can free the task.286task->lock()->notify_all();287}288}289if (free_task) {290// The task can only be freed once the task lock is released.291CompileTask::free(task);292}293} else {294task->mark_complete();295296// By convention, the compiling thread is responsible for297// recycling a non-blocking CompileTask.298CompileTask::free(task);299}300}301302/**303* Check if a CompilerThread can be removed and update count if requested.304*/305bool CompileBroker::can_remove(CompilerThread *ct, bool do_it) {306assert(UseDynamicNumberOfCompilerThreads, "or shouldn't be here");307if (!ReduceNumberOfCompilerThreads) return false;308309AbstractCompiler *compiler = ct->compiler();310int compiler_count = compiler->num_compiler_threads();311bool c1 = compiler->is_c1();312313// Keep at least 1 compiler thread of each type.314if (compiler_count < 2) return false;315316// Keep thread alive for at least some time.317if (ct->idle_time_millis() < (c1 ? 500 : 100)) return false;318319#if INCLUDE_JVMCI320if (compiler->is_jvmci()) {321// Handles for JVMCI thread objects may get released concurrently.322if (do_it) {323assert(CompileThread_lock->owner() == ct, "must be holding lock");324} else {325// Skip check if it's the last thread and let caller check again.326return true;327}328}329#endif330331// We only allow the last compiler thread of each type to get removed.332jobject last_compiler = c1 ? compiler1_object(compiler_count - 1)333: compiler2_object(compiler_count - 1);334if (ct->threadObj() == JNIHandles::resolve_non_null(last_compiler)) {335if (do_it) {336assert_locked_or_safepoint(CompileThread_lock); // Update must be consistent.337compiler->set_num_compiler_threads(compiler_count - 1);338#if INCLUDE_JVMCI339if (compiler->is_jvmci()) {340// Old j.l.Thread object can die when no longer referenced elsewhere.341JNIHandles::destroy_global(compiler2_object(compiler_count - 1));342_compiler2_objects[compiler_count - 1] = NULL;343}344#endif345}346return true;347}348return false;349}350351/**352* Add a CompileTask to a CompileQueue.353*/354void CompileQueue::add(CompileTask* task) {355assert(MethodCompileQueue_lock->owned_by_self(), "must own lock");356357task->set_next(NULL);358task->set_prev(NULL);359360if (_last == NULL) {361// The compile queue is empty.362assert(_first == NULL, "queue is empty");363_first = task;364_last = task;365} else {366// Append the task to the queue.367assert(_last->next() == NULL, "not last");368_last->set_next(task);369task->set_prev(_last);370_last = task;371}372++_size;373374// Mark the method as being in the compile queue.375task->method()->set_queued_for_compilation();376377if (CIPrintCompileQueue) {378print_tty();379}380381if (LogCompilation && xtty != NULL) {382task->log_task_queued();383}384385// Notify CompilerThreads that a task is available.386MethodCompileQueue_lock->notify_all();387}388389/**390* Empties compilation queue by putting all compilation tasks onto391* a freelist. Furthermore, the method wakes up all threads that are392* waiting on a compilation task to finish. This can happen if background393* compilation is disabled.394*/395void CompileQueue::free_all() {396MutexLocker mu(MethodCompileQueue_lock);397CompileTask* next = _first;398399// Iterate over all tasks in the compile queue400while (next != NULL) {401CompileTask* current = next;402next = current->next();403{404// Wake up thread that blocks on the compile task.405MutexLocker ct_lock(current->lock());406current->lock()->notify();407}408// Put the task back on the freelist.409CompileTask::free(current);410}411_first = NULL;412413// Wake up all threads that block on the queue.414MethodCompileQueue_lock->notify_all();415}416417/**418* Get the next CompileTask from a CompileQueue419*/420CompileTask* CompileQueue::get() {421// save methods from RedefineClasses across safepoint422// across MethodCompileQueue_lock below.423methodHandle save_method;424methodHandle save_hot_method;425426MonitorLocker locker(MethodCompileQueue_lock);427// If _first is NULL we have no more compile jobs. There are two reasons for428// having no compile jobs: First, we compiled everything we wanted. Second,429// we ran out of code cache so compilation has been disabled. In the latter430// case we perform code cache sweeps to free memory such that we can re-enable431// compilation.432while (_first == NULL) {433// Exit loop if compilation is disabled forever434if (CompileBroker::is_compilation_disabled_forever()) {435return NULL;436}437438// If there are no compilation tasks and we can compile new jobs439// (i.e., there is enough free space in the code cache) there is440// no need to invoke the sweeper. As a result, the hotness of methods441// remains unchanged. This behavior is desired, since we want to keep442// the stable state, i.e., we do not want to evict methods from the443// code cache if it is unnecessary.444// We need a timed wait here, since compiler threads can exit if compilation445// is disabled forever. We use 5 seconds wait time; the exiting of compiler threads446// is not critical and we do not want idle compiler threads to wake up too often.447locker.wait(5*1000);448449if (UseDynamicNumberOfCompilerThreads && _first == NULL) {450// Still nothing to compile. Give caller a chance to stop this thread.451if (CompileBroker::can_remove(CompilerThread::current(), false)) return NULL;452}453}454455if (CompileBroker::is_compilation_disabled_forever()) {456return NULL;457}458459CompileTask* task;460{461NoSafepointVerifier nsv;462task = CompilationPolicy::select_task(this);463if (task != NULL) {464task = task->select_for_compilation();465}466}467468if (task != NULL) {469// Save method pointers across unlock safepoint. The task is removed from470// the compilation queue, which is walked during RedefineClasses.471Thread* thread = Thread::current();472save_method = methodHandle(thread, task->method());473save_hot_method = methodHandle(thread, task->hot_method());474475remove(task);476}477purge_stale_tasks(); // may temporarily release MCQ lock478return task;479}480481// Clean & deallocate stale compile tasks.482// Temporarily releases MethodCompileQueue lock.483void CompileQueue::purge_stale_tasks() {484assert(MethodCompileQueue_lock->owned_by_self(), "must own lock");485if (_first_stale != NULL) {486// Stale tasks are purged when MCQ lock is released,487// but _first_stale updates are protected by MCQ lock.488// Once task processing starts and MCQ lock is released,489// other compiler threads can reuse _first_stale.490CompileTask* head = _first_stale;491_first_stale = NULL;492{493MutexUnlocker ul(MethodCompileQueue_lock);494for (CompileTask* task = head; task != NULL; ) {495CompileTask* next_task = task->next();496CompileTaskWrapper ctw(task); // Frees the task497task->set_failure_reason("stale task");498task = next_task;499}500}501}502}503504void CompileQueue::remove(CompileTask* task) {505assert(MethodCompileQueue_lock->owned_by_self(), "must own lock");506if (task->prev() != NULL) {507task->prev()->set_next(task->next());508} else {509// max is the first element510assert(task == _first, "Sanity");511_first = task->next();512}513514if (task->next() != NULL) {515task->next()->set_prev(task->prev());516} else {517// max is the last element518assert(task == _last, "Sanity");519_last = task->prev();520}521--_size;522}523524void CompileQueue::remove_and_mark_stale(CompileTask* task) {525assert(MethodCompileQueue_lock->owned_by_self(), "must own lock");526remove(task);527528// Enqueue the task for reclamation (should be done outside MCQ lock)529task->set_next(_first_stale);530task->set_prev(NULL);531_first_stale = task;532}533534// methods in the compile queue need to be marked as used on the stack535// so that they don't get reclaimed by Redefine Classes536void CompileQueue::mark_on_stack() {537CompileTask* task = _first;538while (task != NULL) {539task->mark_on_stack();540task = task->next();541}542}543544545CompileQueue* CompileBroker::compile_queue(int comp_level) {546if (is_c2_compile(comp_level)) return _c2_compile_queue;547if (is_c1_compile(comp_level)) return _c1_compile_queue;548return NULL;549}550551void CompileBroker::print_compile_queues(outputStream* st) {552st->print_cr("Current compiles: ");553554char buf[2000];555int buflen = sizeof(buf);556Threads::print_threads_compiling(st, buf, buflen, /* short_form = */ true);557558st->cr();559if (_c1_compile_queue != NULL) {560_c1_compile_queue->print(st);561}562if (_c2_compile_queue != NULL) {563_c2_compile_queue->print(st);564}565}566567void CompileQueue::print(outputStream* st) {568assert_locked_or_safepoint(MethodCompileQueue_lock);569st->print_cr("%s:", name());570CompileTask* task = _first;571if (task == NULL) {572st->print_cr("Empty");573} else {574while (task != NULL) {575task->print(st, NULL, true, true);576task = task->next();577}578}579st->cr();580}581582void CompileQueue::print_tty() {583ResourceMark rm;584stringStream ss;585// Dump the compile queue into a buffer before locking the tty586print(&ss);587{588ttyLocker ttyl;589tty->print("%s", ss.as_string());590}591}592593CompilerCounters::CompilerCounters() {594_current_method[0] = '\0';595_compile_type = CompileBroker::no_compile;596}597598#if INCLUDE_JFR && COMPILER2_OR_JVMCI599// It appends new compiler phase names to growable array phase_names(a new CompilerPhaseType mapping600// in compiler/compilerEvent.cpp) and registers it with its serializer.601//602// c2 uses explicit CompilerPhaseType idToPhase mapping in opto/phasetype.hpp,603// so if c2 is used, it should be always registered first.604// This function is called during vm initialization.605void register_jfr_phasetype_serializer(CompilerType compiler_type) {606ResourceMark rm;607static bool first_registration = true;608if (compiler_type == compiler_jvmci) {609CompilerEvent::PhaseEvent::get_phase_id("NOT_A_PHASE_NAME", false, false, false);610first_registration = false;611#ifdef COMPILER2612} else if (compiler_type == compiler_c2) {613assert(first_registration, "invariant"); // c2 must be registered first.614GrowableArray<const char*>* c2_phase_names = new GrowableArray<const char*>(PHASE_NUM_TYPES);615for (int i = 0; i < PHASE_NUM_TYPES; i++) {616const char* phase_name = CompilerPhaseTypeHelper::to_string((CompilerPhaseType) i);617CompilerEvent::PhaseEvent::get_phase_id(phase_name, false, false, false);618}619first_registration = false;620#endif // COMPILER2621}622}623#endif // INCLUDE_JFR && COMPILER2_OR_JVMCI624625// ------------------------------------------------------------------626// CompileBroker::compilation_init627//628// Initialize the Compilation object629void CompileBroker::compilation_init_phase1(JavaThread* THREAD) {630// No need to initialize compilation system if we do not use it.631if (!UseCompiler) {632return;633}634// Set the interface to the current compiler(s).635_c1_count = CompilationPolicy::c1_count();636_c2_count = CompilationPolicy::c2_count();637638#if INCLUDE_JVMCI639if (EnableJVMCI) {640// This is creating a JVMCICompiler singleton.641JVMCICompiler* jvmci = new JVMCICompiler();642643if (UseJVMCICompiler) {644_compilers[1] = jvmci;645if (FLAG_IS_DEFAULT(JVMCIThreads)) {646if (BootstrapJVMCI) {647// JVMCI will bootstrap so give it more threads648_c2_count = MIN2(32, os::active_processor_count());649}650} else {651_c2_count = JVMCIThreads;652}653if (FLAG_IS_DEFAULT(JVMCIHostThreads)) {654} else {655#ifdef COMPILER1656_c1_count = JVMCIHostThreads;657#endif // COMPILER1658}659}660}661#endif // INCLUDE_JVMCI662663#ifdef COMPILER1664if (_c1_count > 0) {665_compilers[0] = new Compiler();666}667#endif // COMPILER1668669#ifdef COMPILER2670if (true JVMCI_ONLY( && !UseJVMCICompiler)) {671if (_c2_count > 0) {672_compilers[1] = new C2Compiler();673// Register c2 first as c2 CompilerPhaseType idToPhase mapping is explicit.674// idToPhase mapping for c2 is in opto/phasetype.hpp675JFR_ONLY(register_jfr_phasetype_serializer(compiler_c2);)676}677}678#endif // COMPILER2679680#if INCLUDE_JVMCI681// Register after c2 registration.682// JVMCI CompilerPhaseType idToPhase mapping is dynamic.683if (EnableJVMCI) {684JFR_ONLY(register_jfr_phasetype_serializer(compiler_jvmci);)685}686#endif // INCLUDE_JVMCI687688// Start the compiler thread(s) and the sweeper thread689init_compiler_sweeper_threads();690// totalTime performance counter is always created as it is required691// by the implementation of java.lang.management.CompilationMXBean.692{693// Ensure OOM leads to vm_exit_during_initialization.694EXCEPTION_MARK;695_perf_total_compilation =696PerfDataManager::create_counter(JAVA_CI, "totalTime",697PerfData::U_Ticks, CHECK);698}699700if (UsePerfData) {701702EXCEPTION_MARK;703704// create the jvmstat performance counters705_perf_osr_compilation =706PerfDataManager::create_counter(SUN_CI, "osrTime",707PerfData::U_Ticks, CHECK);708709_perf_standard_compilation =710PerfDataManager::create_counter(SUN_CI, "standardTime",711PerfData::U_Ticks, CHECK);712713_perf_total_bailout_count =714PerfDataManager::create_counter(SUN_CI, "totalBailouts",715PerfData::U_Events, CHECK);716717_perf_total_invalidated_count =718PerfDataManager::create_counter(SUN_CI, "totalInvalidates",719PerfData::U_Events, CHECK);720721_perf_total_compile_count =722PerfDataManager::create_counter(SUN_CI, "totalCompiles",723PerfData::U_Events, CHECK);724_perf_total_osr_compile_count =725PerfDataManager::create_counter(SUN_CI, "osrCompiles",726PerfData::U_Events, CHECK);727728_perf_total_standard_compile_count =729PerfDataManager::create_counter(SUN_CI, "standardCompiles",730PerfData::U_Events, CHECK);731732_perf_sum_osr_bytes_compiled =733PerfDataManager::create_counter(SUN_CI, "osrBytes",734PerfData::U_Bytes, CHECK);735736_perf_sum_standard_bytes_compiled =737PerfDataManager::create_counter(SUN_CI, "standardBytes",738PerfData::U_Bytes, CHECK);739740_perf_sum_nmethod_size =741PerfDataManager::create_counter(SUN_CI, "nmethodSize",742PerfData::U_Bytes, CHECK);743744_perf_sum_nmethod_code_size =745PerfDataManager::create_counter(SUN_CI, "nmethodCodeSize",746PerfData::U_Bytes, CHECK);747748_perf_last_method =749PerfDataManager::create_string_variable(SUN_CI, "lastMethod",750CompilerCounters::cmname_buffer_length,751"", CHECK);752753_perf_last_failed_method =754PerfDataManager::create_string_variable(SUN_CI, "lastFailedMethod",755CompilerCounters::cmname_buffer_length,756"", CHECK);757758_perf_last_invalidated_method =759PerfDataManager::create_string_variable(SUN_CI, "lastInvalidatedMethod",760CompilerCounters::cmname_buffer_length,761"", CHECK);762763_perf_last_compile_type =764PerfDataManager::create_variable(SUN_CI, "lastType",765PerfData::U_None,766(jlong)CompileBroker::no_compile,767CHECK);768769_perf_last_compile_size =770PerfDataManager::create_variable(SUN_CI, "lastSize",771PerfData::U_Bytes,772(jlong)CompileBroker::no_compile,773CHECK);774775776_perf_last_failed_type =777PerfDataManager::create_variable(SUN_CI, "lastFailedType",778PerfData::U_None,779(jlong)CompileBroker::no_compile,780CHECK);781782_perf_last_invalidated_type =783PerfDataManager::create_variable(SUN_CI, "lastInvalidatedType",784PerfData::U_None,785(jlong)CompileBroker::no_compile,786CHECK);787}788}789790// Completes compiler initialization. Compilation requests submitted791// prior to this will be silently ignored.792void CompileBroker::compilation_init_phase2() {793_initialized = true;794}795796Handle CompileBroker::create_thread_oop(const char* name, TRAPS) {797Handle string = java_lang_String::create_from_str(name, CHECK_NH);798Handle thread_group(THREAD, Universe::system_thread_group());799return JavaCalls::construct_new_instance(800vmClasses::Thread_klass(),801vmSymbols::threadgroup_string_void_signature(),802thread_group,803string,804CHECK_NH);805}806807#if defined(ASSERT) && COMPILER2_OR_JVMCI808// Stress testing. Dedicated threads revert optimizations based on escape analysis concurrently to809// the running java application. Configured with vm options DeoptimizeObjectsALot*.810class DeoptimizeObjectsALotThread : public JavaThread {811812static void deopt_objs_alot_thread_entry(JavaThread* thread, TRAPS);813void deoptimize_objects_alot_loop_single();814void deoptimize_objects_alot_loop_all();815816public:817DeoptimizeObjectsALotThread() : JavaThread(&deopt_objs_alot_thread_entry) { }818819bool is_hidden_from_external_view() const { return true; }820};821822// Entry for DeoptimizeObjectsALotThread. The threads are started in823// CompileBroker::init_compiler_sweeper_threads() iff DeoptimizeObjectsALot is enabled824void DeoptimizeObjectsALotThread::deopt_objs_alot_thread_entry(JavaThread* thread, TRAPS) {825DeoptimizeObjectsALotThread* dt = ((DeoptimizeObjectsALotThread*) thread);826bool enter_single_loop;827{828MonitorLocker ml(dt, EscapeBarrier_lock, Mutex::_no_safepoint_check_flag);829static int single_thread_count = 0;830enter_single_loop = single_thread_count++ < DeoptimizeObjectsALotThreadCountSingle;831}832if (enter_single_loop) {833dt->deoptimize_objects_alot_loop_single();834} else {835dt->deoptimize_objects_alot_loop_all();836}837}838839// Execute EscapeBarriers in an endless loop to revert optimizations based on escape analysis. Each840// barrier targets a single thread which is selected round robin.841void DeoptimizeObjectsALotThread::deoptimize_objects_alot_loop_single() {842HandleMark hm(this);843while (true) {844for (JavaThreadIteratorWithHandle jtiwh; JavaThread *deoptee_thread = jtiwh.next(); ) {845{ // Begin new scope for escape barrier846HandleMarkCleaner hmc(this);847ResourceMark rm(this);848EscapeBarrier eb(true, this, deoptee_thread);849eb.deoptimize_objects(100);850}851// Now sleep after the escape barriers destructor resumed deoptee_thread.852sleep(DeoptimizeObjectsALotInterval);853}854}855}856857// Execute EscapeBarriers in an endless loop to revert optimizations based on escape analysis. Each858// barrier targets all java threads in the vm at once.859void DeoptimizeObjectsALotThread::deoptimize_objects_alot_loop_all() {860HandleMark hm(this);861while (true) {862{ // Begin new scope for escape barrier863HandleMarkCleaner hmc(this);864ResourceMark rm(this);865EscapeBarrier eb(true, this);866eb.deoptimize_objects_all_threads();867}868// Now sleep after the escape barriers destructor resumed the java threads.869sleep(DeoptimizeObjectsALotInterval);870}871}872#endif // defined(ASSERT) && COMPILER2_OR_JVMCI873874875JavaThread* CompileBroker::make_thread(ThreadType type, jobject thread_handle, CompileQueue* queue, AbstractCompiler* comp, JavaThread* THREAD) {876JavaThread* new_thread = NULL;877{878MutexLocker mu(THREAD, Threads_lock);879switch (type) {880case compiler_t:881assert(comp != NULL, "Compiler instance missing.");882if (!InjectCompilerCreationFailure || comp->num_compiler_threads() == 0) {883CompilerCounters* counters = new CompilerCounters();884new_thread = new CompilerThread(queue, counters);885}886break;887case sweeper_t:888new_thread = new CodeCacheSweeperThread();889break;890#if defined(ASSERT) && COMPILER2_OR_JVMCI891case deoptimizer_t:892new_thread = new DeoptimizeObjectsALotThread();893break;894#endif // ASSERT895default:896ShouldNotReachHere();897}898899// At this point the new CompilerThread data-races with this startup900// thread (which I believe is the primoridal thread and NOT the VM901// thread). This means Java bytecodes being executed at startup can902// queue compile jobs which will run at whatever default priority the903// newly created CompilerThread runs at.904905906// At this point it may be possible that no osthread was created for the907// JavaThread due to lack of memory. We would have to throw an exception908// in that case. However, since this must work and we do not allow909// exceptions anyway, check and abort if this fails. But first release the910// lock.911912if (new_thread != NULL && new_thread->osthread() != NULL) {913914java_lang_Thread::set_thread(JNIHandles::resolve_non_null(thread_handle), new_thread);915916// Note that this only sets the JavaThread _priority field, which by917// definition is limited to Java priorities and not OS priorities.918// The os-priority is set in the CompilerThread startup code itself919920java_lang_Thread::set_priority(JNIHandles::resolve_non_null(thread_handle), NearMaxPriority);921922// Note that we cannot call os::set_priority because it expects Java923// priorities and we are *explicitly* using OS priorities so that it's924// possible to set the compiler thread priority higher than any Java925// thread.926927int native_prio = CompilerThreadPriority;928if (native_prio == -1) {929if (UseCriticalCompilerThreadPriority) {930native_prio = os::java_to_os_priority[CriticalPriority];931} else {932native_prio = os::java_to_os_priority[NearMaxPriority];933}934}935os::set_native_priority(new_thread, native_prio);936937java_lang_Thread::set_daemon(JNIHandles::resolve_non_null(thread_handle));938939new_thread->set_threadObj(JNIHandles::resolve_non_null(thread_handle));940if (type == compiler_t) {941CompilerThread::cast(new_thread)->set_compiler(comp);942}943Threads::add(new_thread);944Thread::start(new_thread);945}946}947948// First release lock before aborting VM.949if (new_thread == NULL || new_thread->osthread() == NULL) {950if (UseDynamicNumberOfCompilerThreads && type == compiler_t && comp->num_compiler_threads() > 0) {951if (new_thread != NULL) {952new_thread->smr_delete();953}954return NULL;955}956vm_exit_during_initialization("java.lang.OutOfMemoryError",957os::native_thread_creation_failed_msg());958}959960// Let go of Threads_lock before yielding961os::naked_yield(); // make sure that the compiler thread is started early (especially helpful on SOLARIS)962963return new_thread;964}965966967void CompileBroker::init_compiler_sweeper_threads() {968NMethodSweeper::set_sweep_threshold_bytes(static_cast<size_t>(SweeperThreshold * ReservedCodeCacheSize / 100.0));969log_info(codecache, sweep)("Sweeper threshold: " SIZE_FORMAT " bytes", NMethodSweeper::sweep_threshold_bytes());970971// Ensure any exceptions lead to vm_exit_during_initialization.972EXCEPTION_MARK;973#if !defined(ZERO)974assert(_c2_count > 0 || _c1_count > 0, "No compilers?");975#endif // !ZERO976// Initialize the compilation queue977if (_c2_count > 0) {978const char* name = JVMCI_ONLY(UseJVMCICompiler ? "JVMCI compile queue" :) "C2 compile queue";979_c2_compile_queue = new CompileQueue(name);980_compiler2_objects = NEW_C_HEAP_ARRAY(jobject, _c2_count, mtCompiler);981_compiler2_logs = NEW_C_HEAP_ARRAY(CompileLog*, _c2_count, mtCompiler);982}983if (_c1_count > 0) {984_c1_compile_queue = new CompileQueue("C1 compile queue");985_compiler1_objects = NEW_C_HEAP_ARRAY(jobject, _c1_count, mtCompiler);986_compiler1_logs = NEW_C_HEAP_ARRAY(CompileLog*, _c1_count, mtCompiler);987}988989char name_buffer[256];990991for (int i = 0; i < _c2_count; i++) {992jobject thread_handle = NULL;993// Create all j.l.Thread objects for C1 and C2 threads here, but only one994// for JVMCI compiler which can create further ones on demand.995JVMCI_ONLY(if (!UseJVMCICompiler || !UseDynamicNumberOfCompilerThreads || i == 0) {)996// Create a name for our thread.997sprintf(name_buffer, "%s CompilerThread%d", _compilers[1]->name(), i);998Handle thread_oop = create_thread_oop(name_buffer, CHECK);999thread_handle = JNIHandles::make_global(thread_oop);1000JVMCI_ONLY(})1001_compiler2_objects[i] = thread_handle;1002_compiler2_logs[i] = NULL;10031004if (!UseDynamicNumberOfCompilerThreads || i == 0) {1005JavaThread *ct = make_thread(compiler_t, thread_handle, _c2_compile_queue, _compilers[1], THREAD);1006assert(ct != NULL, "should have been handled for initial thread");1007_compilers[1]->set_num_compiler_threads(i + 1);1008if (TraceCompilerThreads) {1009ResourceMark rm;1010ThreadsListHandle tlh; // get_thread_name() depends on the TLH.1011assert(tlh.includes(ct), "ct=" INTPTR_FORMAT " exited unexpectedly.", p2i(ct));1012tty->print_cr("Added initial compiler thread %s", ct->get_thread_name());1013}1014}1015}10161017for (int i = 0; i < _c1_count; i++) {1018// Create a name for our thread.1019sprintf(name_buffer, "C1 CompilerThread%d", i);1020Handle thread_oop = create_thread_oop(name_buffer, CHECK);1021jobject thread_handle = JNIHandles::make_global(thread_oop);1022_compiler1_objects[i] = thread_handle;1023_compiler1_logs[i] = NULL;10241025if (!UseDynamicNumberOfCompilerThreads || i == 0) {1026JavaThread *ct = make_thread(compiler_t, thread_handle, _c1_compile_queue, _compilers[0], THREAD);1027assert(ct != NULL, "should have been handled for initial thread");1028_compilers[0]->set_num_compiler_threads(i + 1);1029if (TraceCompilerThreads) {1030ResourceMark rm;1031ThreadsListHandle tlh; // get_thread_name() depends on the TLH.1032assert(tlh.includes(ct), "ct=" INTPTR_FORMAT " exited unexpectedly.", p2i(ct));1033tty->print_cr("Added initial compiler thread %s", ct->get_thread_name());1034}1035}1036}10371038if (UsePerfData) {1039PerfDataManager::create_constant(SUN_CI, "threads", PerfData::U_Bytes, _c1_count + _c2_count, CHECK);1040}10411042if (MethodFlushing) {1043// Initialize the sweeper thread1044Handle thread_oop = create_thread_oop("Sweeper thread", CHECK);1045jobject thread_handle = JNIHandles::make_local(THREAD, thread_oop());1046make_thread(sweeper_t, thread_handle, NULL, NULL, THREAD);1047}10481049#if defined(ASSERT) && COMPILER2_OR_JVMCI1050if (DeoptimizeObjectsALot) {1051// Initialize and start the object deoptimizer threads1052const int total_count = DeoptimizeObjectsALotThreadCountSingle + DeoptimizeObjectsALotThreadCountAll;1053for (int count = 0; count < total_count; count++) {1054Handle thread_oop = create_thread_oop("Deoptimize objects a lot single mode", CHECK);1055jobject thread_handle = JNIHandles::make_local(THREAD, thread_oop());1056make_thread(deoptimizer_t, thread_handle, NULL, NULL, THREAD);1057}1058}1059#endif // defined(ASSERT) && COMPILER2_OR_JVMCI1060}10611062void CompileBroker::possibly_add_compiler_threads(JavaThread* THREAD) {10631064julong available_memory = os::available_memory();1065// If SegmentedCodeCache is off, both values refer to the single heap (with type CodeBlobType::All).1066size_t available_cc_np = CodeCache::unallocated_capacity(CodeBlobType::MethodNonProfiled),1067available_cc_p = CodeCache::unallocated_capacity(CodeBlobType::MethodProfiled);10681069// Only do attempt to start additional threads if the lock is free.1070if (!CompileThread_lock->try_lock()) return;10711072if (_c2_compile_queue != NULL) {1073int old_c2_count = _compilers[1]->num_compiler_threads();1074int new_c2_count = MIN4(_c2_count,1075_c2_compile_queue->size() / 2,1076(int)(available_memory / (200*M)),1077(int)(available_cc_np / (128*K)));10781079for (int i = old_c2_count; i < new_c2_count; i++) {1080#if INCLUDE_JVMCI1081if (UseJVMCICompiler) {1082// Native compiler threads as used in C1/C2 can reuse the j.l.Thread1083// objects as their existence is completely hidden from the rest of1084// the VM (and those compiler threads can't call Java code to do the1085// creation anyway). For JVMCI we have to create new j.l.Thread objects1086// as they are visible and we can see unexpected thread lifecycle1087// transitions if we bind them to new JavaThreads.1088if (!THREAD->can_call_java()) break;1089char name_buffer[256];1090sprintf(name_buffer, "%s CompilerThread%d", _compilers[1]->name(), i);1091Handle thread_oop;1092{1093// We have to give up the lock temporarily for the Java calls.1094MutexUnlocker mu(CompileThread_lock);1095thread_oop = create_thread_oop(name_buffer, THREAD);1096}1097if (HAS_PENDING_EXCEPTION) {1098if (TraceCompilerThreads) {1099ResourceMark rm;1100tty->print_cr("JVMCI compiler thread creation failed:");1101PENDING_EXCEPTION->print();1102}1103CLEAR_PENDING_EXCEPTION;1104break;1105}1106// Check if another thread has beaten us during the Java calls.1107if (_compilers[1]->num_compiler_threads() != i) break;1108jobject thread_handle = JNIHandles::make_global(thread_oop);1109assert(compiler2_object(i) == NULL, "Old one must be released!");1110_compiler2_objects[i] = thread_handle;1111}1112#endif1113JavaThread *ct = make_thread(compiler_t, compiler2_object(i), _c2_compile_queue, _compilers[1], THREAD);1114if (ct == NULL) break;1115_compilers[1]->set_num_compiler_threads(i + 1);1116if (TraceCompilerThreads) {1117ResourceMark rm;1118ThreadsListHandle tlh; // get_thread_name() depends on the TLH.1119assert(tlh.includes(ct), "ct=" INTPTR_FORMAT " exited unexpectedly.", p2i(ct));1120tty->print_cr("Added compiler thread %s (available memory: %dMB, available non-profiled code cache: %dMB)",1121ct->get_thread_name(), (int)(available_memory/M), (int)(available_cc_np/M));1122}1123}1124}11251126if (_c1_compile_queue != NULL) {1127int old_c1_count = _compilers[0]->num_compiler_threads();1128int new_c1_count = MIN4(_c1_count,1129_c1_compile_queue->size() / 4,1130(int)(available_memory / (100*M)),1131(int)(available_cc_p / (128*K)));11321133for (int i = old_c1_count; i < new_c1_count; i++) {1134JavaThread *ct = make_thread(compiler_t, compiler1_object(i), _c1_compile_queue, _compilers[0], THREAD);1135if (ct == NULL) break;1136_compilers[0]->set_num_compiler_threads(i + 1);1137if (TraceCompilerThreads) {1138ResourceMark rm;1139ThreadsListHandle tlh; // get_thread_name() depends on the TLH.1140assert(tlh.includes(ct), "ct=" INTPTR_FORMAT " exited unexpectedly.", p2i(ct));1141tty->print_cr("Added compiler thread %s (available memory: %dMB, available profiled code cache: %dMB)",1142ct->get_thread_name(), (int)(available_memory/M), (int)(available_cc_p/M));1143}1144}1145}11461147CompileThread_lock->unlock();1148}114911501151/**1152* Set the methods on the stack as on_stack so that redefine classes doesn't1153* reclaim them. This method is executed at a safepoint.1154*/1155void CompileBroker::mark_on_stack() {1156assert(SafepointSynchronize::is_at_safepoint(), "sanity check");1157// Since we are at a safepoint, we do not need a lock to access1158// the compile queues.1159if (_c2_compile_queue != NULL) {1160_c2_compile_queue->mark_on_stack();1161}1162if (_c1_compile_queue != NULL) {1163_c1_compile_queue->mark_on_stack();1164}1165}11661167// ------------------------------------------------------------------1168// CompileBroker::compile_method1169//1170// Request compilation of a method.1171void CompileBroker::compile_method_base(const methodHandle& method,1172int osr_bci,1173int comp_level,1174const methodHandle& hot_method,1175int hot_count,1176CompileTask::CompileReason compile_reason,1177bool blocking,1178Thread* thread) {1179guarantee(!method->is_abstract(), "cannot compile abstract methods");1180assert(method->method_holder()->is_instance_klass(),1181"sanity check");1182assert(!method->method_holder()->is_not_initialized(),1183"method holder must be initialized");1184assert(!method->is_method_handle_intrinsic(), "do not enqueue these guys");11851186if (CIPrintRequests) {1187tty->print("request: ");1188method->print_short_name(tty);1189if (osr_bci != InvocationEntryBci) {1190tty->print(" osr_bci: %d", osr_bci);1191}1192tty->print(" level: %d comment: %s count: %d", comp_level, CompileTask::reason_name(compile_reason), hot_count);1193if (!hot_method.is_null()) {1194tty->print(" hot: ");1195if (hot_method() != method()) {1196hot_method->print_short_name(tty);1197} else {1198tty->print("yes");1199}1200}1201tty->cr();1202}12031204// A request has been made for compilation. Before we do any1205// real work, check to see if the method has been compiled1206// in the meantime with a definitive result.1207if (compilation_is_complete(method, osr_bci, comp_level)) {1208return;1209}12101211#ifndef PRODUCT1212if (osr_bci != -1 && !FLAG_IS_DEFAULT(OSROnlyBCI)) {1213if ((OSROnlyBCI > 0) ? (OSROnlyBCI != osr_bci) : (-OSROnlyBCI == osr_bci)) {1214// Positive OSROnlyBCI means only compile that bci. Negative means don't compile that BCI.1215return;1216}1217}1218#endif12191220// If this method is already in the compile queue, then1221// we do not block the current thread.1222if (compilation_is_in_queue(method)) {1223// We may want to decay our counter a bit here to prevent1224// multiple denied requests for compilation. This is an1225// open compilation policy issue. Note: The other possibility,1226// in the case that this is a blocking compile request, is to have1227// all subsequent blocking requesters wait for completion of1228// ongoing compiles. Note that in this case we'll need a protocol1229// for freeing the associated compile tasks. [Or we could have1230// a single static monitor on which all these waiters sleep.]1231return;1232}12331234// Tiered policy requires MethodCounters to exist before adding a method to1235// the queue. Create if we don't have them yet.1236method->get_method_counters(thread);12371238// Outputs from the following MutexLocker block:1239CompileTask* task = NULL;1240CompileQueue* queue = compile_queue(comp_level);12411242// Acquire our lock.1243{1244MutexLocker locker(thread, MethodCompileQueue_lock);12451246// Make sure the method has not slipped into the queues since1247// last we checked; note that those checks were "fast bail-outs".1248// Here we need to be more careful, see 14012000 below.1249if (compilation_is_in_queue(method)) {1250return;1251}12521253// We need to check again to see if the compilation has1254// completed. A previous compilation may have registered1255// some result.1256if (compilation_is_complete(method, osr_bci, comp_level)) {1257return;1258}12591260// We now know that this compilation is not pending, complete,1261// or prohibited. Assign a compile_id to this compilation1262// and check to see if it is in our [Start..Stop) range.1263int compile_id = assign_compile_id(method, osr_bci);1264if (compile_id == 0) {1265// The compilation falls outside the allowed range.1266return;1267}12681269#if INCLUDE_JVMCI1270if (UseJVMCICompiler && blocking) {1271// Don't allow blocking compiles for requests triggered by JVMCI.1272if (thread->is_Compiler_thread()) {1273blocking = false;1274}12751276if (!UseJVMCINativeLibrary) {1277// Don't allow blocking compiles if inside a class initializer or while performing class loading1278vframeStream vfst(thread->as_Java_thread());1279for (; !vfst.at_end(); vfst.next()) {1280if (vfst.method()->is_static_initializer() ||1281(vfst.method()->method_holder()->is_subclass_of(vmClasses::ClassLoader_klass()) &&1282vfst.method()->name() == vmSymbols::loadClass_name())) {1283blocking = false;1284break;1285}1286}1287}12881289// Don't allow blocking compilation requests to JVMCI1290// if JVMCI itself is not yet initialized1291if (!JVMCI::is_compiler_initialized() && compiler(comp_level)->is_jvmci()) {1292blocking = false;1293}12941295// Don't allow blocking compilation requests if we are in JVMCIRuntime::shutdown1296// to avoid deadlock between compiler thread(s) and threads run at shutdown1297// such as the DestroyJavaVM thread.1298if (JVMCI::in_shutdown()) {1299blocking = false;1300}1301}1302#endif // INCLUDE_JVMCI13031304// We will enter the compilation in the queue.1305// 14012000: Note that this sets the queued_for_compile bits in1306// the target method. We can now reason that a method cannot be1307// queued for compilation more than once, as follows:1308// Before a thread queues a task for compilation, it first acquires1309// the compile queue lock, then checks if the method's queued bits1310// are set or it has already been compiled. Thus there can not be two1311// instances of a compilation task for the same method on the1312// compilation queue. Consider now the case where the compilation1313// thread has already removed a task for that method from the queue1314// and is in the midst of compiling it. In this case, the1315// queued_for_compile bits must be set in the method (and these1316// will be visible to the current thread, since the bits were set1317// under protection of the compile queue lock, which we hold now.1318// When the compilation completes, the compiler thread first sets1319// the compilation result and then clears the queued_for_compile1320// bits. Neither of these actions are protected by a barrier (or done1321// under the protection of a lock), so the only guarantee we have1322// (on machines with TSO (Total Store Order)) is that these values1323// will update in that order. As a result, the only combinations of1324// these bits that the current thread will see are, in temporal order:1325// <RESULT, QUEUE> :1326// <0, 1> : in compile queue, but not yet compiled1327// <1, 1> : compiled but queue bit not cleared1328// <1, 0> : compiled and queue bit cleared1329// Because we first check the queue bits then check the result bits,1330// we are assured that we cannot introduce a duplicate task.1331// Note that if we did the tests in the reverse order (i.e. check1332// result then check queued bit), we could get the result bit before1333// the compilation completed, and the queue bit after the compilation1334// completed, and end up introducing a "duplicate" (redundant) task.1335// In that case, the compiler thread should first check if a method1336// has already been compiled before trying to compile it.1337// NOTE: in the event that there are multiple compiler threads and1338// there is de-optimization/recompilation, things will get hairy,1339// and in that case it's best to protect both the testing (here) of1340// these bits, and their updating (here and elsewhere) under a1341// common lock.1342task = create_compile_task(queue,1343compile_id, method,1344osr_bci, comp_level,1345hot_method, hot_count, compile_reason,1346blocking);1347}13481349if (blocking) {1350wait_for_completion(task);1351}1352}13531354nmethod* CompileBroker::compile_method(const methodHandle& method, int osr_bci,1355int comp_level,1356const methodHandle& hot_method, int hot_count,1357CompileTask::CompileReason compile_reason,1358TRAPS) {1359// Do nothing if compilebroker is not initalized or compiles are submitted on level none1360if (!_initialized || comp_level == CompLevel_none) {1361return NULL;1362}13631364AbstractCompiler *comp = CompileBroker::compiler(comp_level);1365assert(comp != NULL, "Ensure we have a compiler");13661367DirectiveSet* directive = DirectivesStack::getMatchingDirective(method, comp);1368// CompileBroker::compile_method can trap and can have pending aysnc exception.1369nmethod* nm = CompileBroker::compile_method(method, osr_bci, comp_level, hot_method, hot_count, compile_reason, directive, THREAD);1370DirectivesStack::release(directive);1371return nm;1372}13731374nmethod* CompileBroker::compile_method(const methodHandle& method, int osr_bci,1375int comp_level,1376const methodHandle& hot_method, int hot_count,1377CompileTask::CompileReason compile_reason,1378DirectiveSet* directive,1379TRAPS) {13801381// make sure arguments make sense1382assert(method->method_holder()->is_instance_klass(), "not an instance method");1383assert(osr_bci == InvocationEntryBci || (0 <= osr_bci && osr_bci < method->code_size()), "bci out of range");1384assert(!method->is_abstract() && (osr_bci == InvocationEntryBci || !method->is_native()), "cannot compile abstract/native methods");1385assert(!method->method_holder()->is_not_initialized(), "method holder must be initialized");1386// return quickly if possible13871388// lock, make sure that the compilation1389// isn't prohibited in a straightforward way.1390AbstractCompiler* comp = CompileBroker::compiler(comp_level);1391if (comp == NULL || compilation_is_prohibited(method, osr_bci, comp_level, directive->ExcludeOption)) {1392return NULL;1393}13941395#if INCLUDE_JVMCI1396if (comp->is_jvmci() && !JVMCI::can_initialize_JVMCI()) {1397return NULL;1398}1399#endif14001401if (osr_bci == InvocationEntryBci) {1402// standard compilation1403CompiledMethod* method_code = method->code();1404if (method_code != NULL && method_code->is_nmethod()) {1405if (compilation_is_complete(method, osr_bci, comp_level)) {1406return (nmethod*) method_code;1407}1408}1409if (method->is_not_compilable(comp_level)) {1410return NULL;1411}1412} else {1413// osr compilation1414// We accept a higher level osr method1415nmethod* nm = method->lookup_osr_nmethod_for(osr_bci, comp_level, false);1416if (nm != NULL) return nm;1417if (method->is_not_osr_compilable(comp_level)) return NULL;1418}14191420assert(!HAS_PENDING_EXCEPTION, "No exception should be present");1421// some prerequisites that are compiler specific1422if (comp->is_c2()) {1423method->constants()->resolve_string_constants(CHECK_AND_CLEAR_NONASYNC_NULL);1424// Resolve all classes seen in the signature of the method1425// we are compiling.1426Method::load_signature_classes(method, CHECK_AND_CLEAR_NONASYNC_NULL);1427}14281429// If the method is native, do the lookup in the thread requesting1430// the compilation. Native lookups can load code, which is not1431// permitted during compilation.1432//1433// Note: A native method implies non-osr compilation which is1434// checked with an assertion at the entry of this method.1435if (method->is_native() && !method->is_method_handle_intrinsic()) {1436address adr = NativeLookup::lookup(method, THREAD);1437if (HAS_PENDING_EXCEPTION) {1438// In case of an exception looking up the method, we just forget1439// about it. The interpreter will kick-in and throw the exception.1440method->set_not_compilable("NativeLookup::lookup failed"); // implies is_not_osr_compilable()1441CLEAR_PENDING_EXCEPTION;1442return NULL;1443}1444assert(method->has_native_function(), "must have native code by now");1445}14461447// RedefineClasses() has replaced this method; just return1448if (method->is_old()) {1449return NULL;1450}14511452// JVMTI -- post_compile_event requires jmethod_id() that may require1453// a lock the compiling thread can not acquire. Prefetch it here.1454if (JvmtiExport::should_post_compiled_method_load()) {1455method->jmethod_id();1456}14571458// do the compilation1459if (method->is_native()) {1460if (!PreferInterpreterNativeStubs || method->is_method_handle_intrinsic()) {1461#if defined(X86) && !defined(ZERO)1462// The following native methods:1463//1464// java.lang.Float.intBitsToFloat1465// java.lang.Float.floatToRawIntBits1466// java.lang.Double.longBitsToDouble1467// java.lang.Double.doubleToRawLongBits1468//1469// are called through the interpreter even if interpreter native stubs1470// are not preferred (i.e., calling through adapter handlers is preferred).1471// The reason is that on x86_32 signaling NaNs (sNaNs) are not preserved1472// if the version of the methods from the native libraries is called.1473// As the interpreter and the C2-intrinsified version of the methods preserves1474// sNaNs, that would result in an inconsistent way of handling of sNaNs.1475if ((UseSSE >= 1 &&1476(method->intrinsic_id() == vmIntrinsics::_intBitsToFloat ||1477method->intrinsic_id() == vmIntrinsics::_floatToRawIntBits)) ||1478(UseSSE >= 2 &&1479(method->intrinsic_id() == vmIntrinsics::_longBitsToDouble ||1480method->intrinsic_id() == vmIntrinsics::_doubleToRawLongBits))) {1481return NULL;1482}1483#endif // X86 && !ZERO14841485// To properly handle the appendix argument for out-of-line calls we are using a small trampoline that1486// pops off the appendix argument and jumps to the target (see gen_special_dispatch in SharedRuntime).1487//1488// Since normal compiled-to-compiled calls are not able to handle such a thing we MUST generate an adapter1489// in this case. If we can't generate one and use it we can not execute the out-of-line method handle calls.1490AdapterHandlerLibrary::create_native_wrapper(method);1491} else {1492return NULL;1493}1494} else {1495// If the compiler is shut off due to code cache getting full1496// fail out now so blocking compiles dont hang the java thread1497if (!should_compile_new_jobs()) {1498return NULL;1499}1500bool is_blocking = !directive->BackgroundCompilationOption || ReplayCompiles;1501compile_method_base(method, osr_bci, comp_level, hot_method, hot_count, compile_reason, is_blocking, THREAD);1502}15031504// return requested nmethod1505// We accept a higher level osr method1506if (osr_bci == InvocationEntryBci) {1507CompiledMethod* code = method->code();1508if (code == NULL) {1509return (nmethod*) code;1510} else {1511return code->as_nmethod_or_null();1512}1513}1514return method->lookup_osr_nmethod_for(osr_bci, comp_level, false);1515}151615171518// ------------------------------------------------------------------1519// CompileBroker::compilation_is_complete1520//1521// See if compilation of this method is already complete.1522bool CompileBroker::compilation_is_complete(const methodHandle& method,1523int osr_bci,1524int comp_level) {1525bool is_osr = (osr_bci != standard_entry_bci);1526if (is_osr) {1527if (method->is_not_osr_compilable(comp_level)) {1528return true;1529} else {1530nmethod* result = method->lookup_osr_nmethod_for(osr_bci, comp_level, true);1531return (result != NULL);1532}1533} else {1534if (method->is_not_compilable(comp_level)) {1535return true;1536} else {1537CompiledMethod* result = method->code();1538if (result == NULL) return false;1539return comp_level == result->comp_level();1540}1541}1542}154315441545/**1546* See if this compilation is already requested.1547*1548* Implementation note: there is only a single "is in queue" bit1549* for each method. This means that the check below is overly1550* conservative in the sense that an osr compilation in the queue1551* will block a normal compilation from entering the queue (and vice1552* versa). This can be remedied by a full queue search to disambiguate1553* cases. If it is deemed profitable, this may be done.1554*/1555bool CompileBroker::compilation_is_in_queue(const methodHandle& method) {1556return method->queued_for_compilation();1557}15581559// ------------------------------------------------------------------1560// CompileBroker::compilation_is_prohibited1561//1562// See if this compilation is not allowed.1563bool CompileBroker::compilation_is_prohibited(const methodHandle& method, int osr_bci, int comp_level, bool excluded) {1564bool is_native = method->is_native();1565// Some compilers may not support the compilation of natives.1566AbstractCompiler *comp = compiler(comp_level);1567if (is_native && (!CICompileNatives || comp == NULL)) {1568method->set_not_compilable_quietly("native methods not supported", comp_level);1569return true;1570}15711572bool is_osr = (osr_bci != standard_entry_bci);1573// Some compilers may not support on stack replacement.1574if (is_osr && (!CICompileOSR || comp == NULL)) {1575method->set_not_osr_compilable("OSR not supported", comp_level);1576return true;1577}15781579// The method may be explicitly excluded by the user.1580double scale;1581if (excluded || (CompilerOracle::has_option_value(method, CompileCommand::CompileThresholdScaling, scale) && scale == 0)) {1582bool quietly = CompilerOracle::be_quiet();1583if (PrintCompilation && !quietly) {1584// This does not happen quietly...1585ResourceMark rm;1586tty->print("### Excluding %s:%s",1587method->is_native() ? "generation of native wrapper" : "compile",1588(method->is_static() ? " static" : ""));1589method->print_short_name(tty);1590tty->cr();1591}1592method->set_not_compilable("excluded by CompileCommand", comp_level, !quietly);1593}15941595return false;1596}15971598/**1599* Generate serialized IDs for compilation requests. If certain debugging flags are used1600* and the ID is not within the specified range, the method is not compiled and 0 is returned.1601* The function also allows to generate separate compilation IDs for OSR compilations.1602*/1603int CompileBroker::assign_compile_id(const methodHandle& method, int osr_bci) {1604#ifdef ASSERT1605bool is_osr = (osr_bci != standard_entry_bci);1606int id;1607if (method->is_native()) {1608assert(!is_osr, "can't be osr");1609// Adapters, native wrappers and method handle intrinsics1610// should be generated always.1611return Atomic::add(&_compilation_id, 1);1612} else if (CICountOSR && is_osr) {1613id = Atomic::add(&_osr_compilation_id, 1);1614if (CIStartOSR <= id && id < CIStopOSR) {1615return id;1616}1617} else {1618id = Atomic::add(&_compilation_id, 1);1619if (CIStart <= id && id < CIStop) {1620return id;1621}1622}16231624// Method was not in the appropriate compilation range.1625method->set_not_compilable_quietly("Not in requested compile id range");1626return 0;1627#else1628// CICountOSR is a develop flag and set to 'false' by default. In a product built,1629// only _compilation_id is incremented.1630return Atomic::add(&_compilation_id, 1);1631#endif1632}16331634// ------------------------------------------------------------------1635// CompileBroker::assign_compile_id_unlocked1636//1637// Public wrapper for assign_compile_id that acquires the needed locks1638uint CompileBroker::assign_compile_id_unlocked(Thread* thread, const methodHandle& method, int osr_bci) {1639MutexLocker locker(thread, MethodCompileQueue_lock);1640return assign_compile_id(method, osr_bci);1641}16421643// ------------------------------------------------------------------1644// CompileBroker::create_compile_task1645//1646// Create a CompileTask object representing the current request for1647// compilation. Add this task to the queue.1648CompileTask* CompileBroker::create_compile_task(CompileQueue* queue,1649int compile_id,1650const methodHandle& method,1651int osr_bci,1652int comp_level,1653const methodHandle& hot_method,1654int hot_count,1655CompileTask::CompileReason compile_reason,1656bool blocking) {1657CompileTask* new_task = CompileTask::allocate();1658new_task->initialize(compile_id, method, osr_bci, comp_level,1659hot_method, hot_count, compile_reason,1660blocking);1661queue->add(new_task);1662return new_task;1663}16641665#if INCLUDE_JVMCI1666// The number of milliseconds to wait before checking if1667// JVMCI compilation has made progress.1668static const long JVMCI_COMPILATION_PROGRESS_WAIT_TIMESLICE = 1000;16691670// The number of JVMCI compilation progress checks that must fail1671// before unblocking a thread waiting for a blocking compilation.1672static const int JVMCI_COMPILATION_PROGRESS_WAIT_ATTEMPTS = 10;16731674/**1675* Waits for a JVMCI compiler to complete a given task. This thread1676* waits until either the task completes or it sees no JVMCI compilation1677* progress for N consecutive milliseconds where N is1678* JVMCI_COMPILATION_PROGRESS_WAIT_TIMESLICE *1679* JVMCI_COMPILATION_PROGRESS_WAIT_ATTEMPTS.1680*1681* @return true if this thread needs to free/recycle the task1682*/1683bool CompileBroker::wait_for_jvmci_completion(JVMCICompiler* jvmci, CompileTask* task, JavaThread* thread) {1684assert(UseJVMCICompiler, "sanity");1685MonitorLocker ml(thread, task->lock());1686int progress_wait_attempts = 0;1687jint thread_jvmci_compilation_ticks = 0;1688jint global_jvmci_compilation_ticks = jvmci->global_compilation_ticks();1689while (!task->is_complete() && !is_compilation_disabled_forever() &&1690ml.wait(JVMCI_COMPILATION_PROGRESS_WAIT_TIMESLICE)) {1691JVMCICompileState* jvmci_compile_state = task->blocking_jvmci_compile_state();16921693bool progress;1694if (jvmci_compile_state != NULL) {1695jint ticks = jvmci_compile_state->compilation_ticks();1696progress = (ticks - thread_jvmci_compilation_ticks) != 0;1697JVMCI_event_1("waiting on compilation %d [ticks=%d]", task->compile_id(), ticks);1698thread_jvmci_compilation_ticks = ticks;1699} else {1700// Still waiting on JVMCI compiler queue. This thread may be holding a lock1701// that all JVMCI compiler threads are blocked on. We use the global JVMCI1702// compilation ticks to determine whether JVMCI compilation1703// is still making progress through the JVMCI compiler queue.1704jint ticks = jvmci->global_compilation_ticks();1705progress = (ticks - global_jvmci_compilation_ticks) != 0;1706JVMCI_event_1("waiting on compilation %d to be queued [ticks=%d]", task->compile_id(), ticks);1707global_jvmci_compilation_ticks = ticks;1708}17091710if (!progress) {1711if (++progress_wait_attempts == JVMCI_COMPILATION_PROGRESS_WAIT_ATTEMPTS) {1712if (PrintCompilation) {1713task->print(tty, "wait for blocking compilation timed out");1714}1715JVMCI_event_1("waiting on compilation %d timed out", task->compile_id());1716break;1717}1718} else {1719progress_wait_attempts = 0;1720}1721}1722task->clear_waiter();1723return task->is_complete();1724}1725#endif17261727/**1728* Wait for the compilation task to complete.1729*/1730void CompileBroker::wait_for_completion(CompileTask* task) {1731if (CIPrintCompileQueue) {1732ttyLocker ttyl;1733tty->print_cr("BLOCKING FOR COMPILE");1734}17351736assert(task->is_blocking(), "can only wait on blocking task");17371738JavaThread* thread = JavaThread::current();17391740methodHandle method(thread, task->method());1741bool free_task;1742#if INCLUDE_JVMCI1743AbstractCompiler* comp = compiler(task->comp_level());1744if (comp->is_jvmci() && !task->should_wait_for_compilation()) {1745// It may return before compilation is completed.1746free_task = wait_for_jvmci_completion((JVMCICompiler*) comp, task, thread);1747} else1748#endif1749{1750MonitorLocker ml(thread, task->lock());1751free_task = true;1752while (!task->is_complete() && !is_compilation_disabled_forever()) {1753ml.wait();1754}1755}17561757if (free_task) {1758if (is_compilation_disabled_forever()) {1759CompileTask::free(task);1760return;1761}17621763// It is harmless to check this status without the lock, because1764// completion is a stable property (until the task object is recycled).1765assert(task->is_complete(), "Compilation should have completed");1766assert(task->code_handle() == NULL, "must be reset");17671768// By convention, the waiter is responsible for recycling a1769// blocking CompileTask. Since there is only one waiter ever1770// waiting on a CompileTask, we know that no one else will1771// be using this CompileTask; we can free it.1772CompileTask::free(task);1773}1774}17751776/**1777* Initialize compiler thread(s) + compiler object(s). The postcondition1778* of this function is that the compiler runtimes are initialized and that1779* compiler threads can start compiling.1780*/1781bool CompileBroker::init_compiler_runtime() {1782CompilerThread* thread = CompilerThread::current();1783AbstractCompiler* comp = thread->compiler();1784// Final sanity check - the compiler object must exist1785guarantee(comp != NULL, "Compiler object must exist");17861787{1788// Must switch to native to allocate ci_env1789ThreadToNativeFromVM ttn(thread);1790ciEnv ci_env((CompileTask*)NULL);1791// Cache Jvmti state1792ci_env.cache_jvmti_state();1793// Cache DTrace flags1794ci_env.cache_dtrace_flags();17951796// Switch back to VM state to do compiler initialization1797ThreadInVMfromNative tv(thread);17981799// Perform per-thread and global initializations1800comp->initialize();1801}18021803if (comp->is_failed()) {1804disable_compilation_forever();1805// If compiler initialization failed, no compiler thread that is specific to a1806// particular compiler runtime will ever start to compile methods.1807shutdown_compiler_runtime(comp, thread);1808return false;1809}18101811// C1 specific check1812if (comp->is_c1() && (thread->get_buffer_blob() == NULL)) {1813warning("Initialization of %s thread failed (no space to run compilers)", thread->name());1814return false;1815}18161817return true;1818}18191820/**1821* If C1 and/or C2 initialization failed, we shut down all compilation.1822* We do this to keep things simple. This can be changed if it ever turns1823* out to be a problem.1824*/1825void CompileBroker::shutdown_compiler_runtime(AbstractCompiler* comp, CompilerThread* thread) {1826// Free buffer blob, if allocated1827if (thread->get_buffer_blob() != NULL) {1828MutexLocker mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);1829CodeCache::free(thread->get_buffer_blob());1830}18311832if (comp->should_perform_shutdown()) {1833// There are two reasons for shutting down the compiler1834// 1) compiler runtime initialization failed1835// 2) The code cache is full and the following flag is set: -XX:-UseCodeCacheFlushing1836warning("%s initialization failed. Shutting down all compilers", comp->name());18371838// Only one thread per compiler runtime object enters here1839// Set state to shut down1840comp->set_shut_down();18411842// Delete all queued compilation tasks to make compiler threads exit faster.1843if (_c1_compile_queue != NULL) {1844_c1_compile_queue->free_all();1845}18461847if (_c2_compile_queue != NULL) {1848_c2_compile_queue->free_all();1849}18501851// Set flags so that we continue execution with using interpreter only.1852UseCompiler = false;1853UseInterpreter = true;18541855// We could delete compiler runtimes also. However, there are references to1856// the compiler runtime(s) (e.g., nmethod::is_compiled_by_c1()) which then1857// fail. This can be done later if necessary.1858}1859}18601861/**1862* Helper function to create new or reuse old CompileLog.1863*/1864CompileLog* CompileBroker::get_log(CompilerThread* ct) {1865if (!LogCompilation) return NULL;18661867AbstractCompiler *compiler = ct->compiler();1868bool c1 = compiler->is_c1();1869jobject* compiler_objects = c1 ? _compiler1_objects : _compiler2_objects;1870assert(compiler_objects != NULL, "must be initialized at this point");1871CompileLog** logs = c1 ? _compiler1_logs : _compiler2_logs;1872assert(logs != NULL, "must be initialized at this point");1873int count = c1 ? _c1_count : _c2_count;18741875// Find Compiler number by its threadObj.1876oop compiler_obj = ct->threadObj();1877int compiler_number = 0;1878bool found = false;1879for (; compiler_number < count; compiler_number++) {1880if (JNIHandles::resolve_non_null(compiler_objects[compiler_number]) == compiler_obj) {1881found = true;1882break;1883}1884}1885assert(found, "Compiler must exist at this point");18861887// Determine pointer for this thread's log.1888CompileLog** log_ptr = &logs[compiler_number];18891890// Return old one if it exists.1891CompileLog* log = *log_ptr;1892if (log != NULL) {1893ct->init_log(log);1894return log;1895}18961897// Create a new one and remember it.1898init_compiler_thread_log();1899log = ct->log();1900*log_ptr = log;1901return log;1902}19031904// ------------------------------------------------------------------1905// CompileBroker::compiler_thread_loop1906//1907// The main loop run by a CompilerThread.1908void CompileBroker::compiler_thread_loop() {1909CompilerThread* thread = CompilerThread::current();1910CompileQueue* queue = thread->queue();1911// For the thread that initializes the ciObjectFactory1912// this resource mark holds all the shared objects1913ResourceMark rm;19141915// First thread to get here will initialize the compiler interface19161917{1918ASSERT_IN_VM;1919MutexLocker only_one (thread, CompileThread_lock);1920if (!ciObjectFactory::is_initialized()) {1921ciObjectFactory::initialize();1922}1923}19241925// Open a log.1926CompileLog* log = get_log(thread);1927if (log != NULL) {1928log->begin_elem("start_compile_thread name='%s' thread='" UINTX_FORMAT "' process='%d'",1929thread->name(),1930os::current_thread_id(),1931os::current_process_id());1932log->stamp();1933log->end_elem();1934}19351936// If compiler thread/runtime initialization fails, exit the compiler thread1937if (!init_compiler_runtime()) {1938return;1939}19401941thread->start_idle_timer();19421943// Poll for new compilation tasks as long as the JVM runs. Compilation1944// should only be disabled if something went wrong while initializing the1945// compiler runtimes. This, in turn, should not happen. The only known case1946// when compiler runtime initialization fails is if there is not enough free1947// space in the code cache to generate the necessary stubs, etc.1948while (!is_compilation_disabled_forever()) {1949// We need this HandleMark to avoid leaking VM handles.1950HandleMark hm(thread);19511952CompileTask* task = queue->get();1953if (task == NULL) {1954if (UseDynamicNumberOfCompilerThreads) {1955// Access compiler_count under lock to enforce consistency.1956MutexLocker only_one(CompileThread_lock);1957if (can_remove(thread, true)) {1958if (TraceCompilerThreads) {1959tty->print_cr("Removing compiler thread %s after " JLONG_FORMAT " ms idle time",1960thread->name(), thread->idle_time_millis());1961}1962// Free buffer blob, if allocated1963if (thread->get_buffer_blob() != NULL) {1964MutexLocker mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);1965CodeCache::free(thread->get_buffer_blob());1966}1967return; // Stop this thread.1968}1969}1970} else {1971// Assign the task to the current thread. Mark this compilation1972// thread as active for the profiler.1973// CompileTaskWrapper also keeps the Method* from being deallocated if redefinition1974// occurs after fetching the compile task off the queue.1975CompileTaskWrapper ctw(task);1976nmethodLocker result_handle; // (handle for the nmethod produced by this task)1977task->set_code_handle(&result_handle);1978methodHandle method(thread, task->method());19791980// Never compile a method if breakpoints are present in it1981if (method()->number_of_breakpoints() == 0) {1982// Compile the method.1983if ((UseCompiler || AlwaysCompileLoopMethods) && CompileBroker::should_compile_new_jobs()) {1984invoke_compiler_on_method(task);1985thread->start_idle_timer();1986} else {1987// After compilation is disabled, remove remaining methods from queue1988method->clear_queued_for_compilation();1989task->set_failure_reason("compilation is disabled");1990}1991}19921993if (UseDynamicNumberOfCompilerThreads) {1994possibly_add_compiler_threads(thread);1995assert(!thread->has_pending_exception(), "should have been handled");1996}1997}1998}19992000// Shut down compiler runtime2001shutdown_compiler_runtime(thread->compiler(), thread);2002}20032004// ------------------------------------------------------------------2005// CompileBroker::init_compiler_thread_log2006//2007// Set up state required by +LogCompilation.2008void CompileBroker::init_compiler_thread_log() {2009CompilerThread* thread = CompilerThread::current();2010char file_name[4*K];2011FILE* fp = NULL;2012intx thread_id = os::current_thread_id();2013for (int try_temp_dir = 1; try_temp_dir >= 0; try_temp_dir--) {2014const char* dir = (try_temp_dir ? os::get_temp_directory() : NULL);2015if (dir == NULL) {2016jio_snprintf(file_name, sizeof(file_name), "hs_c" UINTX_FORMAT "_pid%u.log",2017thread_id, os::current_process_id());2018} else {2019jio_snprintf(file_name, sizeof(file_name),2020"%s%shs_c" UINTX_FORMAT "_pid%u.log", dir,2021os::file_separator(), thread_id, os::current_process_id());2022}20232024fp = fopen(file_name, "wt");2025if (fp != NULL) {2026if (LogCompilation && Verbose) {2027tty->print_cr("Opening compilation log %s", file_name);2028}2029CompileLog* log = new(ResourceObj::C_HEAP, mtCompiler) CompileLog(file_name, fp, thread_id);2030if (log == NULL) {2031fclose(fp);2032return;2033}2034thread->init_log(log);20352036if (xtty != NULL) {2037ttyLocker ttyl;2038// Record any per thread log files2039xtty->elem("thread_logfile thread='" INTX_FORMAT "' filename='%s'", thread_id, file_name);2040}2041return;2042}2043}2044warning("Cannot open log file: %s", file_name);2045}20462047void CompileBroker::log_metaspace_failure() {2048const char* message = "some methods may not be compiled because metaspace "2049"is out of memory";2050if (_compilation_log != NULL) {2051_compilation_log->log_metaspace_failure(message);2052}2053if (PrintCompilation) {2054tty->print_cr("COMPILE PROFILING SKIPPED: %s", message);2055}2056}205720582059// ------------------------------------------------------------------2060// CompileBroker::set_should_block2061//2062// Set _should_block.2063// Call this from the VM, with Threads_lock held and a safepoint requested.2064void CompileBroker::set_should_block() {2065assert(Threads_lock->owner() == Thread::current(), "must have threads lock");2066assert(SafepointSynchronize::is_at_safepoint(), "must be at a safepoint already");2067#ifndef PRODUCT2068if (PrintCompilation && (Verbose || WizardMode))2069tty->print_cr("notifying compiler thread pool to block");2070#endif2071_should_block = true;2072}20732074// ------------------------------------------------------------------2075// CompileBroker::maybe_block2076//2077// Call this from the compiler at convenient points, to poll for _should_block.2078void CompileBroker::maybe_block() {2079if (_should_block) {2080#ifndef PRODUCT2081if (PrintCompilation && (Verbose || WizardMode))2082tty->print_cr("compiler thread " INTPTR_FORMAT " poll detects block request", p2i(Thread::current()));2083#endif2084ThreadInVMfromNative tivfn(JavaThread::current());2085}2086}20872088// wrapper for CodeCache::print_summary()2089static void codecache_print(bool detailed)2090{2091ResourceMark rm;2092stringStream s;2093// Dump code cache into a buffer before locking the tty,2094{2095MutexLocker mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);2096CodeCache::print_summary(&s, detailed);2097}2098ttyLocker ttyl;2099tty->print("%s", s.as_string());2100}21012102// wrapper for CodeCache::print_summary() using outputStream2103static void codecache_print(outputStream* out, bool detailed) {2104ResourceMark rm;2105stringStream s;21062107// Dump code cache into a buffer2108{2109MutexLocker mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);2110CodeCache::print_summary(&s, detailed);2111}21122113char* remaining_log = s.as_string();2114while (*remaining_log != '\0') {2115char* eol = strchr(remaining_log, '\n');2116if (eol == NULL) {2117out->print_cr("%s", remaining_log);2118remaining_log = remaining_log + strlen(remaining_log);2119} else {2120*eol = '\0';2121out->print_cr("%s", remaining_log);2122remaining_log = eol + 1;2123}2124}2125}21262127void CompileBroker::post_compile(CompilerThread* thread, CompileTask* task, bool success, ciEnv* ci_env,2128int compilable, const char* failure_reason) {2129if (success) {2130task->mark_success();2131if (ci_env != NULL) {2132task->set_num_inlined_bytecodes(ci_env->num_inlined_bytecodes());2133}2134if (_compilation_log != NULL) {2135nmethod* code = task->code();2136if (code != NULL) {2137_compilation_log->log_nmethod(thread, code);2138}2139}2140} else if (AbortVMOnCompilationFailure) {2141if (compilable == ciEnv::MethodCompilable_not_at_tier) {2142fatal("Not compilable at tier %d: %s", task->comp_level(), failure_reason);2143}2144if (compilable == ciEnv::MethodCompilable_never) {2145fatal("Never compilable: %s", failure_reason);2146}2147}2148// simulate crash during compilation2149assert(task->compile_id() != CICrashAt, "just as planned");2150}21512152static void post_compilation_event(EventCompilation& event, CompileTask* task) {2153assert(task != NULL, "invariant");2154CompilerEvent::CompilationEvent::post(event,2155task->compile_id(),2156task->compiler()->type(),2157task->method(),2158task->comp_level(),2159task->is_success(),2160task->osr_bci() != CompileBroker::standard_entry_bci,2161(task->code() == NULL) ? 0 : task->code()->total_size(),2162task->num_inlined_bytecodes());2163}21642165int DirectivesStack::_depth = 0;2166CompilerDirectives* DirectivesStack::_top = NULL;2167CompilerDirectives* DirectivesStack::_bottom = NULL;21682169// ------------------------------------------------------------------2170// CompileBroker::invoke_compiler_on_method2171//2172// Compile a method.2173//2174void CompileBroker::invoke_compiler_on_method(CompileTask* task) {2175task->print_ul();2176if (PrintCompilation) {2177ResourceMark rm;2178task->print_tty();2179}2180elapsedTimer time;21812182CompilerThread* thread = CompilerThread::current();2183ResourceMark rm(thread);21842185if (LogEvents) {2186_compilation_log->log_compile(thread, task);2187}21882189// Common flags.2190uint compile_id = task->compile_id();2191int osr_bci = task->osr_bci();2192bool is_osr = (osr_bci != standard_entry_bci);2193bool should_log = (thread->log() != NULL);2194bool should_break = false;2195const int task_level = task->comp_level();2196AbstractCompiler* comp = task->compiler();21972198DirectiveSet* directive;2199{2200// create the handle inside it's own block so it can't2201// accidentally be referenced once the thread transitions to2202// native. The NoHandleMark before the transition should catch2203// any cases where this occurs in the future.2204methodHandle method(thread, task->method());2205assert(!method->is_native(), "no longer compile natives");22062207// Look up matching directives2208directive = DirectivesStack::getMatchingDirective(method, comp);22092210// Update compile information when using perfdata.2211if (UsePerfData) {2212update_compile_perf_data(thread, method, is_osr);2213}22142215DTRACE_METHOD_COMPILE_BEGIN_PROBE(method, compiler_name(task_level));2216}22172218should_break = directive->BreakAtCompileOption || task->check_break_at_flags();2219if (should_log && !directive->LogOption) {2220should_log = false;2221}22222223// Allocate a new set of JNI handles.2224push_jni_handle_block();2225Method* target_handle = task->method();2226int compilable = ciEnv::MethodCompilable;2227const char* failure_reason = NULL;2228bool failure_reason_on_C_heap = false;2229const char* retry_message = NULL;22302231#if INCLUDE_JVMCI2232if (UseJVMCICompiler && comp != NULL && comp->is_jvmci()) {2233JVMCICompiler* jvmci = (JVMCICompiler*) comp;22342235TraceTime t1("compilation", &time);2236EventCompilation event;2237JVMCICompileState compile_state(task, jvmci);2238JVMCIRuntime *runtime = NULL;22392240if (JVMCI::in_shutdown()) {2241failure_reason = "in JVMCI shutdown";2242retry_message = "not retryable";2243compilable = ciEnv::MethodCompilable_never;2244} else if (compile_state.target_method_is_old()) {2245// Skip redefined methods2246failure_reason = "redefined method";2247retry_message = "not retryable";2248compilable = ciEnv::MethodCompilable_never;2249} else {2250JVMCIEnv env(thread, &compile_state, __FILE__, __LINE__);2251methodHandle method(thread, target_handle);2252runtime = env.runtime();2253runtime->compile_method(&env, jvmci, method, osr_bci);22542255failure_reason = compile_state.failure_reason();2256failure_reason_on_C_heap = compile_state.failure_reason_on_C_heap();2257if (!compile_state.retryable()) {2258retry_message = "not retryable";2259compilable = ciEnv::MethodCompilable_not_at_tier;2260}2261if (task->code() == NULL) {2262assert(failure_reason != NULL, "must specify failure_reason");2263}2264}2265post_compile(thread, task, task->code() != NULL, NULL, compilable, failure_reason);2266if (event.should_commit()) {2267post_compilation_event(event, task);2268}22692270} else2271#endif // INCLUDE_JVMCI2272{2273NoHandleMark nhm;2274ThreadToNativeFromVM ttn(thread);22752276ciEnv ci_env(task);2277if (should_break) {2278ci_env.set_break_at_compile(true);2279}2280if (should_log) {2281ci_env.set_log(thread->log());2282}2283assert(thread->env() == &ci_env, "set by ci_env");2284// The thread-env() field is cleared in ~CompileTaskWrapper.22852286// Cache Jvmti state2287bool method_is_old = ci_env.cache_jvmti_state();22882289// Skip redefined methods2290if (method_is_old) {2291ci_env.record_method_not_compilable("redefined method", true);2292}22932294// Cache DTrace flags2295ci_env.cache_dtrace_flags();22962297ciMethod* target = ci_env.get_method_from_handle(target_handle);22982299TraceTime t1("compilation", &time);2300EventCompilation event;23012302if (comp == NULL) {2303ci_env.record_method_not_compilable("no compiler");2304} else if (!ci_env.failing()) {2305if (WhiteBoxAPI && WhiteBox::compilation_locked) {2306MonitorLocker locker(Compilation_lock, Mutex::_no_safepoint_check_flag);2307while (WhiteBox::compilation_locked) {2308locker.wait();2309}2310}2311comp->compile_method(&ci_env, target, osr_bci, true, directive);23122313/* Repeat compilation without installing code for profiling purposes */2314int repeat_compilation_count = directive->RepeatCompilationOption;2315while (repeat_compilation_count > 0) {2316task->print_ul("NO CODE INSTALLED");2317comp->compile_method(&ci_env, target, osr_bci, false , directive);2318repeat_compilation_count--;2319}2320}23212322if (!ci_env.failing() && task->code() == NULL) {2323//assert(false, "compiler should always document failure");2324// The compiler elected, without comment, not to register a result.2325// Do not attempt further compilations of this method.2326ci_env.record_method_not_compilable("compile failed");2327}23282329// Copy this bit to the enclosing block:2330compilable = ci_env.compilable();23312332if (ci_env.failing()) {2333failure_reason = ci_env.failure_reason();2334retry_message = ci_env.retry_message();2335ci_env.report_failure(failure_reason);2336}23372338post_compile(thread, task, !ci_env.failing(), &ci_env, compilable, failure_reason);2339if (event.should_commit()) {2340post_compilation_event(event, task);2341}2342}2343// Remove the JNI handle block after the ciEnv destructor has run in2344// the previous block.2345pop_jni_handle_block();23462347if (failure_reason != NULL) {2348task->set_failure_reason(failure_reason, failure_reason_on_C_heap);2349if (_compilation_log != NULL) {2350_compilation_log->log_failure(thread, task, failure_reason, retry_message);2351}2352if (PrintCompilation) {2353FormatBufferResource msg = retry_message != NULL ?2354FormatBufferResource("COMPILE SKIPPED: %s (%s)", failure_reason, retry_message) :2355FormatBufferResource("COMPILE SKIPPED: %s", failure_reason);2356task->print(tty, msg);2357}2358}23592360methodHandle method(thread, task->method());23612362DTRACE_METHOD_COMPILE_END_PROBE(method, compiler_name(task_level), task->is_success());23632364collect_statistics(thread, time, task);23652366nmethod* nm = task->code();2367if (nm != NULL) {2368nm->maybe_print_nmethod(directive);2369}2370DirectivesStack::release(directive);23712372if (PrintCompilation && PrintCompilation2) {2373tty->print("%7d ", (int) tty->time_stamp().milliseconds()); // print timestamp2374tty->print("%4d ", compile_id); // print compilation number2375tty->print("%s ", (is_osr ? "%" : " "));2376if (task->code() != NULL) {2377tty->print("size: %d(%d) ", task->code()->total_size(), task->code()->insts_size());2378}2379tty->print_cr("time: %d inlined: %d bytes", (int)time.milliseconds(), task->num_inlined_bytecodes());2380}23812382Log(compilation, codecache) log;2383if (log.is_debug()) {2384LogStream ls(log.debug());2385codecache_print(&ls, /* detailed= */ false);2386}2387if (PrintCodeCacheOnCompilation) {2388codecache_print(/* detailed= */ false);2389}2390// Disable compilation, if required.2391switch (compilable) {2392case ciEnv::MethodCompilable_never:2393if (is_osr)2394method->set_not_osr_compilable_quietly("MethodCompilable_never");2395else2396method->set_not_compilable_quietly("MethodCompilable_never");2397break;2398case ciEnv::MethodCompilable_not_at_tier:2399if (is_osr)2400method->set_not_osr_compilable_quietly("MethodCompilable_not_at_tier", task_level);2401else2402method->set_not_compilable_quietly("MethodCompilable_not_at_tier", task_level);2403break;2404}24052406// Note that the queued_for_compilation bits are cleared without2407// protection of a mutex. [They were set by the requester thread,2408// when adding the task to the compile queue -- at which time the2409// compile queue lock was held. Subsequently, we acquired the compile2410// queue lock to get this task off the compile queue; thus (to belabour2411// the point somewhat) our clearing of the bits must be occurring2412// only after the setting of the bits. See also 14012000 above.2413method->clear_queued_for_compilation();2414}24152416/**2417* The CodeCache is full. Print warning and disable compilation.2418* Schedule code cache cleaning so compilation can continue later.2419* This function needs to be called only from CodeCache::allocate(),2420* since we currently handle a full code cache uniformly.2421*/2422void CompileBroker::handle_full_code_cache(int code_blob_type) {2423UseInterpreter = true;2424if (UseCompiler || AlwaysCompileLoopMethods ) {2425if (xtty != NULL) {2426ResourceMark rm;2427stringStream s;2428// Dump code cache state into a buffer before locking the tty,2429// because log_state() will use locks causing lock conflicts.2430CodeCache::log_state(&s);2431// Lock to prevent tearing2432ttyLocker ttyl;2433xtty->begin_elem("code_cache_full");2434xtty->print("%s", s.as_string());2435xtty->stamp();2436xtty->end_elem();2437}24382439#ifndef PRODUCT2440if (ExitOnFullCodeCache) {2441codecache_print(/* detailed= */ true);2442before_exit(JavaThread::current());2443exit_globals(); // will delete tty2444vm_direct_exit(1);2445}2446#endif2447if (UseCodeCacheFlushing) {2448// Since code cache is full, immediately stop new compiles2449if (CompileBroker::set_should_compile_new_jobs(CompileBroker::stop_compilation)) {2450NMethodSweeper::log_sweep("disable_compiler");2451}2452} else {2453disable_compilation_forever();2454}24552456CodeCache::report_codemem_full(code_blob_type, should_print_compiler_warning());2457}2458}24592460// ------------------------------------------------------------------2461// CompileBroker::update_compile_perf_data2462//2463// Record this compilation for debugging purposes.2464void CompileBroker::update_compile_perf_data(CompilerThread* thread, const methodHandle& method, bool is_osr) {2465ResourceMark rm;2466char* method_name = method->name()->as_C_string();2467char current_method[CompilerCounters::cmname_buffer_length];2468size_t maxLen = CompilerCounters::cmname_buffer_length;24692470const char* class_name = method->method_holder()->name()->as_C_string();24712472size_t s1len = strlen(class_name);2473size_t s2len = strlen(method_name);24742475// check if we need to truncate the string2476if (s1len + s2len + 2 > maxLen) {24772478// the strategy is to lop off the leading characters of the2479// class name and the trailing characters of the method name.24802481if (s2len + 2 > maxLen) {2482// lop of the entire class name string, let snprintf handle2483// truncation of the method name.2484class_name += s1len; // null string2485}2486else {2487// lop off the extra characters from the front of the class name2488class_name += ((s1len + s2len + 2) - maxLen);2489}2490}24912492jio_snprintf(current_method, maxLen, "%s %s", class_name, method_name);24932494int last_compile_type = normal_compile;2495if (CICountOSR && is_osr) {2496last_compile_type = osr_compile;2497}24982499CompilerCounters* counters = thread->counters();2500counters->set_current_method(current_method);2501counters->set_compile_type((jlong) last_compile_type);2502}25032504// ------------------------------------------------------------------2505// CompileBroker::push_jni_handle_block2506//2507// Push on a new block of JNI handles.2508void CompileBroker::push_jni_handle_block() {2509JavaThread* thread = JavaThread::current();25102511// Allocate a new block for JNI handles.2512// Inlined code from jni_PushLocalFrame()2513JNIHandleBlock* java_handles = thread->active_handles();2514JNIHandleBlock* compile_handles = JNIHandleBlock::allocate_block(thread);2515assert(compile_handles != NULL && java_handles != NULL, "should not be NULL");2516compile_handles->set_pop_frame_link(java_handles); // make sure java handles get gc'd.2517thread->set_active_handles(compile_handles);2518}251925202521// ------------------------------------------------------------------2522// CompileBroker::pop_jni_handle_block2523//2524// Pop off the current block of JNI handles.2525void CompileBroker::pop_jni_handle_block() {2526JavaThread* thread = JavaThread::current();25272528// Release our JNI handle block2529JNIHandleBlock* compile_handles = thread->active_handles();2530JNIHandleBlock* java_handles = compile_handles->pop_frame_link();2531thread->set_active_handles(java_handles);2532compile_handles->set_pop_frame_link(NULL);2533JNIHandleBlock::release_block(compile_handles, thread); // may block2534}25352536// ------------------------------------------------------------------2537// CompileBroker::collect_statistics2538//2539// Collect statistics about the compilation.25402541void CompileBroker::collect_statistics(CompilerThread* thread, elapsedTimer time, CompileTask* task) {2542bool success = task->is_success();2543methodHandle method (thread, task->method());2544uint compile_id = task->compile_id();2545bool is_osr = (task->osr_bci() != standard_entry_bci);2546const int comp_level = task->comp_level();2547nmethod* code = task->code();2548CompilerCounters* counters = thread->counters();25492550assert(code == NULL || code->is_locked_by_vm(), "will survive the MutexLocker");2551MutexLocker locker(CompileStatistics_lock);25522553// _perf variables are production performance counters which are2554// updated regardless of the setting of the CITime and CITimeEach flags2555//25562557// account all time, including bailouts and failures in this counter;2558// C1 and C2 counters are counting both successful and unsuccessful compiles2559_t_total_compilation.add(time);25602561if (!success) {2562_total_bailout_count++;2563if (UsePerfData) {2564_perf_last_failed_method->set_value(counters->current_method());2565_perf_last_failed_type->set_value(counters->compile_type());2566_perf_total_bailout_count->inc();2567}2568_t_bailedout_compilation.add(time);2569} else if (code == NULL) {2570if (UsePerfData) {2571_perf_last_invalidated_method->set_value(counters->current_method());2572_perf_last_invalidated_type->set_value(counters->compile_type());2573_perf_total_invalidated_count->inc();2574}2575_total_invalidated_count++;2576_t_invalidated_compilation.add(time);2577} else {2578// Compilation succeeded25792580// update compilation ticks - used by the implementation of2581// java.lang.management.CompilationMXBean2582_perf_total_compilation->inc(time.ticks());2583_peak_compilation_time = time.milliseconds() > _peak_compilation_time ? time.milliseconds() : _peak_compilation_time;25842585if (CITime) {2586int bytes_compiled = method->code_size() + task->num_inlined_bytecodes();2587if (is_osr) {2588_t_osr_compilation.add(time);2589_sum_osr_bytes_compiled += bytes_compiled;2590} else {2591_t_standard_compilation.add(time);2592_sum_standard_bytes_compiled += method->code_size() + task->num_inlined_bytecodes();2593}25942595// Collect statistic per compilation level2596if (comp_level > CompLevel_none && comp_level <= CompLevel_full_optimization) {2597CompilerStatistics* stats = &_stats_per_level[comp_level-1];2598if (is_osr) {2599stats->_osr.update(time, bytes_compiled);2600} else {2601stats->_standard.update(time, bytes_compiled);2602}2603stats->_nmethods_size += code->total_size();2604stats->_nmethods_code_size += code->insts_size();2605} else {2606assert(false, "CompilerStatistics object does not exist for compilation level %d", comp_level);2607}26082609// Collect statistic per compiler2610AbstractCompiler* comp = compiler(comp_level);2611if (comp) {2612CompilerStatistics* stats = comp->stats();2613if (is_osr) {2614stats->_osr.update(time, bytes_compiled);2615} else {2616stats->_standard.update(time, bytes_compiled);2617}2618stats->_nmethods_size += code->total_size();2619stats->_nmethods_code_size += code->insts_size();2620} else { // if (!comp)2621assert(false, "Compiler object must exist");2622}2623}26242625if (UsePerfData) {2626// save the name of the last method compiled2627_perf_last_method->set_value(counters->current_method());2628_perf_last_compile_type->set_value(counters->compile_type());2629_perf_last_compile_size->set_value(method->code_size() +2630task->num_inlined_bytecodes());2631if (is_osr) {2632_perf_osr_compilation->inc(time.ticks());2633_perf_sum_osr_bytes_compiled->inc(method->code_size() + task->num_inlined_bytecodes());2634} else {2635_perf_standard_compilation->inc(time.ticks());2636_perf_sum_standard_bytes_compiled->inc(method->code_size() + task->num_inlined_bytecodes());2637}2638}26392640if (CITimeEach) {2641double compile_time = time.seconds();2642double bytes_per_sec = compile_time == 0.0 ? 0.0 : (double)(method->code_size() + task->num_inlined_bytecodes()) / compile_time;2643tty->print_cr("%3d seconds: %6.3f bytes/sec : %f (bytes %d + %d inlined)",2644compile_id, compile_time, bytes_per_sec, method->code_size(), task->num_inlined_bytecodes());2645}26462647// Collect counts of successful compilations2648_sum_nmethod_size += code->total_size();2649_sum_nmethod_code_size += code->insts_size();2650_total_compile_count++;26512652if (UsePerfData) {2653_perf_sum_nmethod_size->inc( code->total_size());2654_perf_sum_nmethod_code_size->inc(code->insts_size());2655_perf_total_compile_count->inc();2656}26572658if (is_osr) {2659if (UsePerfData) _perf_total_osr_compile_count->inc();2660_total_osr_compile_count++;2661} else {2662if (UsePerfData) _perf_total_standard_compile_count->inc();2663_total_standard_compile_count++;2664}2665}2666// set the current method for the thread to null2667if (UsePerfData) counters->set_current_method("");2668}26692670const char* CompileBroker::compiler_name(int comp_level) {2671AbstractCompiler *comp = CompileBroker::compiler(comp_level);2672if (comp == NULL) {2673return "no compiler";2674} else {2675return (comp->name());2676}2677}26782679jlong CompileBroker::total_compilation_ticks() {2680return _perf_total_compilation != NULL ? _perf_total_compilation->get_value() : 0;2681}26822683void CompileBroker::print_times(const char* name, CompilerStatistics* stats) {2684tty->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}",2685name, stats->bytes_per_second(),2686stats->_standard._time.seconds(), stats->_standard._bytes, stats->_standard._count,2687stats->_osr._time.seconds(), stats->_osr._bytes, stats->_osr._count,2688stats->_nmethods_size, stats->_nmethods_code_size);2689}26902691void CompileBroker::print_times(bool per_compiler, bool aggregate) {2692if (per_compiler) {2693if (aggregate) {2694tty->cr();2695tty->print_cr("Individual compiler times (for compiled methods only)");2696tty->print_cr("------------------------------------------------");2697tty->cr();2698}2699for (unsigned int i = 0; i < sizeof(_compilers) / sizeof(AbstractCompiler*); i++) {2700AbstractCompiler* comp = _compilers[i];2701if (comp != NULL) {2702print_times(comp->name(), comp->stats());2703}2704}2705if (aggregate) {2706tty->cr();2707tty->print_cr("Individual compilation Tier times (for compiled methods only)");2708tty->print_cr("------------------------------------------------");2709tty->cr();2710}2711char tier_name[256];2712for (int tier = CompLevel_simple; tier <= CompilationPolicy::highest_compile_level(); tier++) {2713CompilerStatistics* stats = &_stats_per_level[tier-1];2714sprintf(tier_name, "Tier%d", tier);2715print_times(tier_name, stats);2716}2717}27182719if (!aggregate) {2720return;2721}27222723elapsedTimer standard_compilation = CompileBroker::_t_standard_compilation;2724elapsedTimer osr_compilation = CompileBroker::_t_osr_compilation;2725elapsedTimer total_compilation = CompileBroker::_t_total_compilation;27262727int standard_bytes_compiled = CompileBroker::_sum_standard_bytes_compiled;2728int osr_bytes_compiled = CompileBroker::_sum_osr_bytes_compiled;27292730int standard_compile_count = CompileBroker::_total_standard_compile_count;2731int osr_compile_count = CompileBroker::_total_osr_compile_count;2732int total_compile_count = CompileBroker::_total_compile_count;2733int total_bailout_count = CompileBroker::_total_bailout_count;2734int total_invalidated_count = CompileBroker::_total_invalidated_count;27352736int nmethods_size = CompileBroker::_sum_nmethod_code_size;2737int nmethods_code_size = CompileBroker::_sum_nmethod_size;27382739tty->cr();2740tty->print_cr("Accumulated compiler times");2741tty->print_cr("----------------------------------------------------------");2742//00000000001111111111222222222233333333334444444444555555555566666666662743//01234567890123456789012345678901234567890123456789012345678901234567892744tty->print_cr(" Total compilation time : %7.3f s", total_compilation.seconds());2745tty->print_cr(" Standard compilation : %7.3f s, Average : %2.3f s",2746standard_compilation.seconds(),2747standard_compile_count == 0 ? 0.0 : standard_compilation.seconds() / standard_compile_count);2748tty->print_cr(" Bailed out compilation : %7.3f s, Average : %2.3f s",2749CompileBroker::_t_bailedout_compilation.seconds(),2750total_bailout_count == 0 ? 0.0 : CompileBroker::_t_bailedout_compilation.seconds() / total_bailout_count);2751tty->print_cr(" On stack replacement : %7.3f s, Average : %2.3f s",2752osr_compilation.seconds(),2753osr_compile_count == 0 ? 0.0 : osr_compilation.seconds() / osr_compile_count);2754tty->print_cr(" Invalidated : %7.3f s, Average : %2.3f s",2755CompileBroker::_t_invalidated_compilation.seconds(),2756total_invalidated_count == 0 ? 0.0 : CompileBroker::_t_invalidated_compilation.seconds() / total_invalidated_count);27572758AbstractCompiler *comp = compiler(CompLevel_simple);2759if (comp != NULL) {2760tty->cr();2761comp->print_timers();2762}2763comp = compiler(CompLevel_full_optimization);2764if (comp != NULL) {2765tty->cr();2766comp->print_timers();2767}2768#if INCLUDE_JVMCI2769if (EnableJVMCI) {2770tty->cr();2771JVMCICompiler::print_hosted_timers();2772}2773#endif27742775tty->cr();2776tty->print_cr(" Total compiled methods : %8d methods", total_compile_count);2777tty->print_cr(" Standard compilation : %8d methods", standard_compile_count);2778tty->print_cr(" On stack replacement : %8d methods", osr_compile_count);2779int tcb = osr_bytes_compiled + standard_bytes_compiled;2780tty->print_cr(" Total compiled bytecodes : %8d bytes", tcb);2781tty->print_cr(" Standard compilation : %8d bytes", standard_bytes_compiled);2782tty->print_cr(" On stack replacement : %8d bytes", osr_bytes_compiled);2783double tcs = total_compilation.seconds();2784int bps = tcs == 0.0 ? 0 : (int)(tcb / tcs);2785tty->print_cr(" Average compilation speed : %8d bytes/s", bps);2786tty->cr();2787tty->print_cr(" nmethod code size : %8d bytes", nmethods_code_size);2788tty->print_cr(" nmethod total size : %8d bytes", nmethods_size);2789}27902791// Print general/accumulated JIT information.2792void CompileBroker::print_info(outputStream *out) {2793if (out == NULL) out = tty;2794out->cr();2795out->print_cr("======================");2796out->print_cr(" General JIT info ");2797out->print_cr("======================");2798out->cr();2799out->print_cr(" JIT is : %7s", should_compile_new_jobs() ? "on" : "off");2800out->print_cr(" Compiler threads : %7d", (int)CICompilerCount);2801out->cr();2802out->print_cr("CodeCache overview");2803out->print_cr("--------------------------------------------------------");2804out->cr();2805out->print_cr(" Reserved size : " SIZE_FORMAT_W(7) " KB", CodeCache::max_capacity() / K);2806out->print_cr(" Committed size : " SIZE_FORMAT_W(7) " KB", CodeCache::capacity() / K);2807out->print_cr(" Unallocated capacity : " SIZE_FORMAT_W(7) " KB", CodeCache::unallocated_capacity() / K);2808out->cr();28092810out->cr();2811out->print_cr("CodeCache cleaning overview");2812out->print_cr("--------------------------------------------------------");2813out->cr();2814NMethodSweeper::print(out);2815out->print_cr("--------------------------------------------------------");2816out->cr();2817}28182819// Note: tty_lock must not be held upon entry to this function.2820// Print functions called from herein do "micro-locking" on tty_lock.2821// That's a tradeoff which keeps together important blocks of output.2822// At the same time, continuous tty_lock hold time is kept in check,2823// preventing concurrently printing threads from stalling a long time.2824void CompileBroker::print_heapinfo(outputStream* out, const char* function, size_t granularity) {2825TimeStamp ts_total;2826TimeStamp ts_global;2827TimeStamp ts;28282829bool allFun = !strcmp(function, "all");2830bool aggregate = !strcmp(function, "aggregate") || !strcmp(function, "analyze") || allFun;2831bool usedSpace = !strcmp(function, "UsedSpace") || allFun;2832bool freeSpace = !strcmp(function, "FreeSpace") || allFun;2833bool methodCount = !strcmp(function, "MethodCount") || allFun;2834bool methodSpace = !strcmp(function, "MethodSpace") || allFun;2835bool methodAge = !strcmp(function, "MethodAge") || allFun;2836bool methodNames = !strcmp(function, "MethodNames") || allFun;2837bool discard = !strcmp(function, "discard") || allFun;28382839if (out == NULL) {2840out = tty;2841}28422843if (!(aggregate || usedSpace || freeSpace || methodCount || methodSpace || methodAge || methodNames || discard)) {2844out->print_cr("\n__ CodeHeapStateAnalytics: Function %s is not supported", function);2845out->cr();2846return;2847}28482849ts_total.update(); // record starting point28502851if (aggregate) {2852print_info(out);2853}28542855// We hold the CodeHeapStateAnalytics_lock all the time, from here until we leave this function.2856// That prevents other threads from destroying (making inconsistent) our view on the CodeHeap.2857// When we request individual parts of the analysis via the jcmd interface, it is possible2858// that in between another thread (another jcmd user or the vm running into CodeCache OOM)2859// updated the aggregated data. We will then see a modified, but again consistent, view2860// on the CodeHeap. That's a tolerable tradeoff we have to accept because we can't hold2861// a lock across user interaction.28622863// We should definitely acquire this lock before acquiring Compile_lock and CodeCache_lock.2864// CodeHeapStateAnalytics_lock may be held by a concurrent thread for a long time,2865// leading to an unnecessarily long hold time of the other locks we acquired before.2866ts.update(); // record starting point2867MutexLocker mu0(CodeHeapStateAnalytics_lock, Mutex::_safepoint_check_flag);2868out->print_cr("\n__ CodeHeapStateAnalytics lock wait took %10.3f seconds _________\n", ts.seconds());28692870// Holding the CodeCache_lock protects from concurrent alterations of the CodeCache.2871// Unfortunately, such protection is not sufficient:2872// When a new nmethod is created via ciEnv::register_method(), the2873// Compile_lock is taken first. After some initializations,2874// nmethod::new_nmethod() takes over, grabbing the CodeCache_lock2875// immediately (after finalizing the oop references). To lock out concurrent2876// modifiers, we have to grab both locks as well in the described sequence.2877//2878// If we serve an "allFun" call, it is beneficial to hold CodeCache_lock and Compile_lock2879// for the entire duration of aggregation and printing. That makes sure we see2880// a consistent picture and do not run into issues caused by concurrent alterations.2881bool should_take_Compile_lock = !SafepointSynchronize::is_at_safepoint() &&2882!Compile_lock->owned_by_self();2883bool should_take_CodeCache_lock = !SafepointSynchronize::is_at_safepoint() &&2884!CodeCache_lock->owned_by_self();2885Mutex* global_lock_1 = allFun ? (should_take_Compile_lock ? Compile_lock : NULL) : NULL;2886Monitor* global_lock_2 = allFun ? (should_take_CodeCache_lock ? CodeCache_lock : NULL) : NULL;2887Mutex* function_lock_1 = allFun ? NULL : (should_take_Compile_lock ? Compile_lock : NULL);2888Monitor* function_lock_2 = allFun ? NULL : (should_take_CodeCache_lock ? CodeCache_lock : NULL);2889ts_global.update(); // record starting point2890MutexLocker mu1(global_lock_1, Mutex::_safepoint_check_flag);2891MutexLocker mu2(global_lock_2, Mutex::_no_safepoint_check_flag);2892if ((global_lock_1 != NULL) || (global_lock_2 != NULL)) {2893out->print_cr("\n__ Compile & CodeCache (global) lock wait took %10.3f seconds _________\n", ts_global.seconds());2894ts_global.update(); // record starting point2895}28962897if (aggregate) {2898ts.update(); // record starting point2899MutexLocker mu11(function_lock_1, Mutex::_safepoint_check_flag);2900MutexLocker mu22(function_lock_2, Mutex::_no_safepoint_check_flag);2901if ((function_lock_1 != NULL) || (function_lock_1 != NULL)) {2902out->print_cr("\n__ Compile & CodeCache (function) lock wait took %10.3f seconds _________\n", ts.seconds());2903}29042905ts.update(); // record starting point2906CodeCache::aggregate(out, granularity);2907if ((function_lock_1 != NULL) || (function_lock_1 != NULL)) {2908out->print_cr("\n__ Compile & CodeCache (function) lock hold took %10.3f seconds _________\n", ts.seconds());2909}2910}29112912if (usedSpace) CodeCache::print_usedSpace(out);2913if (freeSpace) CodeCache::print_freeSpace(out);2914if (methodCount) CodeCache::print_count(out);2915if (methodSpace) CodeCache::print_space(out);2916if (methodAge) CodeCache::print_age(out);2917if (methodNames) {2918if (allFun) {2919// print_names() can only be used safely if the locks have been continuously held2920// since aggregation begin. That is true only for function "all".2921CodeCache::print_names(out);2922} else {2923out->print_cr("\nCodeHeapStateAnalytics: Function 'MethodNames' is only available as part of function 'all'");2924}2925}2926if (discard) CodeCache::discard(out);29272928if ((global_lock_1 != NULL) || (global_lock_2 != NULL)) {2929out->print_cr("\n__ Compile & CodeCache (global) lock hold took %10.3f seconds _________\n", ts_global.seconds());2930}2931out->print_cr("\n__ CodeHeapStateAnalytics total duration %10.3f seconds _________\n", ts_total.seconds());2932}293329342935