Path: blob/aarch64-shenandoah-jdk8u272-b10/hotspot/src/share/vm/compiler/compileBroker.cpp
32285 views
/*1* Copyright (c) 1999, 2019, 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 "classfile/systemDictionary.hpp"26#include "classfile/vmSymbols.hpp"27#include "code/codeCache.hpp"28#include "compiler/compileBroker.hpp"29#include "compiler/compileLog.hpp"30#include "compiler/compilerOracle.hpp"31#include "interpreter/linkResolver.hpp"32#include "jfr/jfrEvents.hpp"33#include "memory/allocation.inline.hpp"34#include "oops/methodData.hpp"35#include "oops/method.hpp"36#include "oops/oop.inline.hpp"37#include "prims/nativeLookup.hpp"38#include "runtime/arguments.hpp"39#include "runtime/compilationPolicy.hpp"40#include "runtime/init.hpp"41#include "runtime/interfaceSupport.hpp"42#include "runtime/javaCalls.hpp"43#include "runtime/os.hpp"44#include "runtime/sharedRuntime.hpp"45#include "runtime/sweeper.hpp"46#include "utilities/dtrace.hpp"47#include "utilities/events.hpp"48#ifdef COMPILER149#include "c1/c1_Compiler.hpp"50#endif51#ifdef COMPILER252#include "opto/c2compiler.hpp"53#endif54#ifdef SHARK55#include "shark/sharkCompiler.hpp"56#endif5758#ifdef DTRACE_ENABLED5960// Only bother with this argument setup if dtrace is available6162#ifndef USDT263HS_DTRACE_PROBE_DECL8(hotspot, method__compile__begin,64char*, intptr_t, char*, intptr_t, char*, intptr_t, char*, intptr_t);65HS_DTRACE_PROBE_DECL9(hotspot, method__compile__end,66char*, intptr_t, char*, intptr_t, char*, intptr_t, char*, intptr_t, bool);6768#define DTRACE_METHOD_COMPILE_BEGIN_PROBE(method, comp_name) \69{ \70Symbol* klass_name = (method)->klass_name(); \71Symbol* name = (method)->name(); \72Symbol* signature = (method)->signature(); \73HS_DTRACE_PROBE8(hotspot, method__compile__begin, \74comp_name, strlen(comp_name), \75klass_name->bytes(), klass_name->utf8_length(), \76name->bytes(), name->utf8_length(), \77signature->bytes(), signature->utf8_length()); \78}7980#define DTRACE_METHOD_COMPILE_END_PROBE(method, comp_name, success) \81{ \82Symbol* klass_name = (method)->klass_name(); \83Symbol* name = (method)->name(); \84Symbol* signature = (method)->signature(); \85HS_DTRACE_PROBE9(hotspot, method__compile__end, \86comp_name, strlen(comp_name), \87klass_name->bytes(), klass_name->utf8_length(), \88name->bytes(), name->utf8_length(), \89signature->bytes(), signature->utf8_length(), (success)); \90}9192#else /* USDT2 */9394#define DTRACE_METHOD_COMPILE_BEGIN_PROBE(method, comp_name) \95{ \96Symbol* klass_name = (method)->klass_name(); \97Symbol* name = (method)->name(); \98Symbol* signature = (method)->signature(); \99HOTSPOT_METHOD_COMPILE_BEGIN( \100comp_name, strlen(comp_name), \101(char *) klass_name->bytes(), klass_name->utf8_length(), \102(char *) name->bytes(), name->utf8_length(), \103(char *) signature->bytes(), signature->utf8_length()); \104}105106#define DTRACE_METHOD_COMPILE_END_PROBE(method, comp_name, success) \107{ \108Symbol* klass_name = (method)->klass_name(); \109Symbol* name = (method)->name(); \110Symbol* signature = (method)->signature(); \111HOTSPOT_METHOD_COMPILE_END( \112comp_name, strlen(comp_name), \113(char *) klass_name->bytes(), klass_name->utf8_length(), \114(char *) name->bytes(), name->utf8_length(), \115(char *) signature->bytes(), signature->utf8_length(), (success)); \116}117#endif /* USDT2 */118119#else // ndef DTRACE_ENABLED120121#define DTRACE_METHOD_COMPILE_BEGIN_PROBE(method, comp_name)122#define DTRACE_METHOD_COMPILE_END_PROBE(method, comp_name, success)123124#endif // ndef DTRACE_ENABLED125126bool CompileBroker::_initialized = false;127volatile bool CompileBroker::_should_block = false;128volatile jint CompileBroker::_print_compilation_warning = 0;129volatile jint CompileBroker::_should_compile_new_jobs = run_compilation;130131// The installed compiler(s)132AbstractCompiler* CompileBroker::_compilers[2];133134// These counters are used to assign an unique ID to each compilation.135volatile jint CompileBroker::_compilation_id = 0;136volatile jint CompileBroker::_osr_compilation_id = 0;137138// Debugging information139int CompileBroker::_last_compile_type = no_compile;140int CompileBroker::_last_compile_level = CompLevel_none;141char CompileBroker::_last_method_compiled[CompileBroker::name_buffer_length];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;171172int CompileBroker::_total_bailout_count = 0;173int CompileBroker::_total_invalidated_count = 0;174int CompileBroker::_total_compile_count = 0;175int CompileBroker::_total_osr_compile_count = 0;176int CompileBroker::_total_standard_compile_count = 0;177178int CompileBroker::_sum_osr_bytes_compiled = 0;179int CompileBroker::_sum_standard_bytes_compiled = 0;180int CompileBroker::_sum_nmethod_size = 0;181int CompileBroker::_sum_nmethod_code_size = 0;182183long CompileBroker::_peak_compilation_time = 0;184185CompileQueue* CompileBroker::_c2_compile_queue = NULL;186CompileQueue* CompileBroker::_c1_compile_queue = NULL;187188GrowableArray<CompilerThread*>* CompileBroker::_compiler_threads = NULL;189190191class CompilationLog : public StringEventLog {192public:193CompilationLog() : StringEventLog("Compilation events") {194}195196void log_compile(JavaThread* thread, CompileTask* task) {197StringLogMessage lm;198stringStream sstr = lm.stream();199// msg.time_stamp().update_to(tty->time_stamp().ticks());200task->print_compilation(&sstr, NULL, true);201log(thread, "%s", (const char*)lm);202}203204void log_nmethod(JavaThread* thread, nmethod* nm) {205log(thread, "nmethod %d%s " INTPTR_FORMAT " code [" INTPTR_FORMAT ", " INTPTR_FORMAT "]",206nm->compile_id(), nm->is_osr_method() ? "%" : "",207p2i(nm), p2i(nm->code_begin()), p2i(nm->code_end()));208}209210void log_failure(JavaThread* thread, CompileTask* task, const char* reason, const char* retry_message) {211StringLogMessage lm;212lm.print("%4d COMPILE SKIPPED: %s", task->compile_id(), reason);213if (retry_message != NULL) {214lm.append(" (%s)", retry_message);215}216lm.print("\n");217log(thread, "%s", (const char*)lm);218}219};220221static CompilationLog* _compilation_log = NULL;222223void compileBroker_init() {224if (LogEvents) {225_compilation_log = new CompilationLog();226}227}228229CompileTaskWrapper::CompileTaskWrapper(CompileTask* task) {230CompilerThread* thread = CompilerThread::current();231thread->set_task(task);232CompileLog* log = thread->log();233if (log != NULL) task->log_task_start(log);234}235236CompileTaskWrapper::~CompileTaskWrapper() {237CompilerThread* thread = CompilerThread::current();238CompileTask* task = thread->task();239CompileLog* log = thread->log();240if (log != NULL) task->log_task_done(log);241thread->set_task(NULL);242task->set_code_handle(NULL);243thread->set_env(NULL);244if (task->is_blocking()) {245MutexLocker notifier(task->lock(), thread);246task->mark_complete();247// Notify the waiting thread that the compilation has completed.248task->lock()->notify_all();249} else {250task->mark_complete();251252// By convention, the compiling thread is responsible for253// recycling a non-blocking CompileTask.254CompileTask::free(task);255}256}257258259CompileTask* CompileTask::_task_free_list = NULL;260#ifdef ASSERT261int CompileTask::_num_allocated_tasks = 0;262#endif263/**264* Allocate a CompileTask, from the free list if possible.265*/266CompileTask* CompileTask::allocate() {267MutexLocker locker(CompileTaskAlloc_lock);268CompileTask* task = NULL;269270if (_task_free_list != NULL) {271task = _task_free_list;272_task_free_list = task->next();273task->set_next(NULL);274} else {275task = new CompileTask();276DEBUG_ONLY(_num_allocated_tasks++;)277assert (_num_allocated_tasks < 10000, "Leaking compilation tasks?");278task->set_next(NULL);279task->set_is_free(true);280}281assert(task->is_free(), "Task must be free.");282task->set_is_free(false);283return task;284}285286287/**288* Add a task to the free list.289*/290void CompileTask::free(CompileTask* task) {291MutexLocker locker(CompileTaskAlloc_lock);292if (!task->is_free()) {293task->set_code(NULL);294assert(!task->lock()->is_locked(), "Should not be locked when freed");295JNIHandles::destroy_global(task->_method_holder);296JNIHandles::destroy_global(task->_hot_method_holder);297298task->set_is_free(true);299task->set_next(_task_free_list);300_task_free_list = task;301}302}303304void CompileTask::initialize(int compile_id,305methodHandle method,306int osr_bci,307int comp_level,308methodHandle hot_method,309int hot_count,310const char* comment,311bool is_blocking) {312assert(!_lock->is_locked(), "bad locking");313314_compile_id = compile_id;315_method = method();316_method_holder = JNIHandles::make_global(method->method_holder()->klass_holder());317_osr_bci = osr_bci;318_is_blocking = is_blocking;319_comp_level = comp_level;320_num_inlined_bytecodes = 0;321322_is_complete = false;323_is_success = false;324_code_handle = NULL;325326_hot_method = NULL;327_hot_method_holder = NULL;328_hot_count = hot_count;329_time_queued = 0; // tidy330_comment = comment;331_failure_reason = NULL;332333if (LogCompilation) {334_time_queued = os::elapsed_counter();335if (hot_method.not_null()) {336if (hot_method == method) {337_hot_method = _method;338} else {339_hot_method = hot_method();340// only add loader or mirror if different from _method_holder341_hot_method_holder = JNIHandles::make_global(hot_method->method_holder()->klass_holder());342}343}344}345346_next = NULL;347}348349// ------------------------------------------------------------------350// CompileTask::code/set_code351nmethod* CompileTask::code() const {352if (_code_handle == NULL) return NULL;353return _code_handle->code();354}355void CompileTask::set_code(nmethod* nm) {356if (_code_handle == NULL && nm == NULL) return;357guarantee(_code_handle != NULL, "");358_code_handle->set_code(nm);359if (nm == NULL) _code_handle = NULL; // drop the handle also360}361362363void CompileTask::mark_on_stack() {364// Mark these methods as something redefine classes cannot remove.365_method->set_on_stack(true);366if (_hot_method != NULL) {367_hot_method->set_on_stack(true);368}369}370371// ------------------------------------------------------------------372// CompileTask::print373void CompileTask::print() {374tty->print("<CompileTask compile_id=%d ", _compile_id);375tty->print("method=");376_method->print_name(tty);377tty->print_cr(" osr_bci=%d is_blocking=%s is_complete=%s is_success=%s>",378_osr_bci, bool_to_str(_is_blocking),379bool_to_str(_is_complete), bool_to_str(_is_success));380}381382383// ------------------------------------------------------------------384// CompileTask::print_line_on_error385//386// This function is called by fatal error handler when the thread387// causing troubles is a compiler thread.388//389// Do not grab any lock, do not allocate memory.390//391// Otherwise it's the same as CompileTask::print_line()392//393void CompileTask::print_line_on_error(outputStream* st, char* buf, int buflen) {394// print compiler name395st->print("%s:", CompileBroker::compiler_name(comp_level()));396print_compilation(st);397}398399// ------------------------------------------------------------------400// CompileTask::print_line401void CompileTask::print_line() {402ttyLocker ttyl; // keep the following output all in one block403// print compiler name if requested404if (CIPrintCompilerName) tty->print("%s:", CompileBroker::compiler_name(comp_level()));405print_compilation();406}407408409// ------------------------------------------------------------------410// CompileTask::print_compilation_impl411void CompileTask::print_compilation_impl(outputStream* st, Method* method, int compile_id, int comp_level,412bool is_osr_method, int osr_bci, bool is_blocking,413const char* msg, bool short_form) {414if (!short_form) {415st->print("%7d ", (int) st->time_stamp().milliseconds()); // print timestamp416}417st->print("%4d ", compile_id); // print compilation number418419// For unloaded methods the transition to zombie occurs after the420// method is cleared so it's impossible to report accurate421// information for that case.422bool is_synchronized = false;423bool has_exception_handler = false;424bool is_native = false;425if (method != NULL) {426is_synchronized = method->is_synchronized();427has_exception_handler = method->has_exception_handler();428is_native = method->is_native();429}430// method attributes431const char compile_type = is_osr_method ? '%' : ' ';432const char sync_char = is_synchronized ? 's' : ' ';433const char exception_char = has_exception_handler ? '!' : ' ';434const char blocking_char = is_blocking ? 'b' : ' ';435const char native_char = is_native ? 'n' : ' ';436437// print method attributes438st->print("%c%c%c%c%c ", compile_type, sync_char, exception_char, blocking_char, native_char);439440if (TieredCompilation) {441if (comp_level != -1) st->print("%d ", comp_level);442else st->print("- ");443}444st->print(" "); // more indent445446if (method == NULL) {447st->print("(method)");448} else {449method->print_short_name(st);450if (is_osr_method) {451st->print(" @ %d", osr_bci);452}453if (method->is_native())454st->print(" (native)");455else456st->print(" (%d bytes)", method->code_size());457}458459if (msg != NULL) {460st->print(" %s", msg);461}462if (!short_form) {463st->cr();464}465}466467// ------------------------------------------------------------------468// CompileTask::print_inlining469void CompileTask::print_inlining(outputStream* st, ciMethod* method, int inline_level, int bci, const char* msg) {470// 1234567471st->print(" "); // print timestamp472// 1234473st->print(" "); // print compilation number474475// method attributes476if (method->is_loaded()) {477const char sync_char = method->is_synchronized() ? 's' : ' ';478const char exception_char = method->has_exception_handlers() ? '!' : ' ';479const char monitors_char = method->has_monitor_bytecodes() ? 'm' : ' ';480481// print method attributes482st->print(" %c%c%c ", sync_char, exception_char, monitors_char);483} else {484// %s!bn485st->print(" "); // print method attributes486}487488if (TieredCompilation) {489st->print(" ");490}491st->print(" "); // more indent492st->print(" "); // initial inlining indent493494for (int i = 0; i < inline_level; i++) st->print(" ");495496st->print("@ %d ", bci); // print bci497method->print_short_name(st);498if (method->is_loaded())499st->print(" (%d bytes)", method->code_size());500else501st->print(" (not loaded)");502503if (msg != NULL) {504st->print(" %s", msg);505}506st->cr();507}508509// ------------------------------------------------------------------510// CompileTask::print_inline_indent511void CompileTask::print_inline_indent(int inline_level, outputStream* st) {512// 1234567513st->print(" "); // print timestamp514// 1234515st->print(" "); // print compilation number516// %s!bn517st->print(" "); // print method attributes518if (TieredCompilation) {519st->print(" ");520}521st->print(" "); // more indent522st->print(" "); // initial inlining indent523for (int i = 0; i < inline_level; i++) st->print(" ");524}525526// ------------------------------------------------------------------527// CompileTask::print_compilation528void CompileTask::print_compilation(outputStream* st, const char* msg, bool short_form) {529bool is_osr_method = osr_bci() != InvocationEntryBci;530print_compilation_impl(st, method(), compile_id(), comp_level(), is_osr_method, osr_bci(), is_blocking(), msg, short_form);531}532533// ------------------------------------------------------------------534// CompileTask::log_task535void CompileTask::log_task(xmlStream* log) {536Thread* thread = Thread::current();537methodHandle method(thread, this->method());538ResourceMark rm(thread);539540// <task id='9' method='M' osr_bci='X' level='1' blocking='1' stamp='1.234'>541log->print(" compile_id='%d'", _compile_id);542if (_osr_bci != CompileBroker::standard_entry_bci) {543log->print(" compile_kind='osr'"); // same as nmethod::compile_kind544} // else compile_kind='c2c'545if (!method.is_null()) log->method(method);546if (_osr_bci != CompileBroker::standard_entry_bci) {547log->print(" osr_bci='%d'", _osr_bci);548}549if (_comp_level != CompLevel_highest_tier) {550log->print(" level='%d'", _comp_level);551}552if (_is_blocking) {553log->print(" blocking='1'");554}555log->stamp();556}557558559// ------------------------------------------------------------------560// CompileTask::log_task_queued561void CompileTask::log_task_queued() {562Thread* thread = Thread::current();563ttyLocker ttyl;564ResourceMark rm(thread);565566xtty->begin_elem("task_queued");567log_task(xtty);568if (_comment != NULL) {569xtty->print(" comment='%s'", _comment);570}571if (_hot_method != NULL) {572methodHandle hot(thread, _hot_method);573methodHandle method(thread, _method);574if (hot() != method()) {575xtty->method(hot);576}577}578if (_hot_count != 0) {579xtty->print(" hot_count='%d'", _hot_count);580}581xtty->end_elem();582}583584585// ------------------------------------------------------------------586// CompileTask::log_task_start587void CompileTask::log_task_start(CompileLog* log) {588log->begin_head("task");589log_task(log);590log->end_head();591}592593594// ------------------------------------------------------------------595// CompileTask::log_task_done596void CompileTask::log_task_done(CompileLog* log) {597Thread* thread = Thread::current();598methodHandle method(thread, this->method());599ResourceMark rm(thread);600601if (!_is_success) {602const char* reason = _failure_reason != NULL ? _failure_reason : "unknown";603log->elem("failure reason='%s'", reason);604}605606// <task_done ... stamp='1.234'> </task>607nmethod* nm = code();608log->begin_elem("task_done success='%d' nmsize='%d' count='%d'",609_is_success, nm == NULL ? 0 : nm->content_size(),610method->invocation_count());611int bec = method->backedge_count();612if (bec != 0) log->print(" backedge_count='%d'", bec);613// Note: "_is_complete" is about to be set, but is not.614if (_num_inlined_bytecodes != 0) {615log->print(" inlined_bytes='%d'", _num_inlined_bytecodes);616}617log->stamp();618log->end_elem();619log->tail("task");620log->clear_identities(); // next task will have different CI621if (log->unflushed_count() > 2000) {622log->flush();623}624log->mark_file_end();625}626627628629/**630* Add a CompileTask to a CompileQueue631*/632void CompileQueue::add(CompileTask* task) {633assert(lock()->owned_by_self(), "must own lock");634assert(!CompileBroker::is_compilation_disabled_forever(), "Do not add task if compilation is turned off forever");635636task->set_next(NULL);637task->set_prev(NULL);638639if (_last == NULL) {640// The compile queue is empty.641assert(_first == NULL, "queue is empty");642_first = task;643_last = task;644} else {645// Append the task to the queue.646assert(_last->next() == NULL, "not last");647_last->set_next(task);648task->set_prev(_last);649_last = task;650}651++_size;652653// Mark the method as being in the compile queue.654task->method()->set_queued_for_compilation();655656NOT_PRODUCT(print();)657658if (LogCompilation && xtty != NULL) {659task->log_task_queued();660}661662// Notify CompilerThreads that a task is available.663lock()->notify_all();664}665666/**667* Empties compilation queue by putting all compilation tasks onto668* a freelist. Furthermore, the method wakes up all threads that are669* waiting on a compilation task to finish. This can happen if background670* compilation is disabled.671*/672void CompileQueue::free_all() {673MutexLocker mu(lock());674CompileTask* next = _first;675676// Iterate over all tasks in the compile queue677while (next != NULL) {678CompileTask* current = next;679next = current->next();680{681// Wake up thread that blocks on the compile task.682MutexLocker ct_lock(current->lock());683current->lock()->notify();684}685// Put the task back on the freelist.686CompileTask::free(current);687}688_first = NULL;689690// Wake up all threads that block on the queue.691lock()->notify_all();692}693694// ------------------------------------------------------------------695// CompileQueue::get696//697// Get the next CompileTask from a CompileQueue698CompileTask* CompileQueue::get() {699NMethodSweeper::possibly_sweep();700701MutexLocker locker(lock());702// If _first is NULL we have no more compile jobs. There are two reasons for703// having no compile jobs: First, we compiled everything we wanted. Second,704// we ran out of code cache so compilation has been disabled. In the latter705// case we perform code cache sweeps to free memory such that we can re-enable706// compilation.707while (_first == NULL) {708// Exit loop if compilation is disabled forever709if (CompileBroker::is_compilation_disabled_forever()) {710return NULL;711}712713if (UseCodeCacheFlushing && !CompileBroker::should_compile_new_jobs()) {714// Wait a certain amount of time to possibly do another sweep.715// We must wait until stack scanning has happened so that we can716// transition a method's state from 'not_entrant' to 'zombie'.717long wait_time = NmethodSweepCheckInterval * 1000;718if (FLAG_IS_DEFAULT(NmethodSweepCheckInterval)) {719// Only one thread at a time can do sweeping. Scale the720// wait time according to the number of compiler threads.721// As a result, the next sweep is likely to happen every 100ms722// with an arbitrary number of threads that do sweeping.723wait_time = 100 * CICompilerCount;724}725bool timeout = lock()->wait(!Mutex::_no_safepoint_check_flag, wait_time);726if (timeout) {727MutexUnlocker ul(lock());728NMethodSweeper::possibly_sweep();729}730} else {731// If there are no compilation tasks and we can compile new jobs732// (i.e., there is enough free space in the code cache) there is733// no need to invoke the sweeper. As a result, the hotness of methods734// remains unchanged. This behavior is desired, since we want to keep735// the stable state, i.e., we do not want to evict methods from the736// code cache if it is unnecessary.737// We need a timed wait here, since compiler threads can exit if compilation738// is disabled forever. We use 5 seconds wait time; the exiting of compiler threads739// is not critical and we do not want idle compiler threads to wake up too often.740lock()->wait(!Mutex::_no_safepoint_check_flag, 5*1000);741}742}743744if (CompileBroker::is_compilation_disabled_forever()) {745return NULL;746}747748CompileTask* task;749{750No_Safepoint_Verifier nsv;751task = CompilationPolicy::policy()->select_task(this);752}753if (task != NULL) {754remove(task);755}756purge_stale_tasks(); // may temporarily release MCQ lock757return task;758}759760// Clean & deallocate stale compile tasks.761// Temporarily releases MethodCompileQueue lock.762void CompileQueue::purge_stale_tasks() {763assert(lock()->owned_by_self(), "must own lock");764if (_first_stale != NULL) {765// Stale tasks are purged when MCQ lock is released,766// but _first_stale updates are protected by MCQ lock.767// Once task processing starts and MCQ lock is released,768// other compiler threads can reuse _first_stale.769CompileTask* head = _first_stale;770_first_stale = NULL;771{772MutexUnlocker ul(lock());773for (CompileTask* task = head; task != NULL; ) {774CompileTask* next_task = task->next();775CompileTaskWrapper ctw(task); // Frees the task776task->set_failure_reason("stale task");777task = next_task;778}779}780}781}782783void CompileQueue::remove(CompileTask* task) {784assert(lock()->owned_by_self(), "must own lock");785if (task->prev() != NULL) {786task->prev()->set_next(task->next());787} else {788// max is the first element789assert(task == _first, "Sanity");790_first = task->next();791}792793if (task->next() != NULL) {794task->next()->set_prev(task->prev());795} else {796// max is the last element797assert(task == _last, "Sanity");798_last = task->prev();799}800--_size;801}802803void CompileQueue::remove_and_mark_stale(CompileTask* task) {804assert(lock()->owned_by_self(), "must own lock");805remove(task);806807// Enqueue the task for reclamation (should be done outside MCQ lock)808task->set_next(_first_stale);809task->set_prev(NULL);810_first_stale = task;811}812813// methods in the compile queue need to be marked as used on the stack814// so that they don't get reclaimed by Redefine Classes815void CompileQueue::mark_on_stack() {816CompileTask* task = _first;817while (task != NULL) {818task->mark_on_stack();819task = task->next();820}821}822823#ifndef PRODUCT824/**825* Print entire compilation queue.826*/827void CompileQueue::print() {828if (CIPrintCompileQueue) {829ttyLocker ttyl;830tty->print_cr("Contents of %s", name());831tty->print_cr("----------------------");832CompileTask* task = _first;833while (task != NULL) {834task->print_line();835task = task->next();836}837tty->print_cr("----------------------");838}839}840#endif // PRODUCT841842CompilerCounters::CompilerCounters(const char* thread_name, int instance, TRAPS) {843844_current_method[0] = '\0';845_compile_type = CompileBroker::no_compile;846847if (UsePerfData) {848ResourceMark rm;849850// create the thread instance name space string - don't create an851// instance subspace if instance is -1 - keeps the adapterThread852// counters from having a ".0" namespace.853const char* thread_i = (instance == -1) ? thread_name :854PerfDataManager::name_space(thread_name, instance);855856857char* name = PerfDataManager::counter_name(thread_i, "method");858_perf_current_method =859PerfDataManager::create_string_variable(SUN_CI, name,860cmname_buffer_length,861_current_method, CHECK);862863name = PerfDataManager::counter_name(thread_i, "type");864_perf_compile_type = PerfDataManager::create_variable(SUN_CI, name,865PerfData::U_None,866(jlong)_compile_type,867CHECK);868869name = PerfDataManager::counter_name(thread_i, "time");870_perf_time = PerfDataManager::create_counter(SUN_CI, name,871PerfData::U_Ticks, CHECK);872873name = PerfDataManager::counter_name(thread_i, "compiles");874_perf_compiles = PerfDataManager::create_counter(SUN_CI, name,875PerfData::U_Events, CHECK);876}877}878879// ------------------------------------------------------------------880// CompileBroker::compilation_init881//882// Initialize the Compilation object883void CompileBroker::compilation_init() {884_last_method_compiled[0] = '\0';885886// No need to initialize compilation system if we do not use it.887if (!UseCompiler) {888return;889}890#ifndef SHARK891// Set the interface to the current compiler(s).892int c1_count = CompilationPolicy::policy()->compiler_count(CompLevel_simple);893int c2_count = CompilationPolicy::policy()->compiler_count(CompLevel_full_optimization);894#ifdef COMPILER1895if (c1_count > 0) {896_compilers[0] = new Compiler();897}898#endif // COMPILER1899900#ifdef COMPILER2901if (c2_count > 0) {902_compilers[1] = new C2Compiler();903}904#endif // COMPILER2905906#else // SHARK907int c1_count = 0;908int c2_count = 1;909910_compilers[1] = new SharkCompiler();911#endif // SHARK912913// Start the CompilerThreads914init_compiler_threads(c1_count, c2_count);915// totalTime performance counter is always created as it is required916// by the implementation of java.lang.management.CompilationMBean.917{918EXCEPTION_MARK;919_perf_total_compilation =920PerfDataManager::create_counter(JAVA_CI, "totalTime",921PerfData::U_Ticks, CHECK);922}923924925if (UsePerfData) {926927EXCEPTION_MARK;928929// create the jvmstat performance counters930_perf_osr_compilation =931PerfDataManager::create_counter(SUN_CI, "osrTime",932PerfData::U_Ticks, CHECK);933934_perf_standard_compilation =935PerfDataManager::create_counter(SUN_CI, "standardTime",936PerfData::U_Ticks, CHECK);937938_perf_total_bailout_count =939PerfDataManager::create_counter(SUN_CI, "totalBailouts",940PerfData::U_Events, CHECK);941942_perf_total_invalidated_count =943PerfDataManager::create_counter(SUN_CI, "totalInvalidates",944PerfData::U_Events, CHECK);945946_perf_total_compile_count =947PerfDataManager::create_counter(SUN_CI, "totalCompiles",948PerfData::U_Events, CHECK);949_perf_total_osr_compile_count =950PerfDataManager::create_counter(SUN_CI, "osrCompiles",951PerfData::U_Events, CHECK);952953_perf_total_standard_compile_count =954PerfDataManager::create_counter(SUN_CI, "standardCompiles",955PerfData::U_Events, CHECK);956957_perf_sum_osr_bytes_compiled =958PerfDataManager::create_counter(SUN_CI, "osrBytes",959PerfData::U_Bytes, CHECK);960961_perf_sum_standard_bytes_compiled =962PerfDataManager::create_counter(SUN_CI, "standardBytes",963PerfData::U_Bytes, CHECK);964965_perf_sum_nmethod_size =966PerfDataManager::create_counter(SUN_CI, "nmethodSize",967PerfData::U_Bytes, CHECK);968969_perf_sum_nmethod_code_size =970PerfDataManager::create_counter(SUN_CI, "nmethodCodeSize",971PerfData::U_Bytes, CHECK);972973_perf_last_method =974PerfDataManager::create_string_variable(SUN_CI, "lastMethod",975CompilerCounters::cmname_buffer_length,976"", CHECK);977978_perf_last_failed_method =979PerfDataManager::create_string_variable(SUN_CI, "lastFailedMethod",980CompilerCounters::cmname_buffer_length,981"", CHECK);982983_perf_last_invalidated_method =984PerfDataManager::create_string_variable(SUN_CI, "lastInvalidatedMethod",985CompilerCounters::cmname_buffer_length,986"", CHECK);987988_perf_last_compile_type =989PerfDataManager::create_variable(SUN_CI, "lastType",990PerfData::U_None,991(jlong)CompileBroker::no_compile,992CHECK);993994_perf_last_compile_size =995PerfDataManager::create_variable(SUN_CI, "lastSize",996PerfData::U_Bytes,997(jlong)CompileBroker::no_compile,998CHECK);99910001001_perf_last_failed_type =1002PerfDataManager::create_variable(SUN_CI, "lastFailedType",1003PerfData::U_None,1004(jlong)CompileBroker::no_compile,1005CHECK);10061007_perf_last_invalidated_type =1008PerfDataManager::create_variable(SUN_CI, "lastInvalidatedType",1009PerfData::U_None,1010(jlong)CompileBroker::no_compile,1011CHECK);1012}10131014_initialized = true;1015}101610171018CompilerThread* CompileBroker::make_compiler_thread(const char* name, CompileQueue* queue, CompilerCounters* counters,1019AbstractCompiler* comp, TRAPS) {1020CompilerThread* compiler_thread = NULL;10211022Klass* k =1023SystemDictionary::resolve_or_fail(vmSymbols::java_lang_Thread(),1024true, CHECK_0);1025instanceKlassHandle klass (THREAD, k);1026instanceHandle thread_oop = klass->allocate_instance_handle(CHECK_0);1027Handle string = java_lang_String::create_from_str(name, CHECK_0);10281029// Initialize thread_oop to put it into the system threadGroup1030Handle thread_group (THREAD, Universe::system_thread_group());1031JavaValue result(T_VOID);1032JavaCalls::call_special(&result, thread_oop,1033klass,1034vmSymbols::object_initializer_name(),1035vmSymbols::threadgroup_string_void_signature(),1036thread_group,1037string,1038CHECK_0);10391040{1041MutexLocker mu(Threads_lock, THREAD);1042compiler_thread = new CompilerThread(queue, counters);1043// At this point the new CompilerThread data-races with this startup1044// thread (which I believe is the primoridal thread and NOT the VM1045// thread). This means Java bytecodes being executed at startup can1046// queue compile jobs which will run at whatever default priority the1047// newly created CompilerThread runs at.104810491050// At this point it may be possible that no osthread was created for the1051// JavaThread due to lack of memory. We would have to throw an exception1052// in that case. However, since this must work and we do not allow1053// exceptions anyway, check and abort if this fails.10541055if (compiler_thread == NULL || compiler_thread->osthread() == NULL){1056vm_exit_during_initialization("java.lang.OutOfMemoryError",1057"unable to create new native thread");1058}10591060java_lang_Thread::set_thread(thread_oop(), compiler_thread);10611062// Note that this only sets the JavaThread _priority field, which by1063// definition is limited to Java priorities and not OS priorities.1064// The os-priority is set in the CompilerThread startup code itself10651066java_lang_Thread::set_priority(thread_oop(), NearMaxPriority);10671068// Note that we cannot call os::set_priority because it expects Java1069// priorities and we are *explicitly* using OS priorities so that it's1070// possible to set the compiler thread priority higher than any Java1071// thread.10721073int native_prio = CompilerThreadPriority;1074if (native_prio == -1) {1075if (UseCriticalCompilerThreadPriority) {1076native_prio = os::java_to_os_priority[CriticalPriority];1077} else {1078native_prio = os::java_to_os_priority[NearMaxPriority];1079}1080}1081os::set_native_priority(compiler_thread, native_prio);10821083java_lang_Thread::set_daemon(thread_oop());10841085compiler_thread->set_threadObj(thread_oop());1086compiler_thread->set_compiler(comp);1087Threads::add(compiler_thread);1088Thread::start(compiler_thread);1089}10901091// Let go of Threads_lock before yielding1092os::yield(); // make sure that the compiler thread is started early (especially helpful on SOLARIS)10931094return compiler_thread;1095}109610971098void CompileBroker::init_compiler_threads(int c1_compiler_count, int c2_compiler_count) {1099EXCEPTION_MARK;1100#if !defined(ZERO) && !defined(SHARK)1101assert(c2_compiler_count > 0 || c1_compiler_count > 0, "No compilers?");1102#endif // !ZERO && !SHARK1103// Initialize the compilation queue1104if (c2_compiler_count > 0) {1105_c2_compile_queue = new CompileQueue("C2 CompileQueue", MethodCompileQueue_lock);1106_compilers[1]->set_num_compiler_threads(c2_compiler_count);1107}1108if (c1_compiler_count > 0) {1109_c1_compile_queue = new CompileQueue("C1 CompileQueue", MethodCompileQueue_lock);1110_compilers[0]->set_num_compiler_threads(c1_compiler_count);1111}11121113int compiler_count = c1_compiler_count + c2_compiler_count;11141115_compiler_threads =1116new (ResourceObj::C_HEAP, mtCompiler) GrowableArray<CompilerThread*>(compiler_count, true);11171118char name_buffer[256];1119for (int i = 0; i < c2_compiler_count; i++) {1120// Create a name for our thread.1121sprintf(name_buffer, "C2 CompilerThread%d", i);1122CompilerCounters* counters = new CompilerCounters("compilerThread", i, CHECK);1123// Shark and C21124CompilerThread* new_thread = make_compiler_thread(name_buffer, _c2_compile_queue, counters, _compilers[1], CHECK);1125_compiler_threads->append(new_thread);1126}11271128for (int i = c2_compiler_count; i < compiler_count; i++) {1129// Create a name for our thread.1130sprintf(name_buffer, "C1 CompilerThread%d", i);1131CompilerCounters* counters = new CompilerCounters("compilerThread", i, CHECK);1132// C11133CompilerThread* new_thread = make_compiler_thread(name_buffer, _c1_compile_queue, counters, _compilers[0], CHECK);1134_compiler_threads->append(new_thread);1135}11361137if (UsePerfData) {1138PerfDataManager::create_constant(SUN_CI, "threads", PerfData::U_Bytes, compiler_count, CHECK);1139}1140}114111421143/**1144* Set the methods on the stack as on_stack so that redefine classes doesn't1145* reclaim them. This method is executed at a safepoint.1146*/1147void CompileBroker::mark_on_stack() {1148assert(SafepointSynchronize::is_at_safepoint(), "sanity check");1149// Since we are at a safepoint, we do not need a lock to access1150// the compile queues.1151if (_c2_compile_queue != NULL) {1152_c2_compile_queue->mark_on_stack();1153}1154if (_c1_compile_queue != NULL) {1155_c1_compile_queue->mark_on_stack();1156}1157}11581159// ------------------------------------------------------------------1160// CompileBroker::compile_method1161//1162// Request compilation of a method.1163void CompileBroker::compile_method_base(methodHandle method,1164int osr_bci,1165int comp_level,1166methodHandle hot_method,1167int hot_count,1168const char* comment,1169Thread* thread) {1170// do nothing if compiler thread(s) is not available1171if (!_initialized) {1172return;1173}11741175guarantee(!method->is_abstract(), "cannot compile abstract methods");1176assert(method->method_holder()->oop_is_instance(),1177"sanity check");1178assert(!method->method_holder()->is_not_initialized(),1179"method holder must be initialized");1180assert(!method->is_method_handle_intrinsic(), "do not enqueue these guys");11811182if (CIPrintRequests) {1183tty->print("request: ");1184method->print_short_name(tty);1185if (osr_bci != InvocationEntryBci) {1186tty->print(" osr_bci: %d", osr_bci);1187}1188tty->print(" comment: %s count: %d", comment, hot_count);1189if (!hot_method.is_null()) {1190tty->print(" hot: ");1191if (hot_method() != method()) {1192hot_method->print_short_name(tty);1193} else {1194tty->print("yes");1195}1196}1197tty->cr();1198}11991200// A request has been made for compilation. Before we do any1201// real work, check to see if the method has been compiled1202// in the meantime with a definitive result.1203if (compilation_is_complete(method, osr_bci, comp_level)) {1204return;1205}12061207#ifndef PRODUCT1208if (osr_bci != -1 && !FLAG_IS_DEFAULT(OSROnlyBCI)) {1209if ((OSROnlyBCI > 0) ? (OSROnlyBCI != osr_bci) : (-OSROnlyBCI == osr_bci)) {1210// Positive OSROnlyBCI means only compile that bci. Negative means don't compile that BCI.1211return;1212}1213}1214#endif12151216// If this method is already in the compile queue, then1217// we do not block the current thread.1218if (compilation_is_in_queue(method)) {1219// We may want to decay our counter a bit here to prevent1220// multiple denied requests for compilation. This is an1221// open compilation policy issue. Note: The other possibility,1222// in the case that this is a blocking compile request, is to have1223// all subsequent blocking requesters wait for completion of1224// ongoing compiles. Note that in this case we'll need a protocol1225// for freeing the associated compile tasks. [Or we could have1226// a single static monitor on which all these waiters sleep.]1227return;1228}12291230// If the requesting thread is holding the pending list lock1231// then we just return. We can't risk blocking while holding1232// the pending list lock or a 3-way deadlock may occur1233// between the reference handler thread, a GC (instigated1234// by a compiler thread), and compiled method registration.1235if (InstanceRefKlass::owns_pending_list_lock(JavaThread::current())) {1236return;1237}12381239if (TieredCompilation) {1240// Tiered policy requires MethodCounters to exist before adding a method to1241// the queue. Create if we don't have them yet.1242method->get_method_counters(thread);1243}12441245// Outputs from the following MutexLocker block:1246CompileTask* task = NULL;1247bool blocking = false;1248CompileQueue* queue = compile_queue(comp_level);12491250// Acquire our lock.1251{1252MutexLocker locker(queue->lock(), thread);12531254// Make sure the method has not slipped into the queues since1255// last we checked; note that those checks were "fast bail-outs".1256// Here we need to be more careful, see 14012000 below.1257if (compilation_is_in_queue(method)) {1258return;1259}12601261// We need to check again to see if the compilation has1262// completed. A previous compilation may have registered1263// some result.1264if (compilation_is_complete(method, osr_bci, comp_level)) {1265return;1266}12671268// We now know that this compilation is not pending, complete,1269// or prohibited. Assign a compile_id to this compilation1270// and check to see if it is in our [Start..Stop) range.1271int compile_id = assign_compile_id(method, osr_bci);1272if (compile_id == 0) {1273// The compilation falls outside the allowed range.1274return;1275}12761277// Should this thread wait for completion of the compile?1278blocking = is_compile_blocking();12791280// We will enter the compilation in the queue.1281// 14012000: Note that this sets the queued_for_compile bits in1282// the target method. We can now reason that a method cannot be1283// queued for compilation more than once, as follows:1284// Before a thread queues a task for compilation, it first acquires1285// the compile queue lock, then checks if the method's queued bits1286// are set or it has already been compiled. Thus there can not be two1287// instances of a compilation task for the same method on the1288// compilation queue. Consider now the case where the compilation1289// thread has already removed a task for that method from the queue1290// and is in the midst of compiling it. In this case, the1291// queued_for_compile bits must be set in the method (and these1292// will be visible to the current thread, since the bits were set1293// under protection of the compile queue lock, which we hold now.1294// When the compilation completes, the compiler thread first sets1295// the compilation result and then clears the queued_for_compile1296// bits. Neither of these actions are protected by a barrier (or done1297// under the protection of a lock), so the only guarantee we have1298// (on machines with TSO (Total Store Order)) is that these values1299// will update in that order. As a result, the only combinations of1300// these bits that the current thread will see are, in temporal order:1301// <RESULT, QUEUE> :1302// <0, 1> : in compile queue, but not yet compiled1303// <1, 1> : compiled but queue bit not cleared1304// <1, 0> : compiled and queue bit cleared1305// Because we first check the queue bits then check the result bits,1306// we are assured that we cannot introduce a duplicate task.1307// Note that if we did the tests in the reverse order (i.e. check1308// result then check queued bit), we could get the result bit before1309// the compilation completed, and the queue bit after the compilation1310// completed, and end up introducing a "duplicate" (redundant) task.1311// In that case, the compiler thread should first check if a method1312// has already been compiled before trying to compile it.1313// NOTE: in the event that there are multiple compiler threads and1314// there is de-optimization/recompilation, things will get hairy,1315// and in that case it's best to protect both the testing (here) of1316// these bits, and their updating (here and elsewhere) under a1317// common lock.1318task = create_compile_task(queue,1319compile_id, method,1320osr_bci, comp_level,1321hot_method, hot_count, comment,1322blocking);1323}13241325if (blocking) {1326wait_for_completion(task);1327}1328}132913301331nmethod* CompileBroker::compile_method(methodHandle method, int osr_bci,1332int comp_level,1333methodHandle hot_method, int hot_count,1334const char* comment, Thread* THREAD) {1335// make sure arguments make sense1336assert(method->method_holder()->oop_is_instance(), "not an instance method");1337assert(osr_bci == InvocationEntryBci || (0 <= osr_bci && osr_bci < method->code_size()), "bci out of range");1338assert(!method->is_abstract() && (osr_bci == InvocationEntryBci || !method->is_native()), "cannot compile abstract/native methods");1339assert(!method->method_holder()->is_not_initialized(), "method holder must be initialized");1340// allow any levels for WhiteBox1341assert(WhiteBoxAPI || TieredCompilation || comp_level == CompLevel_highest_tier, "only CompLevel_highest_tier must be used in non-tiered");1342// return quickly if possible13431344// lock, make sure that the compilation1345// isn't prohibited in a straightforward way.1346AbstractCompiler *comp = CompileBroker::compiler(comp_level);1347if (comp == NULL || !comp->can_compile_method(method) ||1348compilation_is_prohibited(method, osr_bci, comp_level)) {1349return NULL;1350}13511352if (osr_bci == InvocationEntryBci) {1353// standard compilation1354nmethod* method_code = method->code();1355if (method_code != NULL) {1356if (compilation_is_complete(method, osr_bci, comp_level)) {1357return method_code;1358}1359}1360if (method->is_not_compilable(comp_level)) {1361return NULL;1362}1363} else {1364// osr compilation1365#ifndef TIERED1366// seems like an assert of dubious value1367assert(comp_level == CompLevel_highest_tier,1368"all OSR compiles are assumed to be at a single compilation lavel");1369#endif // TIERED1370// We accept a higher level osr method1371nmethod* nm = method->lookup_osr_nmethod_for(osr_bci, comp_level, false);1372if (nm != NULL) return nm;1373if (method->is_not_osr_compilable(comp_level)) return NULL;1374}13751376assert(!HAS_PENDING_EXCEPTION, "No exception should be present");1377// some prerequisites that are compiler specific1378if (comp->is_c2() || comp->is_shark()) {1379method->constants()->resolve_string_constants(CHECK_AND_CLEAR_NULL);1380// Resolve all classes seen in the signature of the method1381// we are compiling.1382Method::load_signature_classes(method, CHECK_AND_CLEAR_NULL);1383}13841385// If the method is native, do the lookup in the thread requesting1386// the compilation. Native lookups can load code, which is not1387// permitted during compilation.1388//1389// Note: A native method implies non-osr compilation which is1390// checked with an assertion at the entry of this method.1391if (method->is_native() && !method->is_method_handle_intrinsic()) {1392bool in_base_library;1393address adr = NativeLookup::lookup(method, in_base_library, THREAD);1394if (HAS_PENDING_EXCEPTION) {1395// In case of an exception looking up the method, we just forget1396// about it. The interpreter will kick-in and throw the exception.1397method->set_not_compilable(); // implies is_not_osr_compilable()1398CLEAR_PENDING_EXCEPTION;1399return NULL;1400}1401assert(method->has_native_function(), "must have native code by now");1402}14031404// RedefineClasses() has replaced this method; just return1405if (method->is_old()) {1406return NULL;1407}14081409// JVMTI -- post_compile_event requires jmethod_id() that may require1410// a lock the compiling thread can not acquire. Prefetch it here.1411if (JvmtiExport::should_post_compiled_method_load()) {1412method->jmethod_id();1413}14141415// do the compilation1416if (method->is_native()) {1417if (!PreferInterpreterNativeStubs || method->is_method_handle_intrinsic()) {1418// To properly handle the appendix argument for out-of-line calls we are using a small trampoline that1419// pops off the appendix argument and jumps to the target (see gen_special_dispatch in SharedRuntime).1420//1421// Since normal compiled-to-compiled calls are not able to handle such a thing we MUST generate an adapter1422// in this case. If we can't generate one and use it we can not execute the out-of-line method handle calls.1423AdapterHandlerLibrary::create_native_wrapper(method);1424} else {1425return NULL;1426}1427} else {1428// If the compiler is shut off due to code cache getting full1429// fail out now so blocking compiles dont hang the java thread1430if (!should_compile_new_jobs()) {1431CompilationPolicy::policy()->delay_compilation(method());1432return NULL;1433}1434compile_method_base(method, osr_bci, comp_level, hot_method, hot_count, comment, THREAD);1435}14361437// return requested nmethod1438// We accept a higher level osr method1439return osr_bci == InvocationEntryBci ? method->code() : method->lookup_osr_nmethod_for(osr_bci, comp_level, false);1440}144114421443// ------------------------------------------------------------------1444// CompileBroker::compilation_is_complete1445//1446// See if compilation of this method is already complete.1447bool CompileBroker::compilation_is_complete(methodHandle method,1448int osr_bci,1449int comp_level) {1450bool is_osr = (osr_bci != standard_entry_bci);1451if (is_osr) {1452if (method->is_not_osr_compilable(comp_level)) {1453return true;1454} else {1455nmethod* result = method->lookup_osr_nmethod_for(osr_bci, comp_level, true);1456return (result != NULL);1457}1458} else {1459if (method->is_not_compilable(comp_level)) {1460return true;1461} else {1462nmethod* result = method->code();1463if (result == NULL) return false;1464return comp_level == result->comp_level();1465}1466}1467}146814691470/**1471* See if this compilation is already requested.1472*1473* Implementation note: there is only a single "is in queue" bit1474* for each method. This means that the check below is overly1475* conservative in the sense that an osr compilation in the queue1476* will block a normal compilation from entering the queue (and vice1477* versa). This can be remedied by a full queue search to disambiguate1478* cases. If it is deemed profitable, this may be done.1479*/1480bool CompileBroker::compilation_is_in_queue(methodHandle method) {1481return method->queued_for_compilation();1482}14831484// ------------------------------------------------------------------1485// CompileBroker::compilation_is_prohibited1486//1487// See if this compilation is not allowed.1488bool CompileBroker::compilation_is_prohibited(methodHandle method, int osr_bci, int comp_level) {1489bool is_native = method->is_native();1490// Some compilers may not support the compilation of natives.1491AbstractCompiler *comp = compiler(comp_level);1492if (is_native &&1493(!CICompileNatives || comp == NULL || !comp->supports_native())) {1494method->set_not_compilable_quietly(comp_level);1495return true;1496}14971498bool is_osr = (osr_bci != standard_entry_bci);1499// Some compilers may not support on stack replacement.1500if (is_osr &&1501(!CICompileOSR || comp == NULL || !comp->supports_osr())) {1502method->set_not_osr_compilable(comp_level);1503return true;1504}15051506// The method may be explicitly excluded by the user.1507bool quietly;1508if (CompilerOracle::should_exclude(method, quietly)) {1509if (!quietly) {1510// This does not happen quietly...1511ResourceMark rm;1512tty->print("### Excluding %s:%s",1513method->is_native() ? "generation of native wrapper" : "compile",1514(method->is_static() ? " static" : ""));1515method->print_short_name(tty);1516tty->cr();1517}1518method->set_not_compilable(CompLevel_all, !quietly, "excluded by CompilerOracle");1519}15201521return false;1522}15231524/**1525* Generate serialized IDs for compilation requests. If certain debugging flags are used1526* and the ID is not within the specified range, the method is not compiled and 0 is returned.1527* The function also allows to generate separate compilation IDs for OSR compilations.1528*/1529int CompileBroker::assign_compile_id(methodHandle method, int osr_bci) {1530#ifdef ASSERT1531bool is_osr = (osr_bci != standard_entry_bci);1532int id;1533if (method->is_native()) {1534assert(!is_osr, "can't be osr");1535// Adapters, native wrappers and method handle intrinsics1536// should be generated always.1537return Atomic::add(1, &_compilation_id);1538} else if (CICountOSR && is_osr) {1539id = Atomic::add(1, &_osr_compilation_id);1540if (CIStartOSR <= id && id < CIStopOSR) {1541return id;1542}1543} else {1544id = Atomic::add(1, &_compilation_id);1545if (CIStart <= id && id < CIStop) {1546return id;1547}1548}15491550// Method was not in the appropriate compilation range.1551method->set_not_compilable_quietly();1552return 0;1553#else1554// CICountOSR is a develop flag and set to 'false' by default. In a product built,1555// only _compilation_id is incremented.1556return Atomic::add(1, &_compilation_id);1557#endif1558}15591560/**1561* Should the current thread block until this compilation request1562* has been fulfilled?1563*/1564bool CompileBroker::is_compile_blocking() {1565assert(!InstanceRefKlass::owns_pending_list_lock(JavaThread::current()), "possible deadlock");1566return !BackgroundCompilation;1567}156815691570// ------------------------------------------------------------------1571// CompileBroker::preload_classes1572void CompileBroker::preload_classes(methodHandle method, TRAPS) {1573// Move this code over from c1_Compiler.cpp1574ShouldNotReachHere();1575}157615771578// ------------------------------------------------------------------1579// CompileBroker::create_compile_task1580//1581// Create a CompileTask object representing the current request for1582// compilation. Add this task to the queue.1583CompileTask* CompileBroker::create_compile_task(CompileQueue* queue,1584int compile_id,1585methodHandle method,1586int osr_bci,1587int comp_level,1588methodHandle hot_method,1589int hot_count,1590const char* comment,1591bool blocking) {1592CompileTask* new_task = CompileTask::allocate();1593new_task->initialize(compile_id, method, osr_bci, comp_level,1594hot_method, hot_count, comment,1595blocking);1596queue->add(new_task);1597return new_task;1598}159916001601/**1602* Wait for the compilation task to complete.1603*/1604void CompileBroker::wait_for_completion(CompileTask* task) {1605if (CIPrintCompileQueue) {1606ttyLocker ttyl;1607tty->print_cr("BLOCKING FOR COMPILE");1608}16091610assert(task->is_blocking(), "can only wait on blocking task");16111612JavaThread* thread = JavaThread::current();1613thread->set_blocked_on_compilation(true);16141615methodHandle method(thread, task->method());1616{1617MutexLocker waiter(task->lock(), thread);16181619while (!task->is_complete() && !is_compilation_disabled_forever()) {1620task->lock()->wait();1621}1622}16231624thread->set_blocked_on_compilation(false);1625if (is_compilation_disabled_forever()) {1626CompileTask::free(task);1627return;1628}16291630// It is harmless to check this status without the lock, because1631// completion is a stable property (until the task object is recycled).1632assert(task->is_complete(), "Compilation should have completed");1633assert(task->code_handle() == NULL, "must be reset");16341635// By convention, the waiter is responsible for recycling a1636// blocking CompileTask. Since there is only one waiter ever1637// waiting on a CompileTask, we know that no one else will1638// be using this CompileTask; we can free it.1639CompileTask::free(task);1640}16411642/**1643* Initialize compiler thread(s) + compiler object(s). The postcondition1644* of this function is that the compiler runtimes are initialized and that1645* compiler threads can start compiling.1646*/1647bool CompileBroker::init_compiler_runtime() {1648CompilerThread* thread = CompilerThread::current();1649AbstractCompiler* comp = thread->compiler();1650// Final sanity check - the compiler object must exist1651guarantee(comp != NULL, "Compiler object must exist");16521653int system_dictionary_modification_counter;1654{1655MutexLocker locker(Compile_lock, thread);1656system_dictionary_modification_counter = SystemDictionary::number_of_modifications();1657}16581659{1660// Must switch to native to allocate ci_env1661ThreadToNativeFromVM ttn(thread);1662ciEnv ci_env(NULL, system_dictionary_modification_counter);1663// Cache Jvmti state1664ci_env.cache_jvmti_state();1665// Cache DTrace flags1666ci_env.cache_dtrace_flags();16671668// Switch back to VM state to do compiler initialization1669ThreadInVMfromNative tv(thread);1670ResetNoHandleMark rnhm;167116721673if (!comp->is_shark()) {1674// Perform per-thread and global initializations1675comp->initialize();1676}1677}16781679if (comp->is_failed()) {1680disable_compilation_forever();1681// If compiler initialization failed, no compiler thread that is specific to a1682// particular compiler runtime will ever start to compile methods.1683shutdown_compiler_runtime(comp, thread);1684return false;1685}16861687// C1 specific check1688if (comp->is_c1() && (thread->get_buffer_blob() == NULL)) {1689warning("Initialization of %s thread failed (no space to run compilers)", thread->name());1690return false;1691}16921693return true;1694}16951696/**1697* If C1 and/or C2 initialization failed, we shut down all compilation.1698* We do this to keep things simple. This can be changed if it ever turns1699* out to be a problem.1700*/1701void CompileBroker::shutdown_compiler_runtime(AbstractCompiler* comp, CompilerThread* thread) {1702// Free buffer blob, if allocated1703if (thread->get_buffer_blob() != NULL) {1704MutexLockerEx mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);1705CodeCache::free(thread->get_buffer_blob());1706}17071708if (comp->should_perform_shutdown()) {1709// There are two reasons for shutting down the compiler1710// 1) compiler runtime initialization failed1711// 2) The code cache is full and the following flag is set: -XX:-UseCodeCacheFlushing1712warning("%s initialization failed. Shutting down all compilers", comp->name());17131714// Only one thread per compiler runtime object enters here1715// Set state to shut down1716comp->set_shut_down();17171718// Delete all queued compilation tasks to make compiler threads exit faster.1719if (_c1_compile_queue != NULL) {1720_c1_compile_queue->free_all();1721}17221723if (_c2_compile_queue != NULL) {1724_c2_compile_queue->free_all();1725}17261727// Set flags so that we continue execution with using interpreter only.1728UseCompiler = false;1729UseInterpreter = true;17301731// We could delete compiler runtimes also. However, there are references to1732// the compiler runtime(s) (e.g., nmethod::is_compiled_by_c1()) which then1733// fail. This can be done later if necessary.1734}1735}17361737// ------------------------------------------------------------------1738// CompileBroker::compiler_thread_loop1739//1740// The main loop run by a CompilerThread.1741void CompileBroker::compiler_thread_loop() {1742CompilerThread* thread = CompilerThread::current();1743CompileQueue* queue = thread->queue();1744// For the thread that initializes the ciObjectFactory1745// this resource mark holds all the shared objects1746ResourceMark rm;17471748// First thread to get here will initialize the compiler interface17491750if (!ciObjectFactory::is_initialized()) {1751ASSERT_IN_VM;1752MutexLocker only_one (CompileThread_lock, thread);1753if (!ciObjectFactory::is_initialized()) {1754ciObjectFactory::initialize();1755}1756}17571758// Open a log.1759if (LogCompilation) {1760init_compiler_thread_log();1761}1762CompileLog* log = thread->log();1763if (log != NULL) {1764log->begin_elem("start_compile_thread name='%s' thread='" UINTX_FORMAT "' process='%d'",1765thread->name(),1766os::current_thread_id(),1767os::current_process_id());1768log->stamp();1769log->end_elem();1770}17711772// If compiler thread/runtime initialization fails, exit the compiler thread1773if (!init_compiler_runtime()) {1774return;1775}17761777// Poll for new compilation tasks as long as the JVM runs. Compilation1778// should only be disabled if something went wrong while initializing the1779// compiler runtimes. This, in turn, should not happen. The only known case1780// when compiler runtime initialization fails is if there is not enough free1781// space in the code cache to generate the necessary stubs, etc.1782while (!is_compilation_disabled_forever()) {1783// We need this HandleMark to avoid leaking VM handles.1784HandleMark hm(thread);17851786if (CodeCache::unallocated_capacity() < CodeCacheMinimumFreeSpace) {1787// the code cache is really full1788handle_full_code_cache();1789}17901791CompileTask* task = queue->get();1792if (task == NULL) {1793continue;1794}17951796// Give compiler threads an extra quanta. They tend to be bursty and1797// this helps the compiler to finish up the job.1798if( CompilerThreadHintNoPreempt )1799os::hint_no_preempt();18001801// trace per thread time and compile statistics1802CompilerCounters* counters = ((CompilerThread*)thread)->counters();1803PerfTraceTimedEvent(counters->time_counter(), counters->compile_counter());18041805// Assign the task to the current thread. Mark this compilation1806// thread as active for the profiler.1807CompileTaskWrapper ctw(task);1808nmethodLocker result_handle; // (handle for the nmethod produced by this task)1809task->set_code_handle(&result_handle);1810methodHandle method(thread, task->method());18111812// Never compile a method if breakpoints are present in it1813if (method()->number_of_breakpoints() == 0) {1814// Compile the method.1815if ((UseCompiler || AlwaysCompileLoopMethods) && CompileBroker::should_compile_new_jobs()) {1816invoke_compiler_on_method(task);1817} else {1818// After compilation is disabled, remove remaining methods from queue1819method->clear_queued_for_compilation();1820task->set_failure_reason("compilation is disabled");1821}1822}1823}18241825// Shut down compiler runtime1826shutdown_compiler_runtime(thread->compiler(), thread);1827}18281829// ------------------------------------------------------------------1830// CompileBroker::init_compiler_thread_log1831//1832// Set up state required by +LogCompilation.1833void CompileBroker::init_compiler_thread_log() {1834CompilerThread* thread = CompilerThread::current();1835char file_name[4*K];1836FILE* fp = NULL;1837intx thread_id = os::current_thread_id();1838for (int try_temp_dir = 1; try_temp_dir >= 0; try_temp_dir--) {1839const char* dir = (try_temp_dir ? os::get_temp_directory() : NULL);1840if (dir == NULL) {1841jio_snprintf(file_name, sizeof(file_name), "hs_c" UINTX_FORMAT "_pid%u.log",1842thread_id, os::current_process_id());1843} else {1844jio_snprintf(file_name, sizeof(file_name),1845"%s%shs_c" UINTX_FORMAT "_pid%u.log", dir,1846os::file_separator(), thread_id, os::current_process_id());1847}18481849fp = fopen(file_name, "wt");1850if (fp != NULL) {1851if (LogCompilation && Verbose) {1852tty->print_cr("Opening compilation log %s", file_name);1853}1854CompileLog* log = new(ResourceObj::C_HEAP, mtCompiler) CompileLog(file_name, fp, thread_id);1855if (log == NULL) {1856fclose(fp);1857return;1858}1859thread->init_log(log);18601861if (xtty != NULL) {1862ttyLocker ttyl;1863// Record any per thread log files1864xtty->elem("thread_logfile thread='" INTX_FORMAT "' filename='%s'", thread_id, file_name);1865}1866return;1867}1868}1869warning("Cannot open log file: %s", file_name);1870}18711872// ------------------------------------------------------------------1873// CompileBroker::set_should_block1874//1875// Set _should_block.1876// Call this from the VM, with Threads_lock held and a safepoint requested.1877void CompileBroker::set_should_block() {1878assert(Threads_lock->owner() == Thread::current(), "must have threads lock");1879assert(SafepointSynchronize::is_at_safepoint(), "must be at a safepoint already");1880#ifndef PRODUCT1881if (PrintCompilation && (Verbose || WizardMode))1882tty->print_cr("notifying compiler thread pool to block");1883#endif1884_should_block = true;1885}18861887// ------------------------------------------------------------------1888// CompileBroker::maybe_block1889//1890// Call this from the compiler at convenient points, to poll for _should_block.1891void CompileBroker::maybe_block() {1892if (_should_block) {1893#ifndef PRODUCT1894if (PrintCompilation && (Verbose || WizardMode))1895tty->print_cr("compiler thread " INTPTR_FORMAT " poll detects block request", p2i(Thread::current()));1896#endif1897ThreadInVMfromNative tivfn(JavaThread::current());1898}1899}19001901// wrapper for CodeCache::print_summary()1902static void codecache_print(bool detailed)1903{1904ResourceMark rm;1905stringStream s;1906// Dump code cache into a buffer before locking the tty,1907{1908MutexLockerEx mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);1909CodeCache::print_summary(&s, detailed);1910}1911ttyLocker ttyl;1912tty->print("%s", s.as_string());1913}19141915static void post_compilation_event(EventCompilation* event, CompileTask* task) {1916assert(event != NULL, "invariant");1917assert(event->should_commit(), "invariant");1918event->set_method(task->method());1919event->set_compileId(task->compile_id());1920event->set_compileLevel(task->comp_level());1921event->set_succeded(task->is_success());1922event->set_isOsr(task->osr_bci() != CompileBroker::standard_entry_bci);1923event->set_codeSize((task->code() == NULL) ? 0 : task->code()->total_size());1924event->set_inlinedBytes(task->num_inlined_bytecodes());1925event->commit();1926}19271928// ------------------------------------------------------------------1929// CompileBroker::invoke_compiler_on_method1930//1931// Compile a method.1932//1933void CompileBroker::invoke_compiler_on_method(CompileTask* task) {1934if (PrintCompilation) {1935ResourceMark rm;1936task->print_line();1937}1938elapsedTimer time;19391940CompilerThread* thread = CompilerThread::current();1941ResourceMark rm(thread);19421943if (LogEvents) {1944_compilation_log->log_compile(thread, task);1945}19461947// Common flags.1948uint compile_id = task->compile_id();1949int osr_bci = task->osr_bci();1950bool is_osr = (osr_bci != standard_entry_bci);1951bool should_log = (thread->log() != NULL);1952bool should_break = false;1953int task_level = task->comp_level();1954{1955// create the handle inside it's own block so it can't1956// accidentally be referenced once the thread transitions to1957// native. The NoHandleMark before the transition should catch1958// any cases where this occurs in the future.1959methodHandle method(thread, task->method());1960should_break = check_break_at(method, compile_id, is_osr);1961if (should_log && !CompilerOracle::should_log(method)) {1962should_log = false;1963}1964assert(!method->is_native(), "no longer compile natives");19651966// Save information about this method in case of failure.1967set_last_compile(thread, method, is_osr, task_level);19681969DTRACE_METHOD_COMPILE_BEGIN_PROBE(method, compiler_name(task_level));1970}19711972// Allocate a new set of JNI handles.1973push_jni_handle_block();1974Method* target_handle = task->method();1975int compilable = ciEnv::MethodCompilable;1976{1977int system_dictionary_modification_counter;1978{1979MutexLocker locker(Compile_lock, thread);1980system_dictionary_modification_counter = SystemDictionary::number_of_modifications();1981}19821983NoHandleMark nhm;1984ThreadToNativeFromVM ttn(thread);19851986ciEnv ci_env(task, system_dictionary_modification_counter);1987if (should_break) {1988ci_env.set_break_at_compile(true);1989}1990if (should_log) {1991ci_env.set_log(thread->log());1992}1993assert(thread->env() == &ci_env, "set by ci_env");1994// The thread-env() field is cleared in ~CompileTaskWrapper.19951996// Cache Jvmti state1997ci_env.cache_jvmti_state();19981999// Cache DTrace flags2000ci_env.cache_dtrace_flags();20012002ciMethod* target = ci_env.get_method_from_handle(target_handle);20032004TraceTime t1("compilation", &time);2005EventCompilation event;20062007AbstractCompiler *comp = compiler(task_level);2008if (comp == NULL) {2009ci_env.record_method_not_compilable("no compiler", !TieredCompilation);2010} else {2011comp->compile_method(&ci_env, target, osr_bci);2012}20132014if (!ci_env.failing() && task->code() == NULL) {2015//assert(false, "compiler should always document failure");2016// The compiler elected, without comment, not to register a result.2017// Do not attempt further compilations of this method.2018ci_env.record_method_not_compilable("compile failed", !TieredCompilation);2019}20202021// Copy this bit to the enclosing block:2022compilable = ci_env.compilable();20232024if (ci_env.failing()) {2025const char* failure_reason = ci_env.failure_reason();2026const char* retry_message = ci_env.retry_message();2027task->set_failure_reason(failure_reason);2028if (_compilation_log != NULL) {2029_compilation_log->log_failure(thread, task, ci_env.failure_reason(), retry_message);2030}2031if (PrintCompilation) {2032FormatBufferResource msg = retry_message != NULL ?2033err_msg_res("COMPILE SKIPPED: %s (%s)", ci_env.failure_reason(), retry_message) :2034err_msg_res("COMPILE SKIPPED: %s", ci_env.failure_reason());2035task->print_compilation(tty, msg);2036}20372038EventCompilationFailure event;2039if (event.should_commit()) {2040event.set_compileId(compile_id);2041event.set_failureMessage(failure_reason);2042event.commit();2043}20442045if (AbortVMOnCompilationFailure) {2046if (compilable == ciEnv::MethodCompilable_not_at_tier) {2047fatal(err_msg("Not compilable at tier %d: %s", task_level, failure_reason));2048}2049if (compilable == ciEnv::MethodCompilable_never) {2050fatal(err_msg("Never compilable: %s", failure_reason));2051}2052}2053} else {2054task->mark_success();2055task->set_num_inlined_bytecodes(ci_env.num_inlined_bytecodes());2056if (_compilation_log != NULL) {2057nmethod* code = task->code();2058if (code != NULL) {2059_compilation_log->log_nmethod(thread, code);2060}2061}2062}2063// simulate crash during compilation2064assert(task->compile_id() != CICrashAt, "just as planned");2065if (event.should_commit()) {2066post_compilation_event(&event, task);2067}2068}2069pop_jni_handle_block();20702071methodHandle method(thread, task->method());20722073DTRACE_METHOD_COMPILE_END_PROBE(method, compiler_name(task_level), task->is_success());20742075collect_statistics(thread, time, task);20762077if (PrintCompilation && PrintCompilation2) {2078tty->print("%7d ", (int) tty->time_stamp().milliseconds()); // print timestamp2079tty->print("%4d ", compile_id); // print compilation number2080tty->print("%s ", (is_osr ? "%" : " "));2081if (task->code() != NULL) {2082tty->print("size: %d(%d) ", task->code()->total_size(), task->code()->insts_size());2083}2084tty->print_cr("time: %d inlined: %d bytes", (int)time.milliseconds(), task->num_inlined_bytecodes());2085}20862087if (PrintCodeCacheOnCompilation)2088codecache_print(/* detailed= */ false);20892090// Disable compilation, if required.2091switch (compilable) {2092case ciEnv::MethodCompilable_never:2093if (is_osr)2094method->set_not_osr_compilable_quietly();2095else2096method->set_not_compilable_quietly();2097break;2098case ciEnv::MethodCompilable_not_at_tier:2099if (is_osr)2100method->set_not_osr_compilable_quietly(task_level);2101else2102method->set_not_compilable_quietly(task_level);2103break;2104}21052106// Note that the queued_for_compilation bits are cleared without2107// protection of a mutex. [They were set by the requester thread,2108// when adding the task to the compile queue -- at which time the2109// compile queue lock was held. Subsequently, we acquired the compile2110// queue lock to get this task off the compile queue; thus (to belabour2111// the point somewhat) our clearing of the bits must be occurring2112// only after the setting of the bits. See also 14012000 above.2113method->clear_queued_for_compilation();21142115#ifdef ASSERT2116if (CollectedHeap::fired_fake_oom()) {2117// The current compile received a fake OOM during compilation so2118// go ahead and exit the VM since the test apparently succeeded2119tty->print_cr("*** Shutting down VM after successful fake OOM");2120vm_exit(0);2121}2122#endif2123}21242125/**2126* The CodeCache is full. Print out warning and disable compilation2127* or try code cache cleaning so compilation can continue later.2128*/2129void CompileBroker::handle_full_code_cache() {2130UseInterpreter = true;2131if (UseCompiler || AlwaysCompileLoopMethods ) {2132if (xtty != NULL) {2133ResourceMark rm;2134stringStream s;2135// Dump code cache state into a buffer before locking the tty,2136// because log_state() will use locks causing lock conflicts.2137CodeCache::log_state(&s);2138// Lock to prevent tearing2139ttyLocker ttyl;2140xtty->begin_elem("code_cache_full");2141xtty->print("%s", s.as_string());2142xtty->stamp();2143xtty->end_elem();2144}21452146CodeCache::report_codemem_full();21472148#ifndef PRODUCT2149if (CompileTheWorld || ExitOnFullCodeCache) {2150codecache_print(/* detailed= */ true);2151before_exit(JavaThread::current());2152exit_globals(); // will delete tty2153vm_direct_exit(CompileTheWorld ? 0 : 1);2154}2155#endif2156if (UseCodeCacheFlushing) {2157// Since code cache is full, immediately stop new compiles2158if (CompileBroker::set_should_compile_new_jobs(CompileBroker::stop_compilation)) {2159NMethodSweeper::log_sweep("disable_compiler");2160}2161// Switch to 'vm_state'. This ensures that possibly_sweep() can be called2162// without having to consider the state in which the current thread is.2163ThreadInVMfromUnknown in_vm;2164NMethodSweeper::possibly_sweep();2165} else {2166disable_compilation_forever();2167}21682169// Print warning only once2170if (should_print_compiler_warning()) {2171warning("CodeCache is full. Compiler has been disabled.");2172warning("Try increasing the code cache size using -XX:ReservedCodeCacheSize=");2173codecache_print(/* detailed= */ true);2174}2175}2176}21772178// ------------------------------------------------------------------2179// CompileBroker::set_last_compile2180//2181// Record this compilation for debugging purposes.2182void CompileBroker::set_last_compile(CompilerThread* thread, methodHandle method, bool is_osr, int comp_level) {2183ResourceMark rm;2184char* method_name = method->name()->as_C_string();2185strncpy(_last_method_compiled, method_name, CompileBroker::name_buffer_length);2186_last_method_compiled[CompileBroker::name_buffer_length - 1] = '\0'; // ensure null terminated2187char current_method[CompilerCounters::cmname_buffer_length];2188size_t maxLen = CompilerCounters::cmname_buffer_length;21892190if (UsePerfData) {2191const char* class_name = method->method_holder()->name()->as_C_string();21922193size_t s1len = strlen(class_name);2194size_t s2len = strlen(method_name);21952196// check if we need to truncate the string2197if (s1len + s2len + 2 > maxLen) {21982199// the strategy is to lop off the leading characters of the2200// class name and the trailing characters of the method name.22012202if (s2len + 2 > maxLen) {2203// lop of the entire class name string, let snprintf handle2204// truncation of the method name.2205class_name += s1len; // null string2206}2207else {2208// lop off the extra characters from the front of the class name2209class_name += ((s1len + s2len + 2) - maxLen);2210}2211}22122213jio_snprintf(current_method, maxLen, "%s %s", class_name, method_name);2214}22152216if (CICountOSR && is_osr) {2217_last_compile_type = osr_compile;2218} else {2219_last_compile_type = normal_compile;2220}2221_last_compile_level = comp_level;22222223if (UsePerfData) {2224CompilerCounters* counters = thread->counters();2225counters->set_current_method(current_method);2226counters->set_compile_type((jlong)_last_compile_type);2227}2228}222922302231// ------------------------------------------------------------------2232// CompileBroker::push_jni_handle_block2233//2234// Push on a new block of JNI handles.2235void CompileBroker::push_jni_handle_block() {2236JavaThread* thread = JavaThread::current();22372238// Allocate a new block for JNI handles.2239// Inlined code from jni_PushLocalFrame()2240JNIHandleBlock* java_handles = thread->active_handles();2241JNIHandleBlock* compile_handles = JNIHandleBlock::allocate_block(thread);2242assert(compile_handles != NULL && java_handles != NULL, "should not be NULL");2243compile_handles->set_pop_frame_link(java_handles); // make sure java handles get gc'd.2244thread->set_active_handles(compile_handles);2245}224622472248// ------------------------------------------------------------------2249// CompileBroker::pop_jni_handle_block2250//2251// Pop off the current block of JNI handles.2252void CompileBroker::pop_jni_handle_block() {2253JavaThread* thread = JavaThread::current();22542255// Release our JNI handle block2256JNIHandleBlock* compile_handles = thread->active_handles();2257JNIHandleBlock* java_handles = compile_handles->pop_frame_link();2258thread->set_active_handles(java_handles);2259compile_handles->set_pop_frame_link(NULL);2260JNIHandleBlock::release_block(compile_handles, thread); // may block2261}226222632264// ------------------------------------------------------------------2265// CompileBroker::check_break_at2266//2267// Should the compilation break at the current compilation.2268bool CompileBroker::check_break_at(methodHandle method, int compile_id, bool is_osr) {2269if (CICountOSR && is_osr && (compile_id == CIBreakAtOSR)) {2270return true;2271} else if( CompilerOracle::should_break_at(method) ) { // break when compiling2272return true;2273} else {2274return (compile_id == CIBreakAt);2275}2276}22772278// ------------------------------------------------------------------2279// CompileBroker::collect_statistics2280//2281// Collect statistics about the compilation.22822283void CompileBroker::collect_statistics(CompilerThread* thread, elapsedTimer time, CompileTask* task) {2284bool success = task->is_success();2285methodHandle method (thread, task->method());2286uint compile_id = task->compile_id();2287bool is_osr = (task->osr_bci() != standard_entry_bci);2288nmethod* code = task->code();2289CompilerCounters* counters = thread->counters();22902291assert(code == NULL || code->is_locked_by_vm(), "will survive the MutexLocker");2292MutexLocker locker(CompileStatistics_lock);22932294// _perf variables are production performance counters which are2295// updated regardless of the setting of the CITime and CITimeEach flags2296//2297if (!success) {2298_total_bailout_count++;2299if (UsePerfData) {2300_perf_last_failed_method->set_value(counters->current_method());2301_perf_last_failed_type->set_value(counters->compile_type());2302_perf_total_bailout_count->inc();2303}2304} else if (code == NULL) {2305if (UsePerfData) {2306_perf_last_invalidated_method->set_value(counters->current_method());2307_perf_last_invalidated_type->set_value(counters->compile_type());2308_perf_total_invalidated_count->inc();2309}2310_total_invalidated_count++;2311} else {2312// Compilation succeeded23132314// update compilation ticks - used by the implementation of2315// java.lang.management.CompilationMBean2316_perf_total_compilation->inc(time.ticks());23172318_t_total_compilation.add(time);2319_peak_compilation_time = time.milliseconds() > _peak_compilation_time ? time.milliseconds() : _peak_compilation_time;23202321if (CITime) {2322if (is_osr) {2323_t_osr_compilation.add(time);2324_sum_osr_bytes_compiled += method->code_size() + task->num_inlined_bytecodes();2325} else {2326_t_standard_compilation.add(time);2327_sum_standard_bytes_compiled += method->code_size() + task->num_inlined_bytecodes();2328}2329}23302331if (UsePerfData) {2332// save the name of the last method compiled2333_perf_last_method->set_value(counters->current_method());2334_perf_last_compile_type->set_value(counters->compile_type());2335_perf_last_compile_size->set_value(method->code_size() +2336task->num_inlined_bytecodes());2337if (is_osr) {2338_perf_osr_compilation->inc(time.ticks());2339_perf_sum_osr_bytes_compiled->inc(method->code_size() + task->num_inlined_bytecodes());2340} else {2341_perf_standard_compilation->inc(time.ticks());2342_perf_sum_standard_bytes_compiled->inc(method->code_size() + task->num_inlined_bytecodes());2343}2344}23452346if (CITimeEach) {2347float bytes_per_sec = 1.0 * (method->code_size() + task->num_inlined_bytecodes()) / time.seconds();2348tty->print_cr("%3d seconds: %f bytes/sec : %f (bytes %d + %d inlined)",2349compile_id, time.seconds(), bytes_per_sec, method->code_size(), task->num_inlined_bytecodes());2350}23512352// Collect counts of successful compilations2353_sum_nmethod_size += code->total_size();2354_sum_nmethod_code_size += code->insts_size();2355_total_compile_count++;23562357if (UsePerfData) {2358_perf_sum_nmethod_size->inc( code->total_size());2359_perf_sum_nmethod_code_size->inc(code->insts_size());2360_perf_total_compile_count->inc();2361}23622363if (is_osr) {2364if (UsePerfData) _perf_total_osr_compile_count->inc();2365_total_osr_compile_count++;2366} else {2367if (UsePerfData) _perf_total_standard_compile_count->inc();2368_total_standard_compile_count++;2369}2370}2371// set the current method for the thread to null2372if (UsePerfData) counters->set_current_method("");2373}23742375const char* CompileBroker::compiler_name(int comp_level) {2376AbstractCompiler *comp = CompileBroker::compiler(comp_level);2377if (comp == NULL) {2378return "no compiler";2379} else {2380return (comp->name());2381}2382}23832384void CompileBroker::print_times() {2385tty->cr();2386tty->print_cr("Accumulated compiler times (for compiled methods only)");2387tty->print_cr("------------------------------------------------");2388//00000000001111111111222222222233333333334444444444555555555566666666662389//01234567890123456789012345678901234567890123456789012345678901234567892390tty->print_cr(" Total compilation time : %6.3f s", CompileBroker::_t_total_compilation.seconds());2391tty->print_cr(" Standard compilation : %6.3f s, Average : %2.3f",2392CompileBroker::_t_standard_compilation.seconds(),2393CompileBroker::_t_standard_compilation.seconds() / CompileBroker::_total_standard_compile_count);2394tty->print_cr(" On stack replacement : %6.3f s, Average : %2.3f", CompileBroker::_t_osr_compilation.seconds(), CompileBroker::_t_osr_compilation.seconds() / CompileBroker::_total_osr_compile_count);23952396AbstractCompiler *comp = compiler(CompLevel_simple);2397if (comp != NULL) {2398comp->print_timers();2399}2400comp = compiler(CompLevel_full_optimization);2401if (comp != NULL) {2402comp->print_timers();2403}2404tty->cr();2405tty->print_cr(" Total compiled methods : %6d methods", CompileBroker::_total_compile_count);2406tty->print_cr(" Standard compilation : %6d methods", CompileBroker::_total_standard_compile_count);2407tty->print_cr(" On stack replacement : %6d methods", CompileBroker::_total_osr_compile_count);2408int tcb = CompileBroker::_sum_osr_bytes_compiled + CompileBroker::_sum_standard_bytes_compiled;2409tty->print_cr(" Total compiled bytecodes : %6d bytes", tcb);2410tty->print_cr(" Standard compilation : %6d bytes", CompileBroker::_sum_standard_bytes_compiled);2411tty->print_cr(" On stack replacement : %6d bytes", CompileBroker::_sum_osr_bytes_compiled);2412int bps = (int)(tcb / CompileBroker::_t_total_compilation.seconds());2413tty->print_cr(" Average compilation speed: %6d bytes/s", bps);2414tty->cr();2415tty->print_cr(" nmethod code size : %6d bytes", CompileBroker::_sum_nmethod_code_size);2416tty->print_cr(" nmethod total size : %6d bytes", CompileBroker::_sum_nmethod_size);2417}24182419// Debugging output for failure2420void CompileBroker::print_last_compile() {2421if ( _last_compile_level != CompLevel_none &&2422compiler(_last_compile_level) != NULL &&2423_last_method_compiled != NULL &&2424_last_compile_type != no_compile) {2425if (_last_compile_type == osr_compile) {2426tty->print_cr("Last parse: [osr]%d+++(%d) %s",2427_osr_compilation_id, _last_compile_level, _last_method_compiled);2428} else {2429tty->print_cr("Last parse: %d+++(%d) %s",2430_compilation_id, _last_compile_level, _last_method_compiled);2431}2432}2433}243424352436void CompileBroker::print_compiler_threads_on(outputStream* st) {2437#ifndef PRODUCT2438st->print_cr("Compiler thread printing unimplemented.");2439st->cr();2440#endif2441}244224432444