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