src/share/vm/compiler/compileBroker.cpp

Wed, 01 Feb 2012 07:59:01 -0800

author
never
date
Wed, 01 Feb 2012 07:59:01 -0800
changeset 3499
aa3d708d67c4
parent 3452
20334ed5ed3c
child 3502
379b22e03c32
permissions
-rw-r--r--

7141200: log some interesting information in ring buffers for crashes
Reviewed-by: kvn, jrose, kevinw, brutisso, twisti, jmasa

     1 /*
     2  * Copyright (c) 1999, 2012, Oracle and/or its affiliates. All rights reserved.
     3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
     4  *
     5  * This code is free software; you can redistribute it and/or modify it
     6  * under the terms of the GNU General Public License version 2 only, as
     7  * published by the Free Software Foundation.
     8  *
     9  * This code is distributed in the hope that it will be useful, but WITHOUT
    10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
    11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
    12  * version 2 for more details (a copy is included in the LICENSE file that
    13  * accompanied this code).
    14  *
    15  * You should have received a copy of the GNU General Public License version
    16  * 2 along with this work; if not, write to the Free Software Foundation,
    17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
    18  *
    19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
    20  * or visit www.oracle.com if you need additional information or have any
    21  * questions.
    22  *
    23  */
    25 #include "precompiled.hpp"
    26 #include "classfile/systemDictionary.hpp"
    27 #include "classfile/vmSymbols.hpp"
    28 #include "code/codeCache.hpp"
    29 #include "compiler/compileBroker.hpp"
    30 #include "compiler/compileLog.hpp"
    31 #include "compiler/compilerOracle.hpp"
    32 #include "interpreter/linkResolver.hpp"
    33 #include "memory/allocation.inline.hpp"
    34 #include "oops/methodDataOop.hpp"
    35 #include "oops/methodOop.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 COMPILER1
    49 #include "c1/c1_Compiler.hpp"
    50 #endif
    51 #ifdef COMPILER2
    52 #include "opto/c2compiler.hpp"
    53 #endif
    54 #ifdef SHARK
    55 #include "shark/sharkCompiler.hpp"
    56 #endif
    58 #ifdef DTRACE_ENABLED
    60 // Only bother with this argument setup if dtrace is available
    62 #ifndef USDT2
    63 HS_DTRACE_PROBE_DECL8(hotspot, method__compile__begin,
    64   char*, intptr_t, char*, intptr_t, char*, intptr_t, char*, intptr_t);
    65 HS_DTRACE_PROBE_DECL9(hotspot, method__compile__end,
    66   char*, intptr_t, char*, intptr_t, char*, intptr_t, char*, intptr_t, bool);
    68 #define DTRACE_METHOD_COMPILE_BEGIN_PROBE(compiler, method)              \
    69   {                                                                      \
    70     char* comp_name = (char*)(compiler)->name();                         \
    71     Symbol* klass_name = (method)->klass_name();                         \
    72     Symbol* name = (method)->name();                                     \
    73     Symbol* signature = (method)->signature();                           \
    74     HS_DTRACE_PROBE8(hotspot, method__compile__begin,                    \
    75       comp_name, strlen(comp_name),                                      \
    76       klass_name->bytes(), klass_name->utf8_length(),                    \
    77       name->bytes(), name->utf8_length(),                                \
    78       signature->bytes(), signature->utf8_length());                     \
    79   }
    81 #define DTRACE_METHOD_COMPILE_END_PROBE(compiler, method, success)       \
    82   {                                                                      \
    83     char* comp_name = (char*)(compiler)->name();                         \
    84     Symbol* klass_name = (method)->klass_name();                         \
    85     Symbol* name = (method)->name();                                     \
    86     Symbol* signature = (method)->signature();                           \
    87     HS_DTRACE_PROBE9(hotspot, method__compile__end,                      \
    88       comp_name, strlen(comp_name),                                      \
    89       klass_name->bytes(), klass_name->utf8_length(),                    \
    90       name->bytes(), name->utf8_length(),                                \
    91       signature->bytes(), signature->utf8_length(), (success));          \
    92   }
    94 #else /* USDT2 */
    96 #define DTRACE_METHOD_COMPILE_BEGIN_PROBE(compiler, method)              \
    97   {                                                                      \
    98     char* comp_name = (char*)(compiler)->name();                         \
    99     Symbol* klass_name = (method)->klass_name();                         \
   100     Symbol* name = (method)->name();                                     \
   101     Symbol* signature = (method)->signature();                           \
   102     HOTSPOT_METHOD_COMPILE_BEGIN(                                       \
   103       comp_name, strlen(comp_name),                                      \
   104       (char *) klass_name->bytes(), klass_name->utf8_length(),          \
   105       (char *) name->bytes(), name->utf8_length(),                       \
   106       (char *) signature->bytes(), signature->utf8_length());            \
   107   }
   109 #define DTRACE_METHOD_COMPILE_END_PROBE(compiler, method, success)       \
   110   {                                                                      \
   111     char* comp_name = (char*)(compiler)->name();                         \
   112     Symbol* klass_name = (method)->klass_name();                         \
   113     Symbol* name = (method)->name();                                     \
   114     Symbol* signature = (method)->signature();                           \
   115     HOTSPOT_METHOD_COMPILE_END(                                          \
   116       comp_name, strlen(comp_name),                                      \
   117       (char *) klass_name->bytes(), klass_name->utf8_length(),           \
   118       (char *) name->bytes(), name->utf8_length(),                       \
   119       (char *) signature->bytes(), signature->utf8_length(), (success)); \
   120   }
   121 #endif /* USDT2 */
   123 #else //  ndef DTRACE_ENABLED
   125 #define DTRACE_METHOD_COMPILE_BEGIN_PROBE(compiler, method)
   126 #define DTRACE_METHOD_COMPILE_END_PROBE(compiler, method, success)
   128 #endif // ndef DTRACE_ENABLED
   130 bool CompileBroker::_initialized = false;
   131 volatile bool CompileBroker::_should_block = false;
   132 volatile jint CompileBroker::_should_compile_new_jobs = run_compilation;
   134 // The installed compiler(s)
   135 AbstractCompiler* CompileBroker::_compilers[2];
   137 // These counters are used for assigning id's to each compilation
   138 uint CompileBroker::_compilation_id        = 0;
   139 uint CompileBroker::_osr_compilation_id    = 0;
   141 // Debugging information
   142 int  CompileBroker::_last_compile_type     = no_compile;
   143 int  CompileBroker::_last_compile_level    = CompLevel_none;
   144 char CompileBroker::_last_method_compiled[CompileBroker::name_buffer_length];
   146 // Performance counters
   147 PerfCounter* CompileBroker::_perf_total_compilation = NULL;
   148 PerfCounter* CompileBroker::_perf_osr_compilation = NULL;
   149 PerfCounter* CompileBroker::_perf_standard_compilation = NULL;
   151 PerfCounter* CompileBroker::_perf_total_bailout_count = NULL;
   152 PerfCounter* CompileBroker::_perf_total_invalidated_count = NULL;
   153 PerfCounter* CompileBroker::_perf_total_compile_count = NULL;
   154 PerfCounter* CompileBroker::_perf_total_osr_compile_count = NULL;
   155 PerfCounter* CompileBroker::_perf_total_standard_compile_count = NULL;
   157 PerfCounter* CompileBroker::_perf_sum_osr_bytes_compiled = NULL;
   158 PerfCounter* CompileBroker::_perf_sum_standard_bytes_compiled = NULL;
   159 PerfCounter* CompileBroker::_perf_sum_nmethod_size = NULL;
   160 PerfCounter* CompileBroker::_perf_sum_nmethod_code_size = NULL;
   162 PerfStringVariable* CompileBroker::_perf_last_method = NULL;
   163 PerfStringVariable* CompileBroker::_perf_last_failed_method = NULL;
   164 PerfStringVariable* CompileBroker::_perf_last_invalidated_method = NULL;
   165 PerfVariable*       CompileBroker::_perf_last_compile_type = NULL;
   166 PerfVariable*       CompileBroker::_perf_last_compile_size = NULL;
   167 PerfVariable*       CompileBroker::_perf_last_failed_type = NULL;
   168 PerfVariable*       CompileBroker::_perf_last_invalidated_type = NULL;
   170 // Timers and counters for generating statistics
   171 elapsedTimer CompileBroker::_t_total_compilation;
   172 elapsedTimer CompileBroker::_t_osr_compilation;
   173 elapsedTimer CompileBroker::_t_standard_compilation;
   175 int CompileBroker::_total_bailout_count          = 0;
   176 int CompileBroker::_total_invalidated_count      = 0;
   177 int CompileBroker::_total_compile_count          = 0;
   178 int CompileBroker::_total_osr_compile_count      = 0;
   179 int CompileBroker::_total_standard_compile_count = 0;
   181 int CompileBroker::_sum_osr_bytes_compiled       = 0;
   182 int CompileBroker::_sum_standard_bytes_compiled  = 0;
   183 int CompileBroker::_sum_nmethod_size             = 0;
   184 int CompileBroker::_sum_nmethod_code_size        = 0;
   186 CompileQueue* CompileBroker::_c2_method_queue   = NULL;
   187 CompileQueue* CompileBroker::_c1_method_queue   = NULL;
   188 CompileTask*  CompileBroker::_task_free_list = NULL;
   190 GrowableArray<CompilerThread*>* CompileBroker::_method_threads = NULL;
   193 class CompilationLog : public StringEventLog {
   194  public:
   195   CompilationLog() : StringEventLog("Compilation events") {
   196   }
   198   void log_compile(JavaThread* thread, CompileTask* task) {
   199     StringLogMessage lm;
   200     stringStream msg = lm.stream();
   201     // msg.time_stamp().update_to(tty->time_stamp().ticks());
   202     task->print_compilation(&msg, true);
   203     log(thread, "%s", (const char*)lm);
   204   }
   206   void log_nmethod(JavaThread* thread, nmethod* nm) {
   207     log(thread, "nmethod " INTPTR_FORMAT " code ["INTPTR_FORMAT ", " INTPTR_FORMAT "]",
   208         nm, nm->code_begin(), nm->code_end());
   209   }
   211   void log_failure(JavaThread* thread, CompileTask* task, const char* reason, const char* retry_message) {
   212     StringLogMessage lm;
   213     lm.print("%4d   COMPILE SKIPPED: %s", task->compile_id(), reason);
   214     if (retry_message != NULL) {
   215       lm.append(" (%s)", retry_message);
   216     }
   217     lm.print("\n");
   218     log(thread, "%s", (const char*)lm);
   219   }
   220 };
   222 static CompilationLog* _compilation_log = NULL;
   224 void compileBroker_init() {
   225   if (LogEvents) {
   226     _compilation_log = new CompilationLog();
   227   }
   228 }
   230 CompileTaskWrapper::CompileTaskWrapper(CompileTask* task) {
   231   CompilerThread* thread = CompilerThread::current();
   232   thread->set_task(task);
   233   CompileLog*     log  = thread->log();
   234   if (log != NULL)  task->log_task_start(log);
   235 }
   237 CompileTaskWrapper::~CompileTaskWrapper() {
   238   CompilerThread* thread = CompilerThread::current();
   239   CompileTask* task = thread->task();
   240   CompileLog*  log  = thread->log();
   241   if (log != NULL)  task->log_task_done(log);
   242   thread->set_task(NULL);
   243   task->set_code_handle(NULL);
   244   DEBUG_ONLY(thread->set_env((ciEnv*)badAddress));
   245   if (task->is_blocking()) {
   246     MutexLocker notifier(task->lock(), thread);
   247     task->mark_complete();
   248     // Notify the waiting thread that the compilation has completed.
   249     task->lock()->notify_all();
   250   } else {
   251     task->mark_complete();
   253     // By convention, the compiling thread is responsible for
   254     // recycling a non-blocking CompileTask.
   255     CompileBroker::free_task(task);
   256   }
   257 }
   260 // ------------------------------------------------------------------
   261 // CompileTask::initialize
   262 void CompileTask::initialize(int compile_id,
   263                              methodHandle method,
   264                              int osr_bci,
   265                              int comp_level,
   266                              methodHandle hot_method,
   267                              int hot_count,
   268                              const char* comment,
   269                              bool is_blocking) {
   270   assert(!_lock->is_locked(), "bad locking");
   272   _compile_id = compile_id;
   273   _method = JNIHandles::make_global(method);
   274   _osr_bci = osr_bci;
   275   _is_blocking = is_blocking;
   276   _comp_level = comp_level;
   277   _num_inlined_bytecodes = 0;
   279   _is_complete = false;
   280   _is_success = false;
   281   _code_handle = NULL;
   283   _hot_method = NULL;
   284   _hot_count = hot_count;
   285   _time_queued = 0;  // tidy
   286   _comment = comment;
   288   if (LogCompilation) {
   289     _time_queued = os::elapsed_counter();
   290     if (hot_method.not_null()) {
   291       if (hot_method == method) {
   292         _hot_method = _method;
   293       } else {
   294         _hot_method = JNIHandles::make_global(hot_method);
   295       }
   296     }
   297   }
   299   _next = NULL;
   300 }
   302 // ------------------------------------------------------------------
   303 // CompileTask::code/set_code
   304 nmethod* CompileTask::code() const {
   305   if (_code_handle == NULL)  return NULL;
   306   return _code_handle->code();
   307 }
   308 void CompileTask::set_code(nmethod* nm) {
   309   if (_code_handle == NULL && nm == NULL)  return;
   310   guarantee(_code_handle != NULL, "");
   311   _code_handle->set_code(nm);
   312   if (nm == NULL)  _code_handle = NULL;  // drop the handle also
   313 }
   315 // ------------------------------------------------------------------
   316 // CompileTask::free
   317 void CompileTask::free() {
   318   set_code(NULL);
   319   assert(!_lock->is_locked(), "Should not be locked when freed");
   320   if (_hot_method != NULL && _hot_method != _method) {
   321     JNIHandles::destroy_global(_hot_method);
   322   }
   323   JNIHandles::destroy_global(_method);
   324 }
   327 // ------------------------------------------------------------------
   328 // CompileTask::print
   329 void CompileTask::print() {
   330   tty->print("<CompileTask compile_id=%d ", _compile_id);
   331   tty->print("method=");
   332   ((methodOop)JNIHandles::resolve(_method))->print_name(tty);
   333   tty->print_cr(" osr_bci=%d is_blocking=%s is_complete=%s is_success=%s>",
   334              _osr_bci, bool_to_str(_is_blocking),
   335              bool_to_str(_is_complete), bool_to_str(_is_success));
   336 }
   339 // ------------------------------------------------------------------
   340 // CompileTask::print_line_on_error
   341 //
   342 // This function is called by fatal error handler when the thread
   343 // causing troubles is a compiler thread.
   344 //
   345 // Do not grab any lock, do not allocate memory.
   346 //
   347 // Otherwise it's the same as CompileTask::print_line()
   348 //
   349 void CompileTask::print_line_on_error(outputStream* st, char* buf, int buflen) {
   350   // print compiler name
   351   st->print("%s:", CompileBroker::compiler(comp_level())->name());
   352   print_compilation(st);
   353 }
   355 // ------------------------------------------------------------------
   356 // CompileTask::print_line
   357 void CompileTask::print_line() {
   358   ttyLocker ttyl;  // keep the following output all in one block
   359   // print compiler name if requested
   360   if (CIPrintCompilerName) tty->print("%s:", CompileBroker::compiler(comp_level())->name());
   361   print_compilation();
   362 }
   365 // ------------------------------------------------------------------
   366 // CompileTask::print_compilation_impl
   367 void CompileTask::print_compilation_impl(outputStream* st, methodOop method, int compile_id, int comp_level,
   368                                          bool is_osr_method, int osr_bci, bool is_blocking,
   369                                          const char* msg, bool short_form) {
   370   if (!short_form) {
   371     st->print("%7d ", (int) st->time_stamp().milliseconds());  // print timestamp
   372   }
   373   st->print("%4d ", compile_id);    // print compilation number
   375   // For unloaded methods the transition to zombie occurs after the
   376   // method is cleared so it's impossible to report accurate
   377   // information for that case.
   378   bool is_synchronized = false;
   379   bool has_exception_handler = false;
   380   bool is_native = false;
   381   if (method != NULL) {
   382     is_synchronized       = method->is_synchronized();
   383     has_exception_handler = method->has_exception_handler();
   384     is_native             = method->is_native();
   385   }
   386   // method attributes
   387   const char compile_type   = is_osr_method                   ? '%' : ' ';
   388   const char sync_char      = is_synchronized                 ? 's' : ' ';
   389   const char exception_char = has_exception_handler           ? '!' : ' ';
   390   const char blocking_char  = is_blocking                     ? 'b' : ' ';
   391   const char native_char    = is_native                       ? 'n' : ' ';
   393   // print method attributes
   394   st->print("%c%c%c%c%c ", compile_type, sync_char, exception_char, blocking_char, native_char);
   396   if (TieredCompilation) {
   397     if (comp_level != -1)  st->print("%d ", comp_level);
   398     else                   st->print("- ");
   399   }
   400   st->print("     ");  // more indent
   402   if (method == NULL) {
   403     st->print("(method)");
   404   } else {
   405     method->print_short_name(st);
   406     if (is_osr_method) {
   407       st->print(" @ %d", osr_bci);
   408     }
   409     st->print(" (%d bytes)", method->code_size());
   410   }
   412   if (msg != NULL) {
   413     st->print("   %s", msg);
   414   }
   415   if (!short_form) {
   416     st->cr();
   417   }
   418 }
   420 // ------------------------------------------------------------------
   421 // CompileTask::print_inlining
   422 void CompileTask::print_inlining(outputStream* st, ciMethod* method, int inline_level, int bci, const char* msg) {
   423   //         1234567
   424   st->print("        ");     // print timestamp
   425   //         1234
   426   st->print("     ");        // print compilation number
   428   // method attributes
   429   const char sync_char      = method->is_synchronized()        ? 's' : ' ';
   430   const char exception_char = method->has_exception_handlers() ? '!' : ' ';
   431   const char monitors_char  = method->has_monitor_bytecodes()  ? 'm' : ' ';
   433   // print method attributes
   434   st->print(" %c%c%c  ", sync_char, exception_char, monitors_char);
   436   if (TieredCompilation) {
   437     st->print("  ");
   438   }
   439   st->print("     ");        // more indent
   440   st->print("    ");         // initial inlining indent
   442   for (int i = 0; i < inline_level; i++)  st->print("  ");
   444   st->print("@ %d  ", bci);  // print bci
   445   method->print_short_name(st);
   446   st->print(" (%d bytes)", method->code_size());
   448   if (msg != NULL) {
   449     st->print("   %s", msg);
   450   }
   451   st->cr();
   452 }
   454 // ------------------------------------------------------------------
   455 // CompileTask::print_inline_indent
   456 void CompileTask::print_inline_indent(int inline_level, outputStream* st) {
   457   //         1234567
   458   st->print("        ");     // print timestamp
   459   //         1234
   460   st->print("     ");        // print compilation number
   461   //         %s!bn
   462   st->print("      ");       // print method attributes
   463   if (TieredCompilation) {
   464     st->print("  ");
   465   }
   466   st->print("     ");        // more indent
   467   st->print("    ");         // initial inlining indent
   468   for (int i = 0; i < inline_level; i++)  st->print("  ");
   469 }
   471 // ------------------------------------------------------------------
   472 // CompileTask::print_compilation
   473 void CompileTask::print_compilation(outputStream* st, bool short_form) {
   474   oop rem = JNIHandles::resolve(method_handle());
   475   assert(rem != NULL && rem->is_method(), "must be");
   476   methodOop method = (methodOop) rem;
   477   bool is_osr_method = osr_bci() != InvocationEntryBci;
   478   print_compilation_impl(st, method, compile_id(), comp_level(), is_osr_method, osr_bci(), is_blocking(), NULL, short_form);
   479 }
   481 // ------------------------------------------------------------------
   482 // CompileTask::log_task
   483 void CompileTask::log_task(xmlStream* log) {
   484   Thread* thread = Thread::current();
   485   methodHandle method(thread,
   486                       (methodOop)JNIHandles::resolve(method_handle()));
   487   ResourceMark rm(thread);
   489   // <task id='9' method='M' osr_bci='X' level='1' blocking='1' stamp='1.234'>
   490   if (_compile_id != 0)   log->print(" compile_id='%d'", _compile_id);
   491   if (_osr_bci != CompileBroker::standard_entry_bci) {
   492     log->print(" compile_kind='osr'");  // same as nmethod::compile_kind
   493   } // else compile_kind='c2c'
   494   if (!method.is_null())  log->method(method);
   495   if (_osr_bci != CompileBroker::standard_entry_bci) {
   496     log->print(" osr_bci='%d'", _osr_bci);
   497   }
   498   if (_comp_level != CompLevel_highest_tier) {
   499     log->print(" level='%d'", _comp_level);
   500   }
   501   if (_is_blocking) {
   502     log->print(" blocking='1'");
   503   }
   504   log->stamp();
   505 }
   508 // ------------------------------------------------------------------
   509 // CompileTask::log_task_queued
   510 void CompileTask::log_task_queued() {
   511   Thread* thread = Thread::current();
   512   ttyLocker ttyl;
   513   ResourceMark rm(thread);
   515   xtty->begin_elem("task_queued");
   516   log_task(xtty);
   517   if (_comment != NULL) {
   518     xtty->print(" comment='%s'", _comment);
   519   }
   520   if (_hot_method != NULL) {
   521     methodHandle hot(thread,
   522                      (methodOop)JNIHandles::resolve(_hot_method));
   523     methodHandle method(thread,
   524                         (methodOop)JNIHandles::resolve(_method));
   525     if (hot() != method()) {
   526       xtty->method(hot);
   527     }
   528   }
   529   if (_hot_count != 0) {
   530     xtty->print(" hot_count='%d'", _hot_count);
   531   }
   532   xtty->end_elem();
   533 }
   536 // ------------------------------------------------------------------
   537 // CompileTask::log_task_start
   538 void CompileTask::log_task_start(CompileLog* log)   {
   539   log->begin_head("task");
   540   log_task(log);
   541   log->end_head();
   542 }
   545 // ------------------------------------------------------------------
   546 // CompileTask::log_task_done
   547 void CompileTask::log_task_done(CompileLog* log) {
   548   Thread* thread = Thread::current();
   549   methodHandle method(thread,
   550                       (methodOop)JNIHandles::resolve(method_handle()));
   551   ResourceMark rm(thread);
   553   // <task_done ... stamp='1.234'>  </task>
   554   nmethod* nm = code();
   555   log->begin_elem("task_done success='%d' nmsize='%d' count='%d'",
   556                   _is_success, nm == NULL ? 0 : nm->content_size(),
   557                   method->invocation_count());
   558   int bec = method->backedge_count();
   559   if (bec != 0)  log->print(" backedge_count='%d'", bec);
   560   // Note:  "_is_complete" is about to be set, but is not.
   561   if (_num_inlined_bytecodes != 0) {
   562     log->print(" inlined_bytes='%d'", _num_inlined_bytecodes);
   563   }
   564   log->stamp();
   565   log->end_elem();
   566   log->tail("task");
   567   log->clear_identities();   // next task will have different CI
   568   if (log->unflushed_count() > 2000) {
   569     log->flush();
   570   }
   571   log->mark_file_end();
   572 }
   576 // ------------------------------------------------------------------
   577 // CompileQueue::add
   578 //
   579 // Add a CompileTask to a CompileQueue
   580 void CompileQueue::add(CompileTask* task) {
   581   assert(lock()->owned_by_self(), "must own lock");
   583   task->set_next(NULL);
   584   task->set_prev(NULL);
   586   if (_last == NULL) {
   587     // The compile queue is empty.
   588     assert(_first == NULL, "queue is empty");
   589     _first = task;
   590     _last = task;
   591   } else {
   592     // Append the task to the queue.
   593     assert(_last->next() == NULL, "not last");
   594     _last->set_next(task);
   595     task->set_prev(_last);
   596     _last = task;
   597   }
   598   ++_size;
   600   // Mark the method as being in the compile queue.
   601   ((methodOop)JNIHandles::resolve(task->method_handle()))->set_queued_for_compilation();
   603   if (CIPrintCompileQueue) {
   604     print();
   605   }
   607   if (LogCompilation && xtty != NULL) {
   608     task->log_task_queued();
   609   }
   611   // Notify CompilerThreads that a task is available.
   612   lock()->notify_all();
   613 }
   615 // ------------------------------------------------------------------
   616 // CompileQueue::get
   617 //
   618 // Get the next CompileTask from a CompileQueue
   619 CompileTask* CompileQueue::get() {
   620   NMethodSweeper::possibly_sweep();
   622   MutexLocker locker(lock());
   623   // Wait for an available CompileTask.
   624   while (_first == NULL) {
   625     // There is no work to be done right now.  Wait.
   626     if (UseCodeCacheFlushing && (!CompileBroker::should_compile_new_jobs() || CodeCache::needs_flushing())) {
   627       // During the emergency sweeping periods, wake up and sweep occasionally
   628       bool timedout = lock()->wait(!Mutex::_no_safepoint_check_flag, NmethodSweepCheckInterval*1000);
   629       if (timedout) {
   630         MutexUnlocker ul(lock());
   631         // When otherwise not busy, run nmethod sweeping
   632         NMethodSweeper::possibly_sweep();
   633       }
   634     } else {
   635       // During normal operation no need to wake up on timer
   636       lock()->wait();
   637     }
   638   }
   639   CompileTask* task = CompilationPolicy::policy()->select_task(this);
   640   remove(task);
   641   return task;
   642 }
   644 void CompileQueue::remove(CompileTask* task)
   645 {
   646    assert(lock()->owned_by_self(), "must own lock");
   647   if (task->prev() != NULL) {
   648     task->prev()->set_next(task->next());
   649   } else {
   650     // max is the first element
   651     assert(task == _first, "Sanity");
   652     _first = task->next();
   653   }
   655   if (task->next() != NULL) {
   656     task->next()->set_prev(task->prev());
   657   } else {
   658     // max is the last element
   659     assert(task == _last, "Sanity");
   660     _last = task->prev();
   661   }
   662   --_size;
   663 }
   665 // ------------------------------------------------------------------
   666 // CompileQueue::print
   667 void CompileQueue::print() {
   668   tty->print_cr("Contents of %s", name());
   669   tty->print_cr("----------------------");
   670   CompileTask* task = _first;
   671   while (task != NULL) {
   672     task->print_line();
   673     task = task->next();
   674   }
   675   tty->print_cr("----------------------");
   676 }
   678 CompilerCounters::CompilerCounters(const char* thread_name, int instance, TRAPS) {
   680   _current_method[0] = '\0';
   681   _compile_type = CompileBroker::no_compile;
   683   if (UsePerfData) {
   684     ResourceMark rm;
   686     // create the thread instance name space string - don't create an
   687     // instance subspace if instance is -1 - keeps the adapterThread
   688     // counters  from having a ".0" namespace.
   689     const char* thread_i = (instance == -1) ? thread_name :
   690                       PerfDataManager::name_space(thread_name, instance);
   693     char* name = PerfDataManager::counter_name(thread_i, "method");
   694     _perf_current_method =
   695                PerfDataManager::create_string_variable(SUN_CI, name,
   696                                                        cmname_buffer_length,
   697                                                        _current_method, CHECK);
   699     name = PerfDataManager::counter_name(thread_i, "type");
   700     _perf_compile_type = PerfDataManager::create_variable(SUN_CI, name,
   701                                                           PerfData::U_None,
   702                                                          (jlong)_compile_type,
   703                                                           CHECK);
   705     name = PerfDataManager::counter_name(thread_i, "time");
   706     _perf_time = PerfDataManager::create_counter(SUN_CI, name,
   707                                                  PerfData::U_Ticks, CHECK);
   709     name = PerfDataManager::counter_name(thread_i, "compiles");
   710     _perf_compiles = PerfDataManager::create_counter(SUN_CI, name,
   711                                                      PerfData::U_Events, CHECK);
   712   }
   713 }
   715 // ------------------------------------------------------------------
   716 // CompileBroker::compilation_init
   717 //
   718 // Initialize the Compilation object
   719 void CompileBroker::compilation_init() {
   720   _last_method_compiled[0] = '\0';
   722 #ifndef SHARK
   723   // Set the interface to the current compiler(s).
   724   int c1_count = CompilationPolicy::policy()->compiler_count(CompLevel_simple);
   725   int c2_count = CompilationPolicy::policy()->compiler_count(CompLevel_full_optimization);
   726 #ifdef COMPILER1
   727   if (c1_count > 0) {
   728     _compilers[0] = new Compiler();
   729   }
   730 #endif // COMPILER1
   732 #ifdef COMPILER2
   733   if (c2_count > 0) {
   734     _compilers[1] = new C2Compiler();
   735   }
   736 #endif // COMPILER2
   738 #else // SHARK
   739   int c1_count = 0;
   740   int c2_count = 1;
   742   _compilers[1] = new SharkCompiler();
   743 #endif // SHARK
   745   // Initialize the CompileTask free list
   746   _task_free_list = NULL;
   748   // Start the CompilerThreads
   749   init_compiler_threads(c1_count, c2_count);
   750   // totalTime performance counter is always created as it is required
   751   // by the implementation of java.lang.management.CompilationMBean.
   752   {
   753     EXCEPTION_MARK;
   754     _perf_total_compilation =
   755                  PerfDataManager::create_counter(JAVA_CI, "totalTime",
   756                                                  PerfData::U_Ticks, CHECK);
   757   }
   760   if (UsePerfData) {
   762     EXCEPTION_MARK;
   764     // create the jvmstat performance counters
   765     _perf_osr_compilation =
   766                  PerfDataManager::create_counter(SUN_CI, "osrTime",
   767                                                  PerfData::U_Ticks, CHECK);
   769     _perf_standard_compilation =
   770                  PerfDataManager::create_counter(SUN_CI, "standardTime",
   771                                                  PerfData::U_Ticks, CHECK);
   773     _perf_total_bailout_count =
   774                  PerfDataManager::create_counter(SUN_CI, "totalBailouts",
   775                                                  PerfData::U_Events, CHECK);
   777     _perf_total_invalidated_count =
   778                  PerfDataManager::create_counter(SUN_CI, "totalInvalidates",
   779                                                  PerfData::U_Events, CHECK);
   781     _perf_total_compile_count =
   782                  PerfDataManager::create_counter(SUN_CI, "totalCompiles",
   783                                                  PerfData::U_Events, CHECK);
   784     _perf_total_osr_compile_count =
   785                  PerfDataManager::create_counter(SUN_CI, "osrCompiles",
   786                                                  PerfData::U_Events, CHECK);
   788     _perf_total_standard_compile_count =
   789                  PerfDataManager::create_counter(SUN_CI, "standardCompiles",
   790                                                  PerfData::U_Events, CHECK);
   792     _perf_sum_osr_bytes_compiled =
   793                  PerfDataManager::create_counter(SUN_CI, "osrBytes",
   794                                                  PerfData::U_Bytes, CHECK);
   796     _perf_sum_standard_bytes_compiled =
   797                  PerfDataManager::create_counter(SUN_CI, "standardBytes",
   798                                                  PerfData::U_Bytes, CHECK);
   800     _perf_sum_nmethod_size =
   801                  PerfDataManager::create_counter(SUN_CI, "nmethodSize",
   802                                                  PerfData::U_Bytes, CHECK);
   804     _perf_sum_nmethod_code_size =
   805                  PerfDataManager::create_counter(SUN_CI, "nmethodCodeSize",
   806                                                  PerfData::U_Bytes, CHECK);
   808     _perf_last_method =
   809                  PerfDataManager::create_string_variable(SUN_CI, "lastMethod",
   810                                        CompilerCounters::cmname_buffer_length,
   811                                        "", CHECK);
   813     _perf_last_failed_method =
   814             PerfDataManager::create_string_variable(SUN_CI, "lastFailedMethod",
   815                                        CompilerCounters::cmname_buffer_length,
   816                                        "", CHECK);
   818     _perf_last_invalidated_method =
   819         PerfDataManager::create_string_variable(SUN_CI, "lastInvalidatedMethod",
   820                                      CompilerCounters::cmname_buffer_length,
   821                                      "", CHECK);
   823     _perf_last_compile_type =
   824              PerfDataManager::create_variable(SUN_CI, "lastType",
   825                                               PerfData::U_None,
   826                                               (jlong)CompileBroker::no_compile,
   827                                               CHECK);
   829     _perf_last_compile_size =
   830              PerfDataManager::create_variable(SUN_CI, "lastSize",
   831                                               PerfData::U_Bytes,
   832                                               (jlong)CompileBroker::no_compile,
   833                                               CHECK);
   836     _perf_last_failed_type =
   837              PerfDataManager::create_variable(SUN_CI, "lastFailedType",
   838                                               PerfData::U_None,
   839                                               (jlong)CompileBroker::no_compile,
   840                                               CHECK);
   842     _perf_last_invalidated_type =
   843          PerfDataManager::create_variable(SUN_CI, "lastInvalidatedType",
   844                                           PerfData::U_None,
   845                                           (jlong)CompileBroker::no_compile,
   846                                           CHECK);
   847   }
   849   _initialized = true;
   850 }
   854 // ------------------------------------------------------------------
   855 // CompileBroker::make_compiler_thread
   856 CompilerThread* CompileBroker::make_compiler_thread(const char* name, CompileQueue* queue, CompilerCounters* counters, TRAPS) {
   857   CompilerThread* compiler_thread = NULL;
   859   klassOop k =
   860     SystemDictionary::resolve_or_fail(vmSymbols::java_lang_Thread(),
   861                                       true, CHECK_0);
   862   instanceKlassHandle klass (THREAD, k);
   863   instanceHandle thread_oop = klass->allocate_instance_handle(CHECK_0);
   864   Handle string = java_lang_String::create_from_str(name, CHECK_0);
   866   // Initialize thread_oop to put it into the system threadGroup
   867   Handle thread_group (THREAD,  Universe::system_thread_group());
   868   JavaValue result(T_VOID);
   869   JavaCalls::call_special(&result, thread_oop,
   870                        klass,
   871                        vmSymbols::object_initializer_name(),
   872                        vmSymbols::threadgroup_string_void_signature(),
   873                        thread_group,
   874                        string,
   875                        CHECK_0);
   877   {
   878     MutexLocker mu(Threads_lock, THREAD);
   879     compiler_thread = new CompilerThread(queue, counters);
   880     // At this point the new CompilerThread data-races with this startup
   881     // thread (which I believe is the primoridal thread and NOT the VM
   882     // thread).  This means Java bytecodes being executed at startup can
   883     // queue compile jobs which will run at whatever default priority the
   884     // newly created CompilerThread runs at.
   887     // At this point it may be possible that no osthread was created for the
   888     // JavaThread due to lack of memory. We would have to throw an exception
   889     // in that case. However, since this must work and we do not allow
   890     // exceptions anyway, check and abort if this fails.
   892     if (compiler_thread == NULL || compiler_thread->osthread() == NULL){
   893       vm_exit_during_initialization("java.lang.OutOfMemoryError",
   894                                     "unable to create new native thread");
   895     }
   897     java_lang_Thread::set_thread(thread_oop(), compiler_thread);
   899     // Note that this only sets the JavaThread _priority field, which by
   900     // definition is limited to Java priorities and not OS priorities.
   901     // The os-priority is set in the CompilerThread startup code itself
   902     java_lang_Thread::set_priority(thread_oop(), NearMaxPriority);
   903     // CLEANUP PRIORITIES: This -if- statement hids a bug whereby the compiler
   904     // threads never have their OS priority set.  The assumption here is to
   905     // enable the Performance group to do flag tuning, figure out a suitable
   906     // CompilerThreadPriority, and then remove this 'if' statement (and
   907     // comment) and unconditionally set the priority.
   909     // Compiler Threads should be at the highest Priority
   910     if ( CompilerThreadPriority != -1 )
   911       os::set_native_priority( compiler_thread, CompilerThreadPriority );
   912     else
   913       os::set_native_priority( compiler_thread, os::java_to_os_priority[NearMaxPriority]);
   915       // Note that I cannot call os::set_priority because it expects Java
   916       // priorities and I am *explicitly* using OS priorities so that it's
   917       // possible to set the compiler thread priority higher than any Java
   918       // thread.
   920     java_lang_Thread::set_daemon(thread_oop());
   922     compiler_thread->set_threadObj(thread_oop());
   923     Threads::add(compiler_thread);
   924     Thread::start(compiler_thread);
   925   }
   926   // Let go of Threads_lock before yielding
   927   os::yield(); // make sure that the compiler thread is started early (especially helpful on SOLARIS)
   929   return compiler_thread;
   930 }
   933 // ------------------------------------------------------------------
   934 // CompileBroker::init_compiler_threads
   935 //
   936 // Initialize the compilation queue
   937 void CompileBroker::init_compiler_threads(int c1_compiler_count, int c2_compiler_count) {
   938   EXCEPTION_MARK;
   939 #if !defined(ZERO) && !defined(SHARK)
   940   assert(c2_compiler_count > 0 || c1_compiler_count > 0, "No compilers?");
   941 #endif // !ZERO && !SHARK
   942   if (c2_compiler_count > 0) {
   943     _c2_method_queue  = new CompileQueue("C2MethodQueue",  MethodCompileQueue_lock);
   944   }
   945   if (c1_compiler_count > 0) {
   946     _c1_method_queue  = new CompileQueue("C1MethodQueue",  MethodCompileQueue_lock);
   947   }
   949   int compiler_count = c1_compiler_count + c2_compiler_count;
   951   _method_threads =
   952     new (ResourceObj::C_HEAP) GrowableArray<CompilerThread*>(compiler_count, true);
   954   char name_buffer[256];
   955   for (int i = 0; i < c2_compiler_count; i++) {
   956     // Create a name for our thread.
   957     sprintf(name_buffer, "C2 CompilerThread%d", i);
   958     CompilerCounters* counters = new CompilerCounters("compilerThread", i, CHECK);
   959     CompilerThread* new_thread = make_compiler_thread(name_buffer, _c2_method_queue, counters, CHECK);
   960     _method_threads->append(new_thread);
   961   }
   963   for (int i = c2_compiler_count; i < compiler_count; i++) {
   964     // Create a name for our thread.
   965     sprintf(name_buffer, "C1 CompilerThread%d", i);
   966     CompilerCounters* counters = new CompilerCounters("compilerThread", i, CHECK);
   967     CompilerThread* new_thread = make_compiler_thread(name_buffer, _c1_method_queue, counters, CHECK);
   968     _method_threads->append(new_thread);
   969   }
   971   if (UsePerfData) {
   972     PerfDataManager::create_constant(SUN_CI, "threads", PerfData::U_Bytes,
   973                                      compiler_count, CHECK);
   974   }
   975 }
   977 // ------------------------------------------------------------------
   978 // CompileBroker::is_idle
   979 bool CompileBroker::is_idle() {
   980   if (_c2_method_queue != NULL && !_c2_method_queue->is_empty()) {
   981     return false;
   982   } else if (_c1_method_queue != NULL && !_c1_method_queue->is_empty()) {
   983     return false;
   984   } else {
   985     int num_threads = _method_threads->length();
   986     for (int i=0; i<num_threads; i++) {
   987       if (_method_threads->at(i)->task() != NULL) {
   988         return false;
   989       }
   990     }
   992     // No pending or active compilations.
   993     return true;
   994   }
   995 }
   998 // ------------------------------------------------------------------
   999 // CompileBroker::compile_method
  1000 //
  1001 // Request compilation of a method.
  1002 void CompileBroker::compile_method_base(methodHandle method,
  1003                                         int osr_bci,
  1004                                         int comp_level,
  1005                                         methodHandle hot_method,
  1006                                         int hot_count,
  1007                                         const char* comment,
  1008                                         Thread* thread) {
  1009   // do nothing if compiler thread(s) is not available
  1010   if (!_initialized ) {
  1011     return;
  1014   guarantee(!method->is_abstract(), "cannot compile abstract methods");
  1015   assert(method->method_holder()->klass_part()->oop_is_instance(),
  1016          "sanity check");
  1017   assert(!instanceKlass::cast(method->method_holder())->is_not_initialized(),
  1018          "method holder must be initialized");
  1020   if (CIPrintRequests) {
  1021     tty->print("request: ");
  1022     method->print_short_name(tty);
  1023     if (osr_bci != InvocationEntryBci) {
  1024       tty->print(" osr_bci: %d", osr_bci);
  1026     tty->print(" comment: %s count: %d", comment, hot_count);
  1027     if (!hot_method.is_null()) {
  1028       tty->print(" hot: ");
  1029       if (hot_method() != method()) {
  1030           hot_method->print_short_name(tty);
  1031       } else {
  1032         tty->print("yes");
  1035     tty->cr();
  1038   // A request has been made for compilation.  Before we do any
  1039   // real work, check to see if the method has been compiled
  1040   // in the meantime with a definitive result.
  1041   if (compilation_is_complete(method, osr_bci, comp_level)) {
  1042     return;
  1045 #ifndef PRODUCT
  1046   if (osr_bci != -1 && !FLAG_IS_DEFAULT(OSROnlyBCI)) {
  1047     if ((OSROnlyBCI > 0) ? (OSROnlyBCI != osr_bci) : (-OSROnlyBCI == osr_bci)) {
  1048       // Positive OSROnlyBCI means only compile that bci.  Negative means don't compile that BCI.
  1049       return;
  1052 #endif
  1054   // If this method is already in the compile queue, then
  1055   // we do not block the current thread.
  1056   if (compilation_is_in_queue(method, osr_bci)) {
  1057     // We may want to decay our counter a bit here to prevent
  1058     // multiple denied requests for compilation.  This is an
  1059     // open compilation policy issue. Note: The other possibility,
  1060     // in the case that this is a blocking compile request, is to have
  1061     // all subsequent blocking requesters wait for completion of
  1062     // ongoing compiles. Note that in this case we'll need a protocol
  1063     // for freeing the associated compile tasks. [Or we could have
  1064     // a single static monitor on which all these waiters sleep.]
  1065     return;
  1068   // If the requesting thread is holding the pending list lock
  1069   // then we just return. We can't risk blocking while holding
  1070   // the pending list lock or a 3-way deadlock may occur
  1071   // between the reference handler thread, a GC (instigated
  1072   // by a compiler thread), and compiled method registration.
  1073   if (instanceRefKlass::owns_pending_list_lock(JavaThread::current())) {
  1074     return;
  1077   // Outputs from the following MutexLocker block:
  1078   CompileTask* task     = NULL;
  1079   bool         blocking = false;
  1080   CompileQueue* queue  = compile_queue(comp_level);
  1082   // Acquire our lock.
  1084     MutexLocker locker(queue->lock(), thread);
  1086     // Make sure the method has not slipped into the queues since
  1087     // last we checked; note that those checks were "fast bail-outs".
  1088     // Here we need to be more careful, see 14012000 below.
  1089     if (compilation_is_in_queue(method, osr_bci)) {
  1090       return;
  1093     // We need to check again to see if the compilation has
  1094     // completed.  A previous compilation may have registered
  1095     // some result.
  1096     if (compilation_is_complete(method, osr_bci, comp_level)) {
  1097       return;
  1100     // We now know that this compilation is not pending, complete,
  1101     // or prohibited.  Assign a compile_id to this compilation
  1102     // and check to see if it is in our [Start..Stop) range.
  1103     uint compile_id = assign_compile_id(method, osr_bci);
  1104     if (compile_id == 0) {
  1105       // The compilation falls outside the allowed range.
  1106       return;
  1109     // Should this thread wait for completion of the compile?
  1110     blocking = is_compile_blocking(method, osr_bci);
  1112     // We will enter the compilation in the queue.
  1113     // 14012000: Note that this sets the queued_for_compile bits in
  1114     // the target method. We can now reason that a method cannot be
  1115     // queued for compilation more than once, as follows:
  1116     // Before a thread queues a task for compilation, it first acquires
  1117     // the compile queue lock, then checks if the method's queued bits
  1118     // are set or it has already been compiled. Thus there can not be two
  1119     // instances of a compilation task for the same method on the
  1120     // compilation queue. Consider now the case where the compilation
  1121     // thread has already removed a task for that method from the queue
  1122     // and is in the midst of compiling it. In this case, the
  1123     // queued_for_compile bits must be set in the method (and these
  1124     // will be visible to the current thread, since the bits were set
  1125     // under protection of the compile queue lock, which we hold now.
  1126     // When the compilation completes, the compiler thread first sets
  1127     // the compilation result and then clears the queued_for_compile
  1128     // bits. Neither of these actions are protected by a barrier (or done
  1129     // under the protection of a lock), so the only guarantee we have
  1130     // (on machines with TSO (Total Store Order)) is that these values
  1131     // will update in that order. As a result, the only combinations of
  1132     // these bits that the current thread will see are, in temporal order:
  1133     // <RESULT, QUEUE> :
  1134     //     <0, 1> : in compile queue, but not yet compiled
  1135     //     <1, 1> : compiled but queue bit not cleared
  1136     //     <1, 0> : compiled and queue bit cleared
  1137     // Because we first check the queue bits then check the result bits,
  1138     // we are assured that we cannot introduce a duplicate task.
  1139     // Note that if we did the tests in the reverse order (i.e. check
  1140     // result then check queued bit), we could get the result bit before
  1141     // the compilation completed, and the queue bit after the compilation
  1142     // completed, and end up introducing a "duplicate" (redundant) task.
  1143     // In that case, the compiler thread should first check if a method
  1144     // has already been compiled before trying to compile it.
  1145     // NOTE: in the event that there are multiple compiler threads and
  1146     // there is de-optimization/recompilation, things will get hairy,
  1147     // and in that case it's best to protect both the testing (here) of
  1148     // these bits, and their updating (here and elsewhere) under a
  1149     // common lock.
  1150     task = create_compile_task(queue,
  1151                                compile_id, method,
  1152                                osr_bci, comp_level,
  1153                                hot_method, hot_count, comment,
  1154                                blocking);
  1157   if (blocking) {
  1158     wait_for_completion(task);
  1163 nmethod* CompileBroker::compile_method(methodHandle method, int osr_bci,
  1164                                        int comp_level,
  1165                                        methodHandle hot_method, int hot_count,
  1166                                        const char* comment, Thread* THREAD) {
  1167   // make sure arguments make sense
  1168   assert(method->method_holder()->klass_part()->oop_is_instance(), "not an instance method");
  1169   assert(osr_bci == InvocationEntryBci || (0 <= osr_bci && osr_bci < method->code_size()), "bci out of range");
  1170   assert(!method->is_abstract() && (osr_bci == InvocationEntryBci || !method->is_native()), "cannot compile abstract/native methods");
  1171   assert(!instanceKlass::cast(method->method_holder())->is_not_initialized(), "method holder must be initialized");
  1173   if (!TieredCompilation) {
  1174     comp_level = CompLevel_highest_tier;
  1177   // return quickly if possible
  1179   // lock, make sure that the compilation
  1180   // isn't prohibited in a straightforward way.
  1182   if (compiler(comp_level) == NULL || compilation_is_prohibited(method, osr_bci, comp_level)) {
  1183     return NULL;
  1186   if (osr_bci == InvocationEntryBci) {
  1187     // standard compilation
  1188     nmethod* method_code = method->code();
  1189     if (method_code != NULL) {
  1190       if (compilation_is_complete(method, osr_bci, comp_level)) {
  1191         return method_code;
  1194     if (method->is_not_compilable(comp_level)) return NULL;
  1196     if (UseCodeCacheFlushing) {
  1197       nmethod* saved = CodeCache::find_and_remove_saved_code(method());
  1198       if (saved != NULL) {
  1199         method->set_code(method, saved);
  1200         return saved;
  1204   } else {
  1205     // osr compilation
  1206 #ifndef TIERED
  1207     // seems like an assert of dubious value
  1208     assert(comp_level == CompLevel_highest_tier,
  1209            "all OSR compiles are assumed to be at a single compilation lavel");
  1210 #endif // TIERED
  1211     // We accept a higher level osr method
  1212     nmethod* nm = method->lookup_osr_nmethod_for(osr_bci, comp_level, false);
  1213     if (nm != NULL) return nm;
  1214     if (method->is_not_osr_compilable()) return NULL;
  1217   assert(!HAS_PENDING_EXCEPTION, "No exception should be present");
  1218   // some prerequisites that are compiler specific
  1219   if (compiler(comp_level)->is_c2() || compiler(comp_level)->is_shark()) {
  1220     method->constants()->resolve_string_constants(CHECK_AND_CLEAR_NULL);
  1221     // Resolve all classes seen in the signature of the method
  1222     // we are compiling.
  1223     methodOopDesc::load_signature_classes(method, CHECK_AND_CLEAR_NULL);
  1226   // If the method is native, do the lookup in the thread requesting
  1227   // the compilation. Native lookups can load code, which is not
  1228   // permitted during compilation.
  1229   //
  1230   // Note: A native method implies non-osr compilation which is
  1231   //       checked with an assertion at the entry of this method.
  1232   if (method->is_native()) {
  1233     bool in_base_library;
  1234     address adr = NativeLookup::lookup(method, in_base_library, THREAD);
  1235     if (HAS_PENDING_EXCEPTION) {
  1236       // In case of an exception looking up the method, we just forget
  1237       // about it. The interpreter will kick-in and throw the exception.
  1238       method->set_not_compilable(); // implies is_not_osr_compilable()
  1239       CLEAR_PENDING_EXCEPTION;
  1240       return NULL;
  1242     assert(method->has_native_function(), "must have native code by now");
  1245   // RedefineClasses() has replaced this method; just return
  1246   if (method->is_old()) {
  1247     return NULL;
  1250   // JVMTI -- post_compile_event requires jmethod_id() that may require
  1251   // a lock the compiling thread can not acquire. Prefetch it here.
  1252   if (JvmtiExport::should_post_compiled_method_load()) {
  1253     method->jmethod_id();
  1256   // If the compiler is shut off due to code cache flushing or otherwise,
  1257   // fail out now so blocking compiles dont hang the java thread
  1258   if (!should_compile_new_jobs() || (UseCodeCacheFlushing && CodeCache::needs_flushing())) {
  1259     CompilationPolicy::policy()->delay_compilation(method());
  1260     return NULL;
  1263   // do the compilation
  1264   if (method->is_native()) {
  1265     if (!PreferInterpreterNativeStubs) {
  1266       // Acquire our lock.
  1267       int compile_id;
  1269         MutexLocker locker(MethodCompileQueue_lock, THREAD);
  1270         compile_id = assign_compile_id(method, standard_entry_bci);
  1272       (void) AdapterHandlerLibrary::create_native_wrapper(method, compile_id);
  1273     } else {
  1274       return NULL;
  1276   } else {
  1277     compile_method_base(method, osr_bci, comp_level, hot_method, hot_count, comment, THREAD);
  1280   // return requested nmethod
  1281   // We accept a higher level osr method
  1282   return osr_bci  == InvocationEntryBci ? method->code() : method->lookup_osr_nmethod_for(osr_bci, comp_level, false);
  1286 // ------------------------------------------------------------------
  1287 // CompileBroker::compilation_is_complete
  1288 //
  1289 // See if compilation of this method is already complete.
  1290 bool CompileBroker::compilation_is_complete(methodHandle method,
  1291                                             int          osr_bci,
  1292                                             int          comp_level) {
  1293   bool is_osr = (osr_bci != standard_entry_bci);
  1294   if (is_osr) {
  1295     if (method->is_not_osr_compilable()) {
  1296       return true;
  1297     } else {
  1298       nmethod* result = method->lookup_osr_nmethod_for(osr_bci, comp_level, true);
  1299       return (result != NULL);
  1301   } else {
  1302     if (method->is_not_compilable(comp_level)) {
  1303       return true;
  1304     } else {
  1305       nmethod* result = method->code();
  1306       if (result == NULL) return false;
  1307       return comp_level == result->comp_level();
  1313 // ------------------------------------------------------------------
  1314 // CompileBroker::compilation_is_in_queue
  1315 //
  1316 // See if this compilation is already requested.
  1317 //
  1318 // Implementation note: there is only a single "is in queue" bit
  1319 // for each method.  This means that the check below is overly
  1320 // conservative in the sense that an osr compilation in the queue
  1321 // will block a normal compilation from entering the queue (and vice
  1322 // versa).  This can be remedied by a full queue search to disambiguate
  1323 // cases.  If it is deemed profitible, this may be done.
  1324 bool CompileBroker::compilation_is_in_queue(methodHandle method,
  1325                                             int          osr_bci) {
  1326   return method->queued_for_compilation();
  1329 // ------------------------------------------------------------------
  1330 // CompileBroker::compilation_is_prohibited
  1331 //
  1332 // See if this compilation is not allowed.
  1333 bool CompileBroker::compilation_is_prohibited(methodHandle method, int osr_bci, int comp_level) {
  1334   bool is_native = method->is_native();
  1335   // Some compilers may not support the compilation of natives.
  1336   if (is_native &&
  1337       (!CICompileNatives || !compiler(comp_level)->supports_native())) {
  1338     method->set_not_compilable_quietly(comp_level);
  1339     return true;
  1342   bool is_osr = (osr_bci != standard_entry_bci);
  1343   // Some compilers may not support on stack replacement.
  1344   if (is_osr &&
  1345       (!CICompileOSR || !compiler(comp_level)->supports_osr())) {
  1346     method->set_not_osr_compilable();
  1347     return true;
  1350   // The method may be explicitly excluded by the user.
  1351   bool quietly;
  1352   if (CompilerOracle::should_exclude(method, quietly)) {
  1353     if (!quietly) {
  1354       // This does not happen quietly...
  1355       ResourceMark rm;
  1356       tty->print("### Excluding %s:%s",
  1357                  method->is_native() ? "generation of native wrapper" : "compile",
  1358                  (method->is_static() ? " static" : ""));
  1359       method->print_short_name(tty);
  1360       tty->cr();
  1362     method->set_not_compilable_quietly();
  1365   return false;
  1369 // ------------------------------------------------------------------
  1370 // CompileBroker::assign_compile_id
  1371 //
  1372 // Assign a serialized id number to this compilation request.  If the
  1373 // number falls out of the allowed range, return a 0.  OSR
  1374 // compilations may be numbered separately from regular compilations
  1375 // if certain debugging flags are used.
  1376 uint CompileBroker::assign_compile_id(methodHandle method, int osr_bci) {
  1377   assert(MethodCompileQueue_lock->owner() == Thread::current(),
  1378          "must hold the compilation queue lock");
  1379   bool is_osr = (osr_bci != standard_entry_bci);
  1380   uint id;
  1381   if (CICountOSR && is_osr) {
  1382     id = ++_osr_compilation_id;
  1383     if ((uint)CIStartOSR <= id && id < (uint)CIStopOSR) {
  1384       return id;
  1386   } else {
  1387     id = ++_compilation_id;
  1388     if ((uint)CIStart <= id && id < (uint)CIStop) {
  1389       return id;
  1393   // Method was not in the appropriate compilation range.
  1394   method->set_not_compilable_quietly();
  1395   return 0;
  1399 // ------------------------------------------------------------------
  1400 // CompileBroker::is_compile_blocking
  1401 //
  1402 // Should the current thread be blocked until this compilation request
  1403 // has been fulfilled?
  1404 bool CompileBroker::is_compile_blocking(methodHandle method, int osr_bci) {
  1405   assert(!instanceRefKlass::owns_pending_list_lock(JavaThread::current()), "possible deadlock");
  1406   return !BackgroundCompilation;
  1410 // ------------------------------------------------------------------
  1411 // CompileBroker::preload_classes
  1412 void CompileBroker::preload_classes(methodHandle method, TRAPS) {
  1413   // Move this code over from c1_Compiler.cpp
  1414   ShouldNotReachHere();
  1418 // ------------------------------------------------------------------
  1419 // CompileBroker::create_compile_task
  1420 //
  1421 // Create a CompileTask object representing the current request for
  1422 // compilation.  Add this task to the queue.
  1423 CompileTask* CompileBroker::create_compile_task(CompileQueue* queue,
  1424                                               int           compile_id,
  1425                                               methodHandle  method,
  1426                                               int           osr_bci,
  1427                                               int           comp_level,
  1428                                               methodHandle  hot_method,
  1429                                               int           hot_count,
  1430                                               const char*   comment,
  1431                                               bool          blocking) {
  1432   CompileTask* new_task = allocate_task();
  1433   new_task->initialize(compile_id, method, osr_bci, comp_level,
  1434                        hot_method, hot_count, comment,
  1435                        blocking);
  1436   queue->add(new_task);
  1437   return new_task;
  1441 // ------------------------------------------------------------------
  1442 // CompileBroker::allocate_task
  1443 //
  1444 // Allocate a CompileTask, from the free list if possible.
  1445 CompileTask* CompileBroker::allocate_task() {
  1446   MutexLocker locker(CompileTaskAlloc_lock);
  1447   CompileTask* task = NULL;
  1448   if (_task_free_list != NULL) {
  1449     task = _task_free_list;
  1450     _task_free_list = task->next();
  1451     task->set_next(NULL);
  1452   } else {
  1453     task = new CompileTask();
  1454     task->set_next(NULL);
  1456   return task;
  1460 // ------------------------------------------------------------------
  1461 // CompileBroker::free_task
  1462 //
  1463 // Add a task to the free list.
  1464 void CompileBroker::free_task(CompileTask* task) {
  1465   MutexLocker locker(CompileTaskAlloc_lock);
  1466   task->free();
  1467   task->set_next(_task_free_list);
  1468   _task_free_list = task;
  1472 // ------------------------------------------------------------------
  1473 // CompileBroker::wait_for_completion
  1474 //
  1475 // Wait for the given method CompileTask to complete.
  1476 void CompileBroker::wait_for_completion(CompileTask* task) {
  1477   if (CIPrintCompileQueue) {
  1478     tty->print_cr("BLOCKING FOR COMPILE");
  1481   assert(task->is_blocking(), "can only wait on blocking task");
  1483   JavaThread *thread = JavaThread::current();
  1484   thread->set_blocked_on_compilation(true);
  1486   methodHandle method(thread,
  1487                       (methodOop)JNIHandles::resolve(task->method_handle()));
  1489     MutexLocker waiter(task->lock(), thread);
  1491     while (!task->is_complete())
  1492       task->lock()->wait();
  1494   // It is harmless to check this status without the lock, because
  1495   // completion is a stable property (until the task object is recycled).
  1496   assert(task->is_complete(), "Compilation should have completed");
  1497   assert(task->code_handle() == NULL, "must be reset");
  1499   thread->set_blocked_on_compilation(false);
  1501   // By convention, the waiter is responsible for recycling a
  1502   // blocking CompileTask. Since there is only one waiter ever
  1503   // waiting on a CompileTask, we know that no one else will
  1504   // be using this CompileTask; we can free it.
  1505   free_task(task);
  1508 // ------------------------------------------------------------------
  1509 // CompileBroker::compiler_thread_loop
  1510 //
  1511 // The main loop run by a CompilerThread.
  1512 void CompileBroker::compiler_thread_loop() {
  1513   CompilerThread* thread = CompilerThread::current();
  1514   CompileQueue* queue = thread->queue();
  1516   // For the thread that initializes the ciObjectFactory
  1517   // this resource mark holds all the shared objects
  1518   ResourceMark rm;
  1520   // First thread to get here will initialize the compiler interface
  1522   if (!ciObjectFactory::is_initialized()) {
  1523     ASSERT_IN_VM;
  1524     MutexLocker only_one (CompileThread_lock, thread);
  1525     if (!ciObjectFactory::is_initialized()) {
  1526       ciObjectFactory::initialize();
  1530   // Open a log.
  1531   if (LogCompilation) {
  1532     init_compiler_thread_log();
  1534   CompileLog* log = thread->log();
  1535   if (log != NULL) {
  1536     log->begin_elem("start_compile_thread thread='" UINTX_FORMAT "' process='%d'",
  1537                     os::current_thread_id(),
  1538                     os::current_process_id());
  1539     log->stamp();
  1540     log->end_elem();
  1543   while (true) {
  1545       // We need this HandleMark to avoid leaking VM handles.
  1546       HandleMark hm(thread);
  1548       if (CodeCache::largest_free_block() < CodeCacheMinimumFreeSpace) {
  1549         // the code cache is really full
  1550         handle_full_code_cache();
  1551       } else if (UseCodeCacheFlushing && CodeCache::needs_flushing()) {
  1552         // Attempt to start cleaning the code cache while there is still a little headroom
  1553         NMethodSweeper::handle_full_code_cache(false);
  1556       CompileTask* task = queue->get();
  1558       // Give compiler threads an extra quanta.  They tend to be bursty and
  1559       // this helps the compiler to finish up the job.
  1560       if( CompilerThreadHintNoPreempt )
  1561         os::hint_no_preempt();
  1563       // trace per thread time and compile statistics
  1564       CompilerCounters* counters = ((CompilerThread*)thread)->counters();
  1565       PerfTraceTimedEvent(counters->time_counter(), counters->compile_counter());
  1567       // Assign the task to the current thread.  Mark this compilation
  1568       // thread as active for the profiler.
  1569       CompileTaskWrapper ctw(task);
  1570       nmethodLocker result_handle;  // (handle for the nmethod produced by this task)
  1571       task->set_code_handle(&result_handle);
  1572       methodHandle method(thread,
  1573                      (methodOop)JNIHandles::resolve(task->method_handle()));
  1575       // Never compile a method if breakpoints are present in it
  1576       if (method()->number_of_breakpoints() == 0) {
  1577         // Compile the method.
  1578         if ((UseCompiler || AlwaysCompileLoopMethods) && CompileBroker::should_compile_new_jobs()) {
  1579 #ifdef COMPILER1
  1580           // Allow repeating compilations for the purpose of benchmarking
  1581           // compile speed. This is not useful for customers.
  1582           if (CompilationRepeat != 0) {
  1583             int compile_count = CompilationRepeat;
  1584             while (compile_count > 0) {
  1585               invoke_compiler_on_method(task);
  1586               nmethod* nm = method->code();
  1587               if (nm != NULL) {
  1588                 nm->make_zombie();
  1589                 method->clear_code();
  1591               compile_count--;
  1594 #endif /* COMPILER1 */
  1595           invoke_compiler_on_method(task);
  1596         } else {
  1597           // After compilation is disabled, remove remaining methods from queue
  1598           method->clear_queued_for_compilation();
  1606 // ------------------------------------------------------------------
  1607 // CompileBroker::init_compiler_thread_log
  1608 //
  1609 // Set up state required by +LogCompilation.
  1610 void CompileBroker::init_compiler_thread_log() {
  1611     CompilerThread* thread = CompilerThread::current();
  1612     char  fileBuf[4*K];
  1613     FILE* fp = NULL;
  1614     char* file = NULL;
  1615     intx thread_id = os::current_thread_id();
  1616     for (int try_temp_dir = 1; try_temp_dir >= 0; try_temp_dir--) {
  1617       const char* dir = (try_temp_dir ? os::get_temp_directory() : NULL);
  1618       if (dir == NULL) {
  1619         jio_snprintf(fileBuf, sizeof(fileBuf), "hs_c" UINTX_FORMAT "_pid%u.log",
  1620                      thread_id, os::current_process_id());
  1621       } else {
  1622         jio_snprintf(fileBuf, sizeof(fileBuf),
  1623                      "%s%shs_c" UINTX_FORMAT "_pid%u.log", dir,
  1624                      os::file_separator(), thread_id, os::current_process_id());
  1626       fp = fopen(fileBuf, "at");
  1627       if (fp != NULL) {
  1628         file = NEW_C_HEAP_ARRAY(char, strlen(fileBuf)+1);
  1629         strcpy(file, fileBuf);
  1630         break;
  1633     if (fp == NULL) {
  1634       warning("Cannot open log file: %s", fileBuf);
  1635     } else {
  1636       if (LogCompilation && Verbose)
  1637         tty->print_cr("Opening compilation log %s", file);
  1638       CompileLog* log = new(ResourceObj::C_HEAP) CompileLog(file, fp, thread_id);
  1639       thread->init_log(log);
  1641       if (xtty != NULL) {
  1642         ttyLocker ttyl;
  1644         // Record any per thread log files
  1645         xtty->elem("thread_logfile thread='%d' filename='%s'", thread_id, file);
  1650 // ------------------------------------------------------------------
  1651 // CompileBroker::set_should_block
  1652 //
  1653 // Set _should_block.
  1654 // Call this from the VM, with Threads_lock held and a safepoint requested.
  1655 void CompileBroker::set_should_block() {
  1656   assert(Threads_lock->owner() == Thread::current(), "must have threads lock");
  1657   assert(SafepointSynchronize::is_at_safepoint(), "must be at a safepoint already");
  1658 #ifndef PRODUCT
  1659   if (PrintCompilation && (Verbose || WizardMode))
  1660     tty->print_cr("notifying compiler thread pool to block");
  1661 #endif
  1662   _should_block = true;
  1665 // ------------------------------------------------------------------
  1666 // CompileBroker::maybe_block
  1667 //
  1668 // Call this from the compiler at convenient points, to poll for _should_block.
  1669 void CompileBroker::maybe_block() {
  1670   if (_should_block) {
  1671 #ifndef PRODUCT
  1672     if (PrintCompilation && (Verbose || WizardMode))
  1673       tty->print_cr("compiler thread " INTPTR_FORMAT " poll detects block request", Thread::current());
  1674 #endif
  1675     ThreadInVMfromNative tivfn(JavaThread::current());
  1680 // ------------------------------------------------------------------
  1681 // CompileBroker::invoke_compiler_on_method
  1682 //
  1683 // Compile a method.
  1684 //
  1685 void CompileBroker::invoke_compiler_on_method(CompileTask* task) {
  1686   if (PrintCompilation) {
  1687     ResourceMark rm;
  1688     task->print_line();
  1690   elapsedTimer time;
  1692   CompilerThread* thread = CompilerThread::current();
  1693   ResourceMark rm(thread);
  1695   if (LogEvents) {
  1696     _compilation_log->log_compile(thread, task);
  1699   // Common flags.
  1700   uint compile_id = task->compile_id();
  1701   int osr_bci = task->osr_bci();
  1702   bool is_osr = (osr_bci != standard_entry_bci);
  1703   bool should_log = (thread->log() != NULL);
  1704   bool should_break = false;
  1706     // create the handle inside it's own block so it can't
  1707     // accidentally be referenced once the thread transitions to
  1708     // native.  The NoHandleMark before the transition should catch
  1709     // any cases where this occurs in the future.
  1710     methodHandle method(thread,
  1711                         (methodOop)JNIHandles::resolve(task->method_handle()));
  1712     should_break = check_break_at(method, compile_id, is_osr);
  1713     if (should_log && !CompilerOracle::should_log(method)) {
  1714       should_log = false;
  1716     assert(!method->is_native(), "no longer compile natives");
  1718     // Save information about this method in case of failure.
  1719     set_last_compile(thread, method, is_osr, task->comp_level());
  1721     DTRACE_METHOD_COMPILE_BEGIN_PROBE(compiler(task->comp_level()), method);
  1724   // Allocate a new set of JNI handles.
  1725   push_jni_handle_block();
  1726   jobject target_handle = JNIHandles::make_local(thread, JNIHandles::resolve(task->method_handle()));
  1727   int compilable = ciEnv::MethodCompilable;
  1729     int system_dictionary_modification_counter;
  1731       MutexLocker locker(Compile_lock, thread);
  1732       system_dictionary_modification_counter = SystemDictionary::number_of_modifications();
  1735     NoHandleMark  nhm;
  1736     ThreadToNativeFromVM ttn(thread);
  1738     ciEnv ci_env(task, system_dictionary_modification_counter);
  1739     if (should_break) {
  1740       ci_env.set_break_at_compile(true);
  1742     if (should_log) {
  1743       ci_env.set_log(thread->log());
  1745     assert(thread->env() == &ci_env, "set by ci_env");
  1746     // The thread-env() field is cleared in ~CompileTaskWrapper.
  1748     // Cache Jvmti state
  1749     ci_env.cache_jvmti_state();
  1751     // Cache DTrace flags
  1752     ci_env.cache_dtrace_flags();
  1754     ciMethod* target = ci_env.get_method_from_handle(target_handle);
  1756     TraceTime t1("compilation", &time);
  1758     compiler(task->comp_level())->compile_method(&ci_env, target, osr_bci);
  1760     if (!ci_env.failing() && task->code() == NULL) {
  1761       //assert(false, "compiler should always document failure");
  1762       // The compiler elected, without comment, not to register a result.
  1763       // Do not attempt further compilations of this method.
  1764       ci_env.record_method_not_compilable("compile failed", !TieredCompilation);
  1767     // Copy this bit to the enclosing block:
  1768     compilable = ci_env.compilable();
  1770     if (ci_env.failing()) {
  1771       const char* retry_message = ci_env.retry_message();
  1772       if (_compilation_log != NULL) {
  1773         _compilation_log->log_failure(thread, task, ci_env.failure_reason(), retry_message);
  1775       if (PrintCompilation) {
  1776         tty->print("%4d   COMPILE SKIPPED: %s", compile_id, ci_env.failure_reason());
  1777         if (retry_message != NULL) {
  1778           tty->print(" (%s)", retry_message);
  1780         tty->cr();
  1782     } else {
  1783       task->mark_success();
  1784       task->set_num_inlined_bytecodes(ci_env.num_inlined_bytecodes());
  1785       if (_compilation_log != NULL) {
  1786         nmethod* code = task->code();
  1787         if (code != NULL) {
  1788           _compilation_log->log_nmethod(thread, code);
  1793   pop_jni_handle_block();
  1795   methodHandle method(thread,
  1796                       (methodOop)JNIHandles::resolve(task->method_handle()));
  1798   DTRACE_METHOD_COMPILE_END_PROBE(compiler(task->comp_level()), method, task->is_success());
  1800   collect_statistics(thread, time, task);
  1802   if (PrintCompilation && PrintCompilation2) {
  1803     tty->print("%7d ", (int) tty->time_stamp().milliseconds());  // print timestamp
  1804     tty->print("%4d ", compile_id);    // print compilation number
  1805     tty->print("%s ", (is_osr ? "%" : " "));
  1806     int code_size = (task->code() == NULL) ? 0 : task->code()->total_size();
  1807     tty->print_cr("size: %d time: %d inlined: %d bytes", code_size, (int)time.milliseconds(), task->num_inlined_bytecodes());
  1810   if (compilable == ciEnv::MethodCompilable_never) {
  1811     if (is_osr) {
  1812       method->set_not_osr_compilable();
  1813     } else {
  1814       method->set_not_compilable_quietly();
  1816   } else if (compilable == ciEnv::MethodCompilable_not_at_tier) {
  1817     method->set_not_compilable_quietly(task->comp_level());
  1820   // Note that the queued_for_compilation bits are cleared without
  1821   // protection of a mutex. [They were set by the requester thread,
  1822   // when adding the task to the complie queue -- at which time the
  1823   // compile queue lock was held. Subsequently, we acquired the compile
  1824   // queue lock to get this task off the compile queue; thus (to belabour
  1825   // the point somewhat) our clearing of the bits must be occurring
  1826   // only after the setting of the bits. See also 14012000 above.
  1827   method->clear_queued_for_compilation();
  1829 #ifdef ASSERT
  1830   if (CollectedHeap::fired_fake_oom()) {
  1831     // The current compile received a fake OOM during compilation so
  1832     // go ahead and exit the VM since the test apparently succeeded
  1833     tty->print_cr("*** Shutting down VM after successful fake OOM");
  1834     vm_exit(0);
  1836 #endif
  1839 // ------------------------------------------------------------------
  1840 // CompileBroker::handle_full_code_cache
  1841 //
  1842 // The CodeCache is full.  Print out warning and disable compilation or
  1843 // try code cache cleaning so compilation can continue later.
  1844 void CompileBroker::handle_full_code_cache() {
  1845   UseInterpreter = true;
  1846   if (UseCompiler || AlwaysCompileLoopMethods ) {
  1847     if (xtty != NULL) {
  1848       stringStream s;
  1849       // Dump code cache state into a buffer before locking the tty,
  1850       // because log_state() will use locks causing lock conflicts.
  1851       CodeCache::log_state(&s);
  1852       // Lock to prevent tearing
  1853       ttyLocker ttyl;
  1854       xtty->begin_elem("code_cache_full");
  1855       xtty->print(s.as_string());
  1856       xtty->stamp();
  1857       xtty->end_elem();
  1859     warning("CodeCache is full. Compiler has been disabled.");
  1860     warning("Try increasing the code cache size using -XX:ReservedCodeCacheSize=");
  1861     CodeCache::print_bounds(tty);
  1862 #ifndef PRODUCT
  1863     if (CompileTheWorld || ExitOnFullCodeCache) {
  1864       before_exit(JavaThread::current());
  1865       exit_globals(); // will delete tty
  1866       vm_direct_exit(CompileTheWorld ? 0 : 1);
  1868 #endif
  1869     if (UseCodeCacheFlushing) {
  1870       NMethodSweeper::handle_full_code_cache(true);
  1871     } else {
  1872       UseCompiler               = false;
  1873       AlwaysCompileLoopMethods  = false;
  1878 // ------------------------------------------------------------------
  1879 // CompileBroker::set_last_compile
  1880 //
  1881 // Record this compilation for debugging purposes.
  1882 void CompileBroker::set_last_compile(CompilerThread* thread, methodHandle method, bool is_osr, int comp_level) {
  1883   ResourceMark rm;
  1884   char* method_name = method->name()->as_C_string();
  1885   strncpy(_last_method_compiled, method_name, CompileBroker::name_buffer_length);
  1886   char current_method[CompilerCounters::cmname_buffer_length];
  1887   size_t maxLen = CompilerCounters::cmname_buffer_length;
  1889   if (UsePerfData) {
  1890     const char* class_name = method->method_holder()->klass_part()->name()->as_C_string();
  1892     size_t s1len = strlen(class_name);
  1893     size_t s2len = strlen(method_name);
  1895     // check if we need to truncate the string
  1896     if (s1len + s2len + 2 > maxLen) {
  1898       // the strategy is to lop off the leading characters of the
  1899       // class name and the trailing characters of the method name.
  1901       if (s2len + 2 > maxLen) {
  1902         // lop of the entire class name string, let snprintf handle
  1903         // truncation of the method name.
  1904         class_name += s1len; // null string
  1906       else {
  1907         // lop off the extra characters from the front of the class name
  1908         class_name += ((s1len + s2len + 2) - maxLen);
  1912     jio_snprintf(current_method, maxLen, "%s %s", class_name, method_name);
  1915   if (CICountOSR && is_osr) {
  1916     _last_compile_type = osr_compile;
  1917   } else {
  1918     _last_compile_type = normal_compile;
  1920   _last_compile_level = comp_level;
  1922   if (UsePerfData) {
  1923     CompilerCounters* counters = thread->counters();
  1924     counters->set_current_method(current_method);
  1925     counters->set_compile_type((jlong)_last_compile_type);
  1930 // ------------------------------------------------------------------
  1931 // CompileBroker::push_jni_handle_block
  1932 //
  1933 // Push on a new block of JNI handles.
  1934 void CompileBroker::push_jni_handle_block() {
  1935   JavaThread* thread = JavaThread::current();
  1937   // Allocate a new block for JNI handles.
  1938   // Inlined code from jni_PushLocalFrame()
  1939   JNIHandleBlock* java_handles = thread->active_handles();
  1940   JNIHandleBlock* compile_handles = JNIHandleBlock::allocate_block(thread);
  1941   assert(compile_handles != NULL && java_handles != NULL, "should not be NULL");
  1942   compile_handles->set_pop_frame_link(java_handles);  // make sure java handles get gc'd.
  1943   thread->set_active_handles(compile_handles);
  1947 // ------------------------------------------------------------------
  1948 // CompileBroker::pop_jni_handle_block
  1949 //
  1950 // Pop off the current block of JNI handles.
  1951 void CompileBroker::pop_jni_handle_block() {
  1952   JavaThread* thread = JavaThread::current();
  1954   // Release our JNI handle block
  1955   JNIHandleBlock* compile_handles = thread->active_handles();
  1956   JNIHandleBlock* java_handles = compile_handles->pop_frame_link();
  1957   thread->set_active_handles(java_handles);
  1958   compile_handles->set_pop_frame_link(NULL);
  1959   JNIHandleBlock::release_block(compile_handles, thread); // may block
  1963 // ------------------------------------------------------------------
  1964 // CompileBroker::check_break_at
  1965 //
  1966 // Should the compilation break at the current compilation.
  1967 bool CompileBroker::check_break_at(methodHandle method, int compile_id, bool is_osr) {
  1968   if (CICountOSR && is_osr && (compile_id == CIBreakAtOSR)) {
  1969     return true;
  1970   } else if( CompilerOracle::should_break_at(method) ) { // break when compiling
  1971     return true;
  1972   } else {
  1973     return (compile_id == CIBreakAt);
  1977 // ------------------------------------------------------------------
  1978 // CompileBroker::collect_statistics
  1979 //
  1980 // Collect statistics about the compilation.
  1982 void CompileBroker::collect_statistics(CompilerThread* thread, elapsedTimer time, CompileTask* task) {
  1983   bool success = task->is_success();
  1984   methodHandle method (thread, (methodOop)JNIHandles::resolve(task->method_handle()));
  1985   uint compile_id = task->compile_id();
  1986   bool is_osr = (task->osr_bci() != standard_entry_bci);
  1987   nmethod* code = task->code();
  1988   CompilerCounters* counters = thread->counters();
  1990   assert(code == NULL || code->is_locked_by_vm(), "will survive the MutexLocker");
  1991   MutexLocker locker(CompileStatistics_lock);
  1993   // _perf variables are production performance counters which are
  1994   // updated regardless of the setting of the CITime and CITimeEach flags
  1995   //
  1996   if (!success) {
  1997     _total_bailout_count++;
  1998     if (UsePerfData) {
  1999       _perf_last_failed_method->set_value(counters->current_method());
  2000       _perf_last_failed_type->set_value(counters->compile_type());
  2001       _perf_total_bailout_count->inc();
  2003   } else if (code == NULL) {
  2004     if (UsePerfData) {
  2005       _perf_last_invalidated_method->set_value(counters->current_method());
  2006       _perf_last_invalidated_type->set_value(counters->compile_type());
  2007       _perf_total_invalidated_count->inc();
  2009     _total_invalidated_count++;
  2010   } else {
  2011     // Compilation succeeded
  2013     // update compilation ticks - used by the implementation of
  2014     // java.lang.management.CompilationMBean
  2015     _perf_total_compilation->inc(time.ticks());
  2017     if (CITime) {
  2018       _t_total_compilation.add(time);
  2019       if (is_osr) {
  2020         _t_osr_compilation.add(time);
  2021         _sum_osr_bytes_compiled += method->code_size() + task->num_inlined_bytecodes();
  2022       } else {
  2023         _t_standard_compilation.add(time);
  2024         _sum_standard_bytes_compiled += method->code_size() + task->num_inlined_bytecodes();
  2028     if (UsePerfData) {
  2029       // save the name of the last method compiled
  2030       _perf_last_method->set_value(counters->current_method());
  2031       _perf_last_compile_type->set_value(counters->compile_type());
  2032       _perf_last_compile_size->set_value(method->code_size() +
  2033                                          task->num_inlined_bytecodes());
  2034       if (is_osr) {
  2035         _perf_osr_compilation->inc(time.ticks());
  2036         _perf_sum_osr_bytes_compiled->inc(method->code_size() + task->num_inlined_bytecodes());
  2037       } else {
  2038         _perf_standard_compilation->inc(time.ticks());
  2039         _perf_sum_standard_bytes_compiled->inc(method->code_size() + task->num_inlined_bytecodes());
  2043     if (CITimeEach) {
  2044       float bytes_per_sec = 1.0 * (method->code_size() + task->num_inlined_bytecodes()) / time.seconds();
  2045       tty->print_cr("%3d   seconds: %f bytes/sec : %f (bytes %d + %d inlined)",
  2046                     compile_id, time.seconds(), bytes_per_sec, method->code_size(), task->num_inlined_bytecodes());
  2049     // Collect counts of successful compilations
  2050     _sum_nmethod_size      += code->total_size();
  2051     _sum_nmethod_code_size += code->insts_size();
  2052     _total_compile_count++;
  2054     if (UsePerfData) {
  2055       _perf_sum_nmethod_size->inc(     code->total_size());
  2056       _perf_sum_nmethod_code_size->inc(code->insts_size());
  2057       _perf_total_compile_count->inc();
  2060     if (is_osr) {
  2061       if (UsePerfData) _perf_total_osr_compile_count->inc();
  2062       _total_osr_compile_count++;
  2063     } else {
  2064       if (UsePerfData) _perf_total_standard_compile_count->inc();
  2065       _total_standard_compile_count++;
  2068   // set the current method for the thread to null
  2069   if (UsePerfData) counters->set_current_method("");
  2074 void CompileBroker::print_times() {
  2075   tty->cr();
  2076   tty->print_cr("Accumulated compiler times (for compiled methods only)");
  2077   tty->print_cr("------------------------------------------------");
  2078                //0000000000111111111122222222223333333333444444444455555555556666666666
  2079                //0123456789012345678901234567890123456789012345678901234567890123456789
  2080   tty->print_cr("  Total compilation time   : %6.3f s", CompileBroker::_t_total_compilation.seconds());
  2081   tty->print_cr("    Standard compilation   : %6.3f s, Average : %2.3f",
  2082                 CompileBroker::_t_standard_compilation.seconds(),
  2083                 CompileBroker::_t_standard_compilation.seconds() / CompileBroker::_total_standard_compile_count);
  2084   tty->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);
  2086   if (compiler(CompLevel_simple) != NULL) {
  2087     compiler(CompLevel_simple)->print_timers();
  2089   if (compiler(CompLevel_full_optimization) != NULL) {
  2090     compiler(CompLevel_full_optimization)->print_timers();
  2092   tty->cr();
  2093   int tcb = CompileBroker::_sum_osr_bytes_compiled + CompileBroker::_sum_standard_bytes_compiled;
  2094   tty->print_cr("  Total compiled bytecodes : %6d bytes", tcb);
  2095   tty->print_cr("    Standard compilation   : %6d bytes", CompileBroker::_sum_standard_bytes_compiled);
  2096   tty->print_cr("    On stack replacement   : %6d bytes", CompileBroker::_sum_osr_bytes_compiled);
  2097   int bps = (int)(tcb / CompileBroker::_t_total_compilation.seconds());
  2098   tty->print_cr("  Average compilation speed: %6d bytes/s", bps);
  2099   tty->cr();
  2100   tty->print_cr("  nmethod code size        : %6d bytes", CompileBroker::_sum_nmethod_code_size);
  2101   tty->print_cr("  nmethod total size       : %6d bytes", CompileBroker::_sum_nmethod_size);
  2105 // Debugging output for failure
  2106 void CompileBroker::print_last_compile() {
  2107   if ( _last_compile_level != CompLevel_none &&
  2108        compiler(_last_compile_level) != NULL &&
  2109        _last_method_compiled != NULL &&
  2110        _last_compile_type != no_compile) {
  2111     if (_last_compile_type == osr_compile) {
  2112       tty->print_cr("Last parse:  [osr]%d+++(%d) %s",
  2113                     _osr_compilation_id, _last_compile_level, _last_method_compiled);
  2114     } else {
  2115       tty->print_cr("Last parse:  %d+++(%d) %s",
  2116                     _compilation_id, _last_compile_level, _last_method_compiled);
  2122 void CompileBroker::print_compiler_threads_on(outputStream* st) {
  2123 #ifndef PRODUCT
  2124   st->print_cr("Compiler thread printing unimplemented.");
  2125   st->cr();
  2126 #endif

mercurial