src/share/vm/compiler/compileBroker.cpp

Fri, 03 Feb 2012 12:08:55 -0800

author
jcoomes
date
Fri, 03 Feb 2012 12:08:55 -0800
changeset 3502
379b22e03c32
parent 3482
bf5da1648543
parent 3499
aa3d708d67c4
child 3571
09d00c18e323
permissions
-rw-r--r--

Merge

     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
   903     java_lang_Thread::set_priority(thread_oop(), NearMaxPriority);
   905     // Note that we cannot call os::set_priority because it expects Java
   906     // priorities and we are *explicitly* using OS priorities so that it's
   907     // possible to set the compiler thread priority higher than any Java
   908     // thread.
   910     int native_prio = CompilerThreadPriority;
   911     if (native_prio == -1) {
   912       if (UseCriticalCompilerThreadPriority) {
   913         native_prio = os::java_to_os_priority[CriticalPriority];
   914       } else {
   915         native_prio = os::java_to_os_priority[NearMaxPriority];
   916       }
   917     }
   918     os::set_native_priority(compiler_thread, native_prio);
   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   }
   927   // Let go of Threads_lock before yielding
   928   os::yield(); // make sure that the compiler thread is started early (especially helpful on SOLARIS)
   930   return compiler_thread;
   931 }
   934 // ------------------------------------------------------------------
   935 // CompileBroker::init_compiler_threads
   936 //
   937 // Initialize the compilation queue
   938 void CompileBroker::init_compiler_threads(int c1_compiler_count, int c2_compiler_count) {
   939   EXCEPTION_MARK;
   940 #if !defined(ZERO) && !defined(SHARK)
   941   assert(c2_compiler_count > 0 || c1_compiler_count > 0, "No compilers?");
   942 #endif // !ZERO && !SHARK
   943   if (c2_compiler_count > 0) {
   944     _c2_method_queue  = new CompileQueue("C2MethodQueue",  MethodCompileQueue_lock);
   945   }
   946   if (c1_compiler_count > 0) {
   947     _c1_method_queue  = new CompileQueue("C1MethodQueue",  MethodCompileQueue_lock);
   948   }
   950   int compiler_count = c1_compiler_count + c2_compiler_count;
   952   _method_threads =
   953     new (ResourceObj::C_HEAP) GrowableArray<CompilerThread*>(compiler_count, true);
   955   char name_buffer[256];
   956   for (int i = 0; i < c2_compiler_count; i++) {
   957     // Create a name for our thread.
   958     sprintf(name_buffer, "C2 CompilerThread%d", i);
   959     CompilerCounters* counters = new CompilerCounters("compilerThread", i, CHECK);
   960     CompilerThread* new_thread = make_compiler_thread(name_buffer, _c2_method_queue, counters, CHECK);
   961     _method_threads->append(new_thread);
   962   }
   964   for (int i = c2_compiler_count; i < compiler_count; i++) {
   965     // Create a name for our thread.
   966     sprintf(name_buffer, "C1 CompilerThread%d", i);
   967     CompilerCounters* counters = new CompilerCounters("compilerThread", i, CHECK);
   968     CompilerThread* new_thread = make_compiler_thread(name_buffer, _c1_method_queue, counters, CHECK);
   969     _method_threads->append(new_thread);
   970   }
   972   if (UsePerfData) {
   973     PerfDataManager::create_constant(SUN_CI, "threads", PerfData::U_Bytes,
   974                                      compiler_count, CHECK);
   975   }
   976 }
   978 // ------------------------------------------------------------------
   979 // CompileBroker::is_idle
   980 bool CompileBroker::is_idle() {
   981   if (_c2_method_queue != NULL && !_c2_method_queue->is_empty()) {
   982     return false;
   983   } else if (_c1_method_queue != NULL && !_c1_method_queue->is_empty()) {
   984     return false;
   985   } else {
   986     int num_threads = _method_threads->length();
   987     for (int i=0; i<num_threads; i++) {
   988       if (_method_threads->at(i)->task() != NULL) {
   989         return false;
   990       }
   991     }
   993     // No pending or active compilations.
   994     return true;
   995   }
   996 }
   999 // ------------------------------------------------------------------
  1000 // CompileBroker::compile_method
  1001 //
  1002 // Request compilation of a method.
  1003 void CompileBroker::compile_method_base(methodHandle method,
  1004                                         int osr_bci,
  1005                                         int comp_level,
  1006                                         methodHandle hot_method,
  1007                                         int hot_count,
  1008                                         const char* comment,
  1009                                         Thread* thread) {
  1010   // do nothing if compiler thread(s) is not available
  1011   if (!_initialized ) {
  1012     return;
  1015   guarantee(!method->is_abstract(), "cannot compile abstract methods");
  1016   assert(method->method_holder()->klass_part()->oop_is_instance(),
  1017          "sanity check");
  1018   assert(!instanceKlass::cast(method->method_holder())->is_not_initialized(),
  1019          "method holder must be initialized");
  1021   if (CIPrintRequests) {
  1022     tty->print("request: ");
  1023     method->print_short_name(tty);
  1024     if (osr_bci != InvocationEntryBci) {
  1025       tty->print(" osr_bci: %d", osr_bci);
  1027     tty->print(" comment: %s count: %d", comment, hot_count);
  1028     if (!hot_method.is_null()) {
  1029       tty->print(" hot: ");
  1030       if (hot_method() != method()) {
  1031           hot_method->print_short_name(tty);
  1032       } else {
  1033         tty->print("yes");
  1036     tty->cr();
  1039   // A request has been made for compilation.  Before we do any
  1040   // real work, check to see if the method has been compiled
  1041   // in the meantime with a definitive result.
  1042   if (compilation_is_complete(method, osr_bci, comp_level)) {
  1043     return;
  1046 #ifndef PRODUCT
  1047   if (osr_bci != -1 && !FLAG_IS_DEFAULT(OSROnlyBCI)) {
  1048     if ((OSROnlyBCI > 0) ? (OSROnlyBCI != osr_bci) : (-OSROnlyBCI == osr_bci)) {
  1049       // Positive OSROnlyBCI means only compile that bci.  Negative means don't compile that BCI.
  1050       return;
  1053 #endif
  1055   // If this method is already in the compile queue, then
  1056   // we do not block the current thread.
  1057   if (compilation_is_in_queue(method, osr_bci)) {
  1058     // We may want to decay our counter a bit here to prevent
  1059     // multiple denied requests for compilation.  This is an
  1060     // open compilation policy issue. Note: The other possibility,
  1061     // in the case that this is a blocking compile request, is to have
  1062     // all subsequent blocking requesters wait for completion of
  1063     // ongoing compiles. Note that in this case we'll need a protocol
  1064     // for freeing the associated compile tasks. [Or we could have
  1065     // a single static monitor on which all these waiters sleep.]
  1066     return;
  1069   // If the requesting thread is holding the pending list lock
  1070   // then we just return. We can't risk blocking while holding
  1071   // the pending list lock or a 3-way deadlock may occur
  1072   // between the reference handler thread, a GC (instigated
  1073   // by a compiler thread), and compiled method registration.
  1074   if (instanceRefKlass::owns_pending_list_lock(JavaThread::current())) {
  1075     return;
  1078   // Outputs from the following MutexLocker block:
  1079   CompileTask* task     = NULL;
  1080   bool         blocking = false;
  1081   CompileQueue* queue  = compile_queue(comp_level);
  1083   // Acquire our lock.
  1085     MutexLocker locker(queue->lock(), thread);
  1087     // Make sure the method has not slipped into the queues since
  1088     // last we checked; note that those checks were "fast bail-outs".
  1089     // Here we need to be more careful, see 14012000 below.
  1090     if (compilation_is_in_queue(method, osr_bci)) {
  1091       return;
  1094     // We need to check again to see if the compilation has
  1095     // completed.  A previous compilation may have registered
  1096     // some result.
  1097     if (compilation_is_complete(method, osr_bci, comp_level)) {
  1098       return;
  1101     // We now know that this compilation is not pending, complete,
  1102     // or prohibited.  Assign a compile_id to this compilation
  1103     // and check to see if it is in our [Start..Stop) range.
  1104     uint compile_id = assign_compile_id(method, osr_bci);
  1105     if (compile_id == 0) {
  1106       // The compilation falls outside the allowed range.
  1107       return;
  1110     // Should this thread wait for completion of the compile?
  1111     blocking = is_compile_blocking(method, osr_bci);
  1113     // We will enter the compilation in the queue.
  1114     // 14012000: Note that this sets the queued_for_compile bits in
  1115     // the target method. We can now reason that a method cannot be
  1116     // queued for compilation more than once, as follows:
  1117     // Before a thread queues a task for compilation, it first acquires
  1118     // the compile queue lock, then checks if the method's queued bits
  1119     // are set or it has already been compiled. Thus there can not be two
  1120     // instances of a compilation task for the same method on the
  1121     // compilation queue. Consider now the case where the compilation
  1122     // thread has already removed a task for that method from the queue
  1123     // and is in the midst of compiling it. In this case, the
  1124     // queued_for_compile bits must be set in the method (and these
  1125     // will be visible to the current thread, since the bits were set
  1126     // under protection of the compile queue lock, which we hold now.
  1127     // When the compilation completes, the compiler thread first sets
  1128     // the compilation result and then clears the queued_for_compile
  1129     // bits. Neither of these actions are protected by a barrier (or done
  1130     // under the protection of a lock), so the only guarantee we have
  1131     // (on machines with TSO (Total Store Order)) is that these values
  1132     // will update in that order. As a result, the only combinations of
  1133     // these bits that the current thread will see are, in temporal order:
  1134     // <RESULT, QUEUE> :
  1135     //     <0, 1> : in compile queue, but not yet compiled
  1136     //     <1, 1> : compiled but queue bit not cleared
  1137     //     <1, 0> : compiled and queue bit cleared
  1138     // Because we first check the queue bits then check the result bits,
  1139     // we are assured that we cannot introduce a duplicate task.
  1140     // Note that if we did the tests in the reverse order (i.e. check
  1141     // result then check queued bit), we could get the result bit before
  1142     // the compilation completed, and the queue bit after the compilation
  1143     // completed, and end up introducing a "duplicate" (redundant) task.
  1144     // In that case, the compiler thread should first check if a method
  1145     // has already been compiled before trying to compile it.
  1146     // NOTE: in the event that there are multiple compiler threads and
  1147     // there is de-optimization/recompilation, things will get hairy,
  1148     // and in that case it's best to protect both the testing (here) of
  1149     // these bits, and their updating (here and elsewhere) under a
  1150     // common lock.
  1151     task = create_compile_task(queue,
  1152                                compile_id, method,
  1153                                osr_bci, comp_level,
  1154                                hot_method, hot_count, comment,
  1155                                blocking);
  1158   if (blocking) {
  1159     wait_for_completion(task);
  1164 nmethod* CompileBroker::compile_method(methodHandle method, int osr_bci,
  1165                                        int comp_level,
  1166                                        methodHandle hot_method, int hot_count,
  1167                                        const char* comment, Thread* THREAD) {
  1168   // make sure arguments make sense
  1169   assert(method->method_holder()->klass_part()->oop_is_instance(), "not an instance method");
  1170   assert(osr_bci == InvocationEntryBci || (0 <= osr_bci && osr_bci < method->code_size()), "bci out of range");
  1171   assert(!method->is_abstract() && (osr_bci == InvocationEntryBci || !method->is_native()), "cannot compile abstract/native methods");
  1172   assert(!instanceKlass::cast(method->method_holder())->is_not_initialized(), "method holder must be initialized");
  1174   if (!TieredCompilation) {
  1175     comp_level = CompLevel_highest_tier;
  1178   // return quickly if possible
  1180   // lock, make sure that the compilation
  1181   // isn't prohibited in a straightforward way.
  1183   if (compiler(comp_level) == NULL || compilation_is_prohibited(method, osr_bci, comp_level)) {
  1184     return NULL;
  1187   if (osr_bci == InvocationEntryBci) {
  1188     // standard compilation
  1189     nmethod* method_code = method->code();
  1190     if (method_code != NULL) {
  1191       if (compilation_is_complete(method, osr_bci, comp_level)) {
  1192         return method_code;
  1195     if (method->is_not_compilable(comp_level)) return NULL;
  1197     if (UseCodeCacheFlushing) {
  1198       nmethod* saved = CodeCache::find_and_remove_saved_code(method());
  1199       if (saved != NULL) {
  1200         method->set_code(method, saved);
  1201         return saved;
  1205   } else {
  1206     // osr compilation
  1207 #ifndef TIERED
  1208     // seems like an assert of dubious value
  1209     assert(comp_level == CompLevel_highest_tier,
  1210            "all OSR compiles are assumed to be at a single compilation lavel");
  1211 #endif // TIERED
  1212     // We accept a higher level osr method
  1213     nmethod* nm = method->lookup_osr_nmethod_for(osr_bci, comp_level, false);
  1214     if (nm != NULL) return nm;
  1215     if (method->is_not_osr_compilable()) return NULL;
  1218   assert(!HAS_PENDING_EXCEPTION, "No exception should be present");
  1219   // some prerequisites that are compiler specific
  1220   if (compiler(comp_level)->is_c2() || compiler(comp_level)->is_shark()) {
  1221     method->constants()->resolve_string_constants(CHECK_AND_CLEAR_NULL);
  1222     // Resolve all classes seen in the signature of the method
  1223     // we are compiling.
  1224     methodOopDesc::load_signature_classes(method, CHECK_AND_CLEAR_NULL);
  1227   // If the method is native, do the lookup in the thread requesting
  1228   // the compilation. Native lookups can load code, which is not
  1229   // permitted during compilation.
  1230   //
  1231   // Note: A native method implies non-osr compilation which is
  1232   //       checked with an assertion at the entry of this method.
  1233   if (method->is_native()) {
  1234     bool in_base_library;
  1235     address adr = NativeLookup::lookup(method, in_base_library, THREAD);
  1236     if (HAS_PENDING_EXCEPTION) {
  1237       // In case of an exception looking up the method, we just forget
  1238       // about it. The interpreter will kick-in and throw the exception.
  1239       method->set_not_compilable(); // implies is_not_osr_compilable()
  1240       CLEAR_PENDING_EXCEPTION;
  1241       return NULL;
  1243     assert(method->has_native_function(), "must have native code by now");
  1246   // RedefineClasses() has replaced this method; just return
  1247   if (method->is_old()) {
  1248     return NULL;
  1251   // JVMTI -- post_compile_event requires jmethod_id() that may require
  1252   // a lock the compiling thread can not acquire. Prefetch it here.
  1253   if (JvmtiExport::should_post_compiled_method_load()) {
  1254     method->jmethod_id();
  1257   // If the compiler is shut off due to code cache flushing or otherwise,
  1258   // fail out now so blocking compiles dont hang the java thread
  1259   if (!should_compile_new_jobs() || (UseCodeCacheFlushing && CodeCache::needs_flushing())) {
  1260     CompilationPolicy::policy()->delay_compilation(method());
  1261     return NULL;
  1264   // do the compilation
  1265   if (method->is_native()) {
  1266     if (!PreferInterpreterNativeStubs) {
  1267       // Acquire our lock.
  1268       int compile_id;
  1270         MutexLocker locker(MethodCompileQueue_lock, THREAD);
  1271         compile_id = assign_compile_id(method, standard_entry_bci);
  1273       (void) AdapterHandlerLibrary::create_native_wrapper(method, compile_id);
  1274     } else {
  1275       return NULL;
  1277   } else {
  1278     compile_method_base(method, osr_bci, comp_level, hot_method, hot_count, comment, THREAD);
  1281   // return requested nmethod
  1282   // We accept a higher level osr method
  1283   return osr_bci  == InvocationEntryBci ? method->code() : method->lookup_osr_nmethod_for(osr_bci, comp_level, false);
  1287 // ------------------------------------------------------------------
  1288 // CompileBroker::compilation_is_complete
  1289 //
  1290 // See if compilation of this method is already complete.
  1291 bool CompileBroker::compilation_is_complete(methodHandle method,
  1292                                             int          osr_bci,
  1293                                             int          comp_level) {
  1294   bool is_osr = (osr_bci != standard_entry_bci);
  1295   if (is_osr) {
  1296     if (method->is_not_osr_compilable()) {
  1297       return true;
  1298     } else {
  1299       nmethod* result = method->lookup_osr_nmethod_for(osr_bci, comp_level, true);
  1300       return (result != NULL);
  1302   } else {
  1303     if (method->is_not_compilable(comp_level)) {
  1304       return true;
  1305     } else {
  1306       nmethod* result = method->code();
  1307       if (result == NULL) return false;
  1308       return comp_level == result->comp_level();
  1314 // ------------------------------------------------------------------
  1315 // CompileBroker::compilation_is_in_queue
  1316 //
  1317 // See if this compilation is already requested.
  1318 //
  1319 // Implementation note: there is only a single "is in queue" bit
  1320 // for each method.  This means that the check below is overly
  1321 // conservative in the sense that an osr compilation in the queue
  1322 // will block a normal compilation from entering the queue (and vice
  1323 // versa).  This can be remedied by a full queue search to disambiguate
  1324 // cases.  If it is deemed profitible, this may be done.
  1325 bool CompileBroker::compilation_is_in_queue(methodHandle method,
  1326                                             int          osr_bci) {
  1327   return method->queued_for_compilation();
  1330 // ------------------------------------------------------------------
  1331 // CompileBroker::compilation_is_prohibited
  1332 //
  1333 // See if this compilation is not allowed.
  1334 bool CompileBroker::compilation_is_prohibited(methodHandle method, int osr_bci, int comp_level) {
  1335   bool is_native = method->is_native();
  1336   // Some compilers may not support the compilation of natives.
  1337   if (is_native &&
  1338       (!CICompileNatives || !compiler(comp_level)->supports_native())) {
  1339     method->set_not_compilable_quietly(comp_level);
  1340     return true;
  1343   bool is_osr = (osr_bci != standard_entry_bci);
  1344   // Some compilers may not support on stack replacement.
  1345   if (is_osr &&
  1346       (!CICompileOSR || !compiler(comp_level)->supports_osr())) {
  1347     method->set_not_osr_compilable();
  1348     return true;
  1351   // The method may be explicitly excluded by the user.
  1352   bool quietly;
  1353   if (CompilerOracle::should_exclude(method, quietly)) {
  1354     if (!quietly) {
  1355       // This does not happen quietly...
  1356       ResourceMark rm;
  1357       tty->print("### Excluding %s:%s",
  1358                  method->is_native() ? "generation of native wrapper" : "compile",
  1359                  (method->is_static() ? " static" : ""));
  1360       method->print_short_name(tty);
  1361       tty->cr();
  1363     method->set_not_compilable_quietly();
  1366   return false;
  1370 // ------------------------------------------------------------------
  1371 // CompileBroker::assign_compile_id
  1372 //
  1373 // Assign a serialized id number to this compilation request.  If the
  1374 // number falls out of the allowed range, return a 0.  OSR
  1375 // compilations may be numbered separately from regular compilations
  1376 // if certain debugging flags are used.
  1377 uint CompileBroker::assign_compile_id(methodHandle method, int osr_bci) {
  1378   assert(MethodCompileQueue_lock->owner() == Thread::current(),
  1379          "must hold the compilation queue lock");
  1380   bool is_osr = (osr_bci != standard_entry_bci);
  1381   uint id;
  1382   if (CICountOSR && is_osr) {
  1383     id = ++_osr_compilation_id;
  1384     if ((uint)CIStartOSR <= id && id < (uint)CIStopOSR) {
  1385       return id;
  1387   } else {
  1388     id = ++_compilation_id;
  1389     if ((uint)CIStart <= id && id < (uint)CIStop) {
  1390       return id;
  1394   // Method was not in the appropriate compilation range.
  1395   method->set_not_compilable_quietly();
  1396   return 0;
  1400 // ------------------------------------------------------------------
  1401 // CompileBroker::is_compile_blocking
  1402 //
  1403 // Should the current thread be blocked until this compilation request
  1404 // has been fulfilled?
  1405 bool CompileBroker::is_compile_blocking(methodHandle method, int osr_bci) {
  1406   assert(!instanceRefKlass::owns_pending_list_lock(JavaThread::current()), "possible deadlock");
  1407   return !BackgroundCompilation;
  1411 // ------------------------------------------------------------------
  1412 // CompileBroker::preload_classes
  1413 void CompileBroker::preload_classes(methodHandle method, TRAPS) {
  1414   // Move this code over from c1_Compiler.cpp
  1415   ShouldNotReachHere();
  1419 // ------------------------------------------------------------------
  1420 // CompileBroker::create_compile_task
  1421 //
  1422 // Create a CompileTask object representing the current request for
  1423 // compilation.  Add this task to the queue.
  1424 CompileTask* CompileBroker::create_compile_task(CompileQueue* queue,
  1425                                               int           compile_id,
  1426                                               methodHandle  method,
  1427                                               int           osr_bci,
  1428                                               int           comp_level,
  1429                                               methodHandle  hot_method,
  1430                                               int           hot_count,
  1431                                               const char*   comment,
  1432                                               bool          blocking) {
  1433   CompileTask* new_task = allocate_task();
  1434   new_task->initialize(compile_id, method, osr_bci, comp_level,
  1435                        hot_method, hot_count, comment,
  1436                        blocking);
  1437   queue->add(new_task);
  1438   return new_task;
  1442 // ------------------------------------------------------------------
  1443 // CompileBroker::allocate_task
  1444 //
  1445 // Allocate a CompileTask, from the free list if possible.
  1446 CompileTask* CompileBroker::allocate_task() {
  1447   MutexLocker locker(CompileTaskAlloc_lock);
  1448   CompileTask* task = NULL;
  1449   if (_task_free_list != NULL) {
  1450     task = _task_free_list;
  1451     _task_free_list = task->next();
  1452     task->set_next(NULL);
  1453   } else {
  1454     task = new CompileTask();
  1455     task->set_next(NULL);
  1457   return task;
  1461 // ------------------------------------------------------------------
  1462 // CompileBroker::free_task
  1463 //
  1464 // Add a task to the free list.
  1465 void CompileBroker::free_task(CompileTask* task) {
  1466   MutexLocker locker(CompileTaskAlloc_lock);
  1467   task->free();
  1468   task->set_next(_task_free_list);
  1469   _task_free_list = task;
  1473 // ------------------------------------------------------------------
  1474 // CompileBroker::wait_for_completion
  1475 //
  1476 // Wait for the given method CompileTask to complete.
  1477 void CompileBroker::wait_for_completion(CompileTask* task) {
  1478   if (CIPrintCompileQueue) {
  1479     tty->print_cr("BLOCKING FOR COMPILE");
  1482   assert(task->is_blocking(), "can only wait on blocking task");
  1484   JavaThread *thread = JavaThread::current();
  1485   thread->set_blocked_on_compilation(true);
  1487   methodHandle method(thread,
  1488                       (methodOop)JNIHandles::resolve(task->method_handle()));
  1490     MutexLocker waiter(task->lock(), thread);
  1492     while (!task->is_complete())
  1493       task->lock()->wait();
  1495   // It is harmless to check this status without the lock, because
  1496   // completion is a stable property (until the task object is recycled).
  1497   assert(task->is_complete(), "Compilation should have completed");
  1498   assert(task->code_handle() == NULL, "must be reset");
  1500   thread->set_blocked_on_compilation(false);
  1502   // By convention, the waiter is responsible for recycling a
  1503   // blocking CompileTask. Since there is only one waiter ever
  1504   // waiting on a CompileTask, we know that no one else will
  1505   // be using this CompileTask; we can free it.
  1506   free_task(task);
  1509 // ------------------------------------------------------------------
  1510 // CompileBroker::compiler_thread_loop
  1511 //
  1512 // The main loop run by a CompilerThread.
  1513 void CompileBroker::compiler_thread_loop() {
  1514   CompilerThread* thread = CompilerThread::current();
  1515   CompileQueue* queue = thread->queue();
  1517   // For the thread that initializes the ciObjectFactory
  1518   // this resource mark holds all the shared objects
  1519   ResourceMark rm;
  1521   // First thread to get here will initialize the compiler interface
  1523   if (!ciObjectFactory::is_initialized()) {
  1524     ASSERT_IN_VM;
  1525     MutexLocker only_one (CompileThread_lock, thread);
  1526     if (!ciObjectFactory::is_initialized()) {
  1527       ciObjectFactory::initialize();
  1531   // Open a log.
  1532   if (LogCompilation) {
  1533     init_compiler_thread_log();
  1535   CompileLog* log = thread->log();
  1536   if (log != NULL) {
  1537     log->begin_elem("start_compile_thread thread='" UINTX_FORMAT "' process='%d'",
  1538                     os::current_thread_id(),
  1539                     os::current_process_id());
  1540     log->stamp();
  1541     log->end_elem();
  1544   while (true) {
  1546       // We need this HandleMark to avoid leaking VM handles.
  1547       HandleMark hm(thread);
  1549       if (CodeCache::largest_free_block() < CodeCacheMinimumFreeSpace) {
  1550         // the code cache is really full
  1551         handle_full_code_cache();
  1552       } else if (UseCodeCacheFlushing && CodeCache::needs_flushing()) {
  1553         // Attempt to start cleaning the code cache while there is still a little headroom
  1554         NMethodSweeper::handle_full_code_cache(false);
  1557       CompileTask* task = queue->get();
  1559       // Give compiler threads an extra quanta.  They tend to be bursty and
  1560       // this helps the compiler to finish up the job.
  1561       if( CompilerThreadHintNoPreempt )
  1562         os::hint_no_preempt();
  1564       // trace per thread time and compile statistics
  1565       CompilerCounters* counters = ((CompilerThread*)thread)->counters();
  1566       PerfTraceTimedEvent(counters->time_counter(), counters->compile_counter());
  1568       // Assign the task to the current thread.  Mark this compilation
  1569       // thread as active for the profiler.
  1570       CompileTaskWrapper ctw(task);
  1571       nmethodLocker result_handle;  // (handle for the nmethod produced by this task)
  1572       task->set_code_handle(&result_handle);
  1573       methodHandle method(thread,
  1574                      (methodOop)JNIHandles::resolve(task->method_handle()));
  1576       // Never compile a method if breakpoints are present in it
  1577       if (method()->number_of_breakpoints() == 0) {
  1578         // Compile the method.
  1579         if ((UseCompiler || AlwaysCompileLoopMethods) && CompileBroker::should_compile_new_jobs()) {
  1580 #ifdef COMPILER1
  1581           // Allow repeating compilations for the purpose of benchmarking
  1582           // compile speed. This is not useful for customers.
  1583           if (CompilationRepeat != 0) {
  1584             int compile_count = CompilationRepeat;
  1585             while (compile_count > 0) {
  1586               invoke_compiler_on_method(task);
  1587               nmethod* nm = method->code();
  1588               if (nm != NULL) {
  1589                 nm->make_zombie();
  1590                 method->clear_code();
  1592               compile_count--;
  1595 #endif /* COMPILER1 */
  1596           invoke_compiler_on_method(task);
  1597         } else {
  1598           // After compilation is disabled, remove remaining methods from queue
  1599           method->clear_queued_for_compilation();
  1607 // ------------------------------------------------------------------
  1608 // CompileBroker::init_compiler_thread_log
  1609 //
  1610 // Set up state required by +LogCompilation.
  1611 void CompileBroker::init_compiler_thread_log() {
  1612     CompilerThread* thread = CompilerThread::current();
  1613     char  fileBuf[4*K];
  1614     FILE* fp = NULL;
  1615     char* file = NULL;
  1616     intx thread_id = os::current_thread_id();
  1617     for (int try_temp_dir = 1; try_temp_dir >= 0; try_temp_dir--) {
  1618       const char* dir = (try_temp_dir ? os::get_temp_directory() : NULL);
  1619       if (dir == NULL) {
  1620         jio_snprintf(fileBuf, sizeof(fileBuf), "hs_c" UINTX_FORMAT "_pid%u.log",
  1621                      thread_id, os::current_process_id());
  1622       } else {
  1623         jio_snprintf(fileBuf, sizeof(fileBuf),
  1624                      "%s%shs_c" UINTX_FORMAT "_pid%u.log", dir,
  1625                      os::file_separator(), thread_id, os::current_process_id());
  1627       fp = fopen(fileBuf, "at");
  1628       if (fp != NULL) {
  1629         file = NEW_C_HEAP_ARRAY(char, strlen(fileBuf)+1);
  1630         strcpy(file, fileBuf);
  1631         break;
  1634     if (fp == NULL) {
  1635       warning("Cannot open log file: %s", fileBuf);
  1636     } else {
  1637       if (LogCompilation && Verbose)
  1638         tty->print_cr("Opening compilation log %s", file);
  1639       CompileLog* log = new(ResourceObj::C_HEAP) CompileLog(file, fp, thread_id);
  1640       thread->init_log(log);
  1642       if (xtty != NULL) {
  1643         ttyLocker ttyl;
  1645         // Record any per thread log files
  1646         xtty->elem("thread_logfile thread='%d' filename='%s'", thread_id, file);
  1651 // ------------------------------------------------------------------
  1652 // CompileBroker::set_should_block
  1653 //
  1654 // Set _should_block.
  1655 // Call this from the VM, with Threads_lock held and a safepoint requested.
  1656 void CompileBroker::set_should_block() {
  1657   assert(Threads_lock->owner() == Thread::current(), "must have threads lock");
  1658   assert(SafepointSynchronize::is_at_safepoint(), "must be at a safepoint already");
  1659 #ifndef PRODUCT
  1660   if (PrintCompilation && (Verbose || WizardMode))
  1661     tty->print_cr("notifying compiler thread pool to block");
  1662 #endif
  1663   _should_block = true;
  1666 // ------------------------------------------------------------------
  1667 // CompileBroker::maybe_block
  1668 //
  1669 // Call this from the compiler at convenient points, to poll for _should_block.
  1670 void CompileBroker::maybe_block() {
  1671   if (_should_block) {
  1672 #ifndef PRODUCT
  1673     if (PrintCompilation && (Verbose || WizardMode))
  1674       tty->print_cr("compiler thread " INTPTR_FORMAT " poll detects block request", Thread::current());
  1675 #endif
  1676     ThreadInVMfromNative tivfn(JavaThread::current());
  1681 // ------------------------------------------------------------------
  1682 // CompileBroker::invoke_compiler_on_method
  1683 //
  1684 // Compile a method.
  1685 //
  1686 void CompileBroker::invoke_compiler_on_method(CompileTask* task) {
  1687   if (PrintCompilation) {
  1688     ResourceMark rm;
  1689     task->print_line();
  1691   elapsedTimer time;
  1693   CompilerThread* thread = CompilerThread::current();
  1694   ResourceMark rm(thread);
  1696   if (LogEvents) {
  1697     _compilation_log->log_compile(thread, task);
  1700   // Common flags.
  1701   uint compile_id = task->compile_id();
  1702   int osr_bci = task->osr_bci();
  1703   bool is_osr = (osr_bci != standard_entry_bci);
  1704   bool should_log = (thread->log() != NULL);
  1705   bool should_break = false;
  1707     // create the handle inside it's own block so it can't
  1708     // accidentally be referenced once the thread transitions to
  1709     // native.  The NoHandleMark before the transition should catch
  1710     // any cases where this occurs in the future.
  1711     methodHandle method(thread,
  1712                         (methodOop)JNIHandles::resolve(task->method_handle()));
  1713     should_break = check_break_at(method, compile_id, is_osr);
  1714     if (should_log && !CompilerOracle::should_log(method)) {
  1715       should_log = false;
  1717     assert(!method->is_native(), "no longer compile natives");
  1719     // Save information about this method in case of failure.
  1720     set_last_compile(thread, method, is_osr, task->comp_level());
  1722     DTRACE_METHOD_COMPILE_BEGIN_PROBE(compiler(task->comp_level()), method);
  1725   // Allocate a new set of JNI handles.
  1726   push_jni_handle_block();
  1727   jobject target_handle = JNIHandles::make_local(thread, JNIHandles::resolve(task->method_handle()));
  1728   int compilable = ciEnv::MethodCompilable;
  1730     int system_dictionary_modification_counter;
  1732       MutexLocker locker(Compile_lock, thread);
  1733       system_dictionary_modification_counter = SystemDictionary::number_of_modifications();
  1736     NoHandleMark  nhm;
  1737     ThreadToNativeFromVM ttn(thread);
  1739     ciEnv ci_env(task, system_dictionary_modification_counter);
  1740     if (should_break) {
  1741       ci_env.set_break_at_compile(true);
  1743     if (should_log) {
  1744       ci_env.set_log(thread->log());
  1746     assert(thread->env() == &ci_env, "set by ci_env");
  1747     // The thread-env() field is cleared in ~CompileTaskWrapper.
  1749     // Cache Jvmti state
  1750     ci_env.cache_jvmti_state();
  1752     // Cache DTrace flags
  1753     ci_env.cache_dtrace_flags();
  1755     ciMethod* target = ci_env.get_method_from_handle(target_handle);
  1757     TraceTime t1("compilation", &time);
  1759     compiler(task->comp_level())->compile_method(&ci_env, target, osr_bci);
  1761     if (!ci_env.failing() && task->code() == NULL) {
  1762       //assert(false, "compiler should always document failure");
  1763       // The compiler elected, without comment, not to register a result.
  1764       // Do not attempt further compilations of this method.
  1765       ci_env.record_method_not_compilable("compile failed", !TieredCompilation);
  1768     // Copy this bit to the enclosing block:
  1769     compilable = ci_env.compilable();
  1771     if (ci_env.failing()) {
  1772       const char* retry_message = ci_env.retry_message();
  1773       if (_compilation_log != NULL) {
  1774         _compilation_log->log_failure(thread, task, ci_env.failure_reason(), retry_message);
  1776       if (PrintCompilation) {
  1777         tty->print("%4d   COMPILE SKIPPED: %s", compile_id, ci_env.failure_reason());
  1778         if (retry_message != NULL) {
  1779           tty->print(" (%s)", retry_message);
  1781         tty->cr();
  1783     } else {
  1784       task->mark_success();
  1785       task->set_num_inlined_bytecodes(ci_env.num_inlined_bytecodes());
  1786       if (_compilation_log != NULL) {
  1787         nmethod* code = task->code();
  1788         if (code != NULL) {
  1789           _compilation_log->log_nmethod(thread, code);
  1794   pop_jni_handle_block();
  1796   methodHandle method(thread,
  1797                       (methodOop)JNIHandles::resolve(task->method_handle()));
  1799   DTRACE_METHOD_COMPILE_END_PROBE(compiler(task->comp_level()), method, task->is_success());
  1801   collect_statistics(thread, time, task);
  1803   if (PrintCompilation && PrintCompilation2) {
  1804     tty->print("%7d ", (int) tty->time_stamp().milliseconds());  // print timestamp
  1805     tty->print("%4d ", compile_id);    // print compilation number
  1806     tty->print("%s ", (is_osr ? "%" : " "));
  1807     int code_size = (task->code() == NULL) ? 0 : task->code()->total_size();
  1808     tty->print_cr("size: %d time: %d inlined: %d bytes", code_size, (int)time.milliseconds(), task->num_inlined_bytecodes());
  1811   if (compilable == ciEnv::MethodCompilable_never) {
  1812     if (is_osr) {
  1813       method->set_not_osr_compilable();
  1814     } else {
  1815       method->set_not_compilable_quietly();
  1817   } else if (compilable == ciEnv::MethodCompilable_not_at_tier) {
  1818     method->set_not_compilable_quietly(task->comp_level());
  1821   // Note that the queued_for_compilation bits are cleared without
  1822   // protection of a mutex. [They were set by the requester thread,
  1823   // when adding the task to the complie queue -- at which time the
  1824   // compile queue lock was held. Subsequently, we acquired the compile
  1825   // queue lock to get this task off the compile queue; thus (to belabour
  1826   // the point somewhat) our clearing of the bits must be occurring
  1827   // only after the setting of the bits. See also 14012000 above.
  1828   method->clear_queued_for_compilation();
  1830 #ifdef ASSERT
  1831   if (CollectedHeap::fired_fake_oom()) {
  1832     // The current compile received a fake OOM during compilation so
  1833     // go ahead and exit the VM since the test apparently succeeded
  1834     tty->print_cr("*** Shutting down VM after successful fake OOM");
  1835     vm_exit(0);
  1837 #endif
  1840 // ------------------------------------------------------------------
  1841 // CompileBroker::handle_full_code_cache
  1842 //
  1843 // The CodeCache is full.  Print out warning and disable compilation or
  1844 // try code cache cleaning so compilation can continue later.
  1845 void CompileBroker::handle_full_code_cache() {
  1846   UseInterpreter = true;
  1847   if (UseCompiler || AlwaysCompileLoopMethods ) {
  1848     if (xtty != NULL) {
  1849       stringStream s;
  1850       // Dump code cache state into a buffer before locking the tty,
  1851       // because log_state() will use locks causing lock conflicts.
  1852       CodeCache::log_state(&s);
  1853       // Lock to prevent tearing
  1854       ttyLocker ttyl;
  1855       xtty->begin_elem("code_cache_full");
  1856       xtty->print(s.as_string());
  1857       xtty->stamp();
  1858       xtty->end_elem();
  1860     warning("CodeCache is full. Compiler has been disabled.");
  1861     warning("Try increasing the code cache size using -XX:ReservedCodeCacheSize=");
  1862     CodeCache::print_bounds(tty);
  1863 #ifndef PRODUCT
  1864     if (CompileTheWorld || ExitOnFullCodeCache) {
  1865       before_exit(JavaThread::current());
  1866       exit_globals(); // will delete tty
  1867       vm_direct_exit(CompileTheWorld ? 0 : 1);
  1869 #endif
  1870     if (UseCodeCacheFlushing) {
  1871       NMethodSweeper::handle_full_code_cache(true);
  1872     } else {
  1873       UseCompiler               = false;
  1874       AlwaysCompileLoopMethods  = false;
  1879 // ------------------------------------------------------------------
  1880 // CompileBroker::set_last_compile
  1881 //
  1882 // Record this compilation for debugging purposes.
  1883 void CompileBroker::set_last_compile(CompilerThread* thread, methodHandle method, bool is_osr, int comp_level) {
  1884   ResourceMark rm;
  1885   char* method_name = method->name()->as_C_string();
  1886   strncpy(_last_method_compiled, method_name, CompileBroker::name_buffer_length);
  1887   char current_method[CompilerCounters::cmname_buffer_length];
  1888   size_t maxLen = CompilerCounters::cmname_buffer_length;
  1890   if (UsePerfData) {
  1891     const char* class_name = method->method_holder()->klass_part()->name()->as_C_string();
  1893     size_t s1len = strlen(class_name);
  1894     size_t s2len = strlen(method_name);
  1896     // check if we need to truncate the string
  1897     if (s1len + s2len + 2 > maxLen) {
  1899       // the strategy is to lop off the leading characters of the
  1900       // class name and the trailing characters of the method name.
  1902       if (s2len + 2 > maxLen) {
  1903         // lop of the entire class name string, let snprintf handle
  1904         // truncation of the method name.
  1905         class_name += s1len; // null string
  1907       else {
  1908         // lop off the extra characters from the front of the class name
  1909         class_name += ((s1len + s2len + 2) - maxLen);
  1913     jio_snprintf(current_method, maxLen, "%s %s", class_name, method_name);
  1916   if (CICountOSR && is_osr) {
  1917     _last_compile_type = osr_compile;
  1918   } else {
  1919     _last_compile_type = normal_compile;
  1921   _last_compile_level = comp_level;
  1923   if (UsePerfData) {
  1924     CompilerCounters* counters = thread->counters();
  1925     counters->set_current_method(current_method);
  1926     counters->set_compile_type((jlong)_last_compile_type);
  1931 // ------------------------------------------------------------------
  1932 // CompileBroker::push_jni_handle_block
  1933 //
  1934 // Push on a new block of JNI handles.
  1935 void CompileBroker::push_jni_handle_block() {
  1936   JavaThread* thread = JavaThread::current();
  1938   // Allocate a new block for JNI handles.
  1939   // Inlined code from jni_PushLocalFrame()
  1940   JNIHandleBlock* java_handles = thread->active_handles();
  1941   JNIHandleBlock* compile_handles = JNIHandleBlock::allocate_block(thread);
  1942   assert(compile_handles != NULL && java_handles != NULL, "should not be NULL");
  1943   compile_handles->set_pop_frame_link(java_handles);  // make sure java handles get gc'd.
  1944   thread->set_active_handles(compile_handles);
  1948 // ------------------------------------------------------------------
  1949 // CompileBroker::pop_jni_handle_block
  1950 //
  1951 // Pop off the current block of JNI handles.
  1952 void CompileBroker::pop_jni_handle_block() {
  1953   JavaThread* thread = JavaThread::current();
  1955   // Release our JNI handle block
  1956   JNIHandleBlock* compile_handles = thread->active_handles();
  1957   JNIHandleBlock* java_handles = compile_handles->pop_frame_link();
  1958   thread->set_active_handles(java_handles);
  1959   compile_handles->set_pop_frame_link(NULL);
  1960   JNIHandleBlock::release_block(compile_handles, thread); // may block
  1964 // ------------------------------------------------------------------
  1965 // CompileBroker::check_break_at
  1966 //
  1967 // Should the compilation break at the current compilation.
  1968 bool CompileBroker::check_break_at(methodHandle method, int compile_id, bool is_osr) {
  1969   if (CICountOSR && is_osr && (compile_id == CIBreakAtOSR)) {
  1970     return true;
  1971   } else if( CompilerOracle::should_break_at(method) ) { // break when compiling
  1972     return true;
  1973   } else {
  1974     return (compile_id == CIBreakAt);
  1978 // ------------------------------------------------------------------
  1979 // CompileBroker::collect_statistics
  1980 //
  1981 // Collect statistics about the compilation.
  1983 void CompileBroker::collect_statistics(CompilerThread* thread, elapsedTimer time, CompileTask* task) {
  1984   bool success = task->is_success();
  1985   methodHandle method (thread, (methodOop)JNIHandles::resolve(task->method_handle()));
  1986   uint compile_id = task->compile_id();
  1987   bool is_osr = (task->osr_bci() != standard_entry_bci);
  1988   nmethod* code = task->code();
  1989   CompilerCounters* counters = thread->counters();
  1991   assert(code == NULL || code->is_locked_by_vm(), "will survive the MutexLocker");
  1992   MutexLocker locker(CompileStatistics_lock);
  1994   // _perf variables are production performance counters which are
  1995   // updated regardless of the setting of the CITime and CITimeEach flags
  1996   //
  1997   if (!success) {
  1998     _total_bailout_count++;
  1999     if (UsePerfData) {
  2000       _perf_last_failed_method->set_value(counters->current_method());
  2001       _perf_last_failed_type->set_value(counters->compile_type());
  2002       _perf_total_bailout_count->inc();
  2004   } else if (code == NULL) {
  2005     if (UsePerfData) {
  2006       _perf_last_invalidated_method->set_value(counters->current_method());
  2007       _perf_last_invalidated_type->set_value(counters->compile_type());
  2008       _perf_total_invalidated_count->inc();
  2010     _total_invalidated_count++;
  2011   } else {
  2012     // Compilation succeeded
  2014     // update compilation ticks - used by the implementation of
  2015     // java.lang.management.CompilationMBean
  2016     _perf_total_compilation->inc(time.ticks());
  2018     if (CITime) {
  2019       _t_total_compilation.add(time);
  2020       if (is_osr) {
  2021         _t_osr_compilation.add(time);
  2022         _sum_osr_bytes_compiled += method->code_size() + task->num_inlined_bytecodes();
  2023       } else {
  2024         _t_standard_compilation.add(time);
  2025         _sum_standard_bytes_compiled += method->code_size() + task->num_inlined_bytecodes();
  2029     if (UsePerfData) {
  2030       // save the name of the last method compiled
  2031       _perf_last_method->set_value(counters->current_method());
  2032       _perf_last_compile_type->set_value(counters->compile_type());
  2033       _perf_last_compile_size->set_value(method->code_size() +
  2034                                          task->num_inlined_bytecodes());
  2035       if (is_osr) {
  2036         _perf_osr_compilation->inc(time.ticks());
  2037         _perf_sum_osr_bytes_compiled->inc(method->code_size() + task->num_inlined_bytecodes());
  2038       } else {
  2039         _perf_standard_compilation->inc(time.ticks());
  2040         _perf_sum_standard_bytes_compiled->inc(method->code_size() + task->num_inlined_bytecodes());
  2044     if (CITimeEach) {
  2045       float bytes_per_sec = 1.0 * (method->code_size() + task->num_inlined_bytecodes()) / time.seconds();
  2046       tty->print_cr("%3d   seconds: %f bytes/sec : %f (bytes %d + %d inlined)",
  2047                     compile_id, time.seconds(), bytes_per_sec, method->code_size(), task->num_inlined_bytecodes());
  2050     // Collect counts of successful compilations
  2051     _sum_nmethod_size      += code->total_size();
  2052     _sum_nmethod_code_size += code->insts_size();
  2053     _total_compile_count++;
  2055     if (UsePerfData) {
  2056       _perf_sum_nmethod_size->inc(     code->total_size());
  2057       _perf_sum_nmethod_code_size->inc(code->insts_size());
  2058       _perf_total_compile_count->inc();
  2061     if (is_osr) {
  2062       if (UsePerfData) _perf_total_osr_compile_count->inc();
  2063       _total_osr_compile_count++;
  2064     } else {
  2065       if (UsePerfData) _perf_total_standard_compile_count->inc();
  2066       _total_standard_compile_count++;
  2069   // set the current method for the thread to null
  2070   if (UsePerfData) counters->set_current_method("");
  2075 void CompileBroker::print_times() {
  2076   tty->cr();
  2077   tty->print_cr("Accumulated compiler times (for compiled methods only)");
  2078   tty->print_cr("------------------------------------------------");
  2079                //0000000000111111111122222222223333333333444444444455555555556666666666
  2080                //0123456789012345678901234567890123456789012345678901234567890123456789
  2081   tty->print_cr("  Total compilation time   : %6.3f s", CompileBroker::_t_total_compilation.seconds());
  2082   tty->print_cr("    Standard compilation   : %6.3f s, Average : %2.3f",
  2083                 CompileBroker::_t_standard_compilation.seconds(),
  2084                 CompileBroker::_t_standard_compilation.seconds() / CompileBroker::_total_standard_compile_count);
  2085   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);
  2087   if (compiler(CompLevel_simple) != NULL) {
  2088     compiler(CompLevel_simple)->print_timers();
  2090   if (compiler(CompLevel_full_optimization) != NULL) {
  2091     compiler(CompLevel_full_optimization)->print_timers();
  2093   tty->cr();
  2094   int tcb = CompileBroker::_sum_osr_bytes_compiled + CompileBroker::_sum_standard_bytes_compiled;
  2095   tty->print_cr("  Total compiled bytecodes : %6d bytes", tcb);
  2096   tty->print_cr("    Standard compilation   : %6d bytes", CompileBroker::_sum_standard_bytes_compiled);
  2097   tty->print_cr("    On stack replacement   : %6d bytes", CompileBroker::_sum_osr_bytes_compiled);
  2098   int bps = (int)(tcb / CompileBroker::_t_total_compilation.seconds());
  2099   tty->print_cr("  Average compilation speed: %6d bytes/s", bps);
  2100   tty->cr();
  2101   tty->print_cr("  nmethod code size        : %6d bytes", CompileBroker::_sum_nmethod_code_size);
  2102   tty->print_cr("  nmethod total size       : %6d bytes", CompileBroker::_sum_nmethod_size);
  2106 // Debugging output for failure
  2107 void CompileBroker::print_last_compile() {
  2108   if ( _last_compile_level != CompLevel_none &&
  2109        compiler(_last_compile_level) != NULL &&
  2110        _last_method_compiled != NULL &&
  2111        _last_compile_type != no_compile) {
  2112     if (_last_compile_type == osr_compile) {
  2113       tty->print_cr("Last parse:  [osr]%d+++(%d) %s",
  2114                     _osr_compilation_id, _last_compile_level, _last_method_compiled);
  2115     } else {
  2116       tty->print_cr("Last parse:  %d+++(%d) %s",
  2117                     _compilation_id, _last_compile_level, _last_method_compiled);
  2123 void CompileBroker::print_compiler_threads_on(outputStream* st) {
  2124 #ifndef PRODUCT
  2125   st->print_cr("Compiler thread printing unimplemented.");
  2126   st->cr();
  2127 #endif

mercurial