1 /*
   2  * Copyright (c) 1999, 2014, 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  */
  24 
  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/methodData.hpp"
  35 #include "oops/method.hpp"
  36 #include "oops/oop.inline.hpp"
  37 #include "prims/nativeLookup.hpp"
  38 #include "runtime/arguments.hpp"
  39 #include "runtime/atomic.inline.hpp"
  40 #include "runtime/compilationPolicy.hpp"
  41 #include "runtime/init.hpp"
  42 #include "runtime/interfaceSupport.hpp"
  43 #include "runtime/javaCalls.hpp"
  44 #include "runtime/os.hpp"
  45 #include "runtime/sharedRuntime.hpp"
  46 #include "runtime/sweeper.hpp"
  47 #include "trace/tracing.hpp"
  48 #include "utilities/dtrace.hpp"
  49 #include "utilities/events.hpp"
  50 #ifdef COMPILER1
  51 #include "c1/c1_Compiler.hpp"
  52 #endif
  53 #ifdef COMPILER2
  54 #include "opto/c2compiler.hpp"
  55 #endif
  56 #ifdef SHARK
  57 #include "shark/sharkCompiler.hpp"
  58 #endif
  59 
  60 #ifdef DTRACE_ENABLED
  61 
  62 // Only bother with this argument setup if dtrace is available
  63 
  64 #define DTRACE_METHOD_COMPILE_BEGIN_PROBE(method, comp_name)             \
  65   {                                                                      \
  66     Symbol* klass_name = (method)->klass_name();                         \
  67     Symbol* name = (method)->name();                                     \
  68     Symbol* signature = (method)->signature();                           \
  69     HOTSPOT_METHOD_COMPILE_BEGIN(                                        \
  70       (char *) comp_name, strlen(comp_name),                             \
  71       (char *) klass_name->bytes(), klass_name->utf8_length(),           \
  72       (char *) name->bytes(), name->utf8_length(),                       \
  73       (char *) signature->bytes(), signature->utf8_length());            \
  74   }
  75 
  76 #define DTRACE_METHOD_COMPILE_END_PROBE(method, comp_name, success)      \
  77   {                                                                      \
  78     Symbol* klass_name = (method)->klass_name();                         \
  79     Symbol* name = (method)->name();                                     \
  80     Symbol* signature = (method)->signature();                           \
  81     HOTSPOT_METHOD_COMPILE_END(                                          \
  82       (char *) comp_name, strlen(comp_name),                             \
  83       (char *) klass_name->bytes(), klass_name->utf8_length(),           \
  84       (char *) name->bytes(), name->utf8_length(),                       \
  85       (char *) signature->bytes(), signature->utf8_length(), (success)); \
  86   }
  87 
  88 #else //  ndef DTRACE_ENABLED
  89 
  90 #define DTRACE_METHOD_COMPILE_BEGIN_PROBE(method, comp_name)
  91 #define DTRACE_METHOD_COMPILE_END_PROBE(method, comp_name, success)
  92 
  93 #endif // ndef DTRACE_ENABLED
  94 
  95 bool CompileBroker::_initialized = false;
  96 volatile bool CompileBroker::_should_block = false;
  97 volatile jint CompileBroker::_print_compilation_warning = 0;
  98 volatile jint CompileBroker::_should_compile_new_jobs = run_compilation;
  99 
 100 // The installed compiler(s)
 101 AbstractCompiler* CompileBroker::_compilers[2];
 102 
 103 // These counters are used to assign an unique ID to each compilation.
 104 volatile jint CompileBroker::_compilation_id     = 0;
 105 volatile jint CompileBroker::_osr_compilation_id = 0;
 106 
 107 // Debugging information
 108 int  CompileBroker::_last_compile_type     = no_compile;
 109 int  CompileBroker::_last_compile_level    = CompLevel_none;
 110 char CompileBroker::_last_method_compiled[CompileBroker::name_buffer_length];
 111 
 112 // Performance counters
 113 PerfCounter* CompileBroker::_perf_total_compilation = NULL;
 114 PerfCounter* CompileBroker::_perf_osr_compilation = NULL;
 115 PerfCounter* CompileBroker::_perf_standard_compilation = NULL;
 116 
 117 PerfCounter* CompileBroker::_perf_total_bailout_count = NULL;
 118 PerfCounter* CompileBroker::_perf_total_invalidated_count = NULL;
 119 PerfCounter* CompileBroker::_perf_total_compile_count = NULL;
 120 PerfCounter* CompileBroker::_perf_total_osr_compile_count = NULL;
 121 PerfCounter* CompileBroker::_perf_total_standard_compile_count = NULL;
 122 
 123 PerfCounter* CompileBroker::_perf_sum_osr_bytes_compiled = NULL;
 124 PerfCounter* CompileBroker::_perf_sum_standard_bytes_compiled = NULL;
 125 PerfCounter* CompileBroker::_perf_sum_nmethod_size = NULL;
 126 PerfCounter* CompileBroker::_perf_sum_nmethod_code_size = NULL;
 127 
 128 PerfStringVariable* CompileBroker::_perf_last_method = NULL;
 129 PerfStringVariable* CompileBroker::_perf_last_failed_method = NULL;
 130 PerfStringVariable* CompileBroker::_perf_last_invalidated_method = NULL;
 131 PerfVariable*       CompileBroker::_perf_last_compile_type = NULL;
 132 PerfVariable*       CompileBroker::_perf_last_compile_size = NULL;
 133 PerfVariable*       CompileBroker::_perf_last_failed_type = NULL;
 134 PerfVariable*       CompileBroker::_perf_last_invalidated_type = NULL;
 135 
 136 // Timers and counters for generating statistics
 137 elapsedTimer CompileBroker::_t_total_compilation;
 138 elapsedTimer CompileBroker::_t_osr_compilation;
 139 elapsedTimer CompileBroker::_t_standard_compilation;
 140 elapsedTimer CompileBroker::_t_invalidated_compilation;
 141 elapsedTimer CompileBroker::_t_bailedout_compilation;
 142 
 143 int CompileBroker::_total_bailout_count          = 0;
 144 int CompileBroker::_total_invalidated_count      = 0;
 145 int CompileBroker::_total_compile_count          = 0;
 146 int CompileBroker::_total_osr_compile_count      = 0;
 147 int CompileBroker::_total_standard_compile_count = 0;
 148 
 149 int CompileBroker::_sum_osr_bytes_compiled       = 0;
 150 int CompileBroker::_sum_standard_bytes_compiled  = 0;
 151 int CompileBroker::_sum_nmethod_size             = 0;
 152 int CompileBroker::_sum_nmethod_code_size        = 0;
 153 
 154 long CompileBroker::_peak_compilation_time       = 0;
 155 
 156 CompileQueue* CompileBroker::_c2_compile_queue   = NULL;
 157 CompileQueue* CompileBroker::_c1_compile_queue   = NULL;
 158 
 159 GrowableArray<CompilerThread*>* CompileBroker::_compiler_threads = NULL;
 160 
 161 
 162 class CompilationLog : public StringEventLog {
 163  public:
 164   CompilationLog() : StringEventLog("Compilation events") {
 165   }
 166 
 167   void log_compile(JavaThread* thread, CompileTask* task) {
 168     StringLogMessage lm;
 169     stringStream sstr = lm.stream();
 170     // msg.time_stamp().update_to(tty->time_stamp().ticks());
 171     task->print_compilation(&sstr, NULL, true, false);
 172     log(thread, "%s", (const char*)lm);
 173   }
 174 
 175   void log_nmethod(JavaThread* thread, nmethod* nm) {
 176     log(thread, "nmethod %d%s " INTPTR_FORMAT " code ["INTPTR_FORMAT ", " INTPTR_FORMAT "]",
 177         nm->compile_id(), nm->is_osr_method() ? "%" : "",
 178         p2i(nm), p2i(nm->code_begin()), p2i(nm->code_end()));
 179   }
 180 
 181   void log_failure(JavaThread* thread, CompileTask* task, const char* reason, const char* retry_message) {
 182     StringLogMessage lm;
 183     lm.print("%4d   COMPILE SKIPPED: %s", task->compile_id(), reason);
 184     if (retry_message != NULL) {
 185       lm.append(" (%s)", retry_message);
 186     }
 187     lm.print("\n");
 188     log(thread, "%s", (const char*)lm);
 189   }
 190 };
 191 
 192 static CompilationLog* _compilation_log = NULL;
 193 
 194 void compileBroker_init() {
 195   if (LogEvents) {
 196     _compilation_log = new CompilationLog();
 197   }
 198 }
 199 
 200 CompileTaskWrapper::CompileTaskWrapper(CompileTask* task) {
 201   CompilerThread* thread = CompilerThread::current();
 202   thread->set_task(task);
 203   CompileLog*     log  = thread->log();
 204   if (log != NULL)  task->log_task_start(log);
 205 }
 206 
 207 CompileTaskWrapper::~CompileTaskWrapper() {
 208   CompilerThread* thread = CompilerThread::current();
 209   CompileTask* task = thread->task();
 210   CompileLog*  log  = thread->log();
 211   if (log != NULL)  task->log_task_done(log);
 212   thread->set_task(NULL);
 213   task->set_code_handle(NULL);
 214   thread->set_env(NULL);
 215   if (task->is_blocking()) {
 216     MutexLocker notifier(task->lock(), thread);
 217     task->mark_complete();
 218     // Notify the waiting thread that the compilation has completed.
 219     task->lock()->notify_all();
 220   } else {
 221     task->mark_complete();
 222 
 223     // By convention, the compiling thread is responsible for
 224     // recycling a non-blocking CompileTask.
 225     CompileTask::free(task);
 226   }
 227 }
 228 
 229 
 230 CompileTask*  CompileTask::_task_free_list = NULL;
 231 #ifdef ASSERT
 232 int CompileTask::_num_allocated_tasks = 0;
 233 #endif
 234 /**
 235  * Allocate a CompileTask, from the free list if possible.
 236  */
 237 CompileTask* CompileTask::allocate() {
 238   MutexLocker locker(CompileTaskAlloc_lock);
 239   CompileTask* task = NULL;
 240 
 241   if (_task_free_list != NULL) {
 242     task = _task_free_list;
 243     _task_free_list = task->next();
 244     task->set_next(NULL);
 245   } else {
 246     task = new CompileTask();
 247     DEBUG_ONLY(_num_allocated_tasks++;)
 248     assert (_num_allocated_tasks < 10000, "Leaking compilation tasks?");
 249     task->set_next(NULL);
 250     task->set_is_free(true);
 251   }
 252   assert(task->is_free(), "Task must be free.");
 253   task->set_is_free(false);
 254   return task;
 255 }
 256 
 257 
 258 /**
 259  * Add a task to the free list.
 260  */
 261 void CompileTask::free(CompileTask* task) {
 262   MutexLocker locker(CompileTaskAlloc_lock);
 263   if (!task->is_free()) {
 264     task->set_code(NULL);
 265     assert(!task->lock()->is_locked(), "Should not be locked when freed");
 266     JNIHandles::destroy_global(task->_method_holder);
 267     JNIHandles::destroy_global(task->_hot_method_holder);
 268 
 269     task->set_is_free(true);
 270     task->set_next(_task_free_list);
 271     _task_free_list = task;
 272   }
 273 }
 274 
 275 void CompileTask::initialize(int compile_id,
 276                              methodHandle method,
 277                              int osr_bci,
 278                              int comp_level,
 279                              methodHandle hot_method,
 280                              int hot_count,
 281                              const char* comment,
 282                              bool is_blocking) {
 283   assert(!_lock->is_locked(), "bad locking");
 284 
 285   _compile_id = compile_id;
 286   _method = method();
 287   _method_holder = JNIHandles::make_global(method->method_holder()->klass_holder());
 288   _osr_bci = osr_bci;
 289   _is_blocking = is_blocking;
 290   _comp_level = comp_level;
 291   _num_inlined_bytecodes = 0;
 292 
 293   _is_complete = false;
 294   _is_success = false;
 295   _code_handle = NULL;
 296 
 297   _hot_method = NULL;
 298   _hot_method_holder = NULL;
 299   _hot_count = hot_count;
 300   _time_queued = 0;  // tidy
 301   _comment = comment;
 302   _failure_reason = NULL;
 303 
 304   if (LogCompilation) {
 305     _time_queued = os::elapsed_counter();
 306     if (hot_method.not_null()) {
 307       if (hot_method == method) {
 308         _hot_method = _method;
 309       } else {
 310         _hot_method = hot_method();
 311         // only add loader or mirror if different from _method_holder
 312         _hot_method_holder = JNIHandles::make_global(hot_method->method_holder()->klass_holder());
 313       }
 314     }
 315   }
 316 
 317   _next = NULL;
 318 }
 319 
 320 // ------------------------------------------------------------------
 321 // CompileTask::code/set_code
 322 nmethod* CompileTask::code() const {
 323   if (_code_handle == NULL)  return NULL;
 324   return _code_handle->code();
 325 }
 326 void CompileTask::set_code(nmethod* nm) {
 327   if (_code_handle == NULL && nm == NULL)  return;
 328   guarantee(_code_handle != NULL, "");
 329   _code_handle->set_code(nm);
 330   if (nm == NULL)  _code_handle = NULL;  // drop the handle also
 331 }
 332 
 333 void CompileTask::mark_on_stack() {
 334   // Mark these methods as something redefine classes cannot remove.
 335   _method->set_on_stack(true);
 336   if (_hot_method != NULL) {
 337     _hot_method->set_on_stack(true);
 338   }
 339 }
 340 
 341 // ------------------------------------------------------------------
 342 // CompileTask::print_line_on_error
 343 //
 344 // This function is called by fatal error handler when the thread
 345 // causing troubles is a compiler thread.
 346 //
 347 // Do not grab any lock, do not allocate memory.
 348 //
 349 // Otherwise it's the same as CompileTask::print_line()
 350 //
 351 void CompileTask::print_line_on_error(outputStream* st, char* buf, int buflen) {
 352   // print compiler name
 353   st->print("%s:", CompileBroker::compiler_name(comp_level()));
 354   print_compilation(st);
 355 }
 356 
 357 // ------------------------------------------------------------------
 358 // CompileTask::print_line
 359 void CompileTask::print_tty() {
 360   ttyLocker ttyl;  // keep the following output all in one block
 361   // print compiler name if requested
 362   if (CIPrintCompilerName) tty->print("%s:", CompileBroker::compiler_name(comp_level()));
 363     print_compilation(tty);
 364 }
 365 
 366 // ------------------------------------------------------------------
 367 // CompileTask::print_compilation_impl
 368 void CompileTask::print_compilation_impl(outputStream* st, Method* method, int compile_id, int comp_level,
 369                                          bool is_osr_method, int osr_bci, bool is_blocking,
 370                                          const char* msg, bool short_form, bool cr) {
 371   if (!short_form) {
 372     st->print("%7d ", (int) st->time_stamp().milliseconds());  // print timestamp
 373   }
 374   st->print("%4d ", compile_id);    // print compilation number
 375 
 376   // For unloaded methods the transition to zombie occurs after the
 377   // method is cleared so it's impossible to report accurate
 378   // information for that case.
 379   bool is_synchronized = false;
 380   bool has_exception_handler = false;
 381   bool is_native = false;
 382   if (method != NULL) {
 383     is_synchronized       = method->is_synchronized();
 384     has_exception_handler = method->has_exception_handler();
 385     is_native             = method->is_native();
 386   }
 387   // method attributes
 388   const char compile_type   = is_osr_method                   ? '%' : ' ';
 389   const char sync_char      = is_synchronized                 ? 's' : ' ';
 390   const char exception_char = has_exception_handler           ? '!' : ' ';
 391   const char blocking_char  = is_blocking                     ? 'b' : ' ';
 392   const char native_char    = is_native                       ? 'n' : ' ';
 393 
 394   // print method attributes
 395   st->print("%c%c%c%c%c ", compile_type, sync_char, exception_char, blocking_char, native_char);
 396 
 397   if (TieredCompilation) {
 398     if (comp_level != -1)  st->print("%d ", comp_level);
 399     else                   st->print("- ");
 400   }
 401   st->print("     ");  // more indent
 402 
 403   if (method == NULL) {
 404     st->print("(method)");
 405   } else {
 406     method->print_short_name(st);
 407     if (is_osr_method) {
 408       st->print(" @ %d", osr_bci);
 409     }
 410     if (method->is_native())
 411       st->print(" (native)");
 412     else
 413       st->print(" (%d bytes)", method->code_size());
 414   }
 415 
 416   if (msg != NULL) {
 417     st->print("   %s", msg);
 418   }
 419   if (cr) {
 420     st->cr();
 421   }
 422 }
 423 
 424 // ------------------------------------------------------------------
 425 // CompileTask::print_inlining
 426 void CompileTask::print_inlining(outputStream* st, ciMethod* method, int inline_level, int bci, const char* msg) {
 427   //         1234567
 428   st->print("        ");     // print timestamp
 429   //         1234
 430   st->print("     ");        // print compilation number
 431 
 432   // method attributes
 433   if (method->is_loaded()) {
 434     const char sync_char      = method->is_synchronized()        ? 's' : ' ';
 435     const char exception_char = method->has_exception_handlers() ? '!' : ' ';
 436     const char monitors_char  = method->has_monitor_bytecodes()  ? 'm' : ' ';
 437 
 438     // print method attributes
 439     st->print(" %c%c%c  ", sync_char, exception_char, monitors_char);
 440   } else {
 441     //         %s!bn
 442     st->print("      ");     // print method attributes
 443   }
 444 
 445   if (TieredCompilation) {
 446     st->print("  ");
 447   }
 448   st->print("     ");        // more indent
 449   st->print("    ");         // initial inlining indent
 450 
 451   for (int i = 0; i < inline_level; i++)  st->print("  ");
 452 
 453   st->print("@ %d  ", bci);  // print bci
 454   method->print_short_name(st);
 455   if (method->is_loaded())
 456     st->print(" (%d bytes)", method->code_size());
 457   else
 458     st->print(" (not loaded)");
 459 
 460   if (msg != NULL) {
 461     st->print("   %s", msg);
 462   }
 463   st->cr();
 464 }
 465 
 466 // ------------------------------------------------------------------
 467 // CompileTask::print_inline_indent
 468 void CompileTask::print_inline_indent(int inline_level, outputStream* st) {
 469   //         1234567
 470   st->print("        ");     // print timestamp
 471   //         1234
 472   st->print("     ");        // print compilation number
 473   //         %s!bn
 474   st->print("      ");       // print method attributes
 475   if (TieredCompilation) {
 476     st->print("  ");
 477   }
 478   st->print("     ");        // more indent
 479   st->print("    ");         // initial inlining indent
 480   for (int i = 0; i < inline_level; i++)  st->print("  ");
 481 }
 482 
 483 // ------------------------------------------------------------------
 484 // CompileTask::print_compilation
 485 void CompileTask::print_compilation(outputStream* st, const char* msg, bool short_form, bool cr) {
 486   bool is_osr_method = osr_bci() != InvocationEntryBci;
 487   print_compilation_impl(st, method(), compile_id(), comp_level(), is_osr_method, osr_bci(), is_blocking(), msg, short_form, cr);
 488 }
 489 
 490 // ------------------------------------------------------------------
 491 // CompileTask::log_task
 492 void CompileTask::log_task(xmlStream* log) {
 493   Thread* thread = Thread::current();
 494   methodHandle method(thread, this->method());
 495   ResourceMark rm(thread);
 496 
 497   // <task id='9' method='M' osr_bci='X' level='1' blocking='1' stamp='1.234'>
 498   log->print(" compile_id='%d'", _compile_id);
 499   if (_osr_bci != CompileBroker::standard_entry_bci) {
 500     log->print(" compile_kind='osr'");  // same as nmethod::compile_kind
 501   } // else compile_kind='c2c'
 502   if (!method.is_null())  log->method(method);
 503   if (_osr_bci != CompileBroker::standard_entry_bci) {
 504     log->print(" osr_bci='%d'", _osr_bci);
 505   }
 506   if (_comp_level != CompLevel_highest_tier) {
 507     log->print(" level='%d'", _comp_level);
 508   }
 509   if (_is_blocking) {
 510     log->print(" blocking='1'");
 511   }
 512   log->stamp();
 513 }
 514 
 515 
 516 // ------------------------------------------------------------------
 517 // CompileTask::log_task_queued
 518 void CompileTask::log_task_queued() {
 519   Thread* thread = Thread::current();
 520   ttyLocker ttyl;
 521   ResourceMark rm(thread);
 522 
 523   xtty->begin_elem("task_queued");
 524   log_task(xtty);
 525   if (_comment != NULL) {
 526     xtty->print(" comment='%s'", _comment);
 527   }
 528   if (_hot_method != NULL) {
 529     methodHandle hot(thread, _hot_method);
 530     methodHandle method(thread, _method);
 531     if (hot() != method()) {
 532       xtty->method(hot);
 533     }
 534   }
 535   if (_hot_count != 0) {
 536     xtty->print(" hot_count='%d'", _hot_count);
 537   }
 538   xtty->end_elem();
 539 }
 540 
 541 
 542 // ------------------------------------------------------------------
 543 // CompileTask::log_task_start
 544 void CompileTask::log_task_start(CompileLog* log)   {
 545   log->begin_head("task");
 546   log_task(log);
 547   log->end_head();
 548 }
 549 
 550 
 551 // ------------------------------------------------------------------
 552 // CompileTask::log_task_done
 553 void CompileTask::log_task_done(CompileLog* log) {
 554   Thread* thread = Thread::current();
 555   methodHandle method(thread, this->method());
 556   ResourceMark rm(thread);
 557 
 558   if (!_is_success) {
 559     const char* reason = _failure_reason != NULL ? _failure_reason : "unknown";
 560     log->elem("failure reason='%s'", reason);
 561   }
 562 
 563   // <task_done ... stamp='1.234'>  </task>
 564   nmethod* nm = code();
 565   log->begin_elem("task_done success='%d' nmsize='%d' count='%d'",
 566                   _is_success, nm == NULL ? 0 : nm->content_size(),
 567                   method->invocation_count());
 568   int bec = method->backedge_count();
 569   if (bec != 0)  log->print(" backedge_count='%d'", bec);
 570   // Note:  "_is_complete" is about to be set, but is not.
 571   if (_num_inlined_bytecodes != 0) {
 572     log->print(" inlined_bytes='%d'", _num_inlined_bytecodes);
 573   }
 574   log->stamp();
 575   log->end_elem();
 576   log->tail("task");
 577   log->clear_identities();   // next task will have different CI
 578   if (log->unflushed_count() > 2000) {
 579     log->flush();
 580   }
 581   log->mark_file_end();
 582 }
 583 
 584 
 585 
 586 /**
 587  * Add a CompileTask to a CompileQueue.
 588  */
 589 void CompileQueue::add(CompileTask* task) {
 590   assert(lock()->owned_by_self(), "must own lock");
 591 
 592   task->set_next(NULL);
 593   task->set_prev(NULL);
 594 
 595   if (_last == NULL) {
 596     // The compile queue is empty.
 597     assert(_first == NULL, "queue is empty");
 598     _first = task;
 599     _last = task;
 600   } else {
 601     // Append the task to the queue.
 602     assert(_last->next() == NULL, "not last");
 603     _last->set_next(task);
 604     task->set_prev(_last);
 605     _last = task;
 606   }
 607   ++_size;
 608 
 609   // Mark the method as being in the compile queue.
 610   task->method()->set_queued_for_compilation();
 611 
 612   if (CIPrintCompileQueue) {
 613     print_tty();
 614   }
 615 
 616   if (LogCompilation && xtty != NULL) {
 617     task->log_task_queued();
 618   }
 619 
 620   // Notify CompilerThreads that a task is available.
 621   lock()->notify_all();
 622 }
 623 
 624 /**
 625  * Empties compilation queue by putting all compilation tasks onto
 626  * a freelist. Furthermore, the method wakes up all threads that are
 627  * waiting on a compilation task to finish. This can happen if background
 628  * compilation is disabled.
 629  */
 630 void CompileQueue::free_all() {
 631   MutexLocker mu(lock());
 632   CompileTask* next = _first;
 633 
 634   // Iterate over all tasks in the compile queue
 635   while (next != NULL) {
 636     CompileTask* current = next;
 637     next = current->next();
 638     {
 639       // Wake up thread that blocks on the compile task.
 640       MutexLocker ct_lock(current->lock());
 641       current->lock()->notify();
 642     }
 643     // Put the task back on the freelist.
 644     CompileTask::free(current);
 645   }
 646   _first = NULL;
 647 
 648   // Wake up all threads that block on the queue.
 649   lock()->notify_all();
 650 }
 651 
 652 // ------------------------------------------------------------------
 653 // CompileQueue::get
 654 //
 655 // Get the next CompileTask from a CompileQueue
 656 CompileTask* CompileQueue::get() {
 657   NMethodSweeper::possibly_sweep();
 658 
 659   MutexLocker locker(lock());
 660   // If _first is NULL we have no more compile jobs. There are two reasons for
 661   // having no compile jobs: First, we compiled everything we wanted. Second,
 662   // we ran out of code cache so compilation has been disabled. In the latter
 663   // case we perform code cache sweeps to free memory such that we can re-enable
 664   // compilation.
 665   while (_first == NULL) {
 666     // Exit loop if compilation is disabled forever
 667     if (CompileBroker::is_compilation_disabled_forever()) {
 668       return NULL;
 669     }
 670 
 671     if (UseCodeCacheFlushing && !CompileBroker::should_compile_new_jobs()) {
 672       // Wait a certain amount of time to possibly do another sweep.
 673       // We must wait until stack scanning has happened so that we can
 674       // transition a method's state from 'not_entrant' to 'zombie'.
 675       long wait_time = NmethodSweepCheckInterval * 1000;
 676       if (FLAG_IS_DEFAULT(NmethodSweepCheckInterval)) {
 677         // Only one thread at a time can do sweeping. Scale the
 678         // wait time according to the number of compiler threads.
 679         // As a result, the next sweep is likely to happen every 100ms
 680         // with an arbitrary number of threads that do sweeping.
 681         wait_time = 100 * CICompilerCount;
 682       }
 683       bool timeout = lock()->wait(!Mutex::_no_safepoint_check_flag, wait_time);
 684       if (timeout) {
 685         MutexUnlocker ul(lock());
 686         NMethodSweeper::possibly_sweep();
 687       }
 688     } else {
 689       // If there are no compilation tasks and we can compile new jobs
 690       // (i.e., there is enough free space in the code cache) there is
 691       // no need to invoke the sweeper. As a result, the hotness of methods
 692       // remains unchanged. This behavior is desired, since we want to keep
 693       // the stable state, i.e., we do not want to evict methods from the
 694       // code cache if it is unnecessary.
 695       // We need a timed wait here, since compiler threads can exit if compilation
 696       // is disabled forever. We use 5 seconds wait time; the exiting of compiler threads
 697       // is not critical and we do not want idle compiler threads to wake up too often.
 698       lock()->wait(!Mutex::_no_safepoint_check_flag, 5*1000);
 699     }
 700   }
 701 
 702   if (CompileBroker::is_compilation_disabled_forever()) {
 703     return NULL;
 704   }
 705 
 706   CompileTask* task;
 707   {
 708     No_Safepoint_Verifier nsv;
 709     task = CompilationPolicy::policy()->select_task(this);
 710   }
 711   remove(task);
 712   purge_stale_tasks(); // may temporarily release MCQ lock
 713   return task;
 714 }
 715 
 716 // Clean & deallocate stale compile tasks.
 717 // Temporarily releases MethodCompileQueue lock.
 718 void CompileQueue::purge_stale_tasks() {
 719   assert(lock()->owned_by_self(), "must own lock");
 720   if (_first_stale != NULL) {
 721     // Stale tasks are purged when MCQ lock is released,
 722     // but _first_stale updates are protected by MCQ lock.
 723     // Once task processing starts and MCQ lock is released,
 724     // other compiler threads can reuse _first_stale.
 725     CompileTask* head = _first_stale;
 726     _first_stale = NULL;
 727     {
 728       MutexUnlocker ul(lock());
 729       for (CompileTask* task = head; task != NULL; ) {
 730         CompileTask* next_task = task->next();
 731         CompileTaskWrapper ctw(task); // Frees the task
 732         task->set_failure_reason("stale task");
 733         task = next_task;
 734       }
 735     }
 736   }
 737 }
 738 
 739 void CompileQueue::remove(CompileTask* task) {
 740    assert(lock()->owned_by_self(), "must own lock");
 741   if (task->prev() != NULL) {
 742     task->prev()->set_next(task->next());
 743   } else {
 744     // max is the first element
 745     assert(task == _first, "Sanity");
 746     _first = task->next();
 747   }
 748 
 749   if (task->next() != NULL) {
 750     task->next()->set_prev(task->prev());
 751   } else {
 752     // max is the last element
 753     assert(task == _last, "Sanity");
 754     _last = task->prev();
 755   }
 756   --_size;
 757 }
 758 
 759 void CompileQueue::remove_and_mark_stale(CompileTask* task) {
 760   assert(lock()->owned_by_self(), "must own lock");
 761   remove(task);
 762 
 763   // Enqueue the task for reclamation (should be done outside MCQ lock)
 764   task->set_next(_first_stale);
 765   task->set_prev(NULL);
 766   _first_stale = task;
 767 }
 768 
 769 // methods in the compile queue need to be marked as used on the stack
 770 // so that they don't get reclaimed by Redefine Classes
 771 void CompileQueue::mark_on_stack() {
 772   CompileTask* task = _first;
 773   while (task != NULL) {
 774     task->mark_on_stack();
 775     task = task->next();
 776   }
 777 }
 778 
 779 
 780 CompileQueue* CompileBroker::compile_queue(int comp_level) {
 781   if (is_c2_compile(comp_level)) return _c2_compile_queue;
 782   if (is_c1_compile(comp_level)) return _c1_compile_queue;
 783   return NULL;
 784 }
 785 
 786 
 787 void CompileBroker::print_compile_queues(outputStream* st) {
 788   _c1_compile_queue->print(st);
 789   _c2_compile_queue->print(st);
 790 }
 791 
 792 
 793 void CompileQueue::print(outputStream* st) {
 794   assert_locked_or_safepoint(lock());
 795   st->print_cr("Contents of %s", name());
 796   st->print_cr("----------------------------");
 797   CompileTask* task = _first;
 798   if (task == NULL) {
 799     st->print_cr("Empty");;
 800   } else {
 801     while (task != NULL) {
 802       task->print_compilation(st, NULL, true, true);
 803       task = task->next();
 804     }
 805   }
 806   st->print_cr("----------------------------");
 807 }
 808 
 809 void CompileQueue::print_tty() {
 810   ttyLocker ttyl;
 811   print(tty);
 812 }
 813 
 814 CompilerCounters::CompilerCounters(const char* thread_name, int instance, TRAPS) {
 815 
 816   _current_method[0] = '\0';
 817   _compile_type = CompileBroker::no_compile;
 818 
 819   if (UsePerfData) {
 820     ResourceMark rm;
 821 
 822     // create the thread instance name space string - don't create an
 823     // instance subspace if instance is -1 - keeps the adapterThread
 824     // counters  from having a ".0" namespace.
 825     const char* thread_i = (instance == -1) ? thread_name :
 826                       PerfDataManager::name_space(thread_name, instance);
 827 
 828 
 829     char* name = PerfDataManager::counter_name(thread_i, "method");
 830     _perf_current_method =
 831                PerfDataManager::create_string_variable(SUN_CI, name,
 832                                                        cmname_buffer_length,
 833                                                        _current_method, CHECK);
 834 
 835     name = PerfDataManager::counter_name(thread_i, "type");
 836     _perf_compile_type = PerfDataManager::create_variable(SUN_CI, name,
 837                                                           PerfData::U_None,
 838                                                          (jlong)_compile_type,
 839                                                           CHECK);
 840 
 841     name = PerfDataManager::counter_name(thread_i, "time");
 842     _perf_time = PerfDataManager::create_counter(SUN_CI, name,
 843                                                  PerfData::U_Ticks, CHECK);
 844 
 845     name = PerfDataManager::counter_name(thread_i, "compiles");
 846     _perf_compiles = PerfDataManager::create_counter(SUN_CI, name,
 847                                                      PerfData::U_Events, CHECK);
 848   }
 849 }
 850 
 851 // ------------------------------------------------------------------
 852 // CompileBroker::compilation_init
 853 //
 854 // Initialize the Compilation object
 855 void CompileBroker::compilation_init() {
 856   _last_method_compiled[0] = '\0';
 857 
 858   // No need to initialize compilation system if we do not use it.
 859   if (!UseCompiler) {
 860     return;
 861   }
 862 #ifndef SHARK
 863   // Set the interface to the current compiler(s).
 864   int c1_count = CompilationPolicy::policy()->compiler_count(CompLevel_simple);
 865   int c2_count = CompilationPolicy::policy()->compiler_count(CompLevel_full_optimization);
 866 #ifdef COMPILER1
 867   if (c1_count > 0) {
 868     _compilers[0] = new Compiler();
 869   }
 870 #endif // COMPILER1
 871 
 872 #ifdef COMPILER2
 873   if (c2_count > 0) {
 874     _compilers[1] = new C2Compiler();
 875   }
 876 #endif // COMPILER2
 877 
 878 #else // SHARK
 879   int c1_count = 0;
 880   int c2_count = 1;
 881 
 882   _compilers[1] = new SharkCompiler();
 883 #endif // SHARK
 884 
 885   // Start the CompilerThreads
 886   init_compiler_threads(c1_count, c2_count);
 887   // totalTime performance counter is always created as it is required
 888   // by the implementation of java.lang.management.CompilationMBean.
 889   {
 890     EXCEPTION_MARK;
 891     _perf_total_compilation =
 892                  PerfDataManager::create_counter(JAVA_CI, "totalTime",
 893                                                  PerfData::U_Ticks, CHECK);
 894   }
 895 
 896 
 897   if (UsePerfData) {
 898 
 899     EXCEPTION_MARK;
 900 
 901     // create the jvmstat performance counters
 902     _perf_osr_compilation =
 903                  PerfDataManager::create_counter(SUN_CI, "osrTime",
 904                                                  PerfData::U_Ticks, CHECK);
 905 
 906     _perf_standard_compilation =
 907                  PerfDataManager::create_counter(SUN_CI, "standardTime",
 908                                                  PerfData::U_Ticks, CHECK);
 909 
 910     _perf_total_bailout_count =
 911                  PerfDataManager::create_counter(SUN_CI, "totalBailouts",
 912                                                  PerfData::U_Events, CHECK);
 913 
 914     _perf_total_invalidated_count =
 915                  PerfDataManager::create_counter(SUN_CI, "totalInvalidates",
 916                                                  PerfData::U_Events, CHECK);
 917 
 918     _perf_total_compile_count =
 919                  PerfDataManager::create_counter(SUN_CI, "totalCompiles",
 920                                                  PerfData::U_Events, CHECK);
 921     _perf_total_osr_compile_count =
 922                  PerfDataManager::create_counter(SUN_CI, "osrCompiles",
 923                                                  PerfData::U_Events, CHECK);
 924 
 925     _perf_total_standard_compile_count =
 926                  PerfDataManager::create_counter(SUN_CI, "standardCompiles",
 927                                                  PerfData::U_Events, CHECK);
 928 
 929     _perf_sum_osr_bytes_compiled =
 930                  PerfDataManager::create_counter(SUN_CI, "osrBytes",
 931                                                  PerfData::U_Bytes, CHECK);
 932 
 933     _perf_sum_standard_bytes_compiled =
 934                  PerfDataManager::create_counter(SUN_CI, "standardBytes",
 935                                                  PerfData::U_Bytes, CHECK);
 936 
 937     _perf_sum_nmethod_size =
 938                  PerfDataManager::create_counter(SUN_CI, "nmethodSize",
 939                                                  PerfData::U_Bytes, CHECK);
 940 
 941     _perf_sum_nmethod_code_size =
 942                  PerfDataManager::create_counter(SUN_CI, "nmethodCodeSize",
 943                                                  PerfData::U_Bytes, CHECK);
 944 
 945     _perf_last_method =
 946                  PerfDataManager::create_string_variable(SUN_CI, "lastMethod",
 947                                        CompilerCounters::cmname_buffer_length,
 948                                        "", CHECK);
 949 
 950     _perf_last_failed_method =
 951             PerfDataManager::create_string_variable(SUN_CI, "lastFailedMethod",
 952                                        CompilerCounters::cmname_buffer_length,
 953                                        "", CHECK);
 954 
 955     _perf_last_invalidated_method =
 956         PerfDataManager::create_string_variable(SUN_CI, "lastInvalidatedMethod",
 957                                      CompilerCounters::cmname_buffer_length,
 958                                      "", CHECK);
 959 
 960     _perf_last_compile_type =
 961              PerfDataManager::create_variable(SUN_CI, "lastType",
 962                                               PerfData::U_None,
 963                                               (jlong)CompileBroker::no_compile,
 964                                               CHECK);
 965 
 966     _perf_last_compile_size =
 967              PerfDataManager::create_variable(SUN_CI, "lastSize",
 968                                               PerfData::U_Bytes,
 969                                               (jlong)CompileBroker::no_compile,
 970                                               CHECK);
 971 
 972 
 973     _perf_last_failed_type =
 974              PerfDataManager::create_variable(SUN_CI, "lastFailedType",
 975                                               PerfData::U_None,
 976                                               (jlong)CompileBroker::no_compile,
 977                                               CHECK);
 978 
 979     _perf_last_invalidated_type =
 980          PerfDataManager::create_variable(SUN_CI, "lastInvalidatedType",
 981                                           PerfData::U_None,
 982                                           (jlong)CompileBroker::no_compile,
 983                                           CHECK);
 984   }
 985 
 986   _initialized = true;
 987 }
 988 
 989 
 990 CompilerThread* CompileBroker::make_compiler_thread(const char* name, CompileQueue* queue, CompilerCounters* counters,
 991                                                     AbstractCompiler* comp, TRAPS) {
 992   CompilerThread* compiler_thread = NULL;
 993 
 994   Klass* k =
 995     SystemDictionary::resolve_or_fail(vmSymbols::java_lang_Thread(),
 996                                       true, CHECK_0);
 997   instanceKlassHandle klass (THREAD, k);
 998   instanceHandle thread_oop = klass->allocate_instance_handle(CHECK_0);
 999   Handle string = java_lang_String::create_from_str(name, CHECK_0);
1000 
1001   // Initialize thread_oop to put it into the system threadGroup
1002   Handle thread_group (THREAD,  Universe::system_thread_group());
1003   JavaValue result(T_VOID);
1004   JavaCalls::call_special(&result, thread_oop,
1005                        klass,
1006                        vmSymbols::object_initializer_name(),
1007                        vmSymbols::threadgroup_string_void_signature(),
1008                        thread_group,
1009                        string,
1010                        CHECK_0);
1011 
1012   {
1013     MutexLocker mu(Threads_lock, THREAD);
1014     compiler_thread = new CompilerThread(queue, counters);
1015     // At this point the new CompilerThread data-races with this startup
1016     // thread (which I believe is the primoridal thread and NOT the VM
1017     // thread).  This means Java bytecodes being executed at startup can
1018     // queue compile jobs which will run at whatever default priority the
1019     // newly created CompilerThread runs at.
1020 
1021 
1022     // At this point it may be possible that no osthread was created for the
1023     // JavaThread due to lack of memory. We would have to throw an exception
1024     // in that case. However, since this must work and we do not allow
1025     // exceptions anyway, check and abort if this fails.
1026 
1027     if (compiler_thread == NULL || compiler_thread->osthread() == NULL){
1028       vm_exit_during_initialization("java.lang.OutOfMemoryError",
1029                                     os::native_thread_creation_failed_msg());
1030     }
1031 
1032     java_lang_Thread::set_thread(thread_oop(), compiler_thread);
1033 
1034     // Note that this only sets the JavaThread _priority field, which by
1035     // definition is limited to Java priorities and not OS priorities.
1036     // The os-priority is set in the CompilerThread startup code itself
1037 
1038     java_lang_Thread::set_priority(thread_oop(), NearMaxPriority);
1039 
1040     // Note that we cannot call os::set_priority because it expects Java
1041     // priorities and we are *explicitly* using OS priorities so that it's
1042     // possible to set the compiler thread priority higher than any Java
1043     // thread.
1044 
1045     int native_prio = CompilerThreadPriority;
1046     if (native_prio == -1) {
1047       if (UseCriticalCompilerThreadPriority) {
1048         native_prio = os::java_to_os_priority[CriticalPriority];
1049       } else {
1050         native_prio = os::java_to_os_priority[NearMaxPriority];
1051       }
1052     }
1053     os::set_native_priority(compiler_thread, native_prio);
1054 
1055     java_lang_Thread::set_daemon(thread_oop());
1056 
1057     compiler_thread->set_threadObj(thread_oop());
1058     compiler_thread->set_compiler(comp);
1059     Threads::add(compiler_thread);
1060     Thread::start(compiler_thread);
1061   }
1062 
1063   // Let go of Threads_lock before yielding
1064   os::naked_yield(); // make sure that the compiler thread is started early (especially helpful on SOLARIS)
1065 
1066   return compiler_thread;
1067 }
1068 
1069 
1070 void CompileBroker::init_compiler_threads(int c1_compiler_count, int c2_compiler_count) {
1071   EXCEPTION_MARK;
1072 #if !defined(ZERO) && !defined(SHARK)
1073   assert(c2_compiler_count > 0 || c1_compiler_count > 0, "No compilers?");
1074 #endif // !ZERO && !SHARK
1075   // Initialize the compilation queue
1076   if (c2_compiler_count > 0) {
1077     _c2_compile_queue  = new CompileQueue("C2 compile queue",  MethodCompileQueue_lock);
1078     _compilers[1]->set_num_compiler_threads(c2_compiler_count);
1079   }
1080   if (c1_compiler_count > 0) {
1081     _c1_compile_queue  = new CompileQueue("C1 compile queue",  MethodCompileQueue_lock);
1082     _compilers[0]->set_num_compiler_threads(c1_compiler_count);
1083   }
1084 
1085   int compiler_count = c1_compiler_count + c2_compiler_count;
1086 
1087   _compiler_threads =
1088     new (ResourceObj::C_HEAP, mtCompiler) GrowableArray<CompilerThread*>(compiler_count, true);
1089 
1090   char name_buffer[256];
1091   for (int i = 0; i < c2_compiler_count; i++) {
1092     // Create a name for our thread.
1093     sprintf(name_buffer, "C2 CompilerThread%d", i);
1094     CompilerCounters* counters = new CompilerCounters("compilerThread", i, CHECK);
1095     // Shark and C2
1096     CompilerThread* new_thread = make_compiler_thread(name_buffer, _c2_compile_queue, counters, _compilers[1], CHECK);
1097     _compiler_threads->append(new_thread);
1098   }
1099 
1100   for (int i = c2_compiler_count; i < compiler_count; i++) {
1101     // Create a name for our thread.
1102     sprintf(name_buffer, "C1 CompilerThread%d", i);
1103     CompilerCounters* counters = new CompilerCounters("compilerThread", i, CHECK);
1104     // C1
1105     CompilerThread* new_thread = make_compiler_thread(name_buffer, _c1_compile_queue, counters, _compilers[0], CHECK);
1106     _compiler_threads->append(new_thread);
1107   }
1108 
1109   if (UsePerfData) {
1110     PerfDataManager::create_constant(SUN_CI, "threads", PerfData::U_Bytes, compiler_count, CHECK);
1111   }
1112 }
1113 
1114 
1115 /**
1116  * Set the methods on the stack as on_stack so that redefine classes doesn't
1117  * reclaim them. This method is executed at a safepoint.
1118  */
1119 void CompileBroker::mark_on_stack() {
1120   assert(SafepointSynchronize::is_at_safepoint(), "sanity check");
1121   // Since we are at a safepoint, we do not need a lock to access
1122   // the compile queues.
1123   if (_c2_compile_queue != NULL) {
1124     _c2_compile_queue->mark_on_stack();
1125   }
1126   if (_c1_compile_queue != NULL) {
1127     _c1_compile_queue->mark_on_stack();
1128   }
1129 }
1130 
1131 // ------------------------------------------------------------------
1132 // CompileBroker::compile_method
1133 //
1134 // Request compilation of a method.
1135 void CompileBroker::compile_method_base(methodHandle method,
1136                                         int osr_bci,
1137                                         int comp_level,
1138                                         methodHandle hot_method,
1139                                         int hot_count,
1140                                         const char* comment,
1141                                         Thread* thread) {
1142   // do nothing if compiler thread(s) is not available
1143   if (!_initialized) {
1144     return;
1145   }
1146 
1147   guarantee(!method->is_abstract(), "cannot compile abstract methods");
1148   assert(method->method_holder()->oop_is_instance(),
1149          "sanity check");
1150   assert(!method->method_holder()->is_not_initialized(),
1151          "method holder must be initialized");
1152   assert(!method->is_method_handle_intrinsic(), "do not enqueue these guys");
1153 
1154   if (CIPrintRequests) {
1155     tty->print("request: ");
1156     method->print_short_name(tty);
1157     if (osr_bci != InvocationEntryBci) {
1158       tty->print(" osr_bci: %d", osr_bci);
1159     }
1160     tty->print(" comment: %s count: %d", comment, hot_count);
1161     if (!hot_method.is_null()) {
1162       tty->print(" hot: ");
1163       if (hot_method() != method()) {
1164           hot_method->print_short_name(tty);
1165       } else {
1166         tty->print("yes");
1167       }
1168     }
1169     tty->cr();
1170   }
1171 
1172   // A request has been made for compilation.  Before we do any
1173   // real work, check to see if the method has been compiled
1174   // in the meantime with a definitive result.
1175   if (compilation_is_complete(method, osr_bci, comp_level)) {
1176     return;
1177   }
1178 
1179 #ifndef PRODUCT
1180   if (osr_bci != -1 && !FLAG_IS_DEFAULT(OSROnlyBCI)) {
1181     if ((OSROnlyBCI > 0) ? (OSROnlyBCI != osr_bci) : (-OSROnlyBCI == osr_bci)) {
1182       // Positive OSROnlyBCI means only compile that bci.  Negative means don't compile that BCI.
1183       return;
1184     }
1185   }
1186 #endif
1187 
1188   // If this method is already in the compile queue, then
1189   // we do not block the current thread.
1190   if (compilation_is_in_queue(method)) {
1191     // We may want to decay our counter a bit here to prevent
1192     // multiple denied requests for compilation.  This is an
1193     // open compilation policy issue. Note: The other possibility,
1194     // in the case that this is a blocking compile request, is to have
1195     // all subsequent blocking requesters wait for completion of
1196     // ongoing compiles. Note that in this case we'll need a protocol
1197     // for freeing the associated compile tasks. [Or we could have
1198     // a single static monitor on which all these waiters sleep.]
1199     return;
1200   }
1201 
1202   // If the requesting thread is holding the pending list lock
1203   // then we just return. We can't risk blocking while holding
1204   // the pending list lock or a 3-way deadlock may occur
1205   // between the reference handler thread, a GC (instigated
1206   // by a compiler thread), and compiled method registration.
1207   if (InstanceRefKlass::owns_pending_list_lock(JavaThread::current())) {
1208     return;
1209   }
1210 
1211   // Outputs from the following MutexLocker block:
1212   CompileTask* task     = NULL;
1213   bool         blocking = false;
1214   CompileQueue* queue  = compile_queue(comp_level);
1215 
1216   // Acquire our lock.
1217   {
1218     MutexLocker locker(queue->lock(), thread);
1219 
1220     // Make sure the method has not slipped into the queues since
1221     // last we checked; note that those checks were "fast bail-outs".
1222     // Here we need to be more careful, see 14012000 below.
1223     if (compilation_is_in_queue(method)) {
1224       return;
1225     }
1226 
1227     // We need to check again to see if the compilation has
1228     // completed.  A previous compilation may have registered
1229     // some result.
1230     if (compilation_is_complete(method, osr_bci, comp_level)) {
1231       return;
1232     }
1233 
1234     // We now know that this compilation is not pending, complete,
1235     // or prohibited.  Assign a compile_id to this compilation
1236     // and check to see if it is in our [Start..Stop) range.
1237     int compile_id = assign_compile_id(method, osr_bci);
1238     if (compile_id == 0) {
1239       // The compilation falls outside the allowed range.
1240       return;
1241     }
1242 
1243     // Should this thread wait for completion of the compile?
1244     blocking = is_compile_blocking();
1245 
1246     // We will enter the compilation in the queue.
1247     // 14012000: Note that this sets the queued_for_compile bits in
1248     // the target method. We can now reason that a method cannot be
1249     // queued for compilation more than once, as follows:
1250     // Before a thread queues a task for compilation, it first acquires
1251     // the compile queue lock, then checks if the method's queued bits
1252     // are set or it has already been compiled. Thus there can not be two
1253     // instances of a compilation task for the same method on the
1254     // compilation queue. Consider now the case where the compilation
1255     // thread has already removed a task for that method from the queue
1256     // and is in the midst of compiling it. In this case, the
1257     // queued_for_compile bits must be set in the method (and these
1258     // will be visible to the current thread, since the bits were set
1259     // under protection of the compile queue lock, which we hold now.
1260     // When the compilation completes, the compiler thread first sets
1261     // the compilation result and then clears the queued_for_compile
1262     // bits. Neither of these actions are protected by a barrier (or done
1263     // under the protection of a lock), so the only guarantee we have
1264     // (on machines with TSO (Total Store Order)) is that these values
1265     // will update in that order. As a result, the only combinations of
1266     // these bits that the current thread will see are, in temporal order:
1267     // <RESULT, QUEUE> :
1268     //     <0, 1> : in compile queue, but not yet compiled
1269     //     <1, 1> : compiled but queue bit not cleared
1270     //     <1, 0> : compiled and queue bit cleared
1271     // Because we first check the queue bits then check the result bits,
1272     // we are assured that we cannot introduce a duplicate task.
1273     // Note that if we did the tests in the reverse order (i.e. check
1274     // result then check queued bit), we could get the result bit before
1275     // the compilation completed, and the queue bit after the compilation
1276     // completed, and end up introducing a "duplicate" (redundant) task.
1277     // In that case, the compiler thread should first check if a method
1278     // has already been compiled before trying to compile it.
1279     // NOTE: in the event that there are multiple compiler threads and
1280     // there is de-optimization/recompilation, things will get hairy,
1281     // and in that case it's best to protect both the testing (here) of
1282     // these bits, and their updating (here and elsewhere) under a
1283     // common lock.
1284     task = create_compile_task(queue,
1285                                compile_id, method,
1286                                osr_bci, comp_level,
1287                                hot_method, hot_count, comment,
1288                                blocking);
1289   }
1290 
1291   if (blocking) {
1292     wait_for_completion(task);
1293   }
1294 }
1295 
1296 
1297 nmethod* CompileBroker::compile_method(methodHandle method, int osr_bci,
1298                                        int comp_level,
1299                                        methodHandle hot_method, int hot_count,
1300                                        const char* comment, Thread* THREAD) {
1301   // make sure arguments make sense
1302   assert(method->method_holder()->oop_is_instance(), "not an instance method");
1303   assert(osr_bci == InvocationEntryBci || (0 <= osr_bci && osr_bci < method->code_size()), "bci out of range");
1304   assert(!method->is_abstract() && (osr_bci == InvocationEntryBci || !method->is_native()), "cannot compile abstract/native methods");
1305   assert(!method->method_holder()->is_not_initialized(), "method holder must be initialized");
1306   // allow any levels for WhiteBox
1307   assert(WhiteBoxAPI || TieredCompilation || comp_level == CompLevel_highest_tier, "only CompLevel_highest_tier must be used in non-tiered");
1308   // return quickly if possible
1309 
1310   // lock, make sure that the compilation
1311   // isn't prohibited in a straightforward way.
1312   AbstractCompiler *comp = CompileBroker::compiler(comp_level);
1313   if (comp == NULL || !comp->can_compile_method(method) ||
1314       compilation_is_prohibited(method, osr_bci, comp_level)) {
1315     return NULL;
1316   }
1317 
1318   if (osr_bci == InvocationEntryBci) {
1319     // standard compilation
1320     nmethod* method_code = method->code();
1321     if (method_code != NULL) {
1322       if (compilation_is_complete(method, osr_bci, comp_level)) {
1323         return method_code;
1324       }
1325     }
1326     if (method->is_not_compilable(comp_level)) {
1327       return NULL;
1328     }
1329   } else {
1330     // osr compilation
1331 #ifndef TIERED
1332     // seems like an assert of dubious value
1333     assert(comp_level == CompLevel_highest_tier,
1334            "all OSR compiles are assumed to be at a single compilation lavel");
1335 #endif // TIERED
1336     // We accept a higher level osr method
1337     nmethod* nm = method->lookup_osr_nmethod_for(osr_bci, comp_level, false);
1338     if (nm != NULL) return nm;
1339     if (method->is_not_osr_compilable(comp_level)) return NULL;
1340   }
1341 
1342   assert(!HAS_PENDING_EXCEPTION, "No exception should be present");
1343   // some prerequisites that are compiler specific
1344   if (comp->is_c2() || comp->is_shark()) {
1345     method->constants()->resolve_string_constants(CHECK_AND_CLEAR_NULL);
1346     // Resolve all classes seen in the signature of the method
1347     // we are compiling.
1348     Method::load_signature_classes(method, CHECK_AND_CLEAR_NULL);
1349   }
1350 
1351   // If the method is native, do the lookup in the thread requesting
1352   // the compilation. Native lookups can load code, which is not
1353   // permitted during compilation.
1354   //
1355   // Note: A native method implies non-osr compilation which is
1356   //       checked with an assertion at the entry of this method.
1357   if (method->is_native() && !method->is_method_handle_intrinsic()) {
1358     bool in_base_library;
1359     address adr = NativeLookup::lookup(method, in_base_library, THREAD);
1360     if (HAS_PENDING_EXCEPTION) {
1361       // In case of an exception looking up the method, we just forget
1362       // about it. The interpreter will kick-in and throw the exception.
1363       method->set_not_compilable(); // implies is_not_osr_compilable()
1364       CLEAR_PENDING_EXCEPTION;
1365       return NULL;
1366     }
1367     assert(method->has_native_function(), "must have native code by now");
1368   }
1369 
1370   // RedefineClasses() has replaced this method; just return
1371   if (method->is_old()) {
1372     return NULL;
1373   }
1374 
1375   // JVMTI -- post_compile_event requires jmethod_id() that may require
1376   // a lock the compiling thread can not acquire. Prefetch it here.
1377   if (JvmtiExport::should_post_compiled_method_load()) {
1378     method->jmethod_id();
1379   }
1380 
1381   // do the compilation
1382   if (method->is_native()) {
1383     if (!PreferInterpreterNativeStubs || method->is_method_handle_intrinsic()) {
1384       // To properly handle the appendix argument for out-of-line calls we are using a small trampoline that
1385       // pops off the appendix argument and jumps to the target (see gen_special_dispatch in SharedRuntime).
1386       //
1387       // Since normal compiled-to-compiled calls are not able to handle such a thing we MUST generate an adapter
1388       // in this case.  If we can't generate one and use it we can not execute the out-of-line method handle calls.
1389       AdapterHandlerLibrary::create_native_wrapper(method);
1390     } else {
1391       return NULL;
1392     }
1393   } else {
1394     // If the compiler is shut off due to code cache getting full
1395     // fail out now so blocking compiles dont hang the java thread
1396     if (!should_compile_new_jobs()) {
1397       CompilationPolicy::policy()->delay_compilation(method());
1398       return NULL;
1399     }
1400     compile_method_base(method, osr_bci, comp_level, hot_method, hot_count, comment, THREAD);
1401   }
1402 
1403   // return requested nmethod
1404   // We accept a higher level osr method
1405   return osr_bci  == InvocationEntryBci ? method->code() : method->lookup_osr_nmethod_for(osr_bci, comp_level, false);
1406 }
1407 
1408 
1409 // ------------------------------------------------------------------
1410 // CompileBroker::compilation_is_complete
1411 //
1412 // See if compilation of this method is already complete.
1413 bool CompileBroker::compilation_is_complete(methodHandle method,
1414                                             int          osr_bci,
1415                                             int          comp_level) {
1416   bool is_osr = (osr_bci != standard_entry_bci);
1417   if (is_osr) {
1418     if (method->is_not_osr_compilable(comp_level)) {
1419       return true;
1420     } else {
1421       nmethod* result = method->lookup_osr_nmethod_for(osr_bci, comp_level, true);
1422       return (result != NULL);
1423     }
1424   } else {
1425     if (method->is_not_compilable(comp_level)) {
1426       return true;
1427     } else {
1428       nmethod* result = method->code();
1429       if (result == NULL) return false;
1430       return comp_level == result->comp_level();
1431     }
1432   }
1433 }
1434 
1435 
1436 /**
1437  * See if this compilation is already requested.
1438  *
1439  * Implementation note: there is only a single "is in queue" bit
1440  * for each method.  This means that the check below is overly
1441  * conservative in the sense that an osr compilation in the queue
1442  * will block a normal compilation from entering the queue (and vice
1443  * versa).  This can be remedied by a full queue search to disambiguate
1444  * cases.  If it is deemed profitable, this may be done.
1445  */
1446 bool CompileBroker::compilation_is_in_queue(methodHandle method) {
1447   return method->queued_for_compilation();
1448 }
1449 
1450 // ------------------------------------------------------------------
1451 // CompileBroker::compilation_is_prohibited
1452 //
1453 // See if this compilation is not allowed.
1454 bool CompileBroker::compilation_is_prohibited(methodHandle method, int osr_bci, int comp_level) {
1455   bool is_native = method->is_native();
1456   // Some compilers may not support the compilation of natives.
1457   AbstractCompiler *comp = compiler(comp_level);
1458   if (is_native &&
1459       (!CICompileNatives || comp == NULL || !comp->supports_native())) {
1460     method->set_not_compilable_quietly(comp_level);
1461     return true;
1462   }
1463 
1464   bool is_osr = (osr_bci != standard_entry_bci);
1465   // Some compilers may not support on stack replacement.
1466   if (is_osr &&
1467       (!CICompileOSR || comp == NULL || !comp->supports_osr())) {
1468     method->set_not_osr_compilable(comp_level);
1469     return true;
1470   }
1471 
1472   // The method may be explicitly excluded by the user.
1473   bool quietly;
1474   if (CompilerOracle::should_exclude(method, quietly)) {
1475     if (!quietly) {
1476       // This does not happen quietly...
1477       ResourceMark rm;
1478       tty->print("### Excluding %s:%s",
1479                  method->is_native() ? "generation of native wrapper" : "compile",
1480                  (method->is_static() ? " static" : ""));
1481       method->print_short_name(tty);
1482       tty->cr();
1483     }
1484     method->set_not_compilable(CompLevel_all, !quietly, "excluded by CompilerOracle");
1485   }
1486 
1487   return false;
1488 }
1489 
1490 /**
1491  * Generate serialized IDs for compilation requests. If certain debugging flags are used
1492  * and the ID is not within the specified range, the method is not compiled and 0 is returned.
1493  * The function also allows to generate separate compilation IDs for OSR compilations.
1494  */
1495 int CompileBroker::assign_compile_id(methodHandle method, int osr_bci) {
1496 #ifdef ASSERT
1497   bool is_osr = (osr_bci != standard_entry_bci);
1498   int id;
1499   if (method->is_native()) {
1500     assert(!is_osr, "can't be osr");
1501     // Adapters, native wrappers and method handle intrinsics
1502     // should be generated always.
1503     return Atomic::add(1, &_compilation_id);
1504   } else if (CICountOSR && is_osr) {
1505     id = Atomic::add(1, &_osr_compilation_id);
1506     if (CIStartOSR <= id && id < CIStopOSR) {
1507       return id;
1508     }
1509   } else {
1510     id = Atomic::add(1, &_compilation_id);
1511     if (CIStart <= id && id < CIStop) {
1512       return id;
1513     }
1514   }
1515 
1516   // Method was not in the appropriate compilation range.
1517   method->set_not_compilable_quietly();
1518   return 0;
1519 #else
1520   // CICountOSR is a develop flag and set to 'false' by default. In a product built,
1521   // only _compilation_id is incremented.
1522   return Atomic::add(1, &_compilation_id);
1523 #endif
1524 }
1525 
1526 /**
1527  * Should the current thread block until this compilation request
1528  * has been fulfilled?
1529  */
1530 bool CompileBroker::is_compile_blocking() {
1531   assert(!InstanceRefKlass::owns_pending_list_lock(JavaThread::current()), "possible deadlock");
1532   return !BackgroundCompilation;
1533 }
1534 
1535 
1536 // ------------------------------------------------------------------
1537 // CompileBroker::preload_classes
1538 void CompileBroker::preload_classes(methodHandle method, TRAPS) {
1539   // Move this code over from c1_Compiler.cpp
1540   ShouldNotReachHere();
1541 }
1542 
1543 
1544 // ------------------------------------------------------------------
1545 // CompileBroker::create_compile_task
1546 //
1547 // Create a CompileTask object representing the current request for
1548 // compilation.  Add this task to the queue.
1549 CompileTask* CompileBroker::create_compile_task(CompileQueue* queue,
1550                                               int           compile_id,
1551                                               methodHandle  method,
1552                                               int           osr_bci,
1553                                               int           comp_level,
1554                                               methodHandle  hot_method,
1555                                               int           hot_count,
1556                                               const char*   comment,
1557                                               bool          blocking) {
1558   CompileTask* new_task = CompileTask::allocate();
1559   new_task->initialize(compile_id, method, osr_bci, comp_level,
1560                        hot_method, hot_count, comment,
1561                        blocking);
1562   queue->add(new_task);
1563   return new_task;
1564 }
1565 
1566 
1567 /**
1568  *  Wait for the compilation task to complete.
1569  */
1570 void CompileBroker::wait_for_completion(CompileTask* task) {
1571   if (CIPrintCompileQueue) {
1572     ttyLocker ttyl;
1573     tty->print_cr("BLOCKING FOR COMPILE");
1574   }
1575 
1576   assert(task->is_blocking(), "can only wait on blocking task");
1577 
1578   JavaThread* thread = JavaThread::current();
1579   thread->set_blocked_on_compilation(true);
1580 
1581   methodHandle method(thread, task->method());
1582   {
1583     MutexLocker waiter(task->lock(), thread);
1584 
1585     while (!task->is_complete() && !is_compilation_disabled_forever()) {
1586       task->lock()->wait();
1587     }
1588   }
1589 
1590   thread->set_blocked_on_compilation(false);
1591   if (is_compilation_disabled_forever()) {
1592     CompileTask::free(task);
1593     return;
1594   }
1595 
1596   // It is harmless to check this status without the lock, because
1597   // completion is a stable property (until the task object is recycled).
1598   assert(task->is_complete(), "Compilation should have completed");
1599   assert(task->code_handle() == NULL, "must be reset");
1600 
1601   // By convention, the waiter is responsible for recycling a
1602   // blocking CompileTask. Since there is only one waiter ever
1603   // waiting on a CompileTask, we know that no one else will
1604   // be using this CompileTask; we can free it.
1605   CompileTask::free(task);
1606 }
1607 
1608 /**
1609  * Initialize compiler thread(s) + compiler object(s). The postcondition
1610  * of this function is that the compiler runtimes are initialized and that
1611  * compiler threads can start compiling.
1612  */
1613 bool CompileBroker::init_compiler_runtime() {
1614   CompilerThread* thread = CompilerThread::current();
1615   AbstractCompiler* comp = thread->compiler();
1616   // Final sanity check - the compiler object must exist
1617   guarantee(comp != NULL, "Compiler object must exist");
1618 
1619   int system_dictionary_modification_counter;
1620   {
1621     MutexLocker locker(Compile_lock, thread);
1622     system_dictionary_modification_counter = SystemDictionary::number_of_modifications();
1623   }
1624 
1625   {
1626     // Must switch to native to allocate ci_env
1627     ThreadToNativeFromVM ttn(thread);
1628     ciEnv ci_env(NULL, system_dictionary_modification_counter);
1629     // Cache Jvmti state
1630     ci_env.cache_jvmti_state();
1631     // Cache DTrace flags
1632     ci_env.cache_dtrace_flags();
1633 
1634     // Switch back to VM state to do compiler initialization
1635     ThreadInVMfromNative tv(thread);
1636     ResetNoHandleMark rnhm;
1637 
1638 
1639     if (!comp->is_shark()) {
1640       // Perform per-thread and global initializations
1641       comp->initialize();
1642     }
1643   }
1644 
1645   if (comp->is_failed()) {
1646     disable_compilation_forever();
1647     // If compiler initialization failed, no compiler thread that is specific to a
1648     // particular compiler runtime will ever start to compile methods.
1649     shutdown_compiler_runtime(comp, thread);
1650     return false;
1651   }
1652 
1653   // C1 specific check
1654   if (comp->is_c1() && (thread->get_buffer_blob() == NULL)) {
1655     warning("Initialization of %s thread failed (no space to run compilers)", thread->name());
1656     return false;
1657   }
1658 
1659   return true;
1660 }
1661 
1662 /**
1663  * If C1 and/or C2 initialization failed, we shut down all compilation.
1664  * We do this to keep things simple. This can be changed if it ever turns
1665  * out to be a problem.
1666  */
1667 void CompileBroker::shutdown_compiler_runtime(AbstractCompiler* comp, CompilerThread* thread) {
1668   // Free buffer blob, if allocated
1669   if (thread->get_buffer_blob() != NULL) {
1670     MutexLockerEx mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
1671     CodeCache::free(thread->get_buffer_blob());
1672   }
1673 
1674   if (comp->should_perform_shutdown()) {
1675     // There are two reasons for shutting down the compiler
1676     // 1) compiler runtime initialization failed
1677     // 2) The code cache is full and the following flag is set: -XX:-UseCodeCacheFlushing
1678     warning("%s initialization failed. Shutting down all compilers", comp->name());
1679 
1680     // Only one thread per compiler runtime object enters here
1681     // Set state to shut down
1682     comp->set_shut_down();
1683 
1684     // Delete all queued compilation tasks to make compiler threads exit faster.
1685     if (_c1_compile_queue != NULL) {
1686       _c1_compile_queue->free_all();
1687     }
1688 
1689     if (_c2_compile_queue != NULL) {
1690       _c2_compile_queue->free_all();
1691     }
1692 
1693     // Set flags so that we continue execution with using interpreter only.
1694     UseCompiler    = false;
1695     UseInterpreter = true;
1696 
1697     // We could delete compiler runtimes also. However, there are references to
1698     // the compiler runtime(s) (e.g.,  nmethod::is_compiled_by_c1()) which then
1699     // fail. This can be done later if necessary.
1700   }
1701 }
1702 
1703 // ------------------------------------------------------------------
1704 // CompileBroker::compiler_thread_loop
1705 //
1706 // The main loop run by a CompilerThread.
1707 void CompileBroker::compiler_thread_loop() {
1708   CompilerThread* thread = CompilerThread::current();
1709   CompileQueue* queue = thread->queue();
1710   // For the thread that initializes the ciObjectFactory
1711   // this resource mark holds all the shared objects
1712   ResourceMark rm;
1713 
1714   // First thread to get here will initialize the compiler interface
1715 
1716   if (!ciObjectFactory::is_initialized()) {
1717     ASSERT_IN_VM;
1718     MutexLocker only_one (CompileThread_lock, thread);
1719     if (!ciObjectFactory::is_initialized()) {
1720       ciObjectFactory::initialize();
1721     }
1722   }
1723 
1724   // Open a log.
1725   if (LogCompilation) {
1726     init_compiler_thread_log();
1727   }
1728   CompileLog* log = thread->log();
1729   if (log != NULL) {
1730     log->begin_elem("start_compile_thread name='%s' thread='" UINTX_FORMAT "' process='%d'",
1731                     thread->name(),
1732                     os::current_thread_id(),
1733                     os::current_process_id());
1734     log->stamp();
1735     log->end_elem();
1736   }
1737 
1738   // If compiler thread/runtime initialization fails, exit the compiler thread
1739   if (!init_compiler_runtime()) {
1740     return;
1741   }
1742 
1743   // Poll for new compilation tasks as long as the JVM runs. Compilation
1744   // should only be disabled if something went wrong while initializing the
1745   // compiler runtimes. This, in turn, should not happen. The only known case
1746   // when compiler runtime initialization fails is if there is not enough free
1747   // space in the code cache to generate the necessary stubs, etc.
1748   while (!is_compilation_disabled_forever()) {
1749     // We need this HandleMark to avoid leaking VM handles.
1750     HandleMark hm(thread);
1751 
1752     if (CodeCache::unallocated_capacity() < CodeCacheMinimumFreeSpace) {
1753       // the code cache is really full
1754       handle_full_code_cache();
1755     }
1756 
1757     CompileTask* task = queue->get();
1758     if (task == NULL) {
1759       continue;
1760     }
1761 
1762     // Give compiler threads an extra quanta.  They tend to be bursty and
1763     // this helps the compiler to finish up the job.
1764     if( CompilerThreadHintNoPreempt )
1765       os::hint_no_preempt();
1766 
1767     // trace per thread time and compile statistics
1768     CompilerCounters* counters = ((CompilerThread*)thread)->counters();
1769     PerfTraceTimedEvent(counters->time_counter(), counters->compile_counter());
1770 
1771     // Assign the task to the current thread.  Mark this compilation
1772     // thread as active for the profiler.
1773     CompileTaskWrapper ctw(task);
1774     nmethodLocker result_handle;  // (handle for the nmethod produced by this task)
1775     task->set_code_handle(&result_handle);
1776     methodHandle method(thread, task->method());
1777 
1778     // Never compile a method if breakpoints are present in it
1779     if (method()->number_of_breakpoints() == 0) {
1780       // Compile the method.
1781       if ((UseCompiler || AlwaysCompileLoopMethods) && CompileBroker::should_compile_new_jobs()) {
1782 #ifdef COMPILER1
1783         // Allow repeating compilations for the purpose of benchmarking
1784         // compile speed. This is not useful for customers.
1785         if (CompilationRepeat != 0) {
1786           int compile_count = CompilationRepeat;
1787           while (compile_count > 0) {
1788             invoke_compiler_on_method(task);
1789             nmethod* nm = method->code();
1790             if (nm != NULL) {
1791               nm->make_zombie();
1792               method->clear_code();
1793             }
1794             compile_count--;
1795           }
1796         }
1797 #endif /* COMPILER1 */
1798         invoke_compiler_on_method(task);
1799       } else {
1800         // After compilation is disabled, remove remaining methods from queue
1801         method->clear_queued_for_compilation();
1802         task->set_failure_reason("compilation is disabled");
1803       }
1804     }
1805   }
1806 
1807   // Shut down compiler runtime
1808   shutdown_compiler_runtime(thread->compiler(), thread);
1809 }
1810 
1811 // ------------------------------------------------------------------
1812 // CompileBroker::init_compiler_thread_log
1813 //
1814 // Set up state required by +LogCompilation.
1815 void CompileBroker::init_compiler_thread_log() {
1816     CompilerThread* thread = CompilerThread::current();
1817     char  file_name[4*K];
1818     FILE* fp = NULL;
1819     intx thread_id = os::current_thread_id();
1820     for (int try_temp_dir = 1; try_temp_dir >= 0; try_temp_dir--) {
1821       const char* dir = (try_temp_dir ? os::get_temp_directory() : NULL);
1822       if (dir == NULL) {
1823         jio_snprintf(file_name, sizeof(file_name), "hs_c" UINTX_FORMAT "_pid%u.log",
1824                      thread_id, os::current_process_id());
1825       } else {
1826         jio_snprintf(file_name, sizeof(file_name),
1827                      "%s%shs_c" UINTX_FORMAT "_pid%u.log", dir,
1828                      os::file_separator(), thread_id, os::current_process_id());
1829       }
1830 
1831       fp = fopen(file_name, "at");
1832       if (fp != NULL) {
1833         if (LogCompilation && Verbose) {
1834           tty->print_cr("Opening compilation log %s", file_name);
1835         }
1836         CompileLog* log = new(ResourceObj::C_HEAP, mtCompiler) CompileLog(file_name, fp, thread_id);
1837         thread->init_log(log);
1838 
1839         if (xtty != NULL) {
1840           ttyLocker ttyl;
1841           // Record any per thread log files
1842           xtty->elem("thread_logfile thread='" INTX_FORMAT "' filename='%s'", thread_id, file_name);
1843         }
1844         return;
1845       }
1846     }
1847     warning("Cannot open log file: %s", file_name);
1848 }
1849 
1850 // ------------------------------------------------------------------
1851 // CompileBroker::set_should_block
1852 //
1853 // Set _should_block.
1854 // Call this from the VM, with Threads_lock held and a safepoint requested.
1855 void CompileBroker::set_should_block() {
1856   assert(Threads_lock->owner() == Thread::current(), "must have threads lock");
1857   assert(SafepointSynchronize::is_at_safepoint(), "must be at a safepoint already");
1858 #ifndef PRODUCT
1859   if (PrintCompilation && (Verbose || WizardMode))
1860     tty->print_cr("notifying compiler thread pool to block");
1861 #endif
1862   _should_block = true;
1863 }
1864 
1865 // ------------------------------------------------------------------
1866 // CompileBroker::maybe_block
1867 //
1868 // Call this from the compiler at convenient points, to poll for _should_block.
1869 void CompileBroker::maybe_block() {
1870   if (_should_block) {
1871 #ifndef PRODUCT
1872     if (PrintCompilation && (Verbose || WizardMode))
1873       tty->print_cr("compiler thread " INTPTR_FORMAT " poll detects block request", p2i(Thread::current()));
1874 #endif
1875     ThreadInVMfromNative tivfn(JavaThread::current());
1876   }
1877 }
1878 
1879 // wrapper for CodeCache::print_summary()
1880 static void codecache_print(bool detailed)
1881 {
1882   ResourceMark rm;
1883   stringStream s;
1884   // Dump code cache  into a buffer before locking the tty,
1885   {
1886     MutexLockerEx mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
1887     CodeCache::print_summary(&s, detailed);
1888   }
1889   ttyLocker ttyl;
1890   tty->print("%s", s.as_string());
1891 }
1892 
1893 // ------------------------------------------------------------------
1894 // CompileBroker::invoke_compiler_on_method
1895 //
1896 // Compile a method.
1897 //
1898 void CompileBroker::invoke_compiler_on_method(CompileTask* task) {
1899   if (PrintCompilation) {
1900     ResourceMark rm;
1901     task->print_tty();
1902   }
1903   elapsedTimer time;
1904 
1905   CompilerThread* thread = CompilerThread::current();
1906   ResourceMark rm(thread);
1907 
1908   if (LogEvents) {
1909     _compilation_log->log_compile(thread, task);
1910   }
1911 
1912   // Common flags.
1913   uint compile_id = task->compile_id();
1914   int osr_bci = task->osr_bci();
1915   bool is_osr = (osr_bci != standard_entry_bci);
1916   bool should_log = (thread->log() != NULL);
1917   bool should_break = false;
1918   int task_level = task->comp_level();
1919   {
1920     // create the handle inside it's own block so it can't
1921     // accidentally be referenced once the thread transitions to
1922     // native.  The NoHandleMark before the transition should catch
1923     // any cases where this occurs in the future.
1924     methodHandle method(thread, task->method());
1925     should_break = check_break_at(method, compile_id, is_osr);
1926     if (should_log && !CompilerOracle::should_log(method)) {
1927       should_log = false;
1928     }
1929     assert(!method->is_native(), "no longer compile natives");
1930 
1931     // Save information about this method in case of failure.
1932     set_last_compile(thread, method, is_osr, task_level);
1933 
1934     DTRACE_METHOD_COMPILE_BEGIN_PROBE(method, compiler_name(task_level));
1935   }
1936 
1937   // Allocate a new set of JNI handles.
1938   push_jni_handle_block();
1939   Method* target_handle = task->method();
1940   int compilable = ciEnv::MethodCompilable;
1941   {
1942     int system_dictionary_modification_counter;
1943     {
1944       MutexLocker locker(Compile_lock, thread);
1945       system_dictionary_modification_counter = SystemDictionary::number_of_modifications();
1946     }
1947 
1948     NoHandleMark  nhm;
1949     ThreadToNativeFromVM ttn(thread);
1950 
1951     ciEnv ci_env(task, system_dictionary_modification_counter);
1952     if (should_break) {
1953       ci_env.set_break_at_compile(true);
1954     }
1955     if (should_log) {
1956       ci_env.set_log(thread->log());
1957     }
1958     assert(thread->env() == &ci_env, "set by ci_env");
1959     // The thread-env() field is cleared in ~CompileTaskWrapper.
1960 
1961     // Cache Jvmti state
1962     ci_env.cache_jvmti_state();
1963 
1964     // Cache DTrace flags
1965     ci_env.cache_dtrace_flags();
1966 
1967     ciMethod* target = ci_env.get_method_from_handle(target_handle);
1968 
1969     TraceTime t1("compilation", &time);
1970     EventCompilation event;
1971 
1972     AbstractCompiler *comp = compiler(task_level);
1973     if (comp == NULL) {
1974       ci_env.record_method_not_compilable("no compiler", !TieredCompilation);
1975     } else {
1976       comp->compile_method(&ci_env, target, osr_bci);
1977     }
1978 
1979     if (!ci_env.failing() && task->code() == NULL) {
1980       //assert(false, "compiler should always document failure");
1981       // The compiler elected, without comment, not to register a result.
1982       // Do not attempt further compilations of this method.
1983       ci_env.record_method_not_compilable("compile failed", !TieredCompilation);
1984     }
1985 
1986     // Copy this bit to the enclosing block:
1987     compilable = ci_env.compilable();
1988 
1989     if (ci_env.failing()) {
1990       task->set_failure_reason(ci_env.failure_reason());
1991       const char* retry_message = ci_env.retry_message();
1992       if (_compilation_log != NULL) {
1993         _compilation_log->log_failure(thread, task, ci_env.failure_reason(), retry_message);
1994       }
1995       if (PrintCompilation) {
1996         FormatBufferResource msg = retry_message != NULL ?
1997             err_msg_res("COMPILE SKIPPED: %s (%s)", ci_env.failure_reason(), retry_message) :
1998             err_msg_res("COMPILE SKIPPED: %s",      ci_env.failure_reason());
1999         task->print_compilation(tty, msg);
2000       }
2001     } else {
2002       task->mark_success();
2003       task->set_num_inlined_bytecodes(ci_env.num_inlined_bytecodes());
2004       if (_compilation_log != NULL) {
2005         nmethod* code = task->code();
2006         if (code != NULL) {
2007           _compilation_log->log_nmethod(thread, code);
2008         }
2009       }
2010     }
2011     // simulate crash during compilation
2012     assert(task->compile_id() != CICrashAt, "just as planned");
2013     if (event.should_commit()) {
2014       event.set_method(target->get_Method());
2015       event.set_compileID(compile_id);
2016       event.set_compileLevel(task->comp_level());
2017       event.set_succeded(task->is_success());
2018       event.set_isOsr(is_osr);
2019       event.set_codeSize((task->code() == NULL) ? 0 : task->code()->total_size());
2020       event.set_inlinedBytes(task->num_inlined_bytecodes());
2021       event.commit();
2022     }
2023   }
2024   pop_jni_handle_block();
2025 
2026   methodHandle method(thread, task->method());
2027 
2028   DTRACE_METHOD_COMPILE_END_PROBE(method, compiler_name(task_level), task->is_success());
2029 
2030   collect_statistics(thread, time, task);
2031 
2032   if (PrintCompilation && PrintCompilation2) {
2033     tty->print("%7d ", (int) tty->time_stamp().milliseconds());  // print timestamp
2034     tty->print("%4d ", compile_id);    // print compilation number
2035     tty->print("%s ", (is_osr ? "%" : " "));
2036     if (task->code() != NULL) {
2037       tty->print("size: %d(%d) ", task->code()->total_size(), task->code()->insts_size());
2038     }
2039     tty->print_cr("time: %d inlined: %d bytes", (int)time.milliseconds(), task->num_inlined_bytecodes());
2040   }
2041 
2042   if (PrintCodeCacheOnCompilation)
2043     codecache_print(/* detailed= */ false);
2044 
2045   // Disable compilation, if required.
2046   switch (compilable) {
2047   case ciEnv::MethodCompilable_never:
2048     if (is_osr)
2049       method->set_not_osr_compilable_quietly();
2050     else
2051       method->set_not_compilable_quietly();
2052     break;
2053   case ciEnv::MethodCompilable_not_at_tier:
2054     if (is_osr)
2055       method->set_not_osr_compilable_quietly(task_level);
2056     else
2057       method->set_not_compilable_quietly(task_level);
2058     break;
2059   }
2060 
2061   // Note that the queued_for_compilation bits are cleared without
2062   // protection of a mutex. [They were set by the requester thread,
2063   // when adding the task to the compile queue -- at which time the
2064   // compile queue lock was held. Subsequently, we acquired the compile
2065   // queue lock to get this task off the compile queue; thus (to belabour
2066   // the point somewhat) our clearing of the bits must be occurring
2067   // only after the setting of the bits. See also 14012000 above.
2068   method->clear_queued_for_compilation();
2069 
2070 #ifdef ASSERT
2071   if (CollectedHeap::fired_fake_oom()) {
2072     // The current compile received a fake OOM during compilation so
2073     // go ahead and exit the VM since the test apparently succeeded
2074     tty->print_cr("*** Shutting down VM after successful fake OOM");
2075     vm_exit(0);
2076   }
2077 #endif
2078 }
2079 
2080 /**
2081  * The CodeCache is full.  Print out warning and disable compilation
2082  * or try code cache cleaning so compilation can continue later.
2083  */
2084 void CompileBroker::handle_full_code_cache() {
2085   UseInterpreter = true;
2086   if (UseCompiler || AlwaysCompileLoopMethods ) {
2087     if (xtty != NULL) {
2088       ResourceMark rm;
2089       stringStream s;
2090       // Dump code cache state into a buffer before locking the tty,
2091       // because log_state() will use locks causing lock conflicts.
2092       CodeCache::log_state(&s);
2093       // Lock to prevent tearing
2094       ttyLocker ttyl;
2095       xtty->begin_elem("code_cache_full");
2096       xtty->print("%s", s.as_string());
2097       xtty->stamp();
2098       xtty->end_elem();
2099     }
2100 
2101     CodeCache::report_codemem_full();
2102 
2103 #ifndef PRODUCT
2104     if (CompileTheWorld || ExitOnFullCodeCache) {
2105       codecache_print(/* detailed= */ true);
2106       before_exit(JavaThread::current());
2107       exit_globals(); // will delete tty
2108       vm_direct_exit(CompileTheWorld ? 0 : 1);
2109     }
2110 #endif
2111     if (UseCodeCacheFlushing) {
2112       // Since code cache is full, immediately stop new compiles
2113       if (CompileBroker::set_should_compile_new_jobs(CompileBroker::stop_compilation)) {
2114         NMethodSweeper::log_sweep("disable_compiler");
2115       }
2116       // Switch to 'vm_state'. This ensures that possibly_sweep() can be called
2117       // without having to consider the state in which the current thread is.
2118       ThreadInVMfromUnknown in_vm;
2119       NMethodSweeper::possibly_sweep();
2120     } else {
2121       disable_compilation_forever();
2122     }
2123 
2124     // Print warning only once
2125     if (should_print_compiler_warning()) {
2126       warning("CodeCache is full. Compiler has been disabled.");
2127       warning("Try increasing the code cache size using -XX:ReservedCodeCacheSize=");
2128       codecache_print(/* detailed= */ true);
2129     }
2130   }
2131 }
2132 
2133 // ------------------------------------------------------------------
2134 // CompileBroker::set_last_compile
2135 //
2136 // Record this compilation for debugging purposes.
2137 void CompileBroker::set_last_compile(CompilerThread* thread, methodHandle method, bool is_osr, int comp_level) {
2138   ResourceMark rm;
2139   char* method_name = method->name()->as_C_string();
2140   strncpy(_last_method_compiled, method_name, CompileBroker::name_buffer_length);
2141   _last_method_compiled[CompileBroker::name_buffer_length - 1] = '\0'; // ensure null terminated
2142   char current_method[CompilerCounters::cmname_buffer_length];
2143   size_t maxLen = CompilerCounters::cmname_buffer_length;
2144 
2145   if (UsePerfData) {
2146     const char* class_name = method->method_holder()->name()->as_C_string();
2147 
2148     size_t s1len = strlen(class_name);
2149     size_t s2len = strlen(method_name);
2150 
2151     // check if we need to truncate the string
2152     if (s1len + s2len + 2 > maxLen) {
2153 
2154       // the strategy is to lop off the leading characters of the
2155       // class name and the trailing characters of the method name.
2156 
2157       if (s2len + 2 > maxLen) {
2158         // lop of the entire class name string, let snprintf handle
2159         // truncation of the method name.
2160         class_name += s1len; // null string
2161       }
2162       else {
2163         // lop off the extra characters from the front of the class name
2164         class_name += ((s1len + s2len + 2) - maxLen);
2165       }
2166     }
2167 
2168     jio_snprintf(current_method, maxLen, "%s %s", class_name, method_name);
2169   }
2170 
2171   if (CICountOSR && is_osr) {
2172     _last_compile_type = osr_compile;
2173   } else {
2174     _last_compile_type = normal_compile;
2175   }
2176   _last_compile_level = comp_level;
2177 
2178   if (UsePerfData) {
2179     CompilerCounters* counters = thread->counters();
2180     counters->set_current_method(current_method);
2181     counters->set_compile_type((jlong)_last_compile_type);
2182   }
2183 }
2184 
2185 
2186 // ------------------------------------------------------------------
2187 // CompileBroker::push_jni_handle_block
2188 //
2189 // Push on a new block of JNI handles.
2190 void CompileBroker::push_jni_handle_block() {
2191   JavaThread* thread = JavaThread::current();
2192 
2193   // Allocate a new block for JNI handles.
2194   // Inlined code from jni_PushLocalFrame()
2195   JNIHandleBlock* java_handles = thread->active_handles();
2196   JNIHandleBlock* compile_handles = JNIHandleBlock::allocate_block(thread);
2197   assert(compile_handles != NULL && java_handles != NULL, "should not be NULL");
2198   compile_handles->set_pop_frame_link(java_handles);  // make sure java handles get gc'd.
2199   thread->set_active_handles(compile_handles);
2200 }
2201 
2202 
2203 // ------------------------------------------------------------------
2204 // CompileBroker::pop_jni_handle_block
2205 //
2206 // Pop off the current block of JNI handles.
2207 void CompileBroker::pop_jni_handle_block() {
2208   JavaThread* thread = JavaThread::current();
2209 
2210   // Release our JNI handle block
2211   JNIHandleBlock* compile_handles = thread->active_handles();
2212   JNIHandleBlock* java_handles = compile_handles->pop_frame_link();
2213   thread->set_active_handles(java_handles);
2214   compile_handles->set_pop_frame_link(NULL);
2215   JNIHandleBlock::release_block(compile_handles, thread); // may block
2216 }
2217 
2218 
2219 // ------------------------------------------------------------------
2220 // CompileBroker::check_break_at
2221 //
2222 // Should the compilation break at the current compilation.
2223 bool CompileBroker::check_break_at(methodHandle method, int compile_id, bool is_osr) {
2224   if (CICountOSR && is_osr && (compile_id == CIBreakAtOSR)) {
2225     return true;
2226   } else if( CompilerOracle::should_break_at(method) ) { // break when compiling
2227     return true;
2228   } else {
2229     return (compile_id == CIBreakAt);
2230   }
2231 }
2232 
2233 // ------------------------------------------------------------------
2234 // CompileBroker::collect_statistics
2235 //
2236 // Collect statistics about the compilation.
2237 
2238 void CompileBroker::collect_statistics(CompilerThread* thread, elapsedTimer time, CompileTask* task) {
2239   bool success = task->is_success();
2240   methodHandle method (thread, task->method());
2241   uint compile_id = task->compile_id();
2242   bool is_osr = (task->osr_bci() != standard_entry_bci);
2243   nmethod* code = task->code();
2244   CompilerCounters* counters = thread->counters();
2245 
2246   assert(code == NULL || code->is_locked_by_vm(), "will survive the MutexLocker");
2247   MutexLocker locker(CompileStatistics_lock);
2248 
2249   // _perf variables are production performance counters which are
2250   // updated regardless of the setting of the CITime and CITimeEach flags
2251   //
2252   
2253   // account all time, including bailouts and failures in this counter;
2254   // C1 and C2 counters are counting both successful and unsuccessful compiles
2255   _t_total_compilation.add(time);
2256   
2257   if (!success) {
2258     _total_bailout_count++;
2259     if (UsePerfData) {
2260       _perf_last_failed_method->set_value(counters->current_method());
2261       _perf_last_failed_type->set_value(counters->compile_type());
2262       _perf_total_bailout_count->inc();
2263     }
2264     _t_bailedout_compilation.add(time);
2265   } else if (code == NULL) {
2266     if (UsePerfData) {
2267       _perf_last_invalidated_method->set_value(counters->current_method());
2268       _perf_last_invalidated_type->set_value(counters->compile_type());
2269       _perf_total_invalidated_count->inc();
2270     }
2271     _total_invalidated_count++;
2272     _t_invalidated_compilation.add(time);
2273   } else {
2274     // Compilation succeeded
2275 
2276     // update compilation ticks - used by the implementation of
2277     // java.lang.management.CompilationMBean
2278     _perf_total_compilation->inc(time.ticks());
2279     _peak_compilation_time = time.milliseconds() > _peak_compilation_time ? time.milliseconds() : _peak_compilation_time;
2280 
2281     if (CITime) {
2282       if (is_osr) {
2283         _t_osr_compilation.add(time);
2284         _sum_osr_bytes_compiled += method->code_size() + task->num_inlined_bytecodes();
2285       } else {
2286         _t_standard_compilation.add(time);
2287         _sum_standard_bytes_compiled += method->code_size() + task->num_inlined_bytecodes();
2288       }
2289     }
2290 
2291     if (UsePerfData) {
2292       // save the name of the last method compiled
2293       _perf_last_method->set_value(counters->current_method());
2294       _perf_last_compile_type->set_value(counters->compile_type());
2295       _perf_last_compile_size->set_value(method->code_size() +
2296                                          task->num_inlined_bytecodes());
2297       if (is_osr) {
2298         _perf_osr_compilation->inc(time.ticks());
2299         _perf_sum_osr_bytes_compiled->inc(method->code_size() + task->num_inlined_bytecodes());
2300       } else {
2301         _perf_standard_compilation->inc(time.ticks());
2302         _perf_sum_standard_bytes_compiled->inc(method->code_size() + task->num_inlined_bytecodes());
2303       }
2304     }
2305 
2306     if (CITimeEach) {
2307       float bytes_per_sec = 1.0 * (method->code_size() + task->num_inlined_bytecodes()) / time.seconds();
2308       tty->print_cr("%3d   seconds: %f bytes/sec : %f (bytes %d + %d inlined)",
2309                     compile_id, time.seconds(), bytes_per_sec, method->code_size(), task->num_inlined_bytecodes());
2310     }
2311 
2312     // Collect counts of successful compilations
2313     _sum_nmethod_size      += code->total_size();
2314     _sum_nmethod_code_size += code->insts_size();
2315     _total_compile_count++;
2316 
2317     if (UsePerfData) {
2318       _perf_sum_nmethod_size->inc(     code->total_size());
2319       _perf_sum_nmethod_code_size->inc(code->insts_size());
2320       _perf_total_compile_count->inc();
2321     }
2322 
2323     if (is_osr) {
2324       if (UsePerfData) _perf_total_osr_compile_count->inc();
2325       _total_osr_compile_count++;
2326     } else {
2327       if (UsePerfData) _perf_total_standard_compile_count->inc();
2328       _total_standard_compile_count++;
2329     }
2330   }
2331   // set the current method for the thread to null
2332   if (UsePerfData) counters->set_current_method("");
2333 }
2334 
2335 const char* CompileBroker::compiler_name(int comp_level) {
2336   AbstractCompiler *comp = CompileBroker::compiler(comp_level);
2337   if (comp == NULL) {
2338     return "no compiler";
2339   } else {
2340     return (comp->name());
2341   }
2342 }
2343 
2344 void CompileBroker::print_times() {
2345   tty->cr();
2346   tty->print_cr("Accumulated compiler times");
2347   tty->print_cr("----------------------------------------------------------");
2348                //0000000000111111111122222222223333333333444444444455555555556666666666
2349                //0123456789012345678901234567890123456789012345678901234567890123456789
2350   tty->print_cr("  Total compilation time   : %7.3f s", CompileBroker::_t_total_compilation.seconds());
2351   tty->print_cr("    Standard compilation   : %7.3f s, Average : %2.3f s",
2352                 CompileBroker::_t_standard_compilation.seconds(),
2353                 CompileBroker::_t_standard_compilation.seconds() / CompileBroker::_total_standard_compile_count);
2354   tty->print_cr("    Bailed out compilation : %7.3f s, Average : %2.3f s", 
2355                 CompileBroker::_t_bailedout_compilation.seconds(),
2356                 CompileBroker::_t_bailedout_compilation.seconds() / CompileBroker::_total_bailout_count);
2357   tty->print_cr("    On stack replacement   : %7.3f s, Average : %2.3f s",
2358                 CompileBroker::_t_osr_compilation.seconds(),
2359                 CompileBroker::_t_osr_compilation.seconds() / CompileBroker::_total_osr_compile_count);
2360   tty->print_cr("    Invalidated            : %7.3f s, Average : %2.3f s",
2361                 CompileBroker::_t_invalidated_compilation.seconds(),
2362                 CompileBroker::_t_invalidated_compilation.seconds() / CompileBroker::_total_invalidated_count);
2363   
2364   AbstractCompiler *comp = compiler(CompLevel_simple);
2365   if (comp != NULL) {
2366     tty->cr();
2367     comp->print_timers();
2368   }
2369   comp = compiler(CompLevel_full_optimization);
2370   if (comp != NULL) {
2371     tty->cr();
2372     comp->print_timers();
2373   }
2374   tty->cr();
2375   tty->print_cr("  Total compiled methods   : %6d methods", CompileBroker::_total_compile_count);
2376   tty->print_cr("    Standard compilation   : %6d methods", CompileBroker::_total_standard_compile_count);
2377   tty->print_cr("    On stack replacement   : %6d methods", CompileBroker::_total_osr_compile_count);
2378   int tcb = CompileBroker::_sum_osr_bytes_compiled + CompileBroker::_sum_standard_bytes_compiled;
2379   tty->print_cr("  Total compiled bytecodes : %6d bytes", tcb);
2380   tty->print_cr("    Standard compilation   : %6d bytes", CompileBroker::_sum_standard_bytes_compiled);
2381   tty->print_cr("    On stack replacement   : %6d bytes", CompileBroker::_sum_osr_bytes_compiled);
2382   int bps = (int)(tcb / CompileBroker::_t_total_compilation.seconds());
2383   tty->print_cr("  Average compilation speed: %6d bytes/s", bps);
2384   tty->cr();
2385   tty->print_cr("  nmethod code size        : %6d bytes", CompileBroker::_sum_nmethod_code_size);
2386   tty->print_cr("  nmethod total size       : %6d bytes", CompileBroker::_sum_nmethod_size);
2387 }
2388 
2389 // Debugging output for failure
2390 void CompileBroker::print_last_compile() {
2391   if ( _last_compile_level != CompLevel_none &&
2392        compiler(_last_compile_level) != NULL &&
2393        _last_method_compiled != NULL &&
2394        _last_compile_type != no_compile) {
2395     if (_last_compile_type == osr_compile) {
2396       tty->print_cr("Last parse:  [osr]%d+++(%d) %s",
2397                     _osr_compilation_id, _last_compile_level, _last_method_compiled);
2398     } else {
2399       tty->print_cr("Last parse:  %d+++(%d) %s",
2400                     _compilation_id, _last_compile_level, _last_method_compiled);
2401     }
2402   }
2403 }
2404 
2405 
2406 void CompileBroker::print_compiler_threads_on(outputStream* st) {
2407 #ifndef PRODUCT
2408   st->print_cr("Compiler thread printing unimplemented.");
2409   st->cr();
2410 #endif
2411 }