< prev index next >

src/hotspot/share/compiler/compileBroker.cpp

Print this page

   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/javaClasses.inline.hpp"
  27 #include "classfile/symbolTable.hpp"
  28 #include "classfile/vmClasses.hpp"
  29 #include "classfile/vmSymbols.hpp"
  30 #include "code/codeCache.hpp"
  31 #include "code/codeHeapState.hpp"
  32 #include "code/dependencyContext.hpp"

  33 #include "compiler/compilationLog.hpp"
  34 #include "compiler/compilationMemoryStatistic.hpp"
  35 #include "compiler/compilationPolicy.hpp"
  36 #include "compiler/compileBroker.hpp"

  37 #include "compiler/compileLog.hpp"
  38 #include "compiler/compilerEvent.hpp"
  39 #include "compiler/compilerOracle.hpp"
  40 #include "compiler/directivesParser.hpp"
  41 #include "interpreter/linkResolver.hpp"
  42 #include "jvm.h"
  43 #include "jfr/jfrEvents.hpp"
  44 #include "logging/log.hpp"
  45 #include "logging/logStream.hpp"
  46 #include "memory/allocation.inline.hpp"
  47 #include "memory/resourceArea.hpp"
  48 #include "memory/universe.hpp"
  49 #include "oops/methodData.hpp"
  50 #include "oops/method.inline.hpp"
  51 #include "oops/oop.inline.hpp"
  52 #include "prims/jvmtiExport.hpp"
  53 #include "prims/nativeLookup.hpp"
  54 #include "prims/whitebox.hpp"
  55 #include "runtime/atomic.hpp"
  56 #include "runtime/escapeBarrier.hpp"
  57 #include "runtime/globals_extension.hpp"
  58 #include "runtime/handles.inline.hpp"
  59 #include "runtime/init.hpp"
  60 #include "runtime/interfaceSupport.inline.hpp"
  61 #include "runtime/java.hpp"
  62 #include "runtime/javaCalls.hpp"
  63 #include "runtime/jniHandles.inline.hpp"
  64 #include "runtime/os.hpp"
  65 #include "runtime/perfData.hpp"
  66 #include "runtime/safepointVerifiers.hpp"
  67 #include "runtime/sharedRuntime.hpp"
  68 #include "runtime/threads.hpp"
  69 #include "runtime/threadSMR.hpp"
  70 #include "runtime/timerTrace.hpp"
  71 #include "runtime/vframe.inline.hpp"

  72 #include "utilities/debug.hpp"
  73 #include "utilities/dtrace.hpp"
  74 #include "utilities/events.hpp"
  75 #include "utilities/formatBuffer.hpp"
  76 #include "utilities/macros.hpp"
  77 #ifdef COMPILER1
  78 #include "c1/c1_Compiler.hpp"
  79 #endif
  80 #ifdef COMPILER2
  81 #include "opto/c2compiler.hpp"
  82 #endif
  83 #if INCLUDE_JVMCI
  84 #include "jvmci/jvmciEnv.hpp"
  85 #include "jvmci/jvmciRuntime.hpp"
  86 #endif
  87 
  88 #ifdef DTRACE_ENABLED
  89 
  90 // Only bother with this argument setup if dtrace is available
  91 

 109     HOTSPOT_METHOD_COMPILE_END(                                          \
 110       (char *) comp_name, strlen(comp_name),                             \
 111       (char *) klass_name->bytes(), klass_name->utf8_length(),           \
 112       (char *) name->bytes(), name->utf8_length(),                       \
 113       (char *) signature->bytes(), signature->utf8_length(), (success)); \
 114   }
 115 
 116 #else //  ndef DTRACE_ENABLED
 117 
 118 #define DTRACE_METHOD_COMPILE_BEGIN_PROBE(method, comp_name)
 119 #define DTRACE_METHOD_COMPILE_END_PROBE(method, comp_name, success)
 120 
 121 #endif // ndef DTRACE_ENABLED
 122 
 123 bool CompileBroker::_initialized = false;
 124 volatile bool CompileBroker::_should_block = false;
 125 volatile int  CompileBroker::_print_compilation_warning = 0;
 126 volatile jint CompileBroker::_should_compile_new_jobs = run_compilation;
 127 
 128 // The installed compiler(s)
 129 AbstractCompiler* CompileBroker::_compilers[2];
 130 
 131 // The maximum numbers of compiler threads to be determined during startup.
 132 int CompileBroker::_c1_count = 0;
 133 int CompileBroker::_c2_count = 0;


 134 
 135 // An array of compiler names as Java String objects
 136 jobject* CompileBroker::_compiler1_objects = nullptr;
 137 jobject* CompileBroker::_compiler2_objects = nullptr;


 138 
 139 CompileLog** CompileBroker::_compiler1_logs = nullptr;
 140 CompileLog** CompileBroker::_compiler2_logs = nullptr;


 141 
 142 // These counters are used to assign an unique ID to each compilation.
 143 volatile jint CompileBroker::_compilation_id     = 0;
 144 volatile jint CompileBroker::_osr_compilation_id = 0;
 145 volatile jint CompileBroker::_native_compilation_id = 0;
 146 
 147 // Performance counters
 148 PerfCounter* CompileBroker::_perf_total_compilation = nullptr;
 149 PerfCounter* CompileBroker::_perf_osr_compilation = nullptr;
 150 PerfCounter* CompileBroker::_perf_standard_compilation = nullptr;
 151 
 152 PerfCounter* CompileBroker::_perf_total_bailout_count = nullptr;
 153 PerfCounter* CompileBroker::_perf_total_invalidated_count = nullptr;
 154 PerfCounter* CompileBroker::_perf_total_compile_count = nullptr;
 155 PerfCounter* CompileBroker::_perf_total_osr_compile_count = nullptr;
 156 PerfCounter* CompileBroker::_perf_total_standard_compile_count = nullptr;
 157 
 158 PerfCounter* CompileBroker::_perf_sum_osr_bytes_compiled = nullptr;
 159 PerfCounter* CompileBroker::_perf_sum_standard_bytes_compiled = nullptr;
 160 PerfCounter* CompileBroker::_perf_sum_nmethod_size = nullptr;
 161 PerfCounter* CompileBroker::_perf_sum_nmethod_code_size = nullptr;
 162 
 163 PerfStringVariable* CompileBroker::_perf_last_method = nullptr;
 164 PerfStringVariable* CompileBroker::_perf_last_failed_method = nullptr;
 165 PerfStringVariable* CompileBroker::_perf_last_invalidated_method = nullptr;
 166 PerfVariable*       CompileBroker::_perf_last_compile_type = nullptr;
 167 PerfVariable*       CompileBroker::_perf_last_compile_size = nullptr;
 168 PerfVariable*       CompileBroker::_perf_last_failed_type = nullptr;
 169 PerfVariable*       CompileBroker::_perf_last_invalidated_type = nullptr;
 170 
 171 // Timers and counters for generating statistics
 172 elapsedTimer CompileBroker::_t_total_compilation;
 173 elapsedTimer CompileBroker::_t_osr_compilation;
 174 elapsedTimer CompileBroker::_t_standard_compilation;
 175 elapsedTimer CompileBroker::_t_invalidated_compilation;
 176 elapsedTimer CompileBroker::_t_bailedout_compilation;
 177 
 178 uint CompileBroker::_total_bailout_count            = 0;
 179 uint CompileBroker::_total_invalidated_count        = 0;

 180 uint CompileBroker::_total_compile_count            = 0;
 181 uint CompileBroker::_total_osr_compile_count        = 0;
 182 uint CompileBroker::_total_standard_compile_count   = 0;
 183 uint CompileBroker::_total_compiler_stopped_count   = 0;
 184 uint CompileBroker::_total_compiler_restarted_count = 0;
 185 
 186 uint CompileBroker::_sum_osr_bytes_compiled         = 0;
 187 uint CompileBroker::_sum_standard_bytes_compiled    = 0;
 188 uint CompileBroker::_sum_nmethod_size               = 0;
 189 uint CompileBroker::_sum_nmethod_code_size          = 0;
 190 
 191 jlong CompileBroker::_peak_compilation_time        = 0;
 192 
 193 CompilerStatistics CompileBroker::_stats_per_level[CompLevel_full_optimization];


 194 

 195 CompileQueue* CompileBroker::_c2_compile_queue     = nullptr;
 196 CompileQueue* CompileBroker::_c1_compile_queue     = nullptr;


 197 
 198 bool compileBroker_init() {
 199   if (LogEvents) {
 200     CompilationLog::init();
 201   }
 202 
 203   // init directives stack, adding default directive
 204   DirectivesStack::init();
 205 
 206   if (DirectivesParser::has_file()) {
 207     return DirectivesParser::parse_from_flag();
 208   } else if (CompilerDirectivesPrint) {
 209     // Print default directive even when no other was added
 210     DirectivesStack::print(tty);
 211   }
 212 
 213   return true;
 214 }
 215 
 216 CompileTaskWrapper::CompileTaskWrapper(CompileTask* task) {
 217   CompilerThread* thread = CompilerThread::current();
 218   thread->set_task(task);
 219   CompileLog*     log  = thread->log();
 220   if (log != nullptr && !task->is_unloaded())  task->log_task_start(log);
 221 }
 222 
 223 CompileTaskWrapper::~CompileTaskWrapper() {
 224   CompilerThread* thread = CompilerThread::current();
 225   CompileTask* task = thread->task();
 226   CompileLog*  log  = thread->log();

 227   if (log != nullptr && !task->is_unloaded())  task->log_task_done(log);
 228   thread->set_task(nullptr);
 229   thread->set_env(nullptr);
 230   if (task->is_blocking()) {
 231     bool free_task = false;
 232     {
 233       MutexLocker notifier(thread, task->lock());
 234       task->mark_complete();
 235 #if INCLUDE_JVMCI
 236       if (CompileBroker::compiler(task->comp_level())->is_jvmci()) {
 237         if (!task->has_waiter()) {
 238           // The waiting thread timed out and thus did not free the task.
 239           free_task = true;
 240         }
 241         task->set_blocking_jvmci_compile_state(nullptr);
 242       }
 243 #endif
 244       if (!free_task) {
 245         // Notify the waiting thread that the compilation has completed
 246         // so that it can free the task.
 247         task->lock()->notify_all();
 248       }
 249     }
 250     if (free_task) {
 251       // The task can only be freed once the task lock is released.
 252       CompileTask::free(task);
 253     }
 254   } else {
 255     task->mark_complete();
 256 
 257     // By convention, the compiling thread is responsible for
 258     // recycling a non-blocking CompileTask.
 259     CompileTask::free(task);
 260   }
 261 }
 262 
 263 /**
 264  * Check if a CompilerThread can be removed and update count if requested.
 265  */
 266 bool CompileBroker::can_remove(CompilerThread *ct, bool do_it) {
 267   assert(UseDynamicNumberOfCompilerThreads, "or shouldn't be here");
 268   if (!ReduceNumberOfCompilerThreads) return false;
 269 


 270   AbstractCompiler *compiler = ct->compiler();
 271   int compiler_count = compiler->num_compiler_threads();
 272   bool c1 = compiler->is_c1();
 273 
 274   // Keep at least 1 compiler thread of each type.
 275   if (compiler_count < 2) return false;
 276 
 277   // Keep thread alive for at least some time.
 278   if (ct->idle_time_millis() < (c1 ? 500 : 100)) return false;
 279 
 280 #if INCLUDE_JVMCI
 281   if (compiler->is_jvmci() && !UseJVMCINativeLibrary) {
 282     // Handles for JVMCI thread objects may get released concurrently.
 283     if (do_it) {
 284       assert(CompileThread_lock->owner() == ct, "must be holding lock");
 285     } else {
 286       // Skip check if it's the last thread and let caller check again.
 287       return true;
 288     }
 289   }

 296     if (do_it) {
 297       assert_locked_or_safepoint(CompileThread_lock); // Update must be consistent.
 298       compiler->set_num_compiler_threads(compiler_count - 1);
 299 #if INCLUDE_JVMCI
 300       if (compiler->is_jvmci() && !UseJVMCINativeLibrary) {
 301         // Old j.l.Thread object can die when no longer referenced elsewhere.
 302         JNIHandles::destroy_global(compiler2_object(compiler_count - 1));
 303         _compiler2_objects[compiler_count - 1] = nullptr;
 304       }
 305 #endif
 306     }
 307     return true;
 308   }
 309   return false;
 310 }
 311 
 312 /**
 313  * Add a CompileTask to a CompileQueue.
 314  */
 315 void CompileQueue::add(CompileTask* task) {
 316   assert(MethodCompileQueue_lock->owned_by_self(), "must own lock");
 317 
 318   task->set_next(nullptr);
 319   task->set_prev(nullptr);
 320 
 321   if (_last == nullptr) {
 322     // The compile queue is empty.
 323     assert(_first == nullptr, "queue is empty");
 324     _first = task;
 325     _last = task;
 326   } else {
 327     // Append the task to the queue.
 328     assert(_last->next() == nullptr, "not last");
 329     _last->set_next(task);
 330     task->set_prev(_last);
 331     _last = task;
 332   }
 333   ++_size;
 334   ++_total_added;
 335   if (_size > _peak_size) {
 336     _peak_size = _size;
 337   }
 338 
 339   // Mark the method as being in the compile queue.
 340   task->method()->set_queued_for_compilation();
 341 


 342   if (CIPrintCompileQueue) {
 343     print_tty();
 344   }
 345 
 346   if (LogCompilation && xtty != nullptr) {
 347     task->log_task_queued();
 348   }
 349 








 350   // Notify CompilerThreads that a task is available.
 351   MethodCompileQueue_lock->notify_all();






































 352 }
 353 
 354 /**
 355  * Empties compilation queue by putting all compilation tasks onto
 356  * a freelist. Furthermore, the method wakes up all threads that are
 357  * waiting on a compilation task to finish. This can happen if background
 358  * compilation is disabled.
 359  */
 360 void CompileQueue::free_all() {
 361   MutexLocker mu(MethodCompileQueue_lock);


 362   CompileTask* next = _first;
 363 
 364   // Iterate over all tasks in the compile queue
 365   while (next != nullptr) {
 366     CompileTask* current = next;
 367     next = current->next();
 368     {
 369       // Wake up thread that blocks on the compile task.
 370       MutexLocker ct_lock(current->lock());
 371       current->lock()->notify();
 372     }
 373     // Put the task back on the freelist.
 374     CompileTask::free(current);
 375   }
 376   _first = nullptr;
 377   _last = nullptr;
 378 
 379   // Wake up all threads that block on the queue.
 380   MethodCompileQueue_lock->notify_all();
 381 }
 382 
 383 /**
 384  * Get the next CompileTask from a CompileQueue
 385  */
 386 CompileTask* CompileQueue::get(CompilerThread* thread) {
 387   // save methods from RedefineClasses across safepoint
 388   // across MethodCompileQueue_lock below.
 389   methodHandle save_method;
 390   methodHandle save_hot_method;
 391 
 392   MonitorLocker locker(MethodCompileQueue_lock);




 393   // If _first is null we have no more compile jobs. There are two reasons for
 394   // having no compile jobs: First, we compiled everything we wanted. Second,
 395   // we ran out of code cache so compilation has been disabled. In the latter
 396   // case we perform code cache sweeps to free memory such that we can re-enable
 397   // compilation.
 398   while (_first == nullptr) {
 399     // Exit loop if compilation is disabled forever
 400     if (CompileBroker::is_compilation_disabled_forever()) {
 401       return nullptr;
 402     }
 403 
 404     AbstractCompiler* compiler = thread->compiler();
 405     guarantee(compiler != nullptr, "Compiler object must exist");
 406     compiler->on_empty_queue(this, thread);
 407     if (_first != nullptr) {
 408       // The call to on_empty_queue may have temporarily unlocked the MCQ lock
 409       // so check again whether any tasks were added to the queue.
 410       break;
 411     }
 412 
 413     // If there are no compilation tasks and we can compile new jobs
 414     // (i.e., there is enough free space in the code cache) there is
 415     // no need to invoke the GC.
 416     // We need a timed wait here, since compiler threads can exit if compilation
 417     // is disabled forever. We use 5 seconds wait time; the exiting of compiler threads
 418     // is not critical and we do not want idle compiler threads to wake up too often.
 419     locker.wait(5*1000);
 420 




 421     if (UseDynamicNumberOfCompilerThreads && _first == nullptr) {
 422       // Still nothing to compile. Give caller a chance to stop this thread.
 423       if (CompileBroker::can_remove(CompilerThread::current(), false)) return nullptr;
 424     }
 425   }
 426 
 427   if (CompileBroker::is_compilation_disabled_forever()) {
 428     return nullptr;
 429   }
 430 
 431   CompileTask* task;
 432   {
 433     NoSafepointVerifier nsv;
 434     task = CompilationPolicy::select_task(this);
 435     if (task != nullptr) {
 436       task = task->select_for_compilation();
 437     }
 438   }
 439 
 440   if (task != nullptr) {
 441     // Save method pointers across unlock safepoint.  The task is removed from
 442     // the compilation queue, which is walked during RedefineClasses.
 443     Thread* thread = Thread::current();
 444     save_method = methodHandle(thread, task->method());
 445     save_hot_method = methodHandle(thread, task->hot_method());
 446 
 447     remove(task);
 448   }
 449   purge_stale_tasks(); // may temporarily release MCQ lock
 450   return task;
 451 }
 452 
 453 // Clean & deallocate stale compile tasks.
 454 // Temporarily releases MethodCompileQueue lock.
 455 void CompileQueue::purge_stale_tasks() {
 456   assert(MethodCompileQueue_lock->owned_by_self(), "must own lock");
 457   if (_first_stale != nullptr) {
 458     // Stale tasks are purged when MCQ lock is released,
 459     // but _first_stale updates are protected by MCQ lock.
 460     // Once task processing starts and MCQ lock is released,
 461     // other compiler threads can reuse _first_stale.
 462     CompileTask* head = _first_stale;
 463     _first_stale = nullptr;
 464     {
 465       MutexUnlocker ul(MethodCompileQueue_lock);
 466       for (CompileTask* task = head; task != nullptr; ) {
 467         CompileTask* next_task = task->next();
 468         CompileTaskWrapper ctw(task); // Frees the task
 469         task->set_failure_reason("stale task");
 470         task = next_task;
 471       }
 472     }

 473   }
 474 }
 475 
 476 void CompileQueue::remove(CompileTask* task) {
 477   assert(MethodCompileQueue_lock->owned_by_self(), "must own lock");
 478   if (task->prev() != nullptr) {
 479     task->prev()->set_next(task->next());
 480   } else {
 481     // max is the first element
 482     assert(task == _first, "Sanity");
 483     _first = task->next();
 484   }
 485 
 486   if (task->next() != nullptr) {
 487     task->next()->set_prev(task->prev());
 488   } else {
 489     // max is the last element
 490     assert(task == _last, "Sanity");
 491     _last = task->prev();
 492   }
 493   --_size;
 494   ++_total_removed;
 495 }
 496 
 497 void CompileQueue::remove_and_mark_stale(CompileTask* task) {
 498   assert(MethodCompileQueue_lock->owned_by_self(), "must own lock");
 499   remove(task);
 500 
 501   // Enqueue the task for reclamation (should be done outside MCQ lock)
 502   task->set_next(_first_stale);
 503   task->set_prev(nullptr);
 504   _first_stale = task;
 505 }
 506 
 507 // methods in the compile queue need to be marked as used on the stack
 508 // so that they don't get reclaimed by Redefine Classes
 509 void CompileQueue::mark_on_stack() {
 510   CompileTask* task = _first;
 511   while (task != nullptr) {
 512     task->mark_on_stack();
 513     task = task->next();
 514   }
 515 }
 516 
 517 
 518 CompileQueue* CompileBroker::compile_queue(int comp_level) {
 519   if (is_c2_compile(comp_level)) return _c2_compile_queue;
 520   if (is_c1_compile(comp_level)) return _c1_compile_queue;
 521   return nullptr;
 522 }
 523 
 524 CompileQueue* CompileBroker::c1_compile_queue() {
 525   return _c1_compile_queue;
 526 }
 527 
 528 CompileQueue* CompileBroker::c2_compile_queue() {
 529   return _c2_compile_queue;
 530 }
 531 
 532 void CompileBroker::print_compile_queues(outputStream* st) {
 533   st->print_cr("Current compiles: ");
 534 
 535   char buf[2000];
 536   int buflen = sizeof(buf);
 537   Threads::print_threads_compiling(st, buf, buflen, /* short_form = */ true);
 538 
 539   st->cr();
 540   if (_c1_compile_queue != nullptr) {
 541     _c1_compile_queue->print(st);
 542   }
 543   if (_c2_compile_queue != nullptr) {
 544     _c2_compile_queue->print(st);
 545   }









 546 }
 547 
 548 void CompileQueue::print(outputStream* st) {
 549   assert_locked_or_safepoint(MethodCompileQueue_lock);
 550   st->print_cr("%s:", name());
 551   CompileTask* task = _first;
 552   if (task == nullptr) {
 553     st->print_cr("Empty");
 554   } else {
 555     while (task != nullptr) {
 556       task->print(st, nullptr, true, true);
 557       task = task->next();
 558     }
 559   }
 560   st->cr();
 561 }
 562 
 563 void CompileQueue::print_tty() {
 564   stringStream ss;
 565   // Dump the compile queue into a buffer before locking the tty
 566   print(&ss);
 567   {
 568     ttyLocker ttyl;
 569     tty->print("%s", ss.freeze());

 596       CompilerEvent::PhaseEvent::get_phase_id(phase_name, false, false, false);
 597     }
 598     first_registration = false;
 599 #endif // COMPILER2
 600   }
 601 }
 602 #endif // INCLUDE_JFR && COMPILER2_OR_JVMCI
 603 
 604 // ------------------------------------------------------------------
 605 // CompileBroker::compilation_init
 606 //
 607 // Initialize the Compilation object
 608 void CompileBroker::compilation_init(JavaThread* THREAD) {
 609   // No need to initialize compilation system if we do not use it.
 610   if (!UseCompiler) {
 611     return;
 612   }
 613   // Set the interface to the current compiler(s).
 614   _c1_count = CompilationPolicy::c1_count();
 615   _c2_count = CompilationPolicy::c2_count();


 616 
 617 #if INCLUDE_JVMCI
 618   if (EnableJVMCI) {
 619     // This is creating a JVMCICompiler singleton.
 620     JVMCICompiler* jvmci = new JVMCICompiler();
 621 
 622     if (UseJVMCICompiler) {
 623       _compilers[1] = jvmci;
 624       if (FLAG_IS_DEFAULT(JVMCIThreads)) {
 625         if (BootstrapJVMCI) {
 626           // JVMCI will bootstrap so give it more threads
 627           _c2_count = MIN2(32, os::active_processor_count());
 628         }
 629       } else {
 630         _c2_count = JVMCIThreads;
 631       }
 632       if (FLAG_IS_DEFAULT(JVMCIHostThreads)) {
 633       } else {
 634 #ifdef COMPILER1
 635         _c1_count = JVMCIHostThreads;
 636 #endif // COMPILER1
 637       }





 638     }
 639   }
 640 #endif // INCLUDE_JVMCI
 641 
 642 #ifdef COMPILER1
 643   if (_c1_count > 0) {
 644     _compilers[0] = new Compiler();
 645   }
 646 #endif // COMPILER1
 647 
 648 #ifdef COMPILER2
 649   if (true JVMCI_ONLY( && !UseJVMCICompiler)) {
 650     if (_c2_count > 0) {
 651       _compilers[1] = new C2Compiler();
 652       // Register c2 first as c2 CompilerPhaseType idToPhase mapping is explicit.
 653       // idToPhase mapping for c2 is in opto/phasetype.hpp
 654       JFR_ONLY(register_jfr_phasetype_serializer(compiler_c2);)
 655     }
 656   }
 657 #endif // COMPILER2

 752     _perf_last_compile_size =
 753              PerfDataManager::create_variable(SUN_CI, "lastSize",
 754                                               PerfData::U_Bytes,
 755                                               (jlong)CompileBroker::no_compile,
 756                                               CHECK);
 757 
 758 
 759     _perf_last_failed_type =
 760              PerfDataManager::create_variable(SUN_CI, "lastFailedType",
 761                                               PerfData::U_None,
 762                                               (jlong)CompileBroker::no_compile,
 763                                               CHECK);
 764 
 765     _perf_last_invalidated_type =
 766          PerfDataManager::create_variable(SUN_CI, "lastInvalidatedType",
 767                                           PerfData::U_None,
 768                                           (jlong)CompileBroker::no_compile,
 769                                           CHECK);
 770   }
 771 

 772   _initialized = true;
 773 }
 774 









 775 #if defined(ASSERT) && COMPILER2_OR_JVMCI
 776 // Stress testing. Dedicated threads revert optimizations based on escape analysis concurrently to
 777 // the running java application.  Configured with vm options DeoptimizeObjectsALot*.
 778 class DeoptimizeObjectsALotThread : public JavaThread {
 779 
 780   static void deopt_objs_alot_thread_entry(JavaThread* thread, TRAPS);
 781   void deoptimize_objects_alot_loop_single();
 782   void deoptimize_objects_alot_loop_all();
 783 
 784 public:
 785   DeoptimizeObjectsALotThread() : JavaThread(&deopt_objs_alot_thread_entry) { }
 786 
 787   bool is_hidden_from_external_view() const      { return true; }
 788 };
 789 
 790 // Entry for DeoptimizeObjectsALotThread. The threads are started in
 791 // CompileBroker::init_compiler_threads() iff DeoptimizeObjectsALot is enabled
 792 void DeoptimizeObjectsALotThread::deopt_objs_alot_thread_entry(JavaThread* thread, TRAPS) {
 793     DeoptimizeObjectsALotThread* dt = ((DeoptimizeObjectsALotThread*) thread);
 794     bool enter_single_loop;

 846   if (java_lang_Thread::thread(thread_oop()) != nullptr) {
 847     assert(type == compiler_t, "should only happen with reused compiler threads");
 848     // The compiler thread hasn't actually exited yet so don't try to reuse it
 849     return nullptr;
 850   }
 851 
 852   JavaThread* new_thread = nullptr;
 853   switch (type) {
 854     case compiler_t:
 855       assert(comp != nullptr, "Compiler instance missing.");
 856       if (!InjectCompilerCreationFailure || comp->num_compiler_threads() == 0) {
 857         CompilerCounters* counters = new CompilerCounters();
 858         new_thread = new CompilerThread(queue, counters);
 859       }
 860       break;
 861 #if defined(ASSERT) && COMPILER2_OR_JVMCI
 862     case deoptimizer_t:
 863       new_thread = new DeoptimizeObjectsALotThread();
 864       break;
 865 #endif // ASSERT



 866     default:
 867       ShouldNotReachHere();
 868   }
 869 
 870   // At this point the new CompilerThread data-races with this startup
 871   // thread (which is the main thread and NOT the VM thread).
 872   // This means Java bytecodes being executed at startup can
 873   // queue compile jobs which will run at whatever default priority the
 874   // newly created CompilerThread runs at.
 875 
 876 
 877   // At this point it may be possible that no osthread was created for the
 878   // JavaThread due to lack of resources. We will handle that failure below.
 879   // Also check new_thread so that static analysis is happy.
 880   if (new_thread != nullptr && new_thread->osthread() != nullptr) {
 881 
 882     if (type == compiler_t) {
 883       CompilerThread::cast(new_thread)->set_compiler(comp);
 884     }
 885 

 925 }
 926 
 927 static jobject create_compiler_thread(AbstractCompiler* compiler, int i, TRAPS) {
 928   char name_buffer[256];
 929   os::snprintf_checked(name_buffer, sizeof(name_buffer), "%s CompilerThread%d", compiler->name(), i);
 930   Handle thread_oop = JavaThread::create_system_thread_object(name_buffer, CHECK_NULL);
 931   return JNIHandles::make_global(thread_oop);
 932 }
 933 
 934 static void print_compiler_threads(stringStream& msg) {
 935   if (TraceCompilerThreads) {
 936     tty->print_cr("%7d %s", (int)tty->time_stamp().milliseconds(), msg.as_string());
 937   }
 938   LogTarget(Debug, jit, thread) lt;
 939   if (lt.is_enabled()) {
 940     LogStream ls(lt);
 941     ls.print_cr("%s", msg.as_string());
 942   }
 943 }
 944 











 945 void CompileBroker::init_compiler_threads() {
 946   // Ensure any exceptions lead to vm_exit_during_initialization.
 947   EXCEPTION_MARK;
 948 #if !defined(ZERO)
 949   assert(_c2_count > 0 || _c1_count > 0, "No compilers?");
 950 #endif // !ZERO
 951   // Initialize the compilation queue
 952   if (_c2_count > 0) {
 953     const char* name = JVMCI_ONLY(UseJVMCICompiler ? "JVMCI compile queue" :) "C2 compile queue";
 954     _c2_compile_queue  = new CompileQueue(name);
 955     _compiler2_objects = NEW_C_HEAP_ARRAY(jobject, _c2_count, mtCompiler);
 956     _compiler2_logs = NEW_C_HEAP_ARRAY(CompileLog*, _c2_count, mtCompiler);
 957   }
 958   if (_c1_count > 0) {
 959     _c1_compile_queue  = new CompileQueue("C1 compile queue");
 960     _compiler1_objects = NEW_C_HEAP_ARRAY(jobject, _c1_count, mtCompiler);
 961     _compiler1_logs = NEW_C_HEAP_ARRAY(CompileLog*, _c1_count, mtCompiler);
 962   }
 963 


















 964   for (int i = 0; i < _c2_count; i++) {
 965     // Create a name for our thread.
 966     jobject thread_handle = create_compiler_thread(_compilers[1], i, CHECK);
 967     _compiler2_objects[i] = thread_handle;
 968     _compiler2_logs[i] = nullptr;
 969 
 970     if (!UseDynamicNumberOfCompilerThreads || i == 0) {
 971       JavaThread *ct = make_thread(compiler_t, thread_handle, _c2_compile_queue, _compilers[1], THREAD);
 972       assert(ct != nullptr, "should have been handled for initial thread");
 973       _compilers[1]->set_num_compiler_threads(i + 1);
 974       if (trace_compiler_threads()) {
 975         ResourceMark rm;
 976         ThreadsListHandle tlh;  // name() depends on the TLH.
 977         assert(tlh.includes(ct), "ct=" INTPTR_FORMAT " exited unexpectedly.", p2i(ct));
 978         stringStream msg;
 979         msg.print("Added initial compiler thread %s", ct->name());
 980         print_compiler_threads(msg);
 981       }
 982     }
 983   }
 984 
 985   for (int i = 0; i < _c1_count; i++) {
 986     // Create a name for our thread.
 987     jobject thread_handle = create_compiler_thread(_compilers[0], i, CHECK);
 988     _compiler1_objects[i] = thread_handle;
 989     _compiler1_logs[i] = nullptr;
 990 
 991     if (!UseDynamicNumberOfCompilerThreads || i == 0) {
 992       JavaThread *ct = make_thread(compiler_t, thread_handle, _c1_compile_queue, _compilers[0], THREAD);
 993       assert(ct != nullptr, "should have been handled for initial thread");
 994       _compilers[0]->set_num_compiler_threads(i + 1);
 995       if (trace_compiler_threads()) {
 996         ResourceMark rm;
 997         ThreadsListHandle tlh;  // name() depends on the TLH.
 998         assert(tlh.includes(ct), "ct=" INTPTR_FORMAT " exited unexpectedly.", p2i(ct));
 999         stringStream msg;
1000         msg.print("Added initial compiler thread %s", ct->name());
1001         print_compiler_threads(msg);
1002       }


































1003     }
1004   }
1005 
1006   if (UsePerfData) {
1007     PerfDataManager::create_constant(SUN_CI, "threads", PerfData::U_Bytes, _c1_count + _c2_count, CHECK);
1008   }
1009 
1010 #if defined(ASSERT) && COMPILER2_OR_JVMCI
1011   if (DeoptimizeObjectsALot) {
1012     // Initialize and start the object deoptimizer threads
1013     const int total_count = DeoptimizeObjectsALotThreadCountSingle + DeoptimizeObjectsALotThreadCountAll;
1014     for (int count = 0; count < total_count; count++) {
1015       Handle thread_oop = JavaThread::create_system_thread_object("Deoptimize objects a lot single mode", CHECK);
1016       jobject thread_handle = JNIHandles::make_local(THREAD, thread_oop());
1017       make_thread(deoptimizer_t, thread_handle, nullptr, nullptr, THREAD);
1018     }
1019   }
1020 #endif // defined(ASSERT) && COMPILER2_OR_JVMCI





1021 }
1022 
1023 void CompileBroker::possibly_add_compiler_threads(JavaThread* THREAD) {
1024 
1025   julong free_memory = os::free_memory();
1026   // If SegmentedCodeCache is off, both values refer to the single heap (with type CodeBlobType::All).
1027   size_t available_cc_np  = CodeCache::unallocated_capacity(CodeBlobType::MethodNonProfiled),
1028          available_cc_p   = CodeCache::unallocated_capacity(CodeBlobType::MethodProfiled);
1029 
1030   // Only do attempt to start additional threads if the lock is free.
1031   if (!CompileThread_lock->try_lock()) return;
1032 
1033   if (_c2_compile_queue != nullptr) {
1034     int old_c2_count = _compilers[1]->num_compiler_threads();
1035     int new_c2_count = MIN4(_c2_count,
1036         _c2_compile_queue->size() / 2,
1037         (int)(free_memory / (200*M)),
1038         (int)(available_cc_np / (128*K)));
1039 
1040     for (int i = old_c2_count; i < new_c2_count; i++) {

1109         stringStream msg;
1110         msg.print("Added compiler thread %s (free memory: %dMB, available profiled code cache: %dMB)",
1111                   ct->name(), (int)(free_memory/M), (int)(available_cc_p/M));
1112         print_compiler_threads(msg);
1113       }
1114     }
1115   }
1116 
1117   CompileThread_lock->unlock();
1118 }
1119 
1120 
1121 /**
1122  * Set the methods on the stack as on_stack so that redefine classes doesn't
1123  * reclaim them. This method is executed at a safepoint.
1124  */
1125 void CompileBroker::mark_on_stack() {
1126   assert(SafepointSynchronize::is_at_safepoint(), "sanity check");
1127   // Since we are at a safepoint, we do not need a lock to access
1128   // the compile queues.



1129   if (_c2_compile_queue != nullptr) {
1130     _c2_compile_queue->mark_on_stack();
1131   }
1132   if (_c1_compile_queue != nullptr) {
1133     _c1_compile_queue->mark_on_stack();
1134   }






1135 }
1136 
1137 // ------------------------------------------------------------------
1138 // CompileBroker::compile_method
1139 //
1140 // Request compilation of a method.
1141 void CompileBroker::compile_method_base(const methodHandle& method,
1142                                         int osr_bci,
1143                                         int comp_level,
1144                                         const methodHandle& hot_method,
1145                                         int hot_count,
1146                                         CompileTask::CompileReason compile_reason,

1147                                         bool blocking,
1148                                         Thread* thread) {
1149   guarantee(!method->is_abstract(), "cannot compile abstract methods");
1150   assert(method->method_holder()->is_instance_klass(),
1151          "sanity check");
1152   assert(!method->method_holder()->is_not_initialized(),
1153          "method holder must be initialized");


1154   assert(!method->is_method_handle_intrinsic(), "do not enqueue these guys");
1155 
1156   if (CIPrintRequests) {
1157     tty->print("request: ");
1158     method->print_short_name(tty);
1159     if (osr_bci != InvocationEntryBci) {
1160       tty->print(" osr_bci: %d", osr_bci);
1161     }
1162     tty->print(" level: %d comment: %s count: %d", comp_level, CompileTask::reason_name(compile_reason), hot_count);
1163     if (!hot_method.is_null()) {
1164       tty->print(" hot: ");
1165       if (hot_method() != method()) {
1166           hot_method->print_short_name(tty);
1167       } else {
1168         tty->print("yes");
1169       }
1170     }
1171     tty->cr();
1172   }
1173 
1174   // A request has been made for compilation.  Before we do any
1175   // real work, check to see if the method has been compiled
1176   // in the meantime with a definitive result.
1177   if (compilation_is_complete(method, osr_bci, comp_level)) {
1178     return;
1179   }
1180 
1181 #ifndef PRODUCT
1182   if (osr_bci != -1 && !FLAG_IS_DEFAULT(OSROnlyBCI)) {
1183     if ((OSROnlyBCI > 0) ? (OSROnlyBCI != osr_bci) : (-OSROnlyBCI == osr_bci)) {
1184       // Positive OSROnlyBCI means only compile that bci.  Negative means don't compile that BCI.
1185       return;
1186     }
1187   }
1188 #endif
1189 
1190   // If this method is already in the compile queue, then
1191   // we do not block the current thread.
1192   if (compilation_is_in_queue(method)) {
1193     // We may want to decay our counter a bit here to prevent
1194     // multiple denied requests for compilation.  This is an
1195     // open compilation policy issue. Note: The other possibility,
1196     // in the case that this is a blocking compile request, is to have
1197     // all subsequent blocking requesters wait for completion of
1198     // ongoing compiles. Note that in this case we'll need a protocol
1199     // for freeing the associated compile tasks. [Or we could have
1200     // a single static monitor on which all these waiters sleep.]
1201     return;
1202   }
1203 
1204   // Tiered policy requires MethodCounters to exist before adding a method to
1205   // the queue. Create if we don't have them yet.
1206   method->get_method_counters(thread);





1207 
1208   // Outputs from the following MutexLocker block:
1209   CompileTask* task     = nullptr;
1210   CompileQueue* queue  = compile_queue(comp_level);








1211 
1212   // Acquire our lock.
1213   {
1214     MutexLocker locker(thread, MethodCompileQueue_lock);
1215 
1216     // Make sure the method has not slipped into the queues since
1217     // last we checked; note that those checks were "fast bail-outs".
1218     // Here we need to be more careful, see 14012000 below.
1219     if (compilation_is_in_queue(method)) {
1220       return;
1221     }
1222 
1223     // We need to check again to see if the compilation has
1224     // completed.  A previous compilation may have registered
1225     // some result.
1226     if (compilation_is_complete(method, osr_bci, comp_level)) {
1227       return;
1228     }
1229 
1230     // We now know that this compilation is not pending, complete,
1231     // or prohibited.  Assign a compile_id to this compilation
1232     // and check to see if it is in our [Start..Stop) range.
1233     int compile_id = assign_compile_id(method, osr_bci);
1234     if (compile_id == 0) {
1235       // The compilation falls outside the allowed range.
1236       return;
1237     }
1238 
1239 #if INCLUDE_JVMCI
1240     if (UseJVMCICompiler && blocking) {
1241       // Don't allow blocking compiles for requests triggered by JVMCI.
1242       if (thread->is_Compiler_thread()) {
1243         blocking = false;
1244       }
1245 
1246       // In libjvmci, JVMCI initialization should not deadlock with other threads

1296     // <RESULT, QUEUE> :
1297     //     <0, 1> : in compile queue, but not yet compiled
1298     //     <1, 1> : compiled but queue bit not cleared
1299     //     <1, 0> : compiled and queue bit cleared
1300     // Because we first check the queue bits then check the result bits,
1301     // we are assured that we cannot introduce a duplicate task.
1302     // Note that if we did the tests in the reverse order (i.e. check
1303     // result then check queued bit), we could get the result bit before
1304     // the compilation completed, and the queue bit after the compilation
1305     // completed, and end up introducing a "duplicate" (redundant) task.
1306     // In that case, the compiler thread should first check if a method
1307     // has already been compiled before trying to compile it.
1308     // NOTE: in the event that there are multiple compiler threads and
1309     // there is de-optimization/recompilation, things will get hairy,
1310     // and in that case it's best to protect both the testing (here) of
1311     // these bits, and their updating (here and elsewhere) under a
1312     // common lock.
1313     task = create_compile_task(queue,
1314                                compile_id, method,
1315                                osr_bci, comp_level,
1316                                hot_method, hot_count, compile_reason,
1317                                blocking);












1318   }
1319 
1320   if (blocking) {
1321     wait_for_completion(task);
1322   }
1323 }
1324 
















1325 nmethod* CompileBroker::compile_method(const methodHandle& method, int osr_bci,
1326                                        int comp_level,
1327                                        const methodHandle& hot_method, int hot_count,

1328                                        CompileTask::CompileReason compile_reason,
1329                                        TRAPS) {
1330   // Do nothing if compilebroker is not initialized or compiles are submitted on level none
1331   if (!_initialized || comp_level == CompLevel_none) {
1332     return nullptr;
1333   }
1334 







1335   AbstractCompiler *comp = CompileBroker::compiler(comp_level);
1336   assert(comp != nullptr, "Ensure we have a compiler");
1337 
1338 #if INCLUDE_JVMCI
1339   if (comp->is_jvmci() && !JVMCI::can_initialize_JVMCI()) {
1340     // JVMCI compilation is not yet initializable.
1341     return nullptr;
1342   }
1343 #endif
1344 
1345   DirectiveSet* directive = DirectivesStack::getMatchingDirective(method, comp);
1346   // CompileBroker::compile_method can trap and can have pending async exception.
1347   nmethod* nm = CompileBroker::compile_method(method, osr_bci, comp_level, hot_method, hot_count, compile_reason, directive, THREAD);
1348   DirectivesStack::release(directive);
1349   return nm;
1350 }
1351 
1352 nmethod* CompileBroker::compile_method(const methodHandle& method, int osr_bci,
1353                                          int comp_level,
1354                                          const methodHandle& hot_method, int hot_count,

1355                                          CompileTask::CompileReason compile_reason,
1356                                          DirectiveSet* directive,
1357                                          TRAPS) {
1358 
1359   // make sure arguments make sense
1360   assert(method->method_holder()->is_instance_klass(), "not an instance method");
1361   assert(osr_bci == InvocationEntryBci || (0 <= osr_bci && osr_bci < method->code_size()), "bci out of range");
1362   assert(!method->is_abstract() && (osr_bci == InvocationEntryBci || !method->is_native()), "cannot compile abstract/native methods");
1363   assert(!method->method_holder()->is_not_initialized(), "method holder must be initialized");



1364   // return quickly if possible
1365 
1366   // lock, make sure that the compilation
1367   // isn't prohibited in a straightforward way.
1368   AbstractCompiler* comp = CompileBroker::compiler(comp_level);
1369   if (comp == nullptr || compilation_is_prohibited(method, osr_bci, comp_level, directive->ExcludeOption)) {
1370     return nullptr;
1371   }
1372 
1373   if (osr_bci == InvocationEntryBci) {
1374     // standard compilation
1375     CompiledMethod* method_code = method->code();
1376     if (method_code != nullptr && method_code->is_nmethod()) {
1377       if (compilation_is_complete(method, osr_bci, comp_level)) {
1378         return (nmethod*) method_code;
1379       }
1380     }
1381     if (method->is_not_compilable(comp_level)) {
1382       return nullptr;
1383     }
1384   } else {
1385     // osr compilation
1386     // We accept a higher level osr method
1387     nmethod* nm = method->lookup_osr_nmethod_for(osr_bci, comp_level, false);
1388     if (nm != nullptr) return nm;
1389     if (method->is_not_osr_compilable(comp_level)) return nullptr;
1390   }
1391 
1392   assert(!HAS_PENDING_EXCEPTION, "No exception should be present");
1393   // some prerequisites that are compiler specific
1394   if (comp->is_c2() || comp->is_jvmci()) {
1395     method->constants()->resolve_string_constants(CHECK_AND_CLEAR_NONASYNC_NULL);
1396     // Resolve all classes seen in the signature of the method
1397     // we are compiling.
1398     Method::load_signature_classes(method, CHECK_AND_CLEAR_NONASYNC_NULL);
1399   }
1400 
1401   // If the method is native, do the lookup in the thread requesting
1402   // the compilation. Native lookups can load code, which is not
1403   // permitted during compilation.
1404   //
1405   // Note: A native method implies non-osr compilation which is
1406   //       checked with an assertion at the entry of this method.
1407   if (method->is_native() && !method->is_method_handle_intrinsic()) {
1408     address adr = NativeLookup::lookup(method, THREAD);
1409     if (HAS_PENDING_EXCEPTION) {
1410       // In case of an exception looking up the method, we just forget
1411       // about it. The interpreter will kick-in and throw the exception.
1412       method->set_not_compilable("NativeLookup::lookup failed"); // implies is_not_osr_compilable()
1413       CLEAR_PENDING_EXCEPTION;
1414       return nullptr;

1452             method->intrinsic_id() == vmIntrinsics::_doubleToRawLongBits))) {
1453         return nullptr;
1454       }
1455 #endif // X86 && !ZERO
1456 
1457       // To properly handle the appendix argument for out-of-line calls we are using a small trampoline that
1458       // pops off the appendix argument and jumps to the target (see gen_special_dispatch in SharedRuntime).
1459       //
1460       // Since normal compiled-to-compiled calls are not able to handle such a thing we MUST generate an adapter
1461       // in this case.  If we can't generate one and use it we can not execute the out-of-line method handle calls.
1462       AdapterHandlerLibrary::create_native_wrapper(method);
1463     } else {
1464       return nullptr;
1465     }
1466   } else {
1467     // If the compiler is shut off due to code cache getting full
1468     // fail out now so blocking compiles dont hang the java thread
1469     if (!should_compile_new_jobs()) {
1470       return nullptr;
1471     }
1472     bool is_blocking = !directive->BackgroundCompilationOption || ReplayCompiles;
1473     compile_method_base(method, osr_bci, comp_level, hot_method, hot_count, compile_reason, is_blocking, THREAD);



1474   }
1475 
1476   // return requested nmethod
1477   // We accept a higher level osr method
1478   if (osr_bci == InvocationEntryBci) {
1479     CompiledMethod* code = method->code();
1480     if (code == nullptr) {
1481       return (nmethod*) code;
1482     } else {
1483       return code->as_nmethod_or_null();
1484     }
1485   }
1486   return method->lookup_osr_nmethod_for(osr_bci, comp_level, false);
1487 }
1488 
1489 
1490 // ------------------------------------------------------------------
1491 // CompileBroker::compilation_is_complete
1492 //
1493 // See if compilation of this method is already complete.
1494 bool CompileBroker::compilation_is_complete(const methodHandle& method,
1495                                             int                 osr_bci,
1496                                             int                 comp_level) {






1497   bool is_osr = (osr_bci != standard_entry_bci);
1498   if (is_osr) {
1499     if (method->is_not_osr_compilable(comp_level)) {
1500       return true;
1501     } else {
1502       nmethod* result = method->lookup_osr_nmethod_for(osr_bci, comp_level, true);
1503       return (result != nullptr);
1504     }
1505   } else {
1506     if (method->is_not_compilable(comp_level)) {
1507       return true;
1508     } else {
1509       CompiledMethod* result = method->code();
1510       if (result == nullptr) return false;
1511       return comp_level == result->comp_level();









1512     }
1513   }
1514 }
1515 
1516 
1517 /**
1518  * See if this compilation is already requested.
1519  *
1520  * Implementation note: there is only a single "is in queue" bit
1521  * for each method.  This means that the check below is overly
1522  * conservative in the sense that an osr compilation in the queue
1523  * will block a normal compilation from entering the queue (and vice
1524  * versa).  This can be remedied by a full queue search to disambiguate
1525  * cases.  If it is deemed profitable, this may be done.
1526  */
1527 bool CompileBroker::compilation_is_in_queue(const methodHandle& method) {
1528   return method->queued_for_compilation();
1529 }
1530 
1531 // ------------------------------------------------------------------

1591     if (CIStart <= id && id < CIStop) {
1592       return id;
1593     }
1594   }
1595 
1596   // Method was not in the appropriate compilation range.
1597   method->set_not_compilable_quietly("Not in requested compile id range");
1598   return 0;
1599 #else
1600   // CICountOSR is a develop flag and set to 'false' by default. In a product built,
1601   // only _compilation_id is incremented.
1602   return Atomic::add(&_compilation_id, 1);
1603 #endif
1604 }
1605 
1606 // ------------------------------------------------------------------
1607 // CompileBroker::assign_compile_id_unlocked
1608 //
1609 // Public wrapper for assign_compile_id that acquires the needed locks
1610 int CompileBroker::assign_compile_id_unlocked(Thread* thread, const methodHandle& method, int osr_bci) {
1611   MutexLocker locker(thread, MethodCompileQueue_lock);
1612   return assign_compile_id(method, osr_bci);
1613 }
1614 
1615 // ------------------------------------------------------------------
1616 // CompileBroker::create_compile_task
1617 //
1618 // Create a CompileTask object representing the current request for
1619 // compilation.  Add this task to the queue.
1620 CompileTask* CompileBroker::create_compile_task(CompileQueue*       queue,
1621                                                 int                 compile_id,
1622                                                 const methodHandle& method,
1623                                                 int                 osr_bci,
1624                                                 int                 comp_level,
1625                                                 const methodHandle& hot_method,
1626                                                 int                 hot_count,

1627                                                 CompileTask::CompileReason compile_reason,

1628                                                 bool                blocking) {
1629   CompileTask* new_task = CompileTask::allocate();
1630   new_task->initialize(compile_id, method, osr_bci, comp_level,
1631                        hot_method, hot_count, compile_reason,
1632                        blocking);
1633   queue->add(new_task);
1634   return new_task;
1635 }
1636 
1637 #if INCLUDE_JVMCI
1638 // The number of milliseconds to wait before checking if
1639 // JVMCI compilation has made progress.
1640 static const long JVMCI_COMPILATION_PROGRESS_WAIT_TIMESLICE = 1000;
1641 
1642 // The number of JVMCI compilation progress checks that must fail
1643 // before unblocking a thread waiting for a blocking compilation.
1644 static const int JVMCI_COMPILATION_PROGRESS_WAIT_ATTEMPTS = 10;
1645 
1646 /**
1647  * Waits for a JVMCI compiler to complete a given task. This thread
1648  * waits until either the task completes or it sees no JVMCI compilation
1649  * progress for N consecutive milliseconds where N is
1650  * JVMCI_COMPILATION_PROGRESS_WAIT_TIMESLICE *
1651  * JVMCI_COMPILATION_PROGRESS_WAIT_ATTEMPTS.
1652  *
1653  * @return true if this thread needs to free/recycle the task

1754  */
1755 bool CompileBroker::init_compiler_runtime() {
1756   CompilerThread* thread = CompilerThread::current();
1757   AbstractCompiler* comp = thread->compiler();
1758   // Final sanity check - the compiler object must exist
1759   guarantee(comp != nullptr, "Compiler object must exist");
1760 
1761   {
1762     // Must switch to native to allocate ci_env
1763     ThreadToNativeFromVM ttn(thread);
1764     ciEnv ci_env((CompileTask*)nullptr);
1765     // Cache Jvmti state
1766     ci_env.cache_jvmti_state();
1767     // Cache DTrace flags
1768     ci_env.cache_dtrace_flags();
1769 
1770     // Switch back to VM state to do compiler initialization
1771     ThreadInVMfromNative tv(thread);
1772 
1773     // Perform per-thread and global initializations




1774     comp->initialize();
1775   }
1776 
1777   if (comp->is_failed()) {
1778     disable_compilation_forever();
1779     // If compiler initialization failed, no compiler thread that is specific to a
1780     // particular compiler runtime will ever start to compile methods.
1781     shutdown_compiler_runtime(comp, thread);
1782     return false;
1783   }
1784 
1785   // C1 specific check
1786   if (comp->is_c1() && (thread->get_buffer_blob() == nullptr)) {
1787     warning("Initialization of %s thread failed (no space to run compilers)", thread->name());
1788     return false;
1789   }
1790 
1791   return true;
1792 }
1793 
1794 void CompileBroker::free_buffer_blob_if_allocated(CompilerThread* thread) {
1795   BufferBlob* blob = thread->get_buffer_blob();
1796   if (blob != nullptr) {
1797     blob->purge(true /* free_code_cache_data */, true /* unregister_nmethod */);
1798     MutexLocker mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
1799     CodeCache::free(blob);
1800   }
1801 }
1802 
1803 /**
1804  * If C1 and/or C2 initialization failed, we shut down all compilation.
1805  * We do this to keep things simple. This can be changed if it ever turns
1806  * out to be a problem.
1807  */
1808 void CompileBroker::shutdown_compiler_runtime(AbstractCompiler* comp, CompilerThread* thread) {
1809   free_buffer_blob_if_allocated(thread);
1810 


1811   if (comp->should_perform_shutdown()) {
1812     // There are two reasons for shutting down the compiler
1813     // 1) compiler runtime initialization failed
1814     // 2) The code cache is full and the following flag is set: -XX:-UseCodeCacheFlushing
1815     warning("%s initialization failed. Shutting down all compilers", comp->name());
1816 
1817     // Only one thread per compiler runtime object enters here
1818     // Set state to shut down
1819     comp->set_shut_down();
1820 
1821     // Delete all queued compilation tasks to make compiler threads exit faster.
1822     if (_c1_compile_queue != nullptr) {
1823       _c1_compile_queue->free_all();
1824     }
1825 
1826     if (_c2_compile_queue != nullptr) {
1827       _c2_compile_queue->free_all();
1828     }
1829 




1830     // Set flags so that we continue execution with using interpreter only.
1831     UseCompiler    = false;
1832     UseInterpreter = true;
1833 
1834     // We could delete compiler runtimes also. However, there are references to
1835     // the compiler runtime(s) (e.g.,  nmethod::is_compiled_by_c1()) which then
1836     // fail. This can be done later if necessary.
1837   }
1838 }
1839 
1840 /**
1841  * Helper function to create new or reuse old CompileLog.
1842  */
1843 CompileLog* CompileBroker::get_log(CompilerThread* ct) {
1844   if (!LogCompilation) return nullptr;
1845 
1846   AbstractCompiler *compiler = ct->compiler();

1847   bool c1 = compiler->is_c1();
1848   jobject* compiler_objects = c1 ? _compiler1_objects : _compiler2_objects;
1849   assert(compiler_objects != nullptr, "must be initialized at this point");
1850   CompileLog** logs = c1 ? _compiler1_logs : _compiler2_logs;
1851   assert(logs != nullptr, "must be initialized at this point");
1852   int count = c1 ? _c1_count : _c2_count;
1853 





1854   // Find Compiler number by its threadObj.
1855   oop compiler_obj = ct->threadObj();
1856   int compiler_number = 0;
1857   bool found = false;
1858   for (; compiler_number < count; compiler_number++) {
1859     if (JNIHandles::resolve_non_null(compiler_objects[compiler_number]) == compiler_obj) {
1860       found = true;
1861       break;
1862     }
1863   }
1864   assert(found, "Compiler must exist at this point");
1865 
1866   // Determine pointer for this thread's log.
1867   CompileLog** log_ptr = &logs[compiler_number];
1868 
1869   // Return old one if it exists.
1870   CompileLog* log = *log_ptr;
1871   if (log != nullptr) {
1872     ct->init_log(log);
1873     return log;

1911     log->stamp();
1912     log->end_elem();
1913   }
1914 
1915   // If compiler thread/runtime initialization fails, exit the compiler thread
1916   if (!init_compiler_runtime()) {
1917     return;
1918   }
1919 
1920   thread->start_idle_timer();
1921 
1922   // Poll for new compilation tasks as long as the JVM runs. Compilation
1923   // should only be disabled if something went wrong while initializing the
1924   // compiler runtimes. This, in turn, should not happen. The only known case
1925   // when compiler runtime initialization fails is if there is not enough free
1926   // space in the code cache to generate the necessary stubs, etc.
1927   while (!is_compilation_disabled_forever()) {
1928     // We need this HandleMark to avoid leaking VM handles.
1929     HandleMark hm(thread);
1930 


1931     CompileTask* task = queue->get(thread);

1932     if (task == nullptr) {
1933       if (UseDynamicNumberOfCompilerThreads) {
1934         // Access compiler_count under lock to enforce consistency.
1935         MutexLocker only_one(CompileThread_lock);
1936         if (can_remove(thread, true)) {
1937           if (trace_compiler_threads()) {
1938             ResourceMark rm;
1939             stringStream msg;
1940             msg.print("Removing compiler thread %s after " JLONG_FORMAT " ms idle time",
1941                       thread->name(), thread->idle_time_millis());
1942             print_compiler_threads(msg);
1943           }
1944 
1945           // Notify compiler that the compiler thread is about to stop
1946           thread->compiler()->stopping_compiler_thread(thread);
1947 
1948           free_buffer_blob_if_allocated(thread);
1949           return; // Stop this thread.
1950         }
1951       }
1952     } else {
1953       // Assign the task to the current thread.  Mark this compilation
1954       // thread as active for the profiler.
1955       // CompileTaskWrapper also keeps the Method* from being deallocated if redefinition
1956       // occurs after fetching the compile task off the queue.
1957       CompileTaskWrapper ctw(task);
1958       methodHandle method(thread, task->method());
1959 
1960       // Never compile a method if breakpoints are present in it
1961       if (method()->number_of_breakpoints() == 0) {
1962         // Compile the method.
1963         if ((UseCompiler || AlwaysCompileLoopMethods) && CompileBroker::should_compile_new_jobs()) {
1964           invoke_compiler_on_method(task);
1965           thread->start_idle_timer();
1966         } else {
1967           // After compilation is disabled, remove remaining methods from queue
1968           method->clear_queued_for_compilation();

1969           task->set_failure_reason("compilation is disabled");
1970         }
1971       } else {
1972         task->set_failure_reason("breakpoints are present");
1973       }
1974 
1975       if (UseDynamicNumberOfCompilerThreads) {
1976         possibly_add_compiler_threads(thread);
1977         assert(!thread->has_pending_exception(), "should have been handled");
1978       }
1979     }
1980   }
1981 
1982   // Shut down compiler runtime
1983   shutdown_compiler_runtime(thread->compiler(), thread);
1984 }
1985 
1986 // ------------------------------------------------------------------
1987 // CompileBroker::init_compiler_thread_log
1988 //

2136 
2137 // Acquires Compilation_lock and waits for it to be notified
2138 // as long as WhiteBox::compilation_locked is true.
2139 static void whitebox_lock_compilation() {
2140   MonitorLocker locker(Compilation_lock, Mutex::_no_safepoint_check_flag);
2141   while (WhiteBox::compilation_locked) {
2142     locker.wait();
2143   }
2144 }
2145 
2146 // ------------------------------------------------------------------
2147 // CompileBroker::invoke_compiler_on_method
2148 //
2149 // Compile a method.
2150 //
2151 void CompileBroker::invoke_compiler_on_method(CompileTask* task) {
2152   task->print_ul();
2153   elapsedTimer time;
2154 
2155   DirectiveSet* directive = task->directive();
2156   if (directive->PrintCompilationOption) {
2157     ResourceMark rm;
2158     task->print_tty();
2159   }
2160 
2161   CompilerThread* thread = CompilerThread::current();
2162   ResourceMark rm(thread);
2163 
2164   if (CompilationLog::log() != nullptr) {
2165     CompilationLog::log()->log_compile(thread, task);
2166   }
2167 
2168   // Common flags.
2169   int compile_id = task->compile_id();
2170   int osr_bci = task->osr_bci();
2171   bool is_osr = (osr_bci != standard_entry_bci);
2172   bool should_log = (thread->log() != nullptr);
2173   bool should_break = false;
2174   const int task_level = task->comp_level();
2175   AbstractCompiler* comp = task->compiler();


2176   {
2177     // create the handle inside it's own block so it can't
2178     // accidentally be referenced once the thread transitions to
2179     // native.  The NoHandleMark before the transition should catch
2180     // any cases where this occurs in the future.
2181     methodHandle method(thread, task->method());
2182 
2183     assert(!method->is_native(), "no longer compile natives");
2184 
2185     // Update compile information when using perfdata.
2186     if (UsePerfData) {
2187       update_compile_perf_data(thread, method, is_osr);
2188     }
2189 
2190     DTRACE_METHOD_COMPILE_BEGIN_PROBE(method, compiler_name(task_level));
2191   }
2192 




2193   should_break = directive->BreakAtCompileOption || task->check_break_at_flags();
2194   if (should_log && !directive->LogOption) {
2195     should_log = false;
2196   }
2197 
2198   // Allocate a new set of JNI handles.
2199   JNIHandleMark jhm(thread);
2200   Method* target_handle = task->method();
2201   int compilable = ciEnv::MethodCompilable;
2202   const char* failure_reason = nullptr;
2203   bool failure_reason_on_C_heap = false;
2204   const char* retry_message = nullptr;
2205 
2206 #if INCLUDE_JVMCI
2207   if (UseJVMCICompiler && comp != nullptr && comp->is_jvmci()) {
2208     JVMCICompiler* jvmci = (JVMCICompiler*) comp;
2209 
2210     TraceTime t1("compilation", &time);
2211     EventCompilation event;
2212     JVMCICompileState compile_state(task, jvmci);

2279     }
2280     assert(thread->env() == &ci_env, "set by ci_env");
2281     // The thread-env() field is cleared in ~CompileTaskWrapper.
2282 
2283     // Cache Jvmti state
2284     bool method_is_old = ci_env.cache_jvmti_state();
2285 
2286     // Skip redefined methods
2287     if (method_is_old) {
2288       ci_env.record_method_not_compilable("redefined method", true);
2289     }
2290 
2291     // Cache DTrace flags
2292     ci_env.cache_dtrace_flags();
2293 
2294     ciMethod* target = ci_env.get_method_from_handle(target_handle);
2295 
2296     TraceTime t1("compilation", &time);
2297     EventCompilation event;
2298 

2299     if (comp == nullptr) {
2300       ci_env.record_method_not_compilable("no compiler");
2301     } else if (!ci_env.failing()) {
2302       if (WhiteBoxAPI && WhiteBox::compilation_locked) {
2303         whitebox_lock_compilation();
2304       }
2305       comp->compile_method(&ci_env, target, osr_bci, true, directive);



2306 
2307       /* Repeat compilation without installing code for profiling purposes */
2308       int repeat_compilation_count = directive->RepeatCompilationOption;
2309       while (repeat_compilation_count > 0) {
2310         ResourceMark rm(thread);
2311         task->print_ul("NO CODE INSTALLED");
2312         comp->compile_method(&ci_env, target, osr_bci, false, directive);
2313         repeat_compilation_count--;
2314       }
2315     }
2316 
2317     DirectivesStack::release(directive);
2318 
2319     if (!ci_env.failing() && !task->is_success()) {
2320       assert(ci_env.failure_reason() != nullptr, "expect failure reason");
2321       assert(false, "compiler should always document failure: %s", ci_env.failure_reason());
2322       // The compiler elected, without comment, not to register a result.
2323       // Do not attempt further compilations of this method.
2324       ci_env.record_method_not_compilable("compile failed");
2325     }
2326 
2327     // Copy this bit to the enclosing block:
2328     compilable = ci_env.compilable();
2329 
2330     if (ci_env.failing()) {
2331       failure_reason = ci_env.failure_reason();
2332       retry_message = ci_env.retry_message();
2333       ci_env.report_failure(failure_reason);
2334     }
2335 
2336     if (ci_env.failing()) {
2337       handle_compile_error(thread, task, &ci_env, compilable, failure_reason);
2338     }
2339     if (event.should_commit()) {
2340       post_compilation_event(event, task);
2341     }
2342   }
2343 
2344   if (failure_reason != nullptr) {
2345     task->set_failure_reason(failure_reason, failure_reason_on_C_heap);
2346     if (CompilationLog::log() != nullptr) {
2347       CompilationLog::log()->log_failure(thread, task, failure_reason, retry_message);
2348     }
2349     if (PrintCompilation) {
2350       FormatBufferResource msg = retry_message != nullptr ?
2351         FormatBufferResource("COMPILE SKIPPED: %s (%s)", failure_reason, retry_message) :
2352         FormatBufferResource("COMPILE SKIPPED: %s",      failure_reason);
2353       task->print(tty, msg);
2354     }
2355   }
2356 









2357   methodHandle method(thread, task->method());
2358 
2359   DTRACE_METHOD_COMPILE_END_PROBE(method, compiler_name(task_level), task->is_success());
2360 
2361   collect_statistics(thread, time, task);
2362 
2363   if (PrintCompilation && PrintCompilation2) {
2364     tty->print("%7d ", (int) tty->time_stamp().milliseconds());  // print timestamp
2365     tty->print("%4d ", compile_id);    // print compilation number
2366     tty->print("%s ", (is_osr ? "%" : " "));
2367     if (task->is_success()) {
2368       tty->print("size: %d(%d) ", task->nm_total_size(), task->nm_insts_size());
2369     }
2370     tty->print_cr("time: %d inlined: %d bytes", (int)time.milliseconds(), task->num_inlined_bytecodes());
2371   }
2372 
2373   Log(compilation, codecache) log;
2374   if (log.is_debug()) {
2375     LogStream ls(log.debug());
2376     codecache_print(&ls, /* detailed= */ false);
2377   }
2378   if (PrintCodeCacheOnCompilation) {
2379     codecache_print(/* detailed= */ false);
2380   }
2381   // Disable compilation, if required.
2382   switch (compilable) {
2383   case ciEnv::MethodCompilable_never:
2384     if (is_osr)
2385       method->set_not_osr_compilable_quietly("MethodCompilable_never");
2386     else
2387       method->set_not_compilable_quietly("MethodCompilable_never");
2388     break;
2389   case ciEnv::MethodCompilable_not_at_tier:
2390     if (is_osr)
2391       method->set_not_osr_compilable_quietly("MethodCompilable_not_at_tier", task_level);
2392     else
2393       method->set_not_compilable_quietly("MethodCompilable_not_at_tier", task_level);
2394     break;
2395   }
2396 
2397   // Note that the queued_for_compilation bits are cleared without
2398   // protection of a mutex. [They were set by the requester thread,
2399   // when adding the task to the compile queue -- at which time the
2400   // compile queue lock was held. Subsequently, we acquired the compile
2401   // queue lock to get this task off the compile queue; thus (to belabour
2402   // the point somewhat) our clearing of the bits must be occurring
2403   // only after the setting of the bits. See also 14012000 above.
2404   method->clear_queued_for_compilation();

2405 }
2406 
2407 /**
2408  * The CodeCache is full. Print warning and disable compilation.
2409  * Schedule code cache cleaning so compilation can continue later.
2410  * This function needs to be called only from CodeCache::allocate(),
2411  * since we currently handle a full code cache uniformly.
2412  */
2413 void CompileBroker::handle_full_code_cache(CodeBlobType code_blob_type) {
2414   UseInterpreter = true;
2415   if (UseCompiler || AlwaysCompileLoopMethods ) {
2416     if (xtty != nullptr) {
2417       stringStream s;
2418       // Dump code cache state into a buffer before locking the tty,
2419       // because log_state() will use locks causing lock conflicts.
2420       CodeCache::log_state(&s);
2421       // Lock to prevent tearing
2422       ttyLocker ttyl;
2423       xtty->begin_elem("code_cache_full");
2424       xtty->print("%s", s.freeze());

2497 // CompileBroker::collect_statistics
2498 //
2499 // Collect statistics about the compilation.
2500 
2501 void CompileBroker::collect_statistics(CompilerThread* thread, elapsedTimer time, CompileTask* task) {
2502   bool success = task->is_success();
2503   methodHandle method (thread, task->method());
2504   int compile_id = task->compile_id();
2505   bool is_osr = (task->osr_bci() != standard_entry_bci);
2506   const int comp_level = task->comp_level();
2507   CompilerCounters* counters = thread->counters();
2508 
2509   MutexLocker locker(CompileStatistics_lock);
2510 
2511   // _perf variables are production performance counters which are
2512   // updated regardless of the setting of the CITime and CITimeEach flags
2513   //
2514 
2515   // account all time, including bailouts and failures in this counter;
2516   // C1 and C2 counters are counting both successful and unsuccessful compiles
2517   _t_total_compilation.add(time);
2518 
2519   if (!success) {
2520     _total_bailout_count++;
2521     if (UsePerfData) {
2522       _perf_last_failed_method->set_value(counters->current_method());
2523       _perf_last_failed_type->set_value(counters->compile_type());
2524       _perf_total_bailout_count->inc();
2525     }
2526     _t_bailedout_compilation.add(time);











2527   } else if (!task->is_success()) {
2528     if (UsePerfData) {
2529       _perf_last_invalidated_method->set_value(counters->current_method());
2530       _perf_last_invalidated_type->set_value(counters->compile_type());
2531       _perf_total_invalidated_count->inc();
2532     }
2533     _total_invalidated_count++;
2534     _t_invalidated_compilation.add(time);











2535   } else {
2536     // Compilation succeeded
2537 
2538     // update compilation ticks - used by the implementation of
2539     // java.lang.management.CompilationMXBean
2540     _perf_total_compilation->inc(time.ticks());
2541     _peak_compilation_time = time.milliseconds() > _peak_compilation_time ? time.milliseconds() : _peak_compilation_time;
2542 
2543     if (CITime) {
2544       int bytes_compiled = method->code_size() + task->num_inlined_bytecodes();
2545       if (is_osr) {
2546         _t_osr_compilation.add(time);
2547         _sum_osr_bytes_compiled += bytes_compiled;
2548       } else {
2549         _t_standard_compilation.add(time);
2550         _sum_standard_bytes_compiled += method->code_size() + task->num_inlined_bytecodes();
2551       }
2552 
2553       // Collect statistic per compilation level
2554       if (comp_level > CompLevel_none && comp_level <= CompLevel_full_optimization) {









2555         CompilerStatistics* stats = &_stats_per_level[comp_level-1];
2556         if (is_osr) {
2557           stats->_osr.update(time, bytes_compiled);
2558         } else {
2559           stats->_standard.update(time, bytes_compiled);
2560         }
2561         stats->_nmethods_size += task->nm_total_size();
2562         stats->_nmethods_code_size += task->nm_insts_size();
2563       } else {
2564         assert(false, "CompilerStatistics object does not exist for compilation level %d", comp_level);
2565       }
2566 
2567       // Collect statistic per compiler
2568       AbstractCompiler* comp = compiler(comp_level);
2569       if (comp) {
2570         CompilerStatistics* stats = comp->stats();
2571         if (is_osr) {
2572           stats->_osr.update(time, bytes_compiled);
2573         } else {
2574           stats->_standard.update(time, bytes_compiled);
2575         }
2576         stats->_nmethods_size += task->nm_total_size();
2577         stats->_nmethods_code_size += task->nm_insts_size();
2578       } else { // if (!comp)
2579         assert(false, "Compiler object must exist");
2580       }
2581     }
2582 
2583     if (UsePerfData) {
2584       // save the name of the last method compiled
2585       _perf_last_method->set_value(counters->current_method());
2586       _perf_last_compile_type->set_value(counters->compile_type());
2587       _perf_last_compile_size->set_value(method->code_size() +
2588                                          task->num_inlined_bytecodes());
2589       if (is_osr) {
2590         _perf_osr_compilation->inc(time.ticks());
2591         _perf_sum_osr_bytes_compiled->inc(method->code_size() + task->num_inlined_bytecodes());
2592       } else {
2593         _perf_standard_compilation->inc(time.ticks());
2594         _perf_sum_standard_bytes_compiled->inc(method->code_size() + task->num_inlined_bytecodes());
2595       }
2596     }
2597 
2598     if (CITimeEach) {

2621       _total_standard_compile_count++;
2622     }
2623   }
2624   // set the current method for the thread to null
2625   if (UsePerfData) counters->set_current_method("");
2626 }
2627 
2628 const char* CompileBroker::compiler_name(int comp_level) {
2629   AbstractCompiler *comp = CompileBroker::compiler(comp_level);
2630   if (comp == nullptr) {
2631     return "no compiler";
2632   } else {
2633     return (comp->name());
2634   }
2635 }
2636 
2637 jlong CompileBroker::total_compilation_ticks() {
2638   return _perf_total_compilation != nullptr ? _perf_total_compilation->get_value() : 0;
2639 }
2640 


















2641 void CompileBroker::print_times(const char* name, CompilerStatistics* stats) {
2642   tty->print_cr("  %s {speed: %6.3f bytes/s; standard: %6.3f s, %u bytes, %u methods; osr: %6.3f s, %u bytes, %u methods; nmethods_size: %u bytes; nmethods_code_size: %u bytes}",
2643                 name, stats->bytes_per_second(),
2644                 stats->_standard._time.seconds(), stats->_standard._bytes, stats->_standard._count,
2645                 stats->_osr._time.seconds(), stats->_osr._bytes, stats->_osr._count,
2646                 stats->_nmethods_size, stats->_nmethods_code_size);
2647 }
2648 












































































































2649 void CompileBroker::print_times(bool per_compiler, bool aggregate) {
2650   if (per_compiler) {
2651     if (aggregate) {
2652       tty->cr();
2653       tty->print_cr("Individual compiler times (for compiled methods only)");
2654       tty->print_cr("------------------------------------------------");
2655       tty->cr();
2656     }
2657     for (unsigned int i = 0; i < sizeof(_compilers) / sizeof(AbstractCompiler*); i++) {
2658       AbstractCompiler* comp = _compilers[i];
2659       if (comp != nullptr) {
2660         print_times(comp->name(), comp->stats());
2661       }
2662     }



2663     if (aggregate) {
2664       tty->cr();
2665       tty->print_cr("Individual compilation Tier times (for compiled methods only)");
2666       tty->print_cr("------------------------------------------------");
2667       tty->cr();
2668     }
2669     char tier_name[256];
2670     for (int tier = CompLevel_simple; tier <= CompilationPolicy::highest_compile_level(); tier++) {
2671       CompilerStatistics* stats = &_stats_per_level[tier-1];
2672       os::snprintf_checked(tier_name, sizeof(tier_name), "Tier%d", tier);
2673       print_times(tier_name, stats);
2674     }







2675   }
2676 
2677   if (!aggregate) {
2678     return;
2679   }
2680 
2681   elapsedTimer standard_compilation = CompileBroker::_t_standard_compilation;
2682   elapsedTimer osr_compilation = CompileBroker::_t_osr_compilation;
2683   elapsedTimer total_compilation = CompileBroker::_t_total_compilation;
2684 
2685   uint standard_bytes_compiled = CompileBroker::_sum_standard_bytes_compiled;
2686   uint osr_bytes_compiled = CompileBroker::_sum_osr_bytes_compiled;
2687 
2688   uint standard_compile_count = CompileBroker::_total_standard_compile_count;
2689   uint osr_compile_count = CompileBroker::_total_osr_compile_count;
2690   uint total_compile_count = CompileBroker::_total_compile_count;
2691   uint total_bailout_count = CompileBroker::_total_bailout_count;
2692   uint total_invalidated_count = CompileBroker::_total_invalidated_count;
2693 
2694   uint nmethods_code_size = CompileBroker::_sum_nmethod_code_size;

2696 
2697   tty->cr();
2698   tty->print_cr("Accumulated compiler times");
2699   tty->print_cr("----------------------------------------------------------");
2700                //0000000000111111111122222222223333333333444444444455555555556666666666
2701                //0123456789012345678901234567890123456789012345678901234567890123456789
2702   tty->print_cr("  Total compilation time   : %7.3f s", total_compilation.seconds());
2703   tty->print_cr("    Standard compilation   : %7.3f s, Average : %2.3f s",
2704                 standard_compilation.seconds(),
2705                 standard_compile_count == 0 ? 0.0 : standard_compilation.seconds() / standard_compile_count);
2706   tty->print_cr("    Bailed out compilation : %7.3f s, Average : %2.3f s",
2707                 CompileBroker::_t_bailedout_compilation.seconds(),
2708                 total_bailout_count == 0 ? 0.0 : CompileBroker::_t_bailedout_compilation.seconds() / total_bailout_count);
2709   tty->print_cr("    On stack replacement   : %7.3f s, Average : %2.3f s",
2710                 osr_compilation.seconds(),
2711                 osr_compile_count == 0 ? 0.0 : osr_compilation.seconds() / osr_compile_count);
2712   tty->print_cr("    Invalidated            : %7.3f s, Average : %2.3f s",
2713                 CompileBroker::_t_invalidated_compilation.seconds(),
2714                 total_invalidated_count == 0 ? 0.0 : CompileBroker::_t_invalidated_compilation.seconds() / total_invalidated_count);
2715 




2716   AbstractCompiler *comp = compiler(CompLevel_simple);
2717   if (comp != nullptr) {
2718     tty->cr();
2719     comp->print_timers();
2720   }
2721   comp = compiler(CompLevel_full_optimization);
2722   if (comp != nullptr) {
2723     tty->cr();
2724     comp->print_timers();
2725   }





2726 #if INCLUDE_JVMCI
2727   if (EnableJVMCI) {
2728     JVMCICompiler *jvmci_comp = JVMCICompiler::instance(false, JavaThread::current_or_null());
2729     if (jvmci_comp != nullptr && jvmci_comp != comp) {
2730       tty->cr();
2731       jvmci_comp->print_timers();
2732     }
2733   }
2734 #endif
2735 
2736   tty->cr();
2737   tty->print_cr("  Total compiled methods    : %8u methods", total_compile_count);
2738   tty->print_cr("    Standard compilation    : %8u methods", standard_compile_count);
2739   tty->print_cr("    On stack replacement    : %8u methods", osr_compile_count);
2740   uint tcb = osr_bytes_compiled + standard_bytes_compiled;
2741   tty->print_cr("  Total compiled bytecodes  : %8u bytes", tcb);
2742   tty->print_cr("    Standard compilation    : %8u bytes", standard_bytes_compiled);
2743   tty->print_cr("    On stack replacement    : %8u bytes", osr_bytes_compiled);
2744   double tcs = total_compilation.seconds();
2745   uint bps = tcs == 0.0 ? 0 : (uint)(tcb / tcs);

   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 "cds/classPrelinker.hpp"
  27 #include "classfile/javaClasses.inline.hpp"
  28 #include "classfile/symbolTable.hpp"
  29 #include "classfile/vmClasses.hpp"
  30 #include "classfile/vmSymbols.hpp"
  31 #include "code/codeCache.hpp"
  32 #include "code/codeHeapState.hpp"
  33 #include "code/dependencyContext.hpp"
  34 #include "code/SCCache.hpp"
  35 #include "compiler/compilationLog.hpp"
  36 #include "compiler/compilationMemoryStatistic.hpp"
  37 #include "compiler/compilationPolicy.hpp"
  38 #include "compiler/compileBroker.hpp"
  39 #include "compiler/compilerDefinitions.inline.hpp"
  40 #include "compiler/compileLog.hpp"
  41 #include "compiler/compilerEvent.hpp"
  42 #include "compiler/compilerOracle.hpp"
  43 #include "compiler/directivesParser.hpp"
  44 #include "interpreter/linkResolver.hpp"
  45 #include "jvm.h"
  46 #include "jfr/jfrEvents.hpp"
  47 #include "logging/log.hpp"
  48 #include "logging/logStream.hpp"
  49 #include "memory/allocation.inline.hpp"
  50 #include "memory/resourceArea.hpp"
  51 #include "memory/universe.hpp"
  52 #include "oops/methodData.hpp"
  53 #include "oops/method.inline.hpp"
  54 #include "oops/oop.inline.hpp"
  55 #include "prims/jvmtiExport.hpp"
  56 #include "prims/nativeLookup.hpp"
  57 #include "prims/whitebox.hpp"
  58 #include "runtime/atomic.hpp"
  59 #include "runtime/escapeBarrier.hpp"
  60 #include "runtime/globals_extension.hpp"
  61 #include "runtime/handles.inline.hpp"
  62 #include "runtime/init.hpp"
  63 #include "runtime/interfaceSupport.inline.hpp"
  64 #include "runtime/java.hpp"
  65 #include "runtime/javaCalls.hpp"
  66 #include "runtime/jniHandles.inline.hpp"
  67 #include "runtime/os.hpp"
  68 #include "runtime/perfData.hpp"
  69 #include "runtime/safepointVerifiers.hpp"
  70 #include "runtime/sharedRuntime.hpp"
  71 #include "runtime/threads.hpp"
  72 #include "runtime/threadSMR.inline.hpp"
  73 #include "runtime/timerTrace.hpp"
  74 #include "runtime/vframe.inline.hpp"
  75 #include "services/management.hpp"
  76 #include "utilities/debug.hpp"
  77 #include "utilities/dtrace.hpp"
  78 #include "utilities/events.hpp"
  79 #include "utilities/formatBuffer.hpp"
  80 #include "utilities/macros.hpp"
  81 #ifdef COMPILER1
  82 #include "c1/c1_Compiler.hpp"
  83 #endif
  84 #ifdef COMPILER2
  85 #include "opto/c2compiler.hpp"
  86 #endif
  87 #if INCLUDE_JVMCI
  88 #include "jvmci/jvmciEnv.hpp"
  89 #include "jvmci/jvmciRuntime.hpp"
  90 #endif
  91 
  92 #ifdef DTRACE_ENABLED
  93 
  94 // Only bother with this argument setup if dtrace is available
  95 

 113     HOTSPOT_METHOD_COMPILE_END(                                          \
 114       (char *) comp_name, strlen(comp_name),                             \
 115       (char *) klass_name->bytes(), klass_name->utf8_length(),           \
 116       (char *) name->bytes(), name->utf8_length(),                       \
 117       (char *) signature->bytes(), signature->utf8_length(), (success)); \
 118   }
 119 
 120 #else //  ndef DTRACE_ENABLED
 121 
 122 #define DTRACE_METHOD_COMPILE_BEGIN_PROBE(method, comp_name)
 123 #define DTRACE_METHOD_COMPILE_END_PROBE(method, comp_name, success)
 124 
 125 #endif // ndef DTRACE_ENABLED
 126 
 127 bool CompileBroker::_initialized = false;
 128 volatile bool CompileBroker::_should_block = false;
 129 volatile int  CompileBroker::_print_compilation_warning = 0;
 130 volatile jint CompileBroker::_should_compile_new_jobs = run_compilation;
 131 
 132 // The installed compiler(s)
 133 AbstractCompiler* CompileBroker::_compilers[3];
 134 
 135 // The maximum numbers of compiler threads to be determined during startup.
 136 int CompileBroker::_c1_count = 0;
 137 int CompileBroker::_c2_count = 0;
 138 int CompileBroker::_c3_count = 0;
 139 int CompileBroker::_sc_count = 0;
 140 
 141 // An array of compiler names as Java String objects
 142 jobject* CompileBroker::_compiler1_objects = nullptr;
 143 jobject* CompileBroker::_compiler2_objects = nullptr;
 144 jobject* CompileBroker::_compiler3_objects = nullptr;
 145 jobject* CompileBroker::_sc_objects = nullptr;
 146 
 147 CompileLog** CompileBroker::_compiler1_logs = nullptr;
 148 CompileLog** CompileBroker::_compiler2_logs = nullptr;
 149 CompileLog** CompileBroker::_compiler3_logs = nullptr;
 150 CompileLog** CompileBroker::_sc_logs = nullptr;
 151 
 152 // These counters are used to assign an unique ID to each compilation.
 153 volatile jint CompileBroker::_compilation_id     = 0;
 154 volatile jint CompileBroker::_osr_compilation_id = 0;
 155 volatile jint CompileBroker::_native_compilation_id = 0;
 156 
 157 // Performance counters
 158 PerfCounter* CompileBroker::_perf_total_compilation = nullptr;
 159 PerfCounter* CompileBroker::_perf_osr_compilation = nullptr;
 160 PerfCounter* CompileBroker::_perf_standard_compilation = nullptr;
 161 
 162 PerfCounter* CompileBroker::_perf_total_bailout_count = nullptr;
 163 PerfCounter* CompileBroker::_perf_total_invalidated_count = nullptr;
 164 PerfCounter* CompileBroker::_perf_total_compile_count = nullptr;
 165 PerfCounter* CompileBroker::_perf_total_osr_compile_count = nullptr;
 166 PerfCounter* CompileBroker::_perf_total_standard_compile_count = nullptr;
 167 
 168 PerfCounter* CompileBroker::_perf_sum_osr_bytes_compiled = nullptr;
 169 PerfCounter* CompileBroker::_perf_sum_standard_bytes_compiled = nullptr;
 170 PerfCounter* CompileBroker::_perf_sum_nmethod_size = nullptr;
 171 PerfCounter* CompileBroker::_perf_sum_nmethod_code_size = nullptr;
 172 
 173 PerfStringVariable* CompileBroker::_perf_last_method = nullptr;
 174 PerfStringVariable* CompileBroker::_perf_last_failed_method = nullptr;
 175 PerfStringVariable* CompileBroker::_perf_last_invalidated_method = nullptr;
 176 PerfVariable*       CompileBroker::_perf_last_compile_type = nullptr;
 177 PerfVariable*       CompileBroker::_perf_last_compile_size = nullptr;
 178 PerfVariable*       CompileBroker::_perf_last_failed_type = nullptr;
 179 PerfVariable*       CompileBroker::_perf_last_invalidated_type = nullptr;
 180 
 181 // Timers and counters for generating statistics
 182 elapsedTimer CompileBroker::_t_total_compilation;
 183 elapsedTimer CompileBroker::_t_osr_compilation;
 184 elapsedTimer CompileBroker::_t_standard_compilation;
 185 elapsedTimer CompileBroker::_t_invalidated_compilation;
 186 elapsedTimer CompileBroker::_t_bailedout_compilation;
 187 
 188 uint CompileBroker::_total_bailout_count            = 0;
 189 uint CompileBroker::_total_invalidated_count        = 0;
 190 uint CompileBroker::_total_not_entrant_count        = 0;
 191 uint CompileBroker::_total_compile_count            = 0;
 192 uint CompileBroker::_total_osr_compile_count        = 0;
 193 uint CompileBroker::_total_standard_compile_count   = 0;
 194 uint CompileBroker::_total_compiler_stopped_count   = 0;
 195 uint CompileBroker::_total_compiler_restarted_count = 0;
 196 
 197 uint CompileBroker::_sum_osr_bytes_compiled         = 0;
 198 uint CompileBroker::_sum_standard_bytes_compiled    = 0;
 199 uint CompileBroker::_sum_nmethod_size               = 0;
 200 uint CompileBroker::_sum_nmethod_code_size          = 0;
 201 
 202 jlong CompileBroker::_peak_compilation_time        = 0;
 203 
 204 CompilerStatistics CompileBroker::_stats_per_level[CompLevel_full_optimization];
 205 CompilerStatistics CompileBroker::_scc_stats;
 206 CompilerStatistics CompileBroker::_scc_stats_per_level[CompLevel_full_optimization + 1];
 207 
 208 CompileQueue* CompileBroker::_c3_compile_queue     = nullptr;
 209 CompileQueue* CompileBroker::_c2_compile_queue     = nullptr;
 210 CompileQueue* CompileBroker::_c1_compile_queue     = nullptr;
 211 CompileQueue* CompileBroker::_sc1_compile_queue    = nullptr;
 212 CompileQueue* CompileBroker::_sc2_compile_queue    = nullptr;
 213 
 214 bool compileBroker_init() {
 215   if (LogEvents) {
 216     CompilationLog::init();
 217   }
 218 
 219   // init directives stack, adding default directive
 220   DirectivesStack::init();
 221 
 222   if (DirectivesParser::has_file()) {
 223     return DirectivesParser::parse_from_flag();
 224   } else if (CompilerDirectivesPrint) {
 225     // Print default directive even when no other was added
 226     DirectivesStack::print(tty);
 227   }
 228 
 229   return true;
 230 }
 231 
 232 CompileTaskWrapper::CompileTaskWrapper(CompileTask* task) {
 233   CompilerThread* thread = CompilerThread::current();
 234   thread->set_task(task);
 235   CompileLog*     log  = thread->log();
 236   if (log != nullptr && !task->is_unloaded())  task->log_task_start(log);
 237 }
 238 
 239 CompileTaskWrapper::~CompileTaskWrapper() {
 240   CompilerThread* thread = CompilerThread::current();
 241   CompileTask* task = thread->task();
 242   CompileLog*  log  = thread->log();
 243   AbstractCompiler* comp = thread->compiler();
 244   if (log != nullptr && !task->is_unloaded())  task->log_task_done(log);
 245   thread->set_task(nullptr);
 246   thread->set_env(nullptr);
 247   if (task->is_blocking()) {
 248     bool free_task = false;
 249     {
 250       MutexLocker notifier(thread, task->lock());
 251       task->mark_complete();
 252 #if INCLUDE_JVMCI
 253       if (comp->is_jvmci()) {
 254         if (!task->has_waiter()) {
 255           // The waiting thread timed out and thus did not free the task.
 256           free_task = true;
 257         }
 258         task->set_blocking_jvmci_compile_state(nullptr);
 259       }
 260 #endif
 261       if (!free_task) {
 262         // Notify the waiting thread that the compilation has completed
 263         // so that it can free the task.
 264         task->lock()->notify_all();
 265       }
 266     }
 267     if (free_task) {
 268       // The task can only be freed once the task lock is released.
 269       CompileTask::free(task);
 270     }
 271   } else {
 272     task->mark_complete();
 273 
 274     // By convention, the compiling thread is responsible for
 275     // recycling a non-blocking CompileTask.
 276     CompileTask::free(task);
 277   }
 278 }
 279 
 280 /**
 281  * Check if a CompilerThread can be removed and update count if requested.
 282  */
 283 bool CompileBroker::can_remove(CompilerThread *ct, bool do_it) {
 284   assert(UseDynamicNumberOfCompilerThreads, "or shouldn't be here");
 285   if (!ReduceNumberOfCompilerThreads) return false;
 286 
 287   if (CompilationPolicy::have_recompilation_work()) return false;
 288 
 289   AbstractCompiler *compiler = ct->compiler();
 290   int compiler_count = compiler->num_compiler_threads();
 291   bool c1 = compiler->is_c1();
 292 
 293   // Keep at least 1 compiler thread of each type.
 294   if (compiler_count < 2) return false;
 295 
 296   // Keep thread alive for at least some time.
 297   if (ct->idle_time_millis() < (c1 ? 500 : 100)) return false;
 298 
 299 #if INCLUDE_JVMCI
 300   if (compiler->is_jvmci() && !UseJVMCINativeLibrary) {
 301     // Handles for JVMCI thread objects may get released concurrently.
 302     if (do_it) {
 303       assert(CompileThread_lock->owner() == ct, "must be holding lock");
 304     } else {
 305       // Skip check if it's the last thread and let caller check again.
 306       return true;
 307     }
 308   }

 315     if (do_it) {
 316       assert_locked_or_safepoint(CompileThread_lock); // Update must be consistent.
 317       compiler->set_num_compiler_threads(compiler_count - 1);
 318 #if INCLUDE_JVMCI
 319       if (compiler->is_jvmci() && !UseJVMCINativeLibrary) {
 320         // Old j.l.Thread object can die when no longer referenced elsewhere.
 321         JNIHandles::destroy_global(compiler2_object(compiler_count - 1));
 322         _compiler2_objects[compiler_count - 1] = nullptr;
 323       }
 324 #endif
 325     }
 326     return true;
 327   }
 328   return false;
 329 }
 330 
 331 /**
 332  * Add a CompileTask to a CompileQueue.
 333  */
 334 void CompileQueue::add(CompileTask* task) {
 335   assert(_lock->owned_by_self(), "must own lock");
 336 
 337   task->set_next(nullptr);
 338   task->set_prev(nullptr);
 339 
 340   if (_last == nullptr) {
 341     // The compile queue is empty.
 342     assert(_first == nullptr, "queue is empty");
 343     _first = task;
 344     _last = task;
 345   } else {
 346     // Append the task to the queue.
 347     assert(_last->next() == nullptr, "not last");
 348     _last->set_next(task);
 349     task->set_prev(_last);
 350     _last = task;
 351   }
 352   ++_size;
 353   ++_total_added;
 354   if (_size > _peak_size) {
 355     _peak_size = _size;
 356   }
 357 
 358   // Mark the method as being in the compile queue.
 359   task->method()->set_queued_for_compilation();
 360 
 361   task->mark_queued(os::elapsed_counter());
 362 
 363   if (CIPrintCompileQueue) {
 364     print_tty();
 365   }
 366 
 367   if (LogCompilation && xtty != nullptr) {
 368     task->log_task_queued();
 369   }
 370 
 371   if (TrainingData::need_data()) {
 372     CompileTrainingData* tdata = CompileTrainingData::make(task);
 373     if (tdata != nullptr) {
 374       tdata->record_compilation_queued(task);
 375       task->set_training_data(tdata);
 376     }
 377   }
 378 
 379   // Notify CompilerThreads that a task is available.
 380   _lock->notify_all();
 381 }
 382 
 383 void CompileQueue::add_pending(CompileTask* task) {
 384   assert(_lock->owned_by_self() == false, "must NOT own lock");
 385   assert(UseLockFreeCompileQueues, "");
 386   task->method()->set_queued_for_compilation();
 387   _queue.push(*task);
 388   // FIXME: additional coordination needed? e.g., is it possible for compiler thread to block w/o processing pending tasks?
 389   if (is_empty()) {
 390     MutexLocker ml(_lock);
 391     _lock->notify_all();
 392   }
 393 }
 394 
 395 void CompileQueue::transfer_pending() {
 396   assert(_lock->owned_by_self(), "must own lock");
 397   while (!_queue.empty()) {
 398     CompileTask* task = _queue.pop();
 399 //    guarantee(task->method()->queued_for_compilation(), "");
 400     task->method()->set_queued_for_compilation(); // FIXME
 401     if (task->method()->pending_queue_processed()) {
 402       task->set_next(_first_stale);
 403       task->set_prev(nullptr);
 404       _first_stale = task;
 405       continue; // skip
 406     } else {
 407       // Mark the method as being in the compile queue.
 408       task->method()->set_pending_queue_processed();
 409     }
 410     if (CompileBroker::compilation_is_complete(task->method(), task->osr_bci(), task->comp_level(),
 411                                                task->requires_online_compilation(), task->compile_reason())) {
 412       task->set_next(_first_stale);
 413       task->set_prev(nullptr);
 414       _first_stale = task;
 415       continue; // skip
 416     }
 417     add(task);
 418   }
 419 }
 420 
 421 /**
 422  * Empties compilation queue by putting all compilation tasks onto
 423  * a freelist. Furthermore, the method wakes up all threads that are
 424  * waiting on a compilation task to finish. This can happen if background
 425  * compilation is disabled.
 426  */
 427 void CompileQueue::free_all() {
 428   MutexLocker mu(_lock);
 429   transfer_pending();
 430 
 431   CompileTask* next = _first;
 432 
 433   // Iterate over all tasks in the compile queue
 434   while (next != nullptr) {
 435     CompileTask* current = next;
 436     next = current->next();
 437     {
 438       // Wake up thread that blocks on the compile task.
 439       MutexLocker ct_lock(current->lock());
 440       current->lock()->notify();
 441     }
 442     // Put the task back on the freelist.
 443     CompileTask::free(current);
 444   }
 445   _first = nullptr;
 446   _last = nullptr;
 447 
 448   // Wake up all threads that block on the queue.
 449   _lock->notify_all();
 450 }
 451 
 452 /**
 453  * Get the next CompileTask from a CompileQueue
 454  */
 455 CompileTask* CompileQueue::get(CompilerThread* thread) {
 456   // save methods from RedefineClasses across safepoint
 457   // across compile queue lock below.
 458   methodHandle save_method;
 459   methodHandle save_hot_method;
 460 
 461   MonitorLocker locker(_lock);
 462   transfer_pending();
 463 
 464   CompilationPolicy::sample_load_average();
 465 
 466   // If _first is null we have no more compile jobs. There are two reasons for
 467   // having no compile jobs: First, we compiled everything we wanted. Second,
 468   // we ran out of code cache so compilation has been disabled. In the latter
 469   // case we perform code cache sweeps to free memory such that we can re-enable
 470   // compilation.
 471   while (_first == nullptr) {
 472     // Exit loop if compilation is disabled forever
 473     if (CompileBroker::is_compilation_disabled_forever()) {
 474       return nullptr;
 475     }
 476 
 477     AbstractCompiler* compiler = thread->compiler();
 478     guarantee(compiler != nullptr, "Compiler object must exist");
 479     compiler->on_empty_queue(this, thread);
 480     if (_first != nullptr) {
 481       // The call to on_empty_queue may have temporarily unlocked the MCQ lock
 482       // so check again whether any tasks were added to the queue.
 483       break;
 484     }
 485 
 486     // If there are no compilation tasks and we can compile new jobs
 487     // (i.e., there is enough free space in the code cache) there is
 488     // no need to invoke the GC.
 489     // We need a timed wait here, since compiler threads can exit if compilation
 490     // is disabled forever. We use 5 seconds wait time; the exiting of compiler threads
 491     // is not critical and we do not want idle compiler threads to wake up too often.
 492     locker.wait(5*1000);
 493 
 494     transfer_pending(); // reacquired lock
 495 
 496     if (CompilationPolicy::have_recompilation_work()) return nullptr;
 497 
 498     if (UseDynamicNumberOfCompilerThreads && _first == nullptr) {
 499       // Still nothing to compile. Give caller a chance to stop this thread.
 500       if (CompileBroker::can_remove(CompilerThread::current(), false)) return nullptr;
 501     }
 502   }
 503 
 504   if (CompileBroker::is_compilation_disabled_forever()) {
 505     return nullptr;
 506   }
 507 
 508   CompileTask* task;
 509   {
 510     NoSafepointVerifier nsv;
 511     task = CompilationPolicy::select_task(this, thread);
 512     if (task != nullptr) {
 513       task = task->select_for_compilation();
 514     }
 515   }
 516 
 517   if (task != nullptr) {
 518     // Save method pointers across unlock safepoint.  The task is removed from
 519     // the compilation queue, which is walked during RedefineClasses.
 520     Thread* thread = Thread::current();
 521     save_method = methodHandle(thread, task->method());
 522     save_hot_method = methodHandle(thread, task->hot_method());
 523 
 524     remove(task);
 525   }
 526   purge_stale_tasks(); // may temporarily release MCQ lock
 527   return task;
 528 }
 529 
 530 // Clean & deallocate stale compile tasks.
 531 // Temporarily releases MethodCompileQueue lock.
 532 void CompileQueue::purge_stale_tasks() {
 533   assert(_lock->owned_by_self(), "must own lock");
 534   if (_first_stale != nullptr) {
 535     // Stale tasks are purged when MCQ lock is released,
 536     // but _first_stale updates are protected by MCQ lock.
 537     // Once task processing starts and MCQ lock is released,
 538     // other compiler threads can reuse _first_stale.
 539     CompileTask* head = _first_stale;
 540     _first_stale = nullptr;
 541     {
 542       MutexUnlocker ul(_lock);
 543       for (CompileTask* task = head; task != nullptr; ) {
 544         CompileTask* next_task = task->next();
 545         CompileTaskWrapper ctw(task); // Frees the task
 546         task->set_failure_reason("stale task");
 547         task = next_task;
 548       }
 549     }
 550     transfer_pending(); // transfer pending after reacquiring MCQ lock
 551   }
 552 }
 553 
 554 void CompileQueue::remove(CompileTask* task) {
 555   assert(_lock->owned_by_self(), "must own lock");
 556   if (task->prev() != nullptr) {
 557     task->prev()->set_next(task->next());
 558   } else {
 559     // max is the first element
 560     assert(task == _first, "Sanity");
 561     _first = task->next();
 562   }
 563 
 564   if (task->next() != nullptr) {
 565     task->next()->set_prev(task->prev());
 566   } else {
 567     // max is the last element
 568     assert(task == _last, "Sanity");
 569     _last = task->prev();
 570   }
 571   --_size;
 572   ++_total_removed;
 573 }
 574 
 575 void CompileQueue::remove_and_mark_stale(CompileTask* task) {
 576   assert(_lock->owned_by_self(), "must own lock");
 577   remove(task);
 578 
 579   // Enqueue the task for reclamation (should be done outside MCQ lock)
 580   task->set_next(_first_stale);
 581   task->set_prev(nullptr);
 582   _first_stale = task;
 583 }
 584 
 585 // methods in the compile queue need to be marked as used on the stack
 586 // so that they don't get reclaimed by Redefine Classes
 587 void CompileQueue::mark_on_stack() {
 588   CompileTask* task = _first;
 589   while (task != nullptr) {
 590     task->mark_on_stack();
 591     task = task->next();
 592   }
 593 }
 594 
 595 
 596 CompileQueue* CompileBroker::compile_queue(int comp_level, bool is_scc) {
 597   if (is_c2_compile(comp_level)) return (is_scc ? _sc2_compile_queue : _c2_compile_queue);
 598   if (is_c1_compile(comp_level)) return (is_scc ? _sc1_compile_queue : _c1_compile_queue);
 599   return nullptr;
 600 }
 601 
 602 CompileQueue* CompileBroker::c1_compile_queue() {
 603   return _c1_compile_queue;
 604 }
 605 
 606 CompileQueue* CompileBroker::c2_compile_queue() {
 607   return _c2_compile_queue;
 608 }
 609 
 610 void CompileBroker::print_compile_queues(outputStream* st) {
 611   st->print_cr("Current compiles: ");
 612 
 613   char buf[2000];
 614   int buflen = sizeof(buf);
 615   Threads::print_threads_compiling(st, buf, buflen, /* short_form = */ true);
 616 
 617   st->cr();
 618   if (_c1_compile_queue != nullptr) {
 619     _c1_compile_queue->print(st);
 620   }
 621   if (_c2_compile_queue != nullptr) {
 622     _c2_compile_queue->print(st);
 623   }
 624   if (_c3_compile_queue != nullptr) {
 625     _c3_compile_queue->print(st);
 626   }
 627   if (_sc1_compile_queue != nullptr) {
 628     _sc1_compile_queue->print(st);
 629   }
 630   if (_sc2_compile_queue != nullptr) {
 631     _sc2_compile_queue->print(st);
 632   }
 633 }
 634 
 635 void CompileQueue::print(outputStream* st) {
 636   assert_locked_or_safepoint(_lock);
 637   st->print_cr("%s:", name());
 638   CompileTask* task = _first;
 639   if (task == nullptr) {
 640     st->print_cr("Empty");
 641   } else {
 642     while (task != nullptr) {
 643       task->print(st, nullptr, true, true);
 644       task = task->next();
 645     }
 646   }
 647   st->cr();
 648 }
 649 
 650 void CompileQueue::print_tty() {
 651   stringStream ss;
 652   // Dump the compile queue into a buffer before locking the tty
 653   print(&ss);
 654   {
 655     ttyLocker ttyl;
 656     tty->print("%s", ss.freeze());

 683       CompilerEvent::PhaseEvent::get_phase_id(phase_name, false, false, false);
 684     }
 685     first_registration = false;
 686 #endif // COMPILER2
 687   }
 688 }
 689 #endif // INCLUDE_JFR && COMPILER2_OR_JVMCI
 690 
 691 // ------------------------------------------------------------------
 692 // CompileBroker::compilation_init
 693 //
 694 // Initialize the Compilation object
 695 void CompileBroker::compilation_init(JavaThread* THREAD) {
 696   // No need to initialize compilation system if we do not use it.
 697   if (!UseCompiler) {
 698     return;
 699   }
 700   // Set the interface to the current compiler(s).
 701   _c1_count = CompilationPolicy::c1_count();
 702   _c2_count = CompilationPolicy::c2_count();
 703   _c3_count = CompilationPolicy::c3_count();
 704   _sc_count = CompilationPolicy::sc_count();
 705 
 706 #if INCLUDE_JVMCI
 707   if (EnableJVMCI) {
 708     // This is creating a JVMCICompiler singleton.
 709     JVMCICompiler* jvmci = new JVMCICompiler();
 710 
 711     if (UseJVMCICompiler) {
 712       _compilers[1] = jvmci;
 713       if (FLAG_IS_DEFAULT(JVMCIThreads)) {
 714         if (BootstrapJVMCI) {
 715           // JVMCI will bootstrap so give it more threads
 716           _c2_count = MIN2(32, os::active_processor_count());
 717         }
 718       } else {
 719         _c2_count = JVMCIThreads;
 720       }
 721       if (FLAG_IS_DEFAULT(JVMCIHostThreads)) {
 722       } else {
 723 #ifdef COMPILER1
 724         _c1_count = JVMCIHostThreads;
 725 #endif // COMPILER1
 726       }
 727 #ifdef COMPILER2
 728       if (SCCache::is_on() && (_c3_count > 0)) {
 729         _compilers[2] = new C2Compiler();
 730       }
 731 #endif
 732     }
 733   }
 734 #endif // INCLUDE_JVMCI
 735 
 736 #ifdef COMPILER1
 737   if (_c1_count > 0) {
 738     _compilers[0] = new Compiler();
 739   }
 740 #endif // COMPILER1
 741 
 742 #ifdef COMPILER2
 743   if (true JVMCI_ONLY( && !UseJVMCICompiler)) {
 744     if (_c2_count > 0) {
 745       _compilers[1] = new C2Compiler();
 746       // Register c2 first as c2 CompilerPhaseType idToPhase mapping is explicit.
 747       // idToPhase mapping for c2 is in opto/phasetype.hpp
 748       JFR_ONLY(register_jfr_phasetype_serializer(compiler_c2);)
 749     }
 750   }
 751 #endif // COMPILER2

 846     _perf_last_compile_size =
 847              PerfDataManager::create_variable(SUN_CI, "lastSize",
 848                                               PerfData::U_Bytes,
 849                                               (jlong)CompileBroker::no_compile,
 850                                               CHECK);
 851 
 852 
 853     _perf_last_failed_type =
 854              PerfDataManager::create_variable(SUN_CI, "lastFailedType",
 855                                               PerfData::U_None,
 856                                               (jlong)CompileBroker::no_compile,
 857                                               CHECK);
 858 
 859     _perf_last_invalidated_type =
 860          PerfDataManager::create_variable(SUN_CI, "lastInvalidatedType",
 861                                           PerfData::U_None,
 862                                           (jlong)CompileBroker::no_compile,
 863                                           CHECK);
 864   }
 865 
 866   log_info(scc, init)("CompileBroker is initialized");
 867   _initialized = true;
 868 }
 869 
 870 Handle CompileBroker::create_thread_oop(const char* name, TRAPS) {
 871   Handle thread_oop = JavaThread::create_system_thread_object(name, CHECK_NH);
 872   return thread_oop;
 873 }
 874 
 875 void TrainingReplayThread::training_replay_thread_entry(JavaThread* thread, TRAPS) {
 876   CompilationPolicy::replay_training_at_init_loop(thread);
 877 }
 878 
 879 #if defined(ASSERT) && COMPILER2_OR_JVMCI
 880 // Stress testing. Dedicated threads revert optimizations based on escape analysis concurrently to
 881 // the running java application.  Configured with vm options DeoptimizeObjectsALot*.
 882 class DeoptimizeObjectsALotThread : public JavaThread {
 883 
 884   static void deopt_objs_alot_thread_entry(JavaThread* thread, TRAPS);
 885   void deoptimize_objects_alot_loop_single();
 886   void deoptimize_objects_alot_loop_all();
 887 
 888 public:
 889   DeoptimizeObjectsALotThread() : JavaThread(&deopt_objs_alot_thread_entry) { }
 890 
 891   bool is_hidden_from_external_view() const      { return true; }
 892 };
 893 
 894 // Entry for DeoptimizeObjectsALotThread. The threads are started in
 895 // CompileBroker::init_compiler_threads() iff DeoptimizeObjectsALot is enabled
 896 void DeoptimizeObjectsALotThread::deopt_objs_alot_thread_entry(JavaThread* thread, TRAPS) {
 897     DeoptimizeObjectsALotThread* dt = ((DeoptimizeObjectsALotThread*) thread);
 898     bool enter_single_loop;

 950   if (java_lang_Thread::thread(thread_oop()) != nullptr) {
 951     assert(type == compiler_t, "should only happen with reused compiler threads");
 952     // The compiler thread hasn't actually exited yet so don't try to reuse it
 953     return nullptr;
 954   }
 955 
 956   JavaThread* new_thread = nullptr;
 957   switch (type) {
 958     case compiler_t:
 959       assert(comp != nullptr, "Compiler instance missing.");
 960       if (!InjectCompilerCreationFailure || comp->num_compiler_threads() == 0) {
 961         CompilerCounters* counters = new CompilerCounters();
 962         new_thread = new CompilerThread(queue, counters);
 963       }
 964       break;
 965 #if defined(ASSERT) && COMPILER2_OR_JVMCI
 966     case deoptimizer_t:
 967       new_thread = new DeoptimizeObjectsALotThread();
 968       break;
 969 #endif // ASSERT
 970     case training_replay_t:
 971       new_thread = new TrainingReplayThread();
 972       break;
 973     default:
 974       ShouldNotReachHere();
 975   }
 976 
 977   // At this point the new CompilerThread data-races with this startup
 978   // thread (which is the main thread and NOT the VM thread).
 979   // This means Java bytecodes being executed at startup can
 980   // queue compile jobs which will run at whatever default priority the
 981   // newly created CompilerThread runs at.
 982 
 983 
 984   // At this point it may be possible that no osthread was created for the
 985   // JavaThread due to lack of resources. We will handle that failure below.
 986   // Also check new_thread so that static analysis is happy.
 987   if (new_thread != nullptr && new_thread->osthread() != nullptr) {
 988 
 989     if (type == compiler_t) {
 990       CompilerThread::cast(new_thread)->set_compiler(comp);
 991     }
 992 

1032 }
1033 
1034 static jobject create_compiler_thread(AbstractCompiler* compiler, int i, TRAPS) {
1035   char name_buffer[256];
1036   os::snprintf_checked(name_buffer, sizeof(name_buffer), "%s CompilerThread%d", compiler->name(), i);
1037   Handle thread_oop = JavaThread::create_system_thread_object(name_buffer, CHECK_NULL);
1038   return JNIHandles::make_global(thread_oop);
1039 }
1040 
1041 static void print_compiler_threads(stringStream& msg) {
1042   if (TraceCompilerThreads) {
1043     tty->print_cr("%7d %s", (int)tty->time_stamp().milliseconds(), msg.as_string());
1044   }
1045   LogTarget(Debug, jit, thread) lt;
1046   if (lt.is_enabled()) {
1047     LogStream ls(lt);
1048     ls.print_cr("%s", msg.as_string());
1049   }
1050 }
1051 
1052 static void print_compiler_thread(JavaThread *ct) {
1053   if (trace_compiler_threads()) {
1054     ResourceMark rm;
1055     ThreadsListHandle tlh;  // name() depends on the TLH.
1056     assert(tlh.includes(ct), "ct=" INTPTR_FORMAT " exited unexpectedly.", p2i(ct));
1057     stringStream msg;
1058     msg.print("Added initial compiler thread %s", ct->name());
1059     print_compiler_threads(msg);
1060   }
1061 }
1062 
1063 void CompileBroker::init_compiler_threads() {
1064   // Ensure any exceptions lead to vm_exit_during_initialization.
1065   EXCEPTION_MARK;
1066 #if !defined(ZERO)
1067   assert(_c2_count > 0 || _c1_count > 0, "No compilers?");
1068 #endif // !ZERO
1069   // Initialize the compilation queue
1070   if (_c2_count > 0) {
1071     const char* name = JVMCI_ONLY(UseJVMCICompiler ? "JVMCI compile queue" :) "C2 compile queue";
1072     _c2_compile_queue  = new CompileQueue(name, MethodCompileQueueC2_lock);
1073     _compiler2_objects = NEW_C_HEAP_ARRAY(jobject, _c2_count, mtCompiler);
1074     _compiler2_logs = NEW_C_HEAP_ARRAY(CompileLog*, _c2_count, mtCompiler);
1075   }
1076   if (_c1_count > 0) {
1077     _c1_compile_queue  = new CompileQueue("C1 compile queue", MethodCompileQueueC1_lock);
1078     _compiler1_objects = NEW_C_HEAP_ARRAY(jobject, _c1_count, mtCompiler);
1079     _compiler1_logs = NEW_C_HEAP_ARRAY(CompileLog*, _c1_count, mtCompiler);
1080   }
1081 
1082   if (_c3_count > 0) {
1083     const char* name = "C2 compile queue";
1084     _c3_compile_queue  = new CompileQueue(name, MethodCompileQueueC3_lock);
1085     _compiler3_objects = NEW_C_HEAP_ARRAY(jobject, _c3_count, mtCompiler);
1086     _compiler3_logs = NEW_C_HEAP_ARRAY(CompileLog*, _c3_count, mtCompiler);
1087   }
1088   if (_sc_count > 0) {
1089     if (_c1_count > 0) { // C1 is present
1090       _sc1_compile_queue  = new CompileQueue("C1 SC compile queue", MethodCompileQueueSC1_lock);
1091     }
1092     if (_c2_count > 0) { // C2 is present
1093       _sc2_compile_queue  = new CompileQueue("C2 SC compile queue", MethodCompileQueueSC2_lock);
1094     }
1095     _sc_objects = NEW_C_HEAP_ARRAY(jobject, _sc_count, mtCompiler);
1096     _sc_logs = NEW_C_HEAP_ARRAY(CompileLog*, _sc_count, mtCompiler);
1097   }
1098   char name_buffer[256];
1099 
1100   for (int i = 0; i < _c2_count; i++) {
1101     // Create a name for our thread.
1102     jobject thread_handle = create_compiler_thread(_compilers[1], i, CHECK);
1103     _compiler2_objects[i] = thread_handle;
1104     _compiler2_logs[i] = nullptr;
1105 
1106     if (!UseDynamicNumberOfCompilerThreads || i == 0) {
1107       JavaThread *ct = make_thread(compiler_t, thread_handle, _c2_compile_queue, _compilers[1], THREAD);
1108       assert(ct != nullptr, "should have been handled for initial thread");
1109       _compilers[1]->set_num_compiler_threads(i + 1);
1110       print_compiler_thread(ct);







1111     }
1112   }
1113 
1114   for (int i = 0; i < _c1_count; i++) {
1115     // Create a name for our thread.
1116     jobject thread_handle = create_compiler_thread(_compilers[0], i, CHECK);
1117     _compiler1_objects[i] = thread_handle;
1118     _compiler1_logs[i] = nullptr;
1119 
1120     if (!UseDynamicNumberOfCompilerThreads || i == 0) {
1121       JavaThread *ct = make_thread(compiler_t, thread_handle, _c1_compile_queue, _compilers[0], THREAD);
1122       assert(ct != nullptr, "should have been handled for initial thread");
1123       _compilers[0]->set_num_compiler_threads(i + 1);
1124       print_compiler_thread(ct);
1125     }
1126   }
1127 
1128   for (int i = 0; i < _c3_count; i++) {
1129     // Create a name for our thread.
1130     os::snprintf_checked(name_buffer, sizeof(name_buffer), "C2 CompilerThread%d", i);
1131     Handle thread_oop = create_thread_oop(name_buffer, CHECK);
1132     jobject thread_handle = JNIHandles::make_global(thread_oop);
1133     _compiler3_objects[i] = thread_handle;
1134     _compiler3_logs[i] = nullptr;
1135 
1136     JavaThread *ct = make_thread(compiler_t, thread_handle, _c3_compile_queue, _compilers[2], THREAD);
1137     assert(ct != nullptr, "should have been handled for initial thread");
1138     _compilers[2]->set_num_compiler_threads(i + 1);
1139     print_compiler_thread(ct);
1140   }
1141 
1142   if (_sc_count > 0) {
1143     int i = 0;
1144     if (_c1_count > 0) { // C1 is present
1145       os::snprintf_checked(name_buffer, sizeof(name_buffer), "C%d SC CompilerThread", 1);
1146       Handle thread_oop = create_thread_oop(name_buffer, CHECK);
1147       jobject thread_handle = JNIHandles::make_global(thread_oop);
1148       _sc_objects[i] = thread_handle;
1149       _sc_logs[i] = nullptr;
1150       i++;
1151 
1152       JavaThread *ct = make_thread(compiler_t, thread_handle, _sc1_compile_queue, _compilers[0], THREAD);
1153       assert(ct != nullptr, "should have been handled for initial thread");
1154       print_compiler_thread(ct);
1155     }
1156     if (_c2_count > 0) { // C2 is present
1157       os::snprintf_checked(name_buffer, sizeof(name_buffer), "C%d SC CompilerThread", 2);
1158       Handle thread_oop = create_thread_oop(name_buffer, CHECK);
1159       jobject thread_handle = JNIHandles::make_global(thread_oop);
1160       _sc_objects[i] = thread_handle;
1161       _sc_logs[i] = nullptr;
1162 
1163       JavaThread *ct = make_thread(compiler_t, thread_handle, _sc2_compile_queue, _compilers[1], THREAD);
1164       assert(ct != nullptr, "should have been handled for initial thread");
1165       print_compiler_thread(ct);
1166     }
1167   }
1168 
1169   if (UsePerfData) {
1170     PerfDataManager::create_constant(SUN_CI, "threads", PerfData::U_Bytes, _c1_count + _c2_count + _c3_count, CHECK);
1171   }
1172 
1173 #if defined(ASSERT) && COMPILER2_OR_JVMCI
1174   if (DeoptimizeObjectsALot) {
1175     // Initialize and start the object deoptimizer threads
1176     const int total_count = DeoptimizeObjectsALotThreadCountSingle + DeoptimizeObjectsALotThreadCountAll;
1177     for (int count = 0; count < total_count; count++) {
1178       Handle thread_oop = JavaThread::create_system_thread_object("Deoptimize objects a lot single mode", CHECK);
1179       jobject thread_handle = JNIHandles::make_local(THREAD, thread_oop());
1180       make_thread(deoptimizer_t, thread_handle, nullptr, nullptr, THREAD);
1181     }
1182   }
1183 #endif // defined(ASSERT) && COMPILER2_OR_JVMCI
1184   if (UseConcurrentTrainingReplay) {
1185     Handle thread_oop = create_thread_oop("Training replay thread", CHECK);
1186     jobject thread_handle = JNIHandles::make_local(THREAD, thread_oop());
1187     make_thread(training_replay_t, thread_handle, nullptr, nullptr, THREAD);
1188   }
1189 }
1190 
1191 void CompileBroker::possibly_add_compiler_threads(JavaThread* THREAD) {
1192 
1193   julong free_memory = os::free_memory();
1194   // If SegmentedCodeCache is off, both values refer to the single heap (with type CodeBlobType::All).
1195   size_t available_cc_np  = CodeCache::unallocated_capacity(CodeBlobType::MethodNonProfiled),
1196          available_cc_p   = CodeCache::unallocated_capacity(CodeBlobType::MethodProfiled);
1197 
1198   // Only do attempt to start additional threads if the lock is free.
1199   if (!CompileThread_lock->try_lock()) return;
1200 
1201   if (_c2_compile_queue != nullptr) {
1202     int old_c2_count = _compilers[1]->num_compiler_threads();
1203     int new_c2_count = MIN4(_c2_count,
1204         _c2_compile_queue->size() / 2,
1205         (int)(free_memory / (200*M)),
1206         (int)(available_cc_np / (128*K)));
1207 
1208     for (int i = old_c2_count; i < new_c2_count; i++) {

1277         stringStream msg;
1278         msg.print("Added compiler thread %s (free memory: %dMB, available profiled code cache: %dMB)",
1279                   ct->name(), (int)(free_memory/M), (int)(available_cc_p/M));
1280         print_compiler_threads(msg);
1281       }
1282     }
1283   }
1284 
1285   CompileThread_lock->unlock();
1286 }
1287 
1288 
1289 /**
1290  * Set the methods on the stack as on_stack so that redefine classes doesn't
1291  * reclaim them. This method is executed at a safepoint.
1292  */
1293 void CompileBroker::mark_on_stack() {
1294   assert(SafepointSynchronize::is_at_safepoint(), "sanity check");
1295   // Since we are at a safepoint, we do not need a lock to access
1296   // the compile queues.
1297   if (_c3_compile_queue != nullptr) {
1298     _c3_compile_queue->mark_on_stack();
1299   }
1300   if (_c2_compile_queue != nullptr) {
1301     _c2_compile_queue->mark_on_stack();
1302   }
1303   if (_c1_compile_queue != nullptr) {
1304     _c1_compile_queue->mark_on_stack();
1305   }
1306   if (_sc1_compile_queue != nullptr) {
1307     _sc1_compile_queue->mark_on_stack();
1308   }
1309   if (_sc2_compile_queue != nullptr) {
1310     _sc2_compile_queue->mark_on_stack();
1311   }
1312 }
1313 
1314 // ------------------------------------------------------------------
1315 // CompileBroker::compile_method
1316 //
1317 // Request compilation of a method.
1318 void CompileBroker::compile_method_base(const methodHandle& method,
1319                                         int osr_bci,
1320                                         int comp_level,
1321                                         const methodHandle& hot_method,
1322                                         int hot_count,
1323                                         CompileTask::CompileReason compile_reason,
1324                                         bool requires_online_compilation,
1325                                         bool blocking,
1326                                         Thread* thread) {
1327   guarantee(!method->is_abstract(), "cannot compile abstract methods");
1328   assert(method->method_holder()->is_instance_klass(),
1329          "sanity check");
1330   assert(!method->method_holder()->is_not_initialized()   ||
1331          compile_reason == CompileTask::Reason_Preload    ||
1332          compile_reason == CompileTask::Reason_Precompile ||
1333          compile_reason == CompileTask::Reason_PrecompileForPreload, "method holder must be initialized");
1334   assert(!method->is_method_handle_intrinsic(), "do not enqueue these guys");
1335 
1336   if (CIPrintRequests) {
1337     tty->print("request: ");
1338     method->print_short_name(tty);
1339     if (osr_bci != InvocationEntryBci) {
1340       tty->print(" osr_bci: %d", osr_bci);
1341     }
1342     tty->print(" level: %d comment: %s count: %d", comp_level, CompileTask::reason_name(compile_reason), hot_count);
1343     if (!hot_method.is_null()) {
1344       tty->print(" hot: ");
1345       if (hot_method() != method()) {
1346           hot_method->print_short_name(tty);
1347       } else {
1348         tty->print("yes");
1349       }
1350     }
1351     tty->cr();
1352   }
1353 
1354   // A request has been made for compilation.  Before we do any
1355   // real work, check to see if the method has been compiled
1356   // in the meantime with a definitive result.
1357   if (compilation_is_complete(method(), osr_bci, comp_level, requires_online_compilation, compile_reason)) {
1358     return;
1359   }
1360 
1361 #ifndef PRODUCT
1362   if (osr_bci != -1 && !FLAG_IS_DEFAULT(OSROnlyBCI)) {
1363     if ((OSROnlyBCI > 0) ? (OSROnlyBCI != osr_bci) : (-OSROnlyBCI == osr_bci)) {
1364       // Positive OSROnlyBCI means only compile that bci.  Negative means don't compile that BCI.
1365       return;
1366     }
1367   }
1368 #endif
1369 
1370   // If this method is already in the compile queue, then
1371   // we do not block the current thread.
1372   if (compilation_is_in_queue(method)) {
1373     // We may want to decay our counter a bit here to prevent
1374     // multiple denied requests for compilation.  This is an
1375     // open compilation policy issue. Note: The other possibility,
1376     // in the case that this is a blocking compile request, is to have
1377     // all subsequent blocking requesters wait for completion of
1378     // ongoing compiles. Note that in this case we'll need a protocol
1379     // for freeing the associated compile tasks. [Or we could have
1380     // a single static monitor on which all these waiters sleep.]
1381     return;
1382   }
1383 
1384   // Tiered policy requires MethodCounters to exist before adding a method to
1385   // the queue. Create if we don't have them yet.
1386   if (compile_reason != CompileTask::Reason_Preload) {
1387     method->get_method_counters(thread);
1388   }
1389 
1390   SCCEntry* scc_entry = find_scc_entry(method, osr_bci, comp_level, compile_reason, requires_online_compilation);
1391   bool is_scc = (scc_entry != nullptr);
1392 
1393   // Outputs from the following MutexLocker block:
1394   CompileTask* task = nullptr;
1395   CompileQueue* queue;
1396 #if INCLUDE_JVMCI
1397   if (is_c2_compile(comp_level) && compiler2()->is_jvmci() && compiler3() != nullptr &&
1398       ((JVMCICompiler*)compiler2())->force_comp_at_level_simple(method)) {
1399     assert(_c3_compile_queue != nullptr, "sanity");
1400     queue = _c3_compile_queue; // JVMCI compiler's methods compilation
1401   } else
1402 #endif
1403   queue = compile_queue(comp_level, is_scc);
1404 
1405   // Acquire our lock.
1406   {
1407     ConditionalMutexLocker locker(thread, queue->lock(), !UseLockFreeCompileQueues);
1408 
1409     // Make sure the method has not slipped into the queues since
1410     // last we checked; note that those checks were "fast bail-outs".
1411     // Here we need to be more careful, see 14012000 below.
1412     if (compilation_is_in_queue(method)) {
1413       return;
1414     }
1415 
1416     // We need to check again to see if the compilation has
1417     // completed.  A previous compilation may have registered
1418     // some result.
1419     if (compilation_is_complete(method(), osr_bci, comp_level, requires_online_compilation, compile_reason)) {
1420       return;
1421     }
1422 
1423     // We now know that this compilation is not pending, complete,
1424     // or prohibited.  Assign a compile_id to this compilation
1425     // and check to see if it is in our [Start..Stop) range.
1426     int compile_id = assign_compile_id(method, osr_bci);
1427     if (compile_id == 0) {
1428       // The compilation falls outside the allowed range.
1429       return;
1430     }
1431 
1432 #if INCLUDE_JVMCI
1433     if (UseJVMCICompiler && blocking) {
1434       // Don't allow blocking compiles for requests triggered by JVMCI.
1435       if (thread->is_Compiler_thread()) {
1436         blocking = false;
1437       }
1438 
1439       // In libjvmci, JVMCI initialization should not deadlock with other threads

1489     // <RESULT, QUEUE> :
1490     //     <0, 1> : in compile queue, but not yet compiled
1491     //     <1, 1> : compiled but queue bit not cleared
1492     //     <1, 0> : compiled and queue bit cleared
1493     // Because we first check the queue bits then check the result bits,
1494     // we are assured that we cannot introduce a duplicate task.
1495     // Note that if we did the tests in the reverse order (i.e. check
1496     // result then check queued bit), we could get the result bit before
1497     // the compilation completed, and the queue bit after the compilation
1498     // completed, and end up introducing a "duplicate" (redundant) task.
1499     // In that case, the compiler thread should first check if a method
1500     // has already been compiled before trying to compile it.
1501     // NOTE: in the event that there are multiple compiler threads and
1502     // there is de-optimization/recompilation, things will get hairy,
1503     // and in that case it's best to protect both the testing (here) of
1504     // these bits, and their updating (here and elsewhere) under a
1505     // common lock.
1506     task = create_compile_task(queue,
1507                                compile_id, method,
1508                                osr_bci, comp_level,
1509                                hot_method, hot_count, scc_entry, compile_reason,
1510                                requires_online_compilation, blocking);
1511 
1512     if (task->is_scc() && (_sc_count > 0)) {
1513       // Put it on SC queue
1514       queue = is_c1_compile(comp_level) ? _sc1_compile_queue : _sc2_compile_queue;
1515     }
1516 
1517     if (UseLockFreeCompileQueues) {
1518       assert(queue->lock()->owned_by_self() == false, "");
1519       queue->add_pending(task);
1520     } else {
1521       queue->add(task);
1522     }
1523   }
1524 
1525   if (blocking) {
1526     wait_for_completion(task);
1527   }
1528 }
1529 
1530 SCCEntry* CompileBroker::find_scc_entry(const methodHandle& method, int osr_bci, int comp_level,
1531                                         CompileTask::CompileReason compile_reason,
1532                                         bool requires_online_compilation) {
1533   SCCEntry* scc_entry = nullptr;
1534   if (_sc_count > 0 && osr_bci == InvocationEntryBci && !requires_online_compilation && SCCache::is_on_for_read()) {
1535     // Check for cached code.
1536     if (compile_reason == CompileTask::Reason_Preload) {
1537       scc_entry = method->scc_entry();
1538       assert(scc_entry != nullptr && scc_entry->for_preload(), "sanity");
1539     } else {
1540       scc_entry = SCCache::find_code_entry(method, comp_level);
1541     }
1542   }
1543   return scc_entry;
1544 }
1545 
1546 nmethod* CompileBroker::compile_method(const methodHandle& method, int osr_bci,
1547                                        int comp_level,
1548                                        const methodHandle& hot_method, int hot_count,
1549                                        bool requires_online_compilation,
1550                                        CompileTask::CompileReason compile_reason,
1551                                        TRAPS) {
1552   // Do nothing if compilebroker is not initialized or compiles are submitted on level none
1553   if (!_initialized || comp_level == CompLevel_none) {
1554     return nullptr;
1555   }
1556 
1557 #if INCLUDE_JVMCI
1558   if (EnableJVMCI && UseJVMCICompiler &&
1559       comp_level == CompLevel_full_optimization && !ClassPrelinker::class_preloading_finished()) {
1560     return nullptr;
1561   }
1562 #endif
1563 
1564   AbstractCompiler *comp = CompileBroker::compiler(comp_level);
1565   assert(comp != nullptr, "Ensure we have a compiler");
1566 
1567 #if INCLUDE_JVMCI
1568   if (comp->is_jvmci() && !JVMCI::can_initialize_JVMCI()) {
1569     // JVMCI compilation is not yet initializable.
1570     return nullptr;
1571   }
1572 #endif
1573 
1574   DirectiveSet* directive = DirectivesStack::getMatchingDirective(method, comp);
1575   // CompileBroker::compile_method can trap and can have pending async exception.
1576   nmethod* nm = CompileBroker::compile_method(method, osr_bci, comp_level, hot_method, hot_count, requires_online_compilation, compile_reason, directive, THREAD);
1577   DirectivesStack::release(directive);
1578   return nm;
1579 }
1580 
1581 nmethod* CompileBroker::compile_method(const methodHandle& method, int osr_bci,
1582                                          int comp_level,
1583                                          const methodHandle& hot_method, int hot_count,
1584                                          bool requires_online_compilation,
1585                                          CompileTask::CompileReason compile_reason,
1586                                          DirectiveSet* directive,
1587                                          TRAPS) {
1588 
1589   // make sure arguments make sense
1590   assert(method->method_holder()->is_instance_klass(), "not an instance method");
1591   assert(osr_bci == InvocationEntryBci || (0 <= osr_bci && osr_bci < method->code_size()), "bci out of range");
1592   assert(!method->is_abstract() && (osr_bci == InvocationEntryBci || !method->is_native()), "cannot compile abstract/native methods");
1593   assert(!method->method_holder()->is_not_initialized()   ||
1594          compile_reason == CompileTask::Reason_Preload    ||
1595          compile_reason == CompileTask::Reason_Precompile ||
1596          compile_reason == CompileTask::Reason_PrecompileForPreload, "method holder must be initialized");
1597   // return quickly if possible
1598 
1599   // lock, make sure that the compilation
1600   // isn't prohibited in a straightforward way.
1601   AbstractCompiler* comp = CompileBroker::compiler(comp_level);
1602   if (comp == nullptr || compilation_is_prohibited(method, osr_bci, comp_level, directive->ExcludeOption)) {
1603     return nullptr;
1604   }
1605 
1606   if (osr_bci == InvocationEntryBci) {
1607     // standard compilation
1608     CompiledMethod* method_code = method->code();
1609     if (method_code != nullptr && method_code->is_nmethod()) {
1610       if (compilation_is_complete(method(), osr_bci, comp_level, requires_online_compilation, compile_reason)) {
1611         return (nmethod*) method_code;
1612       }
1613     }
1614     if (method->is_not_compilable(comp_level)) {
1615       return nullptr;
1616     }
1617   } else {
1618     // osr compilation
1619     // We accept a higher level osr method
1620     nmethod* nm = method->lookup_osr_nmethod_for(osr_bci, comp_level, false);
1621     if (nm != nullptr) return nm;
1622     if (method->is_not_osr_compilable(comp_level)) return nullptr;
1623   }
1624 
1625   assert(!HAS_PENDING_EXCEPTION, "No exception should be present");
1626   // some prerequisites that are compiler specific
1627   if (compile_reason != CompileTask::Reason_Preload && (comp->is_c2() || comp->is_jvmci())) {
1628     method->constants()->resolve_string_constants(CHECK_AND_CLEAR_NONASYNC_NULL);
1629     // Resolve all classes seen in the signature of the method
1630     // we are compiling.
1631     Method::load_signature_classes(method, CHECK_AND_CLEAR_NONASYNC_NULL);
1632   }
1633 
1634   // If the method is native, do the lookup in the thread requesting
1635   // the compilation. Native lookups can load code, which is not
1636   // permitted during compilation.
1637   //
1638   // Note: A native method implies non-osr compilation which is
1639   //       checked with an assertion at the entry of this method.
1640   if (method->is_native() && !method->is_method_handle_intrinsic()) {
1641     address adr = NativeLookup::lookup(method, THREAD);
1642     if (HAS_PENDING_EXCEPTION) {
1643       // In case of an exception looking up the method, we just forget
1644       // about it. The interpreter will kick-in and throw the exception.
1645       method->set_not_compilable("NativeLookup::lookup failed"); // implies is_not_osr_compilable()
1646       CLEAR_PENDING_EXCEPTION;
1647       return nullptr;

1685             method->intrinsic_id() == vmIntrinsics::_doubleToRawLongBits))) {
1686         return nullptr;
1687       }
1688 #endif // X86 && !ZERO
1689 
1690       // To properly handle the appendix argument for out-of-line calls we are using a small trampoline that
1691       // pops off the appendix argument and jumps to the target (see gen_special_dispatch in SharedRuntime).
1692       //
1693       // Since normal compiled-to-compiled calls are not able to handle such a thing we MUST generate an adapter
1694       // in this case.  If we can't generate one and use it we can not execute the out-of-line method handle calls.
1695       AdapterHandlerLibrary::create_native_wrapper(method);
1696     } else {
1697       return nullptr;
1698     }
1699   } else {
1700     // If the compiler is shut off due to code cache getting full
1701     // fail out now so blocking compiles dont hang the java thread
1702     if (!should_compile_new_jobs()) {
1703       return nullptr;
1704     }
1705     bool is_blocking = ReplayCompiles                                             ||
1706                        !directive->BackgroundCompilationOption                    ||
1707                        (compile_reason == CompileTask::Reason_Precompile)         ||
1708                        (compile_reason == CompileTask::Reason_PrecompileForPreload);
1709 	  compile_method_base(method, osr_bci, comp_level, hot_method, hot_count, compile_reason, requires_online_compilation, is_blocking, THREAD);
1710   }
1711 
1712   // return requested nmethod
1713   // We accept a higher level osr method
1714   if (osr_bci == InvocationEntryBci) {
1715     CompiledMethod* code = method->code();
1716     if (code == nullptr) {
1717       return (nmethod*) code;
1718     } else {
1719       return code->as_nmethod_or_null();
1720     }
1721   }
1722   return method->lookup_osr_nmethod_for(osr_bci, comp_level, false);
1723 }
1724 
1725 
1726 // ------------------------------------------------------------------
1727 // CompileBroker::compilation_is_complete
1728 //
1729 // See if compilation of this method is already complete.
1730 bool CompileBroker::compilation_is_complete(Method*                    method,
1731                                             int                        osr_bci,
1732                                             int                        comp_level,
1733                                             bool                       online_only,
1734                                             CompileTask::CompileReason compile_reason) {
1735   if (compile_reason == CompileTask::Reason_Precompile ||
1736       compile_reason == CompileTask::Reason_PrecompileForPreload) {
1737     return false; // FIXME: any restrictions?
1738   }
1739   bool is_osr = (osr_bci != standard_entry_bci);
1740   if (is_osr) {
1741     if (method->is_not_osr_compilable(comp_level)) {
1742       return true;
1743     } else {
1744       nmethod* result = method->lookup_osr_nmethod_for(osr_bci, comp_level, true);
1745       return (result != nullptr);
1746     }
1747   } else {
1748     if (method->is_not_compilable(comp_level)) {
1749       return true;
1750     } else {
1751       CompiledMethod* result = method->code();
1752       if (result == nullptr) {
1753         return false;
1754       }
1755       if (online_only && result->is_scc()) {
1756         return false;
1757       }
1758       bool same_level = (comp_level == result->comp_level());
1759       if (result->has_clinit_barriers()) {
1760         return !same_level; // Allow replace preloaded code with new code of the same level
1761       }
1762       return same_level;
1763     }
1764   }
1765 }
1766 
1767 
1768 /**
1769  * See if this compilation is already requested.
1770  *
1771  * Implementation note: there is only a single "is in queue" bit
1772  * for each method.  This means that the check below is overly
1773  * conservative in the sense that an osr compilation in the queue
1774  * will block a normal compilation from entering the queue (and vice
1775  * versa).  This can be remedied by a full queue search to disambiguate
1776  * cases.  If it is deemed profitable, this may be done.
1777  */
1778 bool CompileBroker::compilation_is_in_queue(const methodHandle& method) {
1779   return method->queued_for_compilation();
1780 }
1781 
1782 // ------------------------------------------------------------------

1842     if (CIStart <= id && id < CIStop) {
1843       return id;
1844     }
1845   }
1846 
1847   // Method was not in the appropriate compilation range.
1848   method->set_not_compilable_quietly("Not in requested compile id range");
1849   return 0;
1850 #else
1851   // CICountOSR is a develop flag and set to 'false' by default. In a product built,
1852   // only _compilation_id is incremented.
1853   return Atomic::add(&_compilation_id, 1);
1854 #endif
1855 }
1856 
1857 // ------------------------------------------------------------------
1858 // CompileBroker::assign_compile_id_unlocked
1859 //
1860 // Public wrapper for assign_compile_id that acquires the needed locks
1861 int CompileBroker::assign_compile_id_unlocked(Thread* thread, const methodHandle& method, int osr_bci) {

1862   return assign_compile_id(method, osr_bci);
1863 }
1864 
1865 // ------------------------------------------------------------------
1866 // CompileBroker::create_compile_task
1867 //
1868 // Create a CompileTask object representing the current request for
1869 // compilation.  Add this task to the queue.
1870 CompileTask* CompileBroker::create_compile_task(CompileQueue*       queue,
1871                                                 int                 compile_id,
1872                                                 const methodHandle& method,
1873                                                 int                 osr_bci,
1874                                                 int                 comp_level,
1875                                                 const methodHandle& hot_method,
1876                                                 int                 hot_count,
1877                                                 SCCEntry*           scc_entry,
1878                                                 CompileTask::CompileReason compile_reason,
1879                                                 bool                requires_online_compilation,
1880                                                 bool                blocking) {
1881   CompileTask* new_task = CompileTask::allocate();
1882   new_task->initialize(compile_id, method, osr_bci, comp_level,
1883                        hot_method, hot_count, scc_entry, compile_reason, queue,
1884                        requires_online_compilation, blocking);

1885   return new_task;
1886 }
1887 
1888 #if INCLUDE_JVMCI
1889 // The number of milliseconds to wait before checking if
1890 // JVMCI compilation has made progress.
1891 static const long JVMCI_COMPILATION_PROGRESS_WAIT_TIMESLICE = 1000;
1892 
1893 // The number of JVMCI compilation progress checks that must fail
1894 // before unblocking a thread waiting for a blocking compilation.
1895 static const int JVMCI_COMPILATION_PROGRESS_WAIT_ATTEMPTS = 10;
1896 
1897 /**
1898  * Waits for a JVMCI compiler to complete a given task. This thread
1899  * waits until either the task completes or it sees no JVMCI compilation
1900  * progress for N consecutive milliseconds where N is
1901  * JVMCI_COMPILATION_PROGRESS_WAIT_TIMESLICE *
1902  * JVMCI_COMPILATION_PROGRESS_WAIT_ATTEMPTS.
1903  *
1904  * @return true if this thread needs to free/recycle the task

2005  */
2006 bool CompileBroker::init_compiler_runtime() {
2007   CompilerThread* thread = CompilerThread::current();
2008   AbstractCompiler* comp = thread->compiler();
2009   // Final sanity check - the compiler object must exist
2010   guarantee(comp != nullptr, "Compiler object must exist");
2011 
2012   {
2013     // Must switch to native to allocate ci_env
2014     ThreadToNativeFromVM ttn(thread);
2015     ciEnv ci_env((CompileTask*)nullptr);
2016     // Cache Jvmti state
2017     ci_env.cache_jvmti_state();
2018     // Cache DTrace flags
2019     ci_env.cache_dtrace_flags();
2020 
2021     // Switch back to VM state to do compiler initialization
2022     ThreadInVMfromNative tv(thread);
2023 
2024     // Perform per-thread and global initializations
2025     {
2026       MutexLocker only_one (thread, CompileThread_lock);
2027       SCCache::init_table();
2028     }
2029     comp->initialize();
2030   }
2031 
2032   if (comp->is_failed()) {
2033     disable_compilation_forever();
2034     // If compiler initialization failed, no compiler thread that is specific to a
2035     // particular compiler runtime will ever start to compile methods.
2036     shutdown_compiler_runtime(comp, thread);
2037     return false;
2038   }
2039 
2040   // C1 specific check
2041   if (comp->is_c1() && (thread->get_buffer_blob() == nullptr)) {
2042     warning("Initialization of %s thread failed (no space to run compilers)", thread->name());
2043     return false;
2044   }
2045 
2046   return true;
2047 }
2048 
2049 void CompileBroker::free_buffer_blob_if_allocated(CompilerThread* thread) {
2050   BufferBlob* blob = thread->get_buffer_blob();
2051   if (blob != nullptr) {
2052     blob->purge(true /* free_code_cache_data */, true /* unregister_nmethod */);
2053     MutexLocker mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
2054     CodeCache::free(blob);
2055   }
2056 }
2057 
2058 /**
2059  * If C1 and/or C2 initialization failed, we shut down all compilation.
2060  * We do this to keep things simple. This can be changed if it ever turns
2061  * out to be a problem.
2062  */
2063 void CompileBroker::shutdown_compiler_runtime(AbstractCompiler* comp, CompilerThread* thread) {
2064   free_buffer_blob_if_allocated(thread);
2065 
2066   log_info(compilation)("shutdown_compiler_runtime: " INTPTR_FORMAT, p2i(thread));
2067 
2068   if (comp->should_perform_shutdown()) {
2069     // There are two reasons for shutting down the compiler
2070     // 1) compiler runtime initialization failed
2071     // 2) The code cache is full and the following flag is set: -XX:-UseCodeCacheFlushing
2072     warning("%s initialization failed. Shutting down all compilers", comp->name());
2073 
2074     // Only one thread per compiler runtime object enters here
2075     // Set state to shut down
2076     comp->set_shut_down();
2077 
2078     // Delete all queued compilation tasks to make compiler threads exit faster.
2079     if (_c1_compile_queue != nullptr) {
2080       _c1_compile_queue->free_all();
2081     }
2082 
2083     if (_c2_compile_queue != nullptr) {
2084       _c2_compile_queue->free_all();
2085     }
2086 
2087     if (_c3_compile_queue != nullptr) {
2088       _c3_compile_queue->free_all();
2089     }
2090 
2091     // Set flags so that we continue execution with using interpreter only.
2092     UseCompiler    = false;
2093     UseInterpreter = true;
2094 
2095     // We could delete compiler runtimes also. However, there are references to
2096     // the compiler runtime(s) (e.g.,  nmethod::is_compiled_by_c1()) which then
2097     // fail. This can be done later if necessary.
2098   }
2099 }
2100 
2101 /**
2102  * Helper function to create new or reuse old CompileLog.
2103  */
2104 CompileLog* CompileBroker::get_log(CompilerThread* ct) {
2105   if (!LogCompilation) return nullptr;
2106 
2107   AbstractCompiler *compiler = ct->compiler();
2108   bool jvmci = JVMCI_ONLY( compiler->is_jvmci() ||) false;
2109   bool c1 = compiler->is_c1();
2110   jobject* compiler_objects = c1 ? _compiler1_objects : (_c3_count == 0 ? _compiler2_objects : (jvmci ? _compiler2_objects : _compiler3_objects));
2111   assert(compiler_objects != nullptr, "must be initialized at this point");
2112   CompileLog** logs = c1 ? _compiler1_logs : (_c3_count == 0 ? _compiler2_logs : (jvmci ? _compiler2_logs : _compiler3_logs));
2113   assert(logs != nullptr, "must be initialized at this point");
2114   int count = c1 ? _c1_count : (_c3_count == 0 ? _c2_count : (jvmci ? _c2_count : _c3_count));
2115 
2116   if (ct->queue() == _sc1_compile_queue || ct->queue() == _sc2_compile_queue) {
2117     compiler_objects = _sc_objects;
2118     logs  = _sc_logs;
2119     count = _sc_count;
2120   }
2121   // Find Compiler number by its threadObj.
2122   oop compiler_obj = ct->threadObj();
2123   int compiler_number = 0;
2124   bool found = false;
2125   for (; compiler_number < count; compiler_number++) {
2126     if (JNIHandles::resolve_non_null(compiler_objects[compiler_number]) == compiler_obj) {
2127       found = true;
2128       break;
2129     }
2130   }
2131   assert(found, "Compiler must exist at this point");
2132 
2133   // Determine pointer for this thread's log.
2134   CompileLog** log_ptr = &logs[compiler_number];
2135 
2136   // Return old one if it exists.
2137   CompileLog* log = *log_ptr;
2138   if (log != nullptr) {
2139     ct->init_log(log);
2140     return log;

2178     log->stamp();
2179     log->end_elem();
2180   }
2181 
2182   // If compiler thread/runtime initialization fails, exit the compiler thread
2183   if (!init_compiler_runtime()) {
2184     return;
2185   }
2186 
2187   thread->start_idle_timer();
2188 
2189   // Poll for new compilation tasks as long as the JVM runs. Compilation
2190   // should only be disabled if something went wrong while initializing the
2191   // compiler runtimes. This, in turn, should not happen. The only known case
2192   // when compiler runtime initialization fails is if there is not enough free
2193   // space in the code cache to generate the necessary stubs, etc.
2194   while (!is_compilation_disabled_forever()) {
2195     // We need this HandleMark to avoid leaking VM handles.
2196     HandleMark hm(thread);
2197 
2198     CompilationPolicy::recompilation_step(RecompilationWorkUnitSize, thread);
2199 
2200     CompileTask* task = queue->get(thread);
2201 
2202     if (task == nullptr) {
2203       if (UseDynamicNumberOfCompilerThreads) {
2204         // Access compiler_count under lock to enforce consistency.
2205         MutexLocker only_one(CompileThread_lock);
2206         if (can_remove(thread, true)) {
2207           if (trace_compiler_threads()) {
2208             ResourceMark rm;
2209             stringStream msg;
2210             msg.print("Removing compiler thread %s after " JLONG_FORMAT " ms idle time",
2211                       thread->name(), thread->idle_time_millis());
2212             print_compiler_threads(msg);
2213           }
2214 
2215           // Notify compiler that the compiler thread is about to stop
2216           thread->compiler()->stopping_compiler_thread(thread);
2217 
2218           free_buffer_blob_if_allocated(thread);
2219           return; // Stop this thread.
2220         }
2221       }
2222     } else {
2223       // Assign the task to the current thread.  Mark this compilation
2224       // thread as active for the profiler.
2225       // CompileTaskWrapper also keeps the Method* from being deallocated if redefinition
2226       // occurs after fetching the compile task off the queue.
2227       CompileTaskWrapper ctw(task);
2228       methodHandle method(thread, task->method());
2229 
2230       // Never compile a method if breakpoints are present in it
2231       if (method()->number_of_breakpoints() == 0) {
2232         // Compile the method.
2233         if ((UseCompiler || AlwaysCompileLoopMethods) && CompileBroker::should_compile_new_jobs()) {
2234           invoke_compiler_on_method(task);
2235           thread->start_idle_timer();
2236         } else {
2237           // After compilation is disabled, remove remaining methods from queue
2238           method->clear_queued_for_compilation();
2239           method->set_pending_queue_processed(false);
2240           task->set_failure_reason("compilation is disabled");
2241         }
2242       } else {
2243         task->set_failure_reason("breakpoints are present");
2244       }
2245 
2246       if (UseDynamicNumberOfCompilerThreads) {
2247         possibly_add_compiler_threads(thread);
2248         assert(!thread->has_pending_exception(), "should have been handled");
2249       }
2250     }
2251   }
2252 
2253   // Shut down compiler runtime
2254   shutdown_compiler_runtime(thread->compiler(), thread);
2255 }
2256 
2257 // ------------------------------------------------------------------
2258 // CompileBroker::init_compiler_thread_log
2259 //

2407 
2408 // Acquires Compilation_lock and waits for it to be notified
2409 // as long as WhiteBox::compilation_locked is true.
2410 static void whitebox_lock_compilation() {
2411   MonitorLocker locker(Compilation_lock, Mutex::_no_safepoint_check_flag);
2412   while (WhiteBox::compilation_locked) {
2413     locker.wait();
2414   }
2415 }
2416 
2417 // ------------------------------------------------------------------
2418 // CompileBroker::invoke_compiler_on_method
2419 //
2420 // Compile a method.
2421 //
2422 void CompileBroker::invoke_compiler_on_method(CompileTask* task) {
2423   task->print_ul();
2424   elapsedTimer time;
2425 
2426   DirectiveSet* directive = task->directive();




2427 
2428   CompilerThread* thread = CompilerThread::current();
2429   ResourceMark rm(thread);
2430 
2431   if (CompilationLog::log() != nullptr) {
2432     CompilationLog::log()->log_compile(thread, task);
2433   }
2434 
2435   // Common flags.
2436   int compile_id = task->compile_id();
2437   int osr_bci = task->osr_bci();
2438   bool is_osr = (osr_bci != standard_entry_bci);
2439   bool should_log = (thread->log() != nullptr);
2440   bool should_break = false;
2441   const int task_level = task->comp_level();
2442   AbstractCompiler* comp = task->compiler();
2443   CompileTrainingData* tdata = task->training_data();
2444   assert(tdata == nullptr || TrainingData::need_data(), "");
2445   {
2446     // create the handle inside it's own block so it can't
2447     // accidentally be referenced once the thread transitions to
2448     // native.  The NoHandleMark before the transition should catch
2449     // any cases where this occurs in the future.
2450     methodHandle method(thread, task->method());
2451 
2452     assert(!method->is_native(), "no longer compile natives");
2453 
2454     // Update compile information when using perfdata.
2455     if (UsePerfData) {
2456       update_compile_perf_data(thread, method, is_osr);
2457     }
2458 
2459     DTRACE_METHOD_COMPILE_BEGIN_PROBE(method, compiler_name(task_level));
2460   }
2461 
2462   if (tdata != nullptr) {
2463     tdata->record_compilation_start(task);
2464   }
2465 
2466   should_break = directive->BreakAtCompileOption || task->check_break_at_flags();
2467   if (should_log && !directive->LogOption) {
2468     should_log = false;
2469   }
2470 
2471   // Allocate a new set of JNI handles.
2472   JNIHandleMark jhm(thread);
2473   Method* target_handle = task->method();
2474   int compilable = ciEnv::MethodCompilable;
2475   const char* failure_reason = nullptr;
2476   bool failure_reason_on_C_heap = false;
2477   const char* retry_message = nullptr;
2478 
2479 #if INCLUDE_JVMCI
2480   if (UseJVMCICompiler && comp != nullptr && comp->is_jvmci()) {
2481     JVMCICompiler* jvmci = (JVMCICompiler*) comp;
2482 
2483     TraceTime t1("compilation", &time);
2484     EventCompilation event;
2485     JVMCICompileState compile_state(task, jvmci);

2552     }
2553     assert(thread->env() == &ci_env, "set by ci_env");
2554     // The thread-env() field is cleared in ~CompileTaskWrapper.
2555 
2556     // Cache Jvmti state
2557     bool method_is_old = ci_env.cache_jvmti_state();
2558 
2559     // Skip redefined methods
2560     if (method_is_old) {
2561       ci_env.record_method_not_compilable("redefined method", true);
2562     }
2563 
2564     // Cache DTrace flags
2565     ci_env.cache_dtrace_flags();
2566 
2567     ciMethod* target = ci_env.get_method_from_handle(target_handle);
2568 
2569     TraceTime t1("compilation", &time);
2570     EventCompilation event;
2571 
2572     bool install_code = true;
2573     if (comp == nullptr) {
2574       ci_env.record_method_not_compilable("no compiler");
2575     } else if (!ci_env.failing()) {
2576       if (WhiteBoxAPI && WhiteBox::compilation_locked) {
2577         whitebox_lock_compilation();
2578       }
2579       if (StoreCachedCode && task->is_precompiled()) {
2580         install_code = false; // not suitable in the current context
2581       }
2582       comp->compile_method(&ci_env, target, osr_bci, install_code, directive);
2583 
2584       /* Repeat compilation without installing code for profiling purposes */
2585       int repeat_compilation_count = directive->RepeatCompilationOption;
2586       while (repeat_compilation_count > 0) {
2587         ResourceMark rm(thread);
2588         task->print_ul("NO CODE INSTALLED");
2589         comp->compile_method(&ci_env, target, osr_bci, false, directive);
2590         repeat_compilation_count--;
2591       }
2592     }
2593 
2594     DirectivesStack::release(directive);
2595 
2596     if (!ci_env.failing() && !task->is_success() && install_code) {
2597       assert(ci_env.failure_reason() != nullptr, "expect failure reason");
2598       assert(false, "compiler should always document failure: %s", ci_env.failure_reason());
2599       // The compiler elected, without comment, not to register a result.
2600       // Do not attempt further compilations of this method.
2601       ci_env.record_method_not_compilable("compile failed");
2602     }
2603 
2604     // Copy this bit to the enclosing block:
2605     compilable = ci_env.compilable();
2606 
2607     if (ci_env.failing()) {
2608       failure_reason = ci_env.failure_reason();
2609       retry_message = ci_env.retry_message();
2610       ci_env.report_failure(failure_reason);
2611     }
2612 
2613     if (ci_env.failing()) {
2614       handle_compile_error(thread, task, &ci_env, compilable, failure_reason);
2615     }
2616     if (event.should_commit()) {
2617       post_compilation_event(event, task);
2618     }
2619   }
2620 
2621   if (failure_reason != nullptr) {
2622     task->set_failure_reason(failure_reason, failure_reason_on_C_heap);
2623     if (CompilationLog::log() != nullptr) {
2624       CompilationLog::log()->log_failure(thread, task, failure_reason, retry_message);
2625     }
2626     if (PrintCompilation) {
2627       FormatBufferResource msg = retry_message != nullptr ?
2628         FormatBufferResource("COMPILE SKIPPED: %s (%s)", failure_reason, retry_message) :
2629         FormatBufferResource("COMPILE SKIPPED: %s",      failure_reason);
2630       task->print(tty, msg);
2631     }
2632   }
2633 
2634   if (tdata != nullptr) {
2635     tdata->record_compilation_end(task);
2636   }
2637 
2638   if (directive->PrintCompilationOption) {
2639     ResourceMark rm;
2640     task->print_tty();
2641   }
2642 
2643   methodHandle method(thread, task->method());
2644 
2645   DTRACE_METHOD_COMPILE_END_PROBE(method, compiler_name(task_level), task->is_success());
2646 
2647   collect_statistics(thread, time, task);
2648 
2649   if (PrintCompilation && PrintCompilation2) {
2650     tty->print("%7d ", (int) tty->time_stamp().milliseconds());  // print timestamp
2651     tty->print("%4d ", compile_id);    // print compilation number
2652     tty->print("%s ", (is_osr ? "%" : (task->is_scc() ? "A" : " ")));
2653     if (task->is_success()) {
2654       tty->print("size: %d(%d) ", task->nm_total_size(), task->nm_insts_size());
2655     }
2656     tty->print_cr("time: %d inlined: %d bytes", (int)time.milliseconds(), task->num_inlined_bytecodes());
2657   }
2658 
2659   Log(compilation, codecache) log;
2660   if (log.is_debug()) {
2661     LogStream ls(log.debug());
2662     codecache_print(&ls, /* detailed= */ false);
2663   }
2664   if (PrintCodeCacheOnCompilation) {
2665     codecache_print(/* detailed= */ false);
2666   }
2667   // Disable compilation, if required.
2668   switch (compilable) {
2669   case ciEnv::MethodCompilable_never:
2670     if (is_osr)
2671       method->set_not_osr_compilable_quietly("MethodCompilable_never");
2672     else
2673       method->set_not_compilable_quietly("MethodCompilable_never");
2674     break;
2675   case ciEnv::MethodCompilable_not_at_tier:
2676     if (is_osr)
2677       method->set_not_osr_compilable_quietly("MethodCompilable_not_at_tier", task_level);
2678     else
2679       method->set_not_compilable_quietly("MethodCompilable_not_at_tier", task_level);
2680     break;
2681   }
2682 
2683   // Note that the queued_for_compilation bits are cleared without
2684   // protection of a mutex. [They were set by the requester thread,
2685   // when adding the task to the compile queue -- at which time the
2686   // compile queue lock was held. Subsequently, we acquired the compile
2687   // queue lock to get this task off the compile queue; thus (to belabour
2688   // the point somewhat) our clearing of the bits must be occurring
2689   // only after the setting of the bits. See also 14012000 above.
2690   method->clear_queued_for_compilation();
2691   method->set_pending_queue_processed(false);
2692 }
2693 
2694 /**
2695  * The CodeCache is full. Print warning and disable compilation.
2696  * Schedule code cache cleaning so compilation can continue later.
2697  * This function needs to be called only from CodeCache::allocate(),
2698  * since we currently handle a full code cache uniformly.
2699  */
2700 void CompileBroker::handle_full_code_cache(CodeBlobType code_blob_type) {
2701   UseInterpreter = true;
2702   if (UseCompiler || AlwaysCompileLoopMethods ) {
2703     if (xtty != nullptr) {
2704       stringStream s;
2705       // Dump code cache state into a buffer before locking the tty,
2706       // because log_state() will use locks causing lock conflicts.
2707       CodeCache::log_state(&s);
2708       // Lock to prevent tearing
2709       ttyLocker ttyl;
2710       xtty->begin_elem("code_cache_full");
2711       xtty->print("%s", s.freeze());

2784 // CompileBroker::collect_statistics
2785 //
2786 // Collect statistics about the compilation.
2787 
2788 void CompileBroker::collect_statistics(CompilerThread* thread, elapsedTimer time, CompileTask* task) {
2789   bool success = task->is_success();
2790   methodHandle method (thread, task->method());
2791   int compile_id = task->compile_id();
2792   bool is_osr = (task->osr_bci() != standard_entry_bci);
2793   const int comp_level = task->comp_level();
2794   CompilerCounters* counters = thread->counters();
2795 
2796   MutexLocker locker(CompileStatistics_lock);
2797 
2798   // _perf variables are production performance counters which are
2799   // updated regardless of the setting of the CITime and CITimeEach flags
2800   //
2801 
2802   // account all time, including bailouts and failures in this counter;
2803   // C1 and C2 counters are counting both successful and unsuccessful compiles
2804   _t_total_compilation.add(&time);
2805 
2806   if (!success) {
2807     _total_bailout_count++;
2808     if (UsePerfData) {
2809       _perf_last_failed_method->set_value(counters->current_method());
2810       _perf_last_failed_type->set_value(counters->compile_type());
2811       _perf_total_bailout_count->inc();
2812     }
2813     _t_bailedout_compilation.add(&time);
2814 
2815     if (CITime || log_is_enabled(Info, init)) {
2816       CompilerStatistics* stats = nullptr;
2817       if (task->is_scc()) {
2818         int level = task->preload() ? CompLevel_full_optimization : (comp_level - 1);
2819         stats = &_scc_stats_per_level[level];
2820       } else {
2821         stats = &_stats_per_level[comp_level-1];
2822       }
2823       stats->_bailout.update(time, 0);
2824     }
2825   } else if (!task->is_success()) {
2826     if (UsePerfData) {
2827       _perf_last_invalidated_method->set_value(counters->current_method());
2828       _perf_last_invalidated_type->set_value(counters->compile_type());
2829       _perf_total_invalidated_count->inc();
2830     }
2831     _total_invalidated_count++;
2832     _t_invalidated_compilation.add(&time);
2833 
2834     if (CITime || log_is_enabled(Info, init)) {
2835       CompilerStatistics* stats = nullptr;
2836       if (task->is_scc()) {
2837         int level = task->preload() ? CompLevel_full_optimization : (comp_level - 1);
2838         stats = &_scc_stats_per_level[level];
2839       } else {
2840         stats = &_stats_per_level[comp_level-1];
2841       }
2842       stats->_invalidated.update(time, 0);
2843     }
2844   } else {
2845     // Compilation succeeded
2846 
2847     // update compilation ticks - used by the implementation of
2848     // java.lang.management.CompilationMXBean
2849     _perf_total_compilation->inc(time.ticks());
2850     _peak_compilation_time = time.milliseconds() > _peak_compilation_time ? time.milliseconds() : _peak_compilation_time;
2851 
2852     if (CITime || log_is_enabled(Info, init)) {
2853       int bytes_compiled = method->code_size() + task->num_inlined_bytecodes();
2854       if (is_osr) {
2855         _t_osr_compilation.add(&time);
2856         _sum_osr_bytes_compiled += bytes_compiled;
2857       } else {
2858         _t_standard_compilation.add(&time);
2859         _sum_standard_bytes_compiled += method->code_size() + task->num_inlined_bytecodes();
2860       }
2861 
2862       // Collect statistic per compilation level
2863       if (task->is_scc()) {
2864         _scc_stats._standard.update(time, bytes_compiled);
2865         _scc_stats._nmethods_size += task->nm_total_size();
2866         _scc_stats._nmethods_code_size += task->nm_insts_size();
2867         int level = task->preload() ? CompLevel_full_optimization : (comp_level - 1);
2868         CompilerStatistics* stats = &_scc_stats_per_level[level];
2869         stats->_standard.update(time, bytes_compiled);
2870         stats->_nmethods_size += task->nm_total_size();
2871         stats->_nmethods_code_size += task->nm_insts_size();
2872       } else if (comp_level > CompLevel_none && comp_level <= CompLevel_full_optimization) {
2873         CompilerStatistics* stats = &_stats_per_level[comp_level-1];
2874         if (is_osr) {
2875           stats->_osr.update(time, bytes_compiled);
2876         } else {
2877           stats->_standard.update(time, bytes_compiled);
2878         }
2879         stats->_nmethods_size += task->nm_total_size();
2880         stats->_nmethods_code_size += task->nm_insts_size();
2881       } else {
2882         assert(false, "CompilerStatistics object does not exist for compilation level %d", comp_level);
2883       }
2884 
2885       // Collect statistic per compiler
2886       AbstractCompiler* comp = task->compiler();
2887       if (comp && !task->is_scc()) {
2888         CompilerStatistics* stats = comp->stats();
2889         if (is_osr) {
2890           stats->_osr.update(time, bytes_compiled);
2891         } else {
2892           stats->_standard.update(time, bytes_compiled);
2893         }
2894         stats->_nmethods_size += task->nm_total_size();
2895         stats->_nmethods_code_size += task->nm_insts_size();
2896       } else if (!task->is_scc()) { // if (!comp)
2897         assert(false, "Compiler object must exist");
2898       }
2899     }
2900 
2901     if (UsePerfData) {
2902       // save the name of the last method compiled
2903       _perf_last_method->set_value(counters->current_method());
2904       _perf_last_compile_type->set_value(counters->compile_type());
2905       _perf_last_compile_size->set_value(method->code_size() +
2906                                          task->num_inlined_bytecodes());
2907       if (is_osr) {
2908         _perf_osr_compilation->inc(time.ticks());
2909         _perf_sum_osr_bytes_compiled->inc(method->code_size() + task->num_inlined_bytecodes());
2910       } else {
2911         _perf_standard_compilation->inc(time.ticks());
2912         _perf_sum_standard_bytes_compiled->inc(method->code_size() + task->num_inlined_bytecodes());
2913       }
2914     }
2915 
2916     if (CITimeEach) {

2939       _total_standard_compile_count++;
2940     }
2941   }
2942   // set the current method for the thread to null
2943   if (UsePerfData) counters->set_current_method("");
2944 }
2945 
2946 const char* CompileBroker::compiler_name(int comp_level) {
2947   AbstractCompiler *comp = CompileBroker::compiler(comp_level);
2948   if (comp == nullptr) {
2949     return "no compiler";
2950   } else {
2951     return (comp->name());
2952   }
2953 }
2954 
2955 jlong CompileBroker::total_compilation_ticks() {
2956   return _perf_total_compilation != nullptr ? _perf_total_compilation->get_value() : 0;
2957 }
2958 
2959 void CompileBroker::log_not_entrant(nmethod* nm) {
2960   _total_not_entrant_count++;
2961   if (CITime || log_is_enabled(Info, init)) {
2962     CompilerStatistics* stats = nullptr;
2963     int level = nm->comp_level();
2964     if (nm->is_scc()) {
2965       if (nm->preloaded()) {
2966         assert(level == CompLevel_full_optimization, "%d", level);
2967         level = CompLevel_full_optimization + 1;
2968       }
2969       stats = &_scc_stats_per_level[level - 1];
2970     } else {
2971       stats = &_stats_per_level[level - 1];
2972     }
2973     stats->_made_not_entrant._count++;
2974   }
2975 }
2976 
2977 void CompileBroker::print_times(const char* name, CompilerStatistics* stats) {
2978   tty->print_cr("  %s {speed: %6.3f bytes/s; standard: %6.3f s, %u bytes, %u methods; osr: %6.3f s, %u bytes, %u methods; nmethods_size: %u bytes; nmethods_code_size: %u bytes}",
2979                 name, stats->bytes_per_second(),
2980                 stats->_standard._time.seconds(), stats->_standard._bytes, stats->_standard._count,
2981                 stats->_osr._time.seconds(), stats->_osr._bytes, stats->_osr._count,
2982                 stats->_nmethods_size, stats->_nmethods_code_size);
2983 }
2984 
2985 static void print_helper(outputStream* st, const char* name, CompilerStatistics::Data data, bool print_time = true) {
2986   if (data._count > 0) {
2987     st->print("; %s: %4u methods", name, data._count);
2988     if (print_time) {
2989       st->print(" (in %.3fs)", data._time.seconds());
2990     }
2991   }
2992 }
2993 
2994 static void print_tier_helper(outputStream* st, const char* prefix, int tier, CompilerStatistics* stats) {
2995   st->print("    %s%d: %5u methods", prefix, tier, stats->_standard._count);
2996   if (stats->_standard._count > 0) {
2997     st->print(" (in %.3fs)", stats->_standard._time.seconds());
2998   }
2999   print_helper(st, "osr",     stats->_osr);
3000   print_helper(st, "bailout", stats->_bailout);
3001   print_helper(st, "invalid", stats->_invalidated);
3002   print_helper(st, "not_entrant", stats->_made_not_entrant, false);
3003   st->cr();
3004 }
3005 
3006 static void print_queue_info(outputStream* st, CompileQueue* queue) {
3007   if (queue != nullptr) {
3008     MutexLocker ml(queue->lock());
3009 
3010     uint  total_cnt = 0;
3011     uint active_cnt = 0;
3012     for (JavaThread* jt : *ThreadsSMRSupport::get_java_thread_list()) {
3013       guarantee(jt != nullptr, "");
3014       if (jt->is_Compiler_thread()) {
3015         CompilerThread* ct = (CompilerThread*)jt;
3016 
3017         guarantee(ct != nullptr, "");
3018         if (ct->queue() == queue) {
3019           ++total_cnt;
3020           CompileTask* task = ct->task();
3021           if (task != nullptr) {
3022             ++active_cnt;
3023           }
3024         }
3025       }
3026     }
3027 
3028     st->print("  %s (%d active / %d total threads): %u tasks",
3029               queue->name(), active_cnt, total_cnt, queue->size());
3030     if (queue->size() > 0) {
3031       uint counts[] = {0, 0, 0, 0, 0}; // T1 ... T5
3032       for (CompileTask* task = queue->first(); task != nullptr; task = task->next()) {
3033         int tier = task->comp_level();
3034         if (task->is_scc() && task->preload()) {
3035           assert(tier == CompLevel_full_optimization, "%d", tier);
3036           tier = CompLevel_full_optimization + 1;
3037         }
3038         counts[tier-1]++;
3039       }
3040       st->print(":");
3041       for (int tier = CompLevel_simple; tier <= CompilationPolicy::highest_compile_level() + 1; tier++) {
3042         uint cnt = counts[tier-1];
3043         if (cnt > 0) {
3044           st->print(" T%d: %u tasks;", tier, cnt);
3045         }
3046       }
3047     }
3048     st->cr();
3049 
3050 //    for (JavaThread* jt : *ThreadsSMRSupport::get_java_thread_list()) {
3051 //      guarantee(jt != nullptr, "");
3052 //      if (jt->is_Compiler_thread()) {
3053 //        CompilerThread* ct = (CompilerThread*)jt;
3054 //
3055 //        guarantee(ct != nullptr, "");
3056 //        if (ct->queue() == queue) {
3057 //          ResourceMark rm;
3058 //          CompileTask* task = ct->task();
3059 //          st->print("    %s: ", ct->name_raw());
3060 //          if (task != nullptr) {
3061 //            task->print(st, nullptr, true /*short_form*/, false /*cr*/);
3062 //          }
3063 //          st->cr();
3064 //        }
3065 //      }
3066 //    }
3067   }
3068 }
3069 void CompileBroker::print_statistics_on(outputStream* st) {
3070   st->print_cr("  Total: %u methods; %u bailouts, %u invalidated, %u non_entrant",
3071                _total_compile_count, _total_bailout_count, _total_invalidated_count, _total_not_entrant_count);
3072   for (int tier = CompLevel_simple; tier <= CompilationPolicy::highest_compile_level(); tier++) {
3073     print_tier_helper(st, "Tier", tier, &_stats_per_level[tier-1]);
3074   }
3075   st->cr();
3076 
3077   if (LoadCachedCode || StoreCachedCode) {
3078     for (int tier = CompLevel_simple; tier <= CompilationPolicy::highest_compile_level() + 1; tier++) {
3079       if (tier != CompLevel_full_profile) {
3080         print_tier_helper(st, "SC T", tier, &_scc_stats_per_level[tier - 1]);
3081       }
3082     }
3083     st->cr();
3084   }
3085 
3086   print_queue_info(st, _c1_compile_queue);
3087   print_queue_info(st, _c2_compile_queue);
3088   print_queue_info(st, _c3_compile_queue);
3089   print_queue_info(st, _sc1_compile_queue);
3090   print_queue_info(st, _sc2_compile_queue);
3091 }
3092 
3093 void CompileBroker::print_times(bool per_compiler, bool aggregate) {
3094   if (per_compiler) {
3095     if (aggregate) {
3096       tty->cr();
3097       tty->print_cr("[%dms] Individual compiler times (for compiled methods only)", (int)tty->time_stamp().milliseconds());
3098       tty->print_cr("------------------------------------------------");
3099       tty->cr();
3100     }
3101     for (unsigned int i = 0; i < sizeof(_compilers) / sizeof(AbstractCompiler*); i++) {
3102       AbstractCompiler* comp = _compilers[i];
3103       if (comp != nullptr) {
3104         print_times(comp->name(), comp->stats());
3105       }
3106     }
3107     if (_scc_stats._standard._count > 0) {
3108       print_times("SC", &_scc_stats);
3109     }
3110     if (aggregate) {
3111       tty->cr();
3112       tty->print_cr("Individual compilation Tier times (for compiled methods only)");
3113       tty->print_cr("------------------------------------------------");
3114       tty->cr();
3115     }
3116     char tier_name[256];
3117     for (int tier = CompLevel_simple; tier <= CompilationPolicy::highest_compile_level(); tier++) {
3118       CompilerStatistics* stats = &_stats_per_level[tier-1];
3119       os::snprintf_checked(tier_name, sizeof(tier_name), "Tier%d", tier);
3120       print_times(tier_name, stats);
3121     }
3122     for (int tier = CompLevel_simple; tier <= CompilationPolicy::highest_compile_level() + 1; tier++) {
3123       CompilerStatistics* stats = &_scc_stats_per_level[tier-1];
3124       if (stats->_standard._bytes > 0) {
3125         os::snprintf_checked(tier_name, sizeof(tier_name), "SC T%d", tier);
3126         print_times(tier_name, stats);
3127       }
3128     }
3129   }
3130 
3131   if (!aggregate) {
3132     return;
3133   }
3134 
3135   elapsedTimer standard_compilation = CompileBroker::_t_standard_compilation;
3136   elapsedTimer osr_compilation = CompileBroker::_t_osr_compilation;
3137   elapsedTimer total_compilation = CompileBroker::_t_total_compilation;
3138 
3139   uint standard_bytes_compiled = CompileBroker::_sum_standard_bytes_compiled;
3140   uint osr_bytes_compiled = CompileBroker::_sum_osr_bytes_compiled;
3141 
3142   uint standard_compile_count = CompileBroker::_total_standard_compile_count;
3143   uint osr_compile_count = CompileBroker::_total_osr_compile_count;
3144   uint total_compile_count = CompileBroker::_total_compile_count;
3145   uint total_bailout_count = CompileBroker::_total_bailout_count;
3146   uint total_invalidated_count = CompileBroker::_total_invalidated_count;
3147 
3148   uint nmethods_code_size = CompileBroker::_sum_nmethod_code_size;

3150 
3151   tty->cr();
3152   tty->print_cr("Accumulated compiler times");
3153   tty->print_cr("----------------------------------------------------------");
3154                //0000000000111111111122222222223333333333444444444455555555556666666666
3155                //0123456789012345678901234567890123456789012345678901234567890123456789
3156   tty->print_cr("  Total compilation time   : %7.3f s", total_compilation.seconds());
3157   tty->print_cr("    Standard compilation   : %7.3f s, Average : %2.3f s",
3158                 standard_compilation.seconds(),
3159                 standard_compile_count == 0 ? 0.0 : standard_compilation.seconds() / standard_compile_count);
3160   tty->print_cr("    Bailed out compilation : %7.3f s, Average : %2.3f s",
3161                 CompileBroker::_t_bailedout_compilation.seconds(),
3162                 total_bailout_count == 0 ? 0.0 : CompileBroker::_t_bailedout_compilation.seconds() / total_bailout_count);
3163   tty->print_cr("    On stack replacement   : %7.3f s, Average : %2.3f s",
3164                 osr_compilation.seconds(),
3165                 osr_compile_count == 0 ? 0.0 : osr_compilation.seconds() / osr_compile_count);
3166   tty->print_cr("    Invalidated            : %7.3f s, Average : %2.3f s",
3167                 CompileBroker::_t_invalidated_compilation.seconds(),
3168                 total_invalidated_count == 0 ? 0.0 : CompileBroker::_t_invalidated_compilation.seconds() / total_invalidated_count);
3169 
3170   if (StoreCachedCode || LoadCachedCode) { // Check flags because SC cache could be closed already
3171     tty->cr();
3172     SCCache::print_timers_on(tty);
3173   }
3174   AbstractCompiler *comp = compiler(CompLevel_simple);
3175   if (comp != nullptr) {
3176     tty->cr();
3177     comp->print_timers();
3178   }
3179   comp = compiler(CompLevel_full_optimization);
3180   if (comp != nullptr) {
3181     tty->cr();
3182     comp->print_timers();
3183   }
3184   comp = _compilers[2];
3185   if (comp != nullptr) {
3186     tty->cr();
3187     comp->print_timers();
3188   }
3189 #if INCLUDE_JVMCI
3190   if (EnableJVMCI) {
3191     JVMCICompiler *jvmci_comp = JVMCICompiler::instance(false, JavaThread::current_or_null());
3192     if (jvmci_comp != nullptr && jvmci_comp != comp) {
3193       tty->cr();
3194       jvmci_comp->print_timers();
3195     }
3196   }
3197 #endif
3198 
3199   tty->cr();
3200   tty->print_cr("  Total compiled methods    : %8u methods", total_compile_count);
3201   tty->print_cr("    Standard compilation    : %8u methods", standard_compile_count);
3202   tty->print_cr("    On stack replacement    : %8u methods", osr_compile_count);
3203   uint tcb = osr_bytes_compiled + standard_bytes_compiled;
3204   tty->print_cr("  Total compiled bytecodes  : %8u bytes", tcb);
3205   tty->print_cr("    Standard compilation    : %8u bytes", standard_bytes_compiled);
3206   tty->print_cr("    On stack replacement    : %8u bytes", osr_bytes_compiled);
3207   double tcs = total_compilation.seconds();
3208   uint bps = tcs == 0.0 ? 0 : (uint)(tcb / tcs);
< prev index next >