< prev index next >

src/hotspot/share/compiler/compileBroker.cpp

Print this page

   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 


  25 #include "classfile/javaClasses.inline.hpp"
  26 #include "classfile/symbolTable.hpp"
  27 #include "classfile/vmClasses.hpp"
  28 #include "classfile/vmSymbols.hpp"
  29 #include "code/codeCache.hpp"
  30 #include "code/codeHeapState.hpp"
  31 #include "code/dependencyContext.hpp"

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

  37 #include "compiler/compilerEvent.hpp"
  38 #include "compiler/compilerOracle.hpp"
  39 #include "compiler/directivesParser.hpp"

  40 #include "gc/shared/memAllocator.hpp"
  41 #include "interpreter/linkResolver.hpp"
  42 #include "jfr/jfrEvents.hpp"
  43 #include "jvm.h"
  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/method.inline.hpp"
  50 #include "oops/methodData.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 
  92 #define DTRACE_METHOD_COMPILE_BEGIN_PROBE(method, comp_name)             \
  93   {                                                                      \
  94     Symbol* klass_name = (method)->klass_name();                         \
  95     Symbol* name = (method)->name();                                     \
  96     Symbol* signature = (method)->signature();                           \

 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     bool found_waiter = false;
 369     {
 370       MutexLocker ct_lock(current->lock());
 371       assert(current->waiting_for_completion_count() <= 1, "more than one thread are waiting for task");
 372       if (current->waiting_for_completion_count() > 0) {
 373         // If another thread waits for this task, we must wake them up
 374         // so they will stop waiting and free the task.
 375         current->lock()->notify();
 376         found_waiter = true;
 377       }
 378     }
 379     if (!found_waiter) {
 380       // If no one was waiting for this task, we need to free it ourselves. In this case, the task
 381       // is also certainly unlocked, because, again, there is no waiter.
 382       // Otherwise, by convention, it's the waiters responsibility to free the task.
 383       // Put the task back on the freelist.
 384       CompileTask::free(current);
 385     }
 386   }
 387   _first = nullptr;
 388   _last = nullptr;
 389 
 390   // Wake up all threads that block on the queue.
 391   MethodCompileQueue_lock->notify_all();
 392 }
 393 
 394 /**
 395  * Get the next CompileTask from a CompileQueue
 396  */
 397 CompileTask* CompileQueue::get(CompilerThread* thread) {
 398   // save methods from RedefineClasses across safepoint
 399   // across MethodCompileQueue_lock below.
 400   methodHandle save_method;
 401   methodHandle save_hot_method;
 402 
 403   MonitorLocker locker(MethodCompileQueue_lock);




 404   // If _first is null we have no more compile jobs. There are two reasons for
 405   // having no compile jobs: First, we compiled everything we wanted. Second,
 406   // we ran out of code cache so compilation has been disabled. In the latter
 407   // case we perform code cache sweeps to free memory such that we can re-enable
 408   // compilation.
 409   while (_first == nullptr) {
 410     // Exit loop if compilation is disabled forever
 411     if (CompileBroker::is_compilation_disabled_forever()) {
 412       return nullptr;
 413     }
 414 
 415     AbstractCompiler* compiler = thread->compiler();
 416     guarantee(compiler != nullptr, "Compiler object must exist");
 417     compiler->on_empty_queue(this, thread);
 418     if (_first != nullptr) {
 419       // The call to on_empty_queue may have temporarily unlocked the MCQ lock
 420       // so check again whether any tasks were added to the queue.
 421       break;
 422     }
 423 
















 424     // If there are no compilation tasks and we can compile new jobs
 425     // (i.e., there is enough free space in the code cache) there is
 426     // no need to invoke the GC.
 427     // We need a timed wait here, since compiler threads can exit if compilation
 428     // is disabled forever. We use 5 seconds wait time; the exiting of compiler threads
 429     // is not critical and we do not want idle compiler threads to wake up too often.
 430     locker.wait(5*1000);
 431 




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

 484   }
 485 }
 486 
 487 void CompileQueue::remove(CompileTask* task) {
 488   assert(MethodCompileQueue_lock->owned_by_self(), "must own lock");
 489   if (task->prev() != nullptr) {
 490     task->prev()->set_next(task->next());
 491   } else {
 492     // max is the first element
 493     assert(task == _first, "Sanity");
 494     _first = task->next();
 495   }
 496 
 497   if (task->next() != nullptr) {
 498     task->next()->set_prev(task->prev());
 499   } else {
 500     // max is the last element
 501     assert(task == _last, "Sanity");
 502     _last = task->prev();
 503   }
 504   --_size;
 505   ++_total_removed;
 506 }
 507 
 508 void CompileQueue::remove_and_mark_stale(CompileTask* task) {
 509   assert(MethodCompileQueue_lock->owned_by_self(), "must own lock");
 510   remove(task);
 511 
 512   // Enqueue the task for reclamation (should be done outside MCQ lock)
 513   task->set_next(_first_stale);
 514   task->set_prev(nullptr);
 515   _first_stale = task;
 516 }
 517 
 518 // methods in the compile queue need to be marked as used on the stack
 519 // so that they don't get reclaimed by Redefine Classes
 520 void CompileQueue::mark_on_stack() {
 521   CompileTask* task = _first;
 522   while (task != nullptr) {



 523     task->mark_on_stack();
 524     task = task->next();
 525   }
 526 }
 527 
 528 
 529 CompileQueue* CompileBroker::compile_queue(int comp_level) {
 530   if (is_c2_compile(comp_level)) return _c2_compile_queue;
 531   if (is_c1_compile(comp_level)) return _c1_compile_queue;
 532   return nullptr;
 533 }
 534 
 535 CompileQueue* CompileBroker::c1_compile_queue() {
 536   return _c1_compile_queue;
 537 }
 538 
 539 CompileQueue* CompileBroker::c2_compile_queue() {
 540   return _c2_compile_queue;
 541 }
 542 
 543 void CompileBroker::print_compile_queues(outputStream* st) {
 544   st->print_cr("Current compiles: ");
 545 
 546   char buf[2000];
 547   int buflen = sizeof(buf);
 548   Threads::print_threads_compiling(st, buf, buflen, /* short_form = */ true);
 549 
 550   st->cr();
 551   if (_c1_compile_queue != nullptr) {
 552     _c1_compile_queue->print(st);
 553   }
 554   if (_c2_compile_queue != nullptr) {
 555     _c2_compile_queue->print(st);
 556   }









 557 }
 558 
 559 void CompileQueue::print(outputStream* st) {
 560   assert_locked_or_safepoint(MethodCompileQueue_lock);
 561   st->print_cr("%s:", name());
 562   CompileTask* task = _first;
 563   if (task == nullptr) {
 564     st->print_cr("Empty");
 565   } else {
 566     while (task != nullptr) {
 567       task->print(st, nullptr, true, true);
 568       task = task->next();
 569     }
 570   }
 571   st->cr();
 572 }
 573 
 574 void CompileQueue::print_tty() {
 575   stringStream ss;
 576   // Dump the compile queue into a buffer before locking the tty
 577   print(&ss);
 578   {
 579     ttyLocker ttyl;
 580     tty->print("%s", ss.freeze());

 607       CompilerEvent::PhaseEvent::get_phase_id(phase_name, false, false, false);
 608     }
 609     first_registration = false;
 610 #endif // COMPILER2
 611   }
 612 }
 613 #endif // INCLUDE_JFR && COMPILER2_OR_JVMCI
 614 
 615 // ------------------------------------------------------------------
 616 // CompileBroker::compilation_init
 617 //
 618 // Initialize the Compilation object
 619 void CompileBroker::compilation_init(JavaThread* THREAD) {
 620   // No need to initialize compilation system if we do not use it.
 621   if (!UseCompiler) {
 622     return;
 623   }
 624   // Set the interface to the current compiler(s).
 625   _c1_count = CompilationPolicy::c1_count();
 626   _c2_count = CompilationPolicy::c2_count();


 627 
 628 #if INCLUDE_JVMCI
 629   if (EnableJVMCI) {
 630     // This is creating a JVMCICompiler singleton.
 631     JVMCICompiler* jvmci = new JVMCICompiler();
 632 
 633     if (UseJVMCICompiler) {
 634       _compilers[1] = jvmci;
 635       if (FLAG_IS_DEFAULT(JVMCIThreads)) {
 636         if (BootstrapJVMCI) {
 637           // JVMCI will bootstrap so give it more threads
 638           _c2_count = MIN2(32, os::active_processor_count());
 639         }
 640       } else {
 641         _c2_count = JVMCIThreads;
 642       }
 643       if (FLAG_IS_DEFAULT(JVMCIHostThreads)) {
 644       } else {
 645 #ifdef COMPILER1
 646         _c1_count = JVMCIHostThreads;
 647 #endif // COMPILER1
 648       }





 649     }
 650   }
 651 #endif // INCLUDE_JVMCI
 652 
 653 #ifdef COMPILER1
 654   if (_c1_count > 0) {
 655     _compilers[0] = new Compiler();
 656   }
 657 #endif // COMPILER1
 658 
 659 #ifdef COMPILER2
 660   if (true JVMCI_ONLY( && !UseJVMCICompiler)) {
 661     if (_c2_count > 0) {
 662       _compilers[1] = new C2Compiler();
 663       // Register c2 first as c2 CompilerPhaseType idToPhase mapping is explicit.
 664       // idToPhase mapping for c2 is in opto/phasetype.hpp
 665       JFR_ONLY(register_jfr_phasetype_serializer(compiler_c2);)
 666     }
 667   }
 668 #endif // COMPILER2

 763     _perf_last_compile_size =
 764              PerfDataManager::create_variable(SUN_CI, "lastSize",
 765                                               PerfData::U_Bytes,
 766                                               (jlong)CompileBroker::no_compile,
 767                                               CHECK);
 768 
 769 
 770     _perf_last_failed_type =
 771              PerfDataManager::create_variable(SUN_CI, "lastFailedType",
 772                                               PerfData::U_None,
 773                                               (jlong)CompileBroker::no_compile,
 774                                               CHECK);
 775 
 776     _perf_last_invalidated_type =
 777          PerfDataManager::create_variable(SUN_CI, "lastInvalidatedType",
 778                                           PerfData::U_None,
 779                                           (jlong)CompileBroker::no_compile,
 780                                           CHECK);
 781   }
 782 

 783   _initialized = true;
 784 }
 785 









 786 #if defined(ASSERT) && COMPILER2_OR_JVMCI
 787 // Entry for DeoptimizeObjectsALotThread. The threads are started in
 788 // CompileBroker::init_compiler_threads() iff DeoptimizeObjectsALot is enabled
 789 void DeoptimizeObjectsALotThread::deopt_objs_alot_thread_entry(JavaThread* thread, TRAPS) {
 790     DeoptimizeObjectsALotThread* dt = ((DeoptimizeObjectsALotThread*) thread);
 791     bool enter_single_loop;
 792     {
 793       MonitorLocker ml(dt, EscapeBarrier_lock, Mutex::_no_safepoint_check_flag);
 794       static int single_thread_count = 0;
 795       enter_single_loop = single_thread_count++ < DeoptimizeObjectsALotThreadCountSingle;
 796     }
 797     if (enter_single_loop) {
 798       dt->deoptimize_objects_alot_loop_single();
 799     } else {
 800       dt->deoptimize_objects_alot_loop_all();
 801     }
 802   }
 803 
 804 // Execute EscapeBarriers in an endless loop to revert optimizations based on escape analysis. Each
 805 // barrier targets a single thread which is selected round robin.

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



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

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











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


















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


































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










1020 void CompileBroker::possibly_add_compiler_threads(JavaThread* THREAD) {
1021 
1022   int old_c2_count = 0, new_c2_count = 0, old_c1_count = 0, new_c1_count = 0;
1023   const int c2_tasks_per_thread = 2, c1_tasks_per_thread = 4;
1024 
1025   // Quick check if we already have enough compiler threads without taking the lock.
1026   // Numbers may change concurrently, so we read them again after we have the lock.
1027   if (_c2_compile_queue != nullptr) {
1028     old_c2_count = get_c2_thread_count();
1029     new_c2_count = MIN2(_c2_count, _c2_compile_queue->size() / c2_tasks_per_thread);
1030   }
1031   if (_c1_compile_queue != nullptr) {
1032     old_c1_count = get_c1_thread_count();
1033     new_c1_count = MIN2(_c1_count, _c1_compile_queue->size() / c1_tasks_per_thread);
1034   }
1035   if (new_c2_count <= old_c2_count && new_c1_count <= old_c1_count) return;
1036 
1037   // Now, we do the more expensive operations.
1038   julong free_memory = os::free_memory();
1039   // If SegmentedCodeCache is off, both values refer to the single heap (with type CodeBlobType::All).

1122         stringStream msg;
1123         msg.print("Added compiler thread %s (free memory: %dMB, available profiled code cache: %dMB)",
1124                   ct->name(), (int)(free_memory/M), (int)(available_cc_p/M));
1125         print_compiler_threads(msg);
1126       }
1127     }
1128   }
1129 
1130   CompileThread_lock->unlock();
1131 }
1132 
1133 
1134 /**
1135  * Set the methods on the stack as on_stack so that redefine classes doesn't
1136  * reclaim them. This method is executed at a safepoint.
1137  */
1138 void CompileBroker::mark_on_stack() {
1139   assert(SafepointSynchronize::is_at_safepoint(), "sanity check");
1140   // Since we are at a safepoint, we do not need a lock to access
1141   // the compile queues.



1142   if (_c2_compile_queue != nullptr) {
1143     _c2_compile_queue->mark_on_stack();
1144   }
1145   if (_c1_compile_queue != nullptr) {
1146     _c1_compile_queue->mark_on_stack();
1147   }






1148 }
1149 
1150 // ------------------------------------------------------------------
1151 // CompileBroker::compile_method
1152 //
1153 // Request compilation of a method.
1154 void CompileBroker::compile_method_base(const methodHandle& method,
1155                                         int osr_bci,
1156                                         int comp_level,
1157                                         const methodHandle& hot_method,
1158                                         int hot_count,
1159                                         CompileTask::CompileReason compile_reason,

1160                                         bool blocking,
1161                                         Thread* thread) {
1162   guarantee(!method->is_abstract(), "cannot compile abstract methods");
1163   assert(method->method_holder()->is_instance_klass(),
1164          "sanity check");
1165   assert(!method->method_holder()->is_not_initialized(),
1166          "method holder must be initialized");


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





1220 
1221   // Outputs from the following MutexLocker block:
1222   CompileTask* task     = nullptr;
1223   CompileQueue* queue  = compile_queue(comp_level);








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

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












1331   }
1332 
1333   if (blocking) {
1334     wait_for_completion(task);
1335   }
1336 }
1337 
















1338 nmethod* CompileBroker::compile_method(const methodHandle& method, int osr_bci,
1339                                        int comp_level,
1340                                        const methodHandle& hot_method, int hot_count,

1341                                        CompileTask::CompileReason compile_reason,
1342                                        TRAPS) {
1343   // Do nothing if compilebroker is not initialized or compiles are submitted on level none
1344   if (!_initialized || comp_level == CompLevel_none) {
1345     return nullptr;
1346   }
1347 







1348   AbstractCompiler *comp = CompileBroker::compiler(comp_level);
1349   assert(comp != nullptr, "Ensure we have a compiler");
1350 
1351 #if INCLUDE_JVMCI
1352   if (comp->is_jvmci() && !JVMCI::can_initialize_JVMCI()) {
1353     // JVMCI compilation is not yet initializable.
1354     return nullptr;
1355   }
1356 #endif
1357 
1358   DirectiveSet* directive = DirectivesStack::getMatchingDirective(method, comp);
1359   // CompileBroker::compile_method can trap and can have pending async exception.
1360   nmethod* nm = CompileBroker::compile_method(method, osr_bci, comp_level, hot_method, hot_count, compile_reason, directive, THREAD);
1361   DirectivesStack::release(directive);
1362   return nm;
1363 }
1364 
1365 nmethod* CompileBroker::compile_method(const methodHandle& method, int osr_bci,
1366                                          int comp_level,
1367                                          const methodHandle& hot_method, int hot_count,

1368                                          CompileTask::CompileReason compile_reason,
1369                                          DirectiveSet* directive,
1370                                          TRAPS) {
1371 
1372   // make sure arguments make sense
1373   assert(method->method_holder()->is_instance_klass(), "not an instance method");
1374   assert(osr_bci == InvocationEntryBci || (0 <= osr_bci && osr_bci < method->code_size()), "bci out of range");
1375   assert(!method->is_abstract() && (osr_bci == InvocationEntryBci || !method->is_native()), "cannot compile abstract/native methods");
1376   assert(!method->method_holder()->is_not_initialized(), "method holder must be initialized");



1377   // return quickly if possible
1378 




1379   // lock, make sure that the compilation
1380   // isn't prohibited in a straightforward way.
1381   AbstractCompiler* comp = CompileBroker::compiler(comp_level);
1382   if (comp == nullptr || compilation_is_prohibited(method, osr_bci, comp_level, directive->ExcludeOption)) {
1383     return nullptr;
1384   }
1385 
1386   if (osr_bci == InvocationEntryBci) {
1387     // standard compilation
1388     nmethod* method_code = method->code();
1389     if (method_code != nullptr) {
1390       if (compilation_is_complete(method, osr_bci, comp_level)) {
1391         return method_code;
1392       }
1393     }
1394     if (method->is_not_compilable(comp_level)) {
1395       return nullptr;
1396     }
1397   } else {
1398     // osr compilation
1399     // We accept a higher level osr method
1400     nmethod* nm = method->lookup_osr_nmethod_for(osr_bci, comp_level, false);
1401     if (nm != nullptr) return nm;
1402     if (method->is_not_osr_compilable(comp_level)) return nullptr;
1403   }
1404 
1405   assert(!HAS_PENDING_EXCEPTION, "No exception should be present");
1406   // some prerequisites that are compiler specific
1407   if (comp->is_c2() || comp->is_jvmci()) {


1408     InternalOOMEMark iom(THREAD);
1409     method->constants()->resolve_string_constants(CHECK_AND_CLEAR_NONASYNC_NULL);
1410     // Resolve all classes seen in the signature of the method
1411     // we are compiling.
1412     Method::load_signature_classes(method, CHECK_AND_CLEAR_NONASYNC_NULL);
1413   }
1414 
1415   // If the method is native, do the lookup in the thread requesting
1416   // the compilation. Native lookups can load code, which is not
1417   // permitted during compilation.
1418   //
1419   // Note: A native method implies non-osr compilation which is
1420   //       checked with an assertion at the entry of this method.
1421   if (method->is_native() && !method->is_method_handle_intrinsic()) {
1422     address adr = NativeLookup::lookup(method, THREAD);
1423     if (HAS_PENDING_EXCEPTION) {
1424       // In case of an exception looking up the method, we just forget
1425       // about it. The interpreter will kick-in and throw the exception.
1426       method->set_not_compilable("NativeLookup::lookup failed"); // implies is_not_osr_compilable()
1427       CLEAR_PENDING_EXCEPTION;

1442   }
1443 
1444   // do the compilation
1445   if (method->is_native()) {
1446     if (!PreferInterpreterNativeStubs || method->is_method_handle_intrinsic()) {
1447       // To properly handle the appendix argument for out-of-line calls we are using a small trampoline that
1448       // pops off the appendix argument and jumps to the target (see gen_special_dispatch in SharedRuntime).
1449       //
1450       // Since normal compiled-to-compiled calls are not able to handle such a thing we MUST generate an adapter
1451       // in this case.  If we can't generate one and use it we can not execute the out-of-line method handle calls.
1452       AdapterHandlerLibrary::create_native_wrapper(method);
1453     } else {
1454       return nullptr;
1455     }
1456   } else {
1457     // If the compiler is shut off due to code cache getting full
1458     // fail out now so blocking compiles dont hang the java thread
1459     if (!should_compile_new_jobs()) {
1460       return nullptr;
1461     }
1462     bool is_blocking = !directive->BackgroundCompilationOption || ReplayCompiles;
1463     compile_method_base(method, osr_bci, comp_level, hot_method, hot_count, compile_reason, is_blocking, THREAD);


1464   }
1465 
1466   // return requested nmethod
1467   // We accept a higher level osr method
1468   if (osr_bci == InvocationEntryBci) {
1469     return method->code();
1470   }
1471   return method->lookup_osr_nmethod_for(osr_bci, comp_level, false);
1472 }
1473 
1474 
1475 // ------------------------------------------------------------------
1476 // CompileBroker::compilation_is_complete
1477 //
1478 // See if compilation of this method is already complete.
1479 bool CompileBroker::compilation_is_complete(const methodHandle& method,
1480                                             int                 osr_bci,
1481                                             int                 comp_level) {






1482   bool is_osr = (osr_bci != standard_entry_bci);
1483   if (is_osr) {
1484     if (method->is_not_osr_compilable(comp_level)) {
1485       return true;
1486     } else {
1487       nmethod* result = method->lookup_osr_nmethod_for(osr_bci, comp_level, true);
1488       return (result != nullptr);
1489     }
1490   } else {
1491     if (method->is_not_compilable(comp_level)) {
1492       return true;
1493     } else {
1494       nmethod* result = method->code();
1495       if (result == nullptr) return false;
1496       return comp_level == result->comp_level();









1497     }
1498   }
1499 }
1500 
1501 
1502 /**
1503  * See if this compilation is already requested.
1504  *
1505  * Implementation note: there is only a single "is in queue" bit
1506  * for each method.  This means that the check below is overly
1507  * conservative in the sense that an osr compilation in the queue
1508  * will block a normal compilation from entering the queue (and vice
1509  * versa).  This can be remedied by a full queue search to disambiguate
1510  * cases.  If it is deemed profitable, this may be done.
1511  */
1512 bool CompileBroker::compilation_is_in_queue(const methodHandle& method) {
1513   return method->queued_for_compilation();
1514 }
1515 
1516 // ------------------------------------------------------------------

1576     if (CIStart <= id && id < CIStop) {
1577       return id;
1578     }
1579   }
1580 
1581   // Method was not in the appropriate compilation range.
1582   method->set_not_compilable_quietly("Not in requested compile id range");
1583   return 0;
1584 #else
1585   // CICountOSR is a develop flag and set to 'false' by default. In a product built,
1586   // only _compilation_id is incremented.
1587   return Atomic::add(&_compilation_id, 1);
1588 #endif
1589 }
1590 
1591 // ------------------------------------------------------------------
1592 // CompileBroker::assign_compile_id_unlocked
1593 //
1594 // Public wrapper for assign_compile_id that acquires the needed locks
1595 int CompileBroker::assign_compile_id_unlocked(Thread* thread, const methodHandle& method, int osr_bci) {
1596   MutexLocker locker(thread, MethodCompileQueue_lock);
1597   return assign_compile_id(method, osr_bci);
1598 }
1599 
1600 // ------------------------------------------------------------------
1601 // CompileBroker::create_compile_task
1602 //
1603 // Create a CompileTask object representing the current request for
1604 // compilation.  Add this task to the queue.
1605 CompileTask* CompileBroker::create_compile_task(CompileQueue*       queue,
1606                                                 int                 compile_id,
1607                                                 const methodHandle& method,
1608                                                 int                 osr_bci,
1609                                                 int                 comp_level,
1610                                                 const methodHandle& hot_method,
1611                                                 int                 hot_count,

1612                                                 CompileTask::CompileReason compile_reason,

1613                                                 bool                blocking) {
1614   CompileTask* new_task = CompileTask::allocate();
1615   new_task->initialize(compile_id, method, osr_bci, comp_level,
1616                        hot_method, hot_count, compile_reason,
1617                        blocking);
1618   queue->add(new_task);
1619   return new_task;
1620 }
1621 
1622 #if INCLUDE_JVMCI
1623 // The number of milliseconds to wait before checking if
1624 // JVMCI compilation has made progress.
1625 static const long JVMCI_COMPILATION_PROGRESS_WAIT_TIMESLICE = 1000;
1626 
1627 // The number of JVMCI compilation progress checks that must fail
1628 // before unblocking a thread waiting for a blocking compilation.
1629 static const int JVMCI_COMPILATION_PROGRESS_WAIT_ATTEMPTS = 10;
1630 
1631 /**
1632  * Waits for a JVMCI compiler to complete a given task. This thread
1633  * waits until either the task completes or it sees no JVMCI compilation
1634  * progress for N consecutive milliseconds where N is
1635  * JVMCI_COMPILATION_PROGRESS_WAIT_TIMESLICE *
1636  * JVMCI_COMPILATION_PROGRESS_WAIT_ATTEMPTS.
1637  *
1638  * @return true if this thread needs to free/recycle the task

1717   }
1718 
1719   if (free_task) {
1720     if (is_compilation_disabled_forever()) {
1721       CompileTask::free(task);
1722       return;
1723     }
1724 
1725     // It is harmless to check this status without the lock, because
1726     // completion is a stable property (until the task object is recycled).
1727     assert(task->is_complete(), "Compilation should have completed");
1728 
1729     // By convention, the waiter is responsible for recycling a
1730     // blocking CompileTask. Since there is only one waiter ever
1731     // waiting on a CompileTask, we know that no one else will
1732     // be using this CompileTask; we can free it.
1733     CompileTask::free(task);
1734   }
1735 }
1736 




1737 /**
1738  * Initialize compiler thread(s) + compiler object(s). The postcondition
1739  * of this function is that the compiler runtimes are initialized and that
1740  * compiler threads can start compiling.
1741  */
1742 bool CompileBroker::init_compiler_runtime() {
1743   CompilerThread* thread = CompilerThread::current();
1744   AbstractCompiler* comp = thread->compiler();
1745   // Final sanity check - the compiler object must exist
1746   guarantee(comp != nullptr, "Compiler object must exist");
1747 
1748   {
1749     // Must switch to native to allocate ci_env
1750     ThreadToNativeFromVM ttn(thread);
1751     ciEnv ci_env((CompileTask*)nullptr);
1752     // Cache Jvmti state
1753     ci_env.cache_jvmti_state();
1754     // Cache DTrace flags
1755     ci_env.cache_dtrace_flags();
1756 
1757     // Switch back to VM state to do compiler initialization
1758     ThreadInVMfromNative tv(thread);
1759 
1760     // Perform per-thread and global initializations
1761     comp->initialize();
1762   }
1763 
1764   if (comp->is_failed()) {
1765     disable_compilation_forever();
1766     // If compiler initialization failed, no compiler thread that is specific to a
1767     // particular compiler runtime will ever start to compile methods.
1768     shutdown_compiler_runtime(comp, thread);
1769     return false;
1770   }
1771 
1772   // C1 specific check
1773   if (comp->is_c1() && (thread->get_buffer_blob() == nullptr)) {
1774     warning("Initialization of %s thread failed (no space to run compilers)", thread->name());
1775     return false;
1776   }
1777 
1778   return true;
1779 }
1780 
1781 void CompileBroker::free_buffer_blob_if_allocated(CompilerThread* thread) {
1782   BufferBlob* blob = thread->get_buffer_blob();
1783   if (blob != nullptr) {
1784     blob->purge();
1785     MutexLocker mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
1786     CodeCache::free(blob);
1787   }
1788 }
1789 
1790 /**
1791  * If C1 and/or C2 initialization failed, we shut down all compilation.
1792  * We do this to keep things simple. This can be changed if it ever turns
1793  * out to be a problem.
1794  */
1795 void CompileBroker::shutdown_compiler_runtime(AbstractCompiler* comp, CompilerThread* thread) {
1796   free_buffer_blob_if_allocated(thread);
1797 


1798   if (comp->should_perform_shutdown()) {
1799     // There are two reasons for shutting down the compiler
1800     // 1) compiler runtime initialization failed
1801     // 2) The code cache is full and the following flag is set: -XX:-UseCodeCacheFlushing
1802     warning("%s initialization failed. Shutting down all compilers", comp->name());
1803 
1804     // Only one thread per compiler runtime object enters here
1805     // Set state to shut down
1806     comp->set_shut_down();
1807 
1808     // Delete all queued compilation tasks to make compiler threads exit faster.
1809     if (_c1_compile_queue != nullptr) {
1810       _c1_compile_queue->free_all();
1811     }
1812 
1813     if (_c2_compile_queue != nullptr) {
1814       _c2_compile_queue->free_all();
1815     }
1816 




1817     // Set flags so that we continue execution with using interpreter only.
1818     UseCompiler    = false;
1819     UseInterpreter = true;
1820 
1821     // We could delete compiler runtimes also. However, there are references to
1822     // the compiler runtime(s) (e.g.,  nmethod::is_compiled_by_c1()) which then
1823     // fail. This can be done later if necessary.
1824   }
1825 }
1826 
1827 /**
1828  * Helper function to create new or reuse old CompileLog.
1829  */
1830 CompileLog* CompileBroker::get_log(CompilerThread* ct) {
1831   if (!LogCompilation) return nullptr;
1832 
1833   AbstractCompiler *compiler = ct->compiler();

1834   bool c1 = compiler->is_c1();
1835   jobject* compiler_objects = c1 ? _compiler1_objects : _compiler2_objects;
1836   assert(compiler_objects != nullptr, "must be initialized at this point");
1837   CompileLog** logs = c1 ? _compiler1_logs : _compiler2_logs;
1838   assert(logs != nullptr, "must be initialized at this point");
1839   int count = c1 ? _c1_count : _c2_count;
1840 





1841   // Find Compiler number by its threadObj.
1842   oop compiler_obj = ct->threadObj();
1843   int compiler_number = 0;
1844   bool found = false;
1845   for (; compiler_number < count; compiler_number++) {
1846     if (JNIHandles::resolve_non_null(compiler_objects[compiler_number]) == compiler_obj) {
1847       found = true;
1848       break;
1849     }
1850   }
1851   assert(found, "Compiler must exist at this point");
1852 
1853   // Determine pointer for this thread's log.
1854   CompileLog** log_ptr = &logs[compiler_number];
1855 
1856   // Return old one if it exists.
1857   CompileLog* log = *log_ptr;
1858   if (log != nullptr) {
1859     ct->init_log(log);
1860     return log;

1898     log->stamp();
1899     log->end_elem();
1900   }
1901 
1902   // If compiler thread/runtime initialization fails, exit the compiler thread
1903   if (!init_compiler_runtime()) {
1904     return;
1905   }
1906 
1907   thread->start_idle_timer();
1908 
1909   // Poll for new compilation tasks as long as the JVM runs. Compilation
1910   // should only be disabled if something went wrong while initializing the
1911   // compiler runtimes. This, in turn, should not happen. The only known case
1912   // when compiler runtime initialization fails is if there is not enough free
1913   // space in the code cache to generate the necessary stubs, etc.
1914   while (!is_compilation_disabled_forever()) {
1915     // We need this HandleMark to avoid leaking VM handles.
1916     HandleMark hm(thread);
1917 


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

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

1956           task->set_failure_reason("compilation is disabled");
1957         }
1958       } else {
1959         task->set_failure_reason("breakpoints are present");
1960       }
1961 
1962       if (UseDynamicNumberOfCompilerThreads) {
1963         possibly_add_compiler_threads(thread);
1964         assert(!thread->has_pending_exception(), "should have been handled");
1965       }
1966     }
1967   }
1968 
1969   // Shut down compiler runtime
1970   shutdown_compiler_runtime(thread->compiler(), thread);
1971 }
1972 
1973 // ------------------------------------------------------------------
1974 // CompileBroker::init_compiler_thread_log
1975 //

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

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

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

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






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

2502 // CompileBroker::collect_statistics
2503 //
2504 // Collect statistics about the compilation.
2505 
2506 void CompileBroker::collect_statistics(CompilerThread* thread, elapsedTimer time, CompileTask* task) {
2507   bool success = task->is_success();
2508   methodHandle method (thread, task->method());
2509   int compile_id = task->compile_id();
2510   bool is_osr = (task->osr_bci() != standard_entry_bci);
2511   const int comp_level = task->comp_level();
2512   CompilerCounters* counters = thread->counters();
2513 
2514   MutexLocker locker(CompileStatistics_lock);
2515 
2516   // _perf variables are production performance counters which are
2517   // updated regardless of the setting of the CITime and CITimeEach flags
2518   //
2519 
2520   // account all time, including bailouts and failures in this counter;
2521   // C1 and C2 counters are counting both successful and unsuccessful compiles
2522   _t_total_compilation.add(time);
2523 
2524   // Update compilation times. Used by the implementation of JFR CompilerStatistics
2525   // and java.lang.management.CompilationMXBean.
2526   _perf_total_compilation->inc(time.ticks());
2527   _peak_compilation_time = MAX2(time.milliseconds(), _peak_compilation_time);
2528 
2529   if (!success) {
2530     _total_bailout_count++;
2531     if (UsePerfData) {
2532       _perf_last_failed_method->set_value(counters->current_method());
2533       _perf_last_failed_type->set_value(counters->compile_type());
2534       _perf_total_bailout_count->inc();
2535     }
2536     _t_bailedout_compilation.add(time);











2537   } else if (!task->is_success()) {
2538     if (UsePerfData) {
2539       _perf_last_invalidated_method->set_value(counters->current_method());
2540       _perf_last_invalidated_type->set_value(counters->compile_type());
2541       _perf_total_invalidated_count->inc();
2542     }
2543     _total_invalidated_count++;
2544     _t_invalidated_compilation.add(time);











2545   } else {
2546     // Compilation succeeded
2547     if (CITime) {
2548       int bytes_compiled = method->code_size() + task->num_inlined_bytecodes();
2549       if (is_osr) {
2550         _t_osr_compilation.add(time);
2551         _sum_osr_bytes_compiled += bytes_compiled;
2552       } else {
2553         _t_standard_compilation.add(time);
2554         _sum_standard_bytes_compiled += method->code_size() + task->num_inlined_bytecodes();
2555       }
2556 
2557       // Collect statistic per compilation level
2558       if (comp_level > CompLevel_none && comp_level <= CompLevel_full_optimization) {









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

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


















2645 void CompileBroker::print_times(const char* name, CompilerStatistics* stats) {
2646   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}",
2647                 name, stats->bytes_per_second(),
2648                 stats->_standard._time.seconds(), stats->_standard._bytes, stats->_standard._count,
2649                 stats->_osr._time.seconds(), stats->_osr._bytes, stats->_osr._count,
2650                 stats->_nmethods_size, stats->_nmethods_code_size);
2651 }
2652 












































































































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



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







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

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




2720   AbstractCompiler *comp = compiler(CompLevel_simple);
2721   if (comp != nullptr) {
2722     tty->cr();
2723     comp->print_timers();
2724   }
2725   comp = compiler(CompLevel_full_optimization);
2726   if (comp != nullptr) {
2727     tty->cr();
2728     comp->print_timers();
2729   }





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

   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "cds/aotLinkedClassBulkLoader.hpp"
  26 #include "cds/cdsConfig.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/compileLog.hpp"
  40 #include "compiler/compilerDefinitions.inline.hpp"
  41 #include "compiler/compilerEvent.hpp"
  42 #include "compiler/compilerOracle.hpp"
  43 #include "compiler/directivesParser.hpp"
  44 #include "compiler/recompilationPolicy.hpp"
  45 #include "gc/shared/memAllocator.hpp"
  46 #include "interpreter/linkResolver.hpp"
  47 #include "jfr/jfrEvents.hpp"
  48 #include "jvm.h"
  49 #include "logging/log.hpp"
  50 #include "logging/logStream.hpp"
  51 #include "memory/allocation.inline.hpp"
  52 #include "memory/resourceArea.hpp"
  53 #include "memory/universe.hpp"
  54 #include "oops/method.inline.hpp"
  55 #include "oops/methodData.hpp"
  56 #include "oops/oop.inline.hpp"
  57 #include "prims/jvmtiExport.hpp"
  58 #include "prims/nativeLookup.hpp"
  59 #include "prims/whitebox.hpp"
  60 #include "runtime/atomic.hpp"
  61 #include "runtime/escapeBarrier.hpp"
  62 #include "runtime/globals_extension.hpp"
  63 #include "runtime/handles.inline.hpp"
  64 #include "runtime/init.hpp"
  65 #include "runtime/interfaceSupport.inline.hpp"
  66 #include "runtime/java.hpp"
  67 #include "runtime/javaCalls.hpp"
  68 #include "runtime/jniHandles.inline.hpp"
  69 #include "runtime/os.hpp"
  70 #include "runtime/perfData.hpp"
  71 #include "runtime/safepointVerifiers.hpp"
  72 #include "runtime/sharedRuntime.hpp"
  73 #include "runtime/threads.hpp"
  74 #include "runtime/threadSMR.inline.hpp"
  75 #include "runtime/timerTrace.hpp"
  76 #include "runtime/vframe.inline.hpp"
  77 #include "services/management.hpp"
  78 #include "utilities/debug.hpp"
  79 #include "utilities/dtrace.hpp"
  80 #include "utilities/events.hpp"
  81 #include "utilities/formatBuffer.hpp"
  82 #include "utilities/macros.hpp"
  83 #include "utilities/nonblockingQueue.inline.hpp"
  84 #ifdef COMPILER1
  85 #include "c1/c1_Compiler.hpp"
  86 #endif
  87 #ifdef COMPILER2
  88 #include "opto/c2compiler.hpp"
  89 #endif
  90 #if INCLUDE_JVMCI
  91 #include "jvmci/jvmciEnv.hpp"
  92 #include "jvmci/jvmciRuntime.hpp"
  93 #endif
  94 
  95 #ifdef DTRACE_ENABLED
  96 
  97 // Only bother with this argument setup if dtrace is available
  98 
  99 #define DTRACE_METHOD_COMPILE_BEGIN_PROBE(method, comp_name)             \
 100   {                                                                      \
 101     Symbol* klass_name = (method)->klass_name();                         \
 102     Symbol* name = (method)->name();                                     \
 103     Symbol* signature = (method)->signature();                           \

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

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

 631   }
 632 }
 633 
 634 
 635 CompileQueue* CompileBroker::compile_queue(int comp_level, bool is_scc) {
 636   if (is_c2_compile(comp_level)) return ((is_scc  && (_sc_count > 0)) ? _sc2_compile_queue : _c2_compile_queue);
 637   if (is_c1_compile(comp_level)) return ((is_scc && (_sc_count > 0)) ? _sc1_compile_queue : _c1_compile_queue);
 638   return nullptr;
 639 }
 640 
 641 CompileQueue* CompileBroker::c1_compile_queue() {
 642   return _c1_compile_queue;
 643 }
 644 
 645 CompileQueue* CompileBroker::c2_compile_queue() {
 646   return _c2_compile_queue;
 647 }
 648 
 649 void CompileBroker::print_compile_queues(outputStream* st) {
 650   st->print_cr("Current compiles: ");
 651 
 652   char buf[2000];
 653   int buflen = sizeof(buf);
 654   Threads::print_threads_compiling(st, buf, buflen, /* short_form = */ true);
 655 
 656   st->cr();
 657   if (_c1_compile_queue != nullptr) {
 658     _c1_compile_queue->print(st);
 659   }
 660   if (_c2_compile_queue != nullptr) {
 661     _c2_compile_queue->print(st);
 662   }
 663   if (_c3_compile_queue != nullptr) {
 664     _c3_compile_queue->print(st);
 665   }
 666   if (_sc1_compile_queue != nullptr) {
 667     _sc1_compile_queue->print(st);
 668   }
 669   if (_sc2_compile_queue != nullptr) {
 670     _sc2_compile_queue->print(st);
 671   }
 672 }
 673 
 674 void CompileQueue::print(outputStream* st) {
 675   assert_locked_or_safepoint(_lock);
 676   st->print_cr("%s:", name());
 677   CompileTask* task = _first;
 678   if (task == nullptr) {
 679     st->print_cr("Empty");
 680   } else {
 681     while (task != nullptr) {
 682       task->print(st, nullptr, true, true);
 683       task = task->next();
 684     }
 685   }
 686   st->cr();
 687 }
 688 
 689 void CompileQueue::print_tty() {
 690   stringStream ss;
 691   // Dump the compile queue into a buffer before locking the tty
 692   print(&ss);
 693   {
 694     ttyLocker ttyl;
 695     tty->print("%s", ss.freeze());

 722       CompilerEvent::PhaseEvent::get_phase_id(phase_name, false, false, false);
 723     }
 724     first_registration = false;
 725 #endif // COMPILER2
 726   }
 727 }
 728 #endif // INCLUDE_JFR && COMPILER2_OR_JVMCI
 729 
 730 // ------------------------------------------------------------------
 731 // CompileBroker::compilation_init
 732 //
 733 // Initialize the Compilation object
 734 void CompileBroker::compilation_init(JavaThread* THREAD) {
 735   // No need to initialize compilation system if we do not use it.
 736   if (!UseCompiler) {
 737     return;
 738   }
 739   // Set the interface to the current compiler(s).
 740   _c1_count = CompilationPolicy::c1_count();
 741   _c2_count = CompilationPolicy::c2_count();
 742   _c3_count = CompilationPolicy::c3_count();
 743   _sc_count = CompilationPolicy::sc_count();
 744 
 745 #if INCLUDE_JVMCI
 746   if (EnableJVMCI) {
 747     // This is creating a JVMCICompiler singleton.
 748     JVMCICompiler* jvmci = new JVMCICompiler();
 749 
 750     if (UseJVMCICompiler) {
 751       _compilers[1] = jvmci;
 752       if (FLAG_IS_DEFAULT(JVMCIThreads)) {
 753         if (BootstrapJVMCI) {
 754           // JVMCI will bootstrap so give it more threads
 755           _c2_count = MIN2(32, os::active_processor_count());
 756         }
 757       } else {
 758         _c2_count = JVMCIThreads;
 759       }
 760       if (FLAG_IS_DEFAULT(JVMCIHostThreads)) {
 761       } else {
 762 #ifdef COMPILER1
 763         _c1_count = JVMCIHostThreads;
 764 #endif // COMPILER1
 765       }
 766 #ifdef COMPILER2
 767       if (SCCache::is_on() && (_c3_count > 0)) {
 768         _compilers[2] = new C2Compiler();
 769       }
 770 #endif
 771     }
 772   }
 773 #endif // INCLUDE_JVMCI
 774 
 775 #ifdef COMPILER1
 776   if (_c1_count > 0) {
 777     _compilers[0] = new Compiler();
 778   }
 779 #endif // COMPILER1
 780 
 781 #ifdef COMPILER2
 782   if (true JVMCI_ONLY( && !UseJVMCICompiler)) {
 783     if (_c2_count > 0) {
 784       _compilers[1] = new C2Compiler();
 785       // Register c2 first as c2 CompilerPhaseType idToPhase mapping is explicit.
 786       // idToPhase mapping for c2 is in opto/phasetype.hpp
 787       JFR_ONLY(register_jfr_phasetype_serializer(compiler_c2);)
 788     }
 789   }
 790 #endif // COMPILER2

 885     _perf_last_compile_size =
 886              PerfDataManager::create_variable(SUN_CI, "lastSize",
 887                                               PerfData::U_Bytes,
 888                                               (jlong)CompileBroker::no_compile,
 889                                               CHECK);
 890 
 891 
 892     _perf_last_failed_type =
 893              PerfDataManager::create_variable(SUN_CI, "lastFailedType",
 894                                               PerfData::U_None,
 895                                               (jlong)CompileBroker::no_compile,
 896                                               CHECK);
 897 
 898     _perf_last_invalidated_type =
 899          PerfDataManager::create_variable(SUN_CI, "lastInvalidatedType",
 900                                           PerfData::U_None,
 901                                           (jlong)CompileBroker::no_compile,
 902                                           CHECK);
 903   }
 904 
 905   log_info(scc, init)("CompileBroker is initialized");
 906   _initialized = true;
 907 }
 908 
 909 Handle CompileBroker::create_thread_oop(const char* name, TRAPS) {
 910   Handle thread_oop = JavaThread::create_system_thread_object(name, CHECK_NH);
 911   return thread_oop;
 912 }
 913 
 914 void TrainingReplayThread::training_replay_thread_entry(JavaThread* thread, TRAPS) {
 915   CompilationPolicy::replay_training_at_init_loop(thread);
 916 }
 917 
 918 #if defined(ASSERT) && COMPILER2_OR_JVMCI
 919 // Entry for DeoptimizeObjectsALotThread. The threads are started in
 920 // CompileBroker::init_compiler_threads() iff DeoptimizeObjectsALot is enabled
 921 void DeoptimizeObjectsALotThread::deopt_objs_alot_thread_entry(JavaThread* thread, TRAPS) {
 922     DeoptimizeObjectsALotThread* dt = ((DeoptimizeObjectsALotThread*) thread);
 923     bool enter_single_loop;
 924     {
 925       MonitorLocker ml(dt, EscapeBarrier_lock, Mutex::_no_safepoint_check_flag);
 926       static int single_thread_count = 0;
 927       enter_single_loop = single_thread_count++ < DeoptimizeObjectsALotThreadCountSingle;
 928     }
 929     if (enter_single_loop) {
 930       dt->deoptimize_objects_alot_loop_single();
 931     } else {
 932       dt->deoptimize_objects_alot_loop_all();
 933     }
 934   }
 935 
 936 // Execute EscapeBarriers in an endless loop to revert optimizations based on escape analysis. Each
 937 // barrier targets a single thread which is selected round robin.

 975   if (java_lang_Thread::thread(thread_oop()) != nullptr) {
 976     assert(type == compiler_t, "should only happen with reused compiler threads");
 977     // The compiler thread hasn't actually exited yet so don't try to reuse it
 978     return nullptr;
 979   }
 980 
 981   JavaThread* new_thread = nullptr;
 982   switch (type) {
 983     case compiler_t:
 984       assert(comp != nullptr, "Compiler instance missing.");
 985       if (!InjectCompilerCreationFailure || comp->num_compiler_threads() == 0) {
 986         CompilerCounters* counters = new CompilerCounters();
 987         new_thread = new CompilerThread(queue, counters);
 988       }
 989       break;
 990 #if defined(ASSERT) && COMPILER2_OR_JVMCI
 991     case deoptimizer_t:
 992       new_thread = new DeoptimizeObjectsALotThread();
 993       break;
 994 #endif // ASSERT
 995     case training_replay_t:
 996       new_thread = new TrainingReplayThread();
 997       break;
 998     default:
 999       ShouldNotReachHere();
1000   }
1001 
1002   // At this point the new CompilerThread data-races with this startup
1003   // thread (which is the main thread and NOT the VM thread).
1004   // This means Java bytecodes being executed at startup can
1005   // queue compile jobs which will run at whatever default priority the
1006   // newly created CompilerThread runs at.
1007 
1008 
1009   // At this point it may be possible that no osthread was created for the
1010   // JavaThread due to lack of resources. We will handle that failure below.
1011   // Also check new_thread so that static analysis is happy.
1012   if (new_thread != nullptr && new_thread->osthread() != nullptr) {
1013 
1014     if (type == compiler_t) {
1015       CompilerThread::cast(new_thread)->set_compiler(comp);
1016     }
1017 

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







1136     }
1137   }
1138 
1139   for (int i = 0; i < _c1_count; i++) {
1140     // Create a name for our thread.
1141     jobject thread_handle = create_compiler_thread(_compilers[0], i, CHECK);
1142     _compiler1_objects[i] = thread_handle;
1143     _compiler1_logs[i] = nullptr;
1144 
1145     if (!UseDynamicNumberOfCompilerThreads || i == 0) {
1146       JavaThread *ct = make_thread(compiler_t, thread_handle, _c1_compile_queue, _compilers[0], THREAD);
1147       assert(ct != nullptr, "should have been handled for initial thread");
1148       _compilers[0]->set_num_compiler_threads(i + 1);
1149       print_compiler_thread(ct);
1150     }
1151   }
1152 
1153   for (int i = 0; i < _c3_count; i++) {
1154     // Create a name for our thread.
1155     os::snprintf_checked(name_buffer, sizeof(name_buffer), "C2 CompilerThread%d", i);
1156     Handle thread_oop = create_thread_oop(name_buffer, CHECK);
1157     jobject thread_handle = JNIHandles::make_global(thread_oop);
1158     _compiler3_objects[i] = thread_handle;
1159     _compiler3_logs[i] = nullptr;
1160 
1161     JavaThread *ct = make_thread(compiler_t, thread_handle, _c3_compile_queue, _compilers[2], THREAD);
1162     assert(ct != nullptr, "should have been handled for initial thread");
1163     _compilers[2]->set_num_compiler_threads(i + 1);
1164     print_compiler_thread(ct);
1165   }
1166 
1167   if (_sc_count > 0) {
1168     int i = 0;
1169     if (_c1_count > 0) { // C1 is present
1170       os::snprintf_checked(name_buffer, sizeof(name_buffer), "C%d SC CompilerThread", 1);
1171       Handle thread_oop = create_thread_oop(name_buffer, CHECK);
1172       jobject thread_handle = JNIHandles::make_global(thread_oop);
1173       _sc_objects[i] = thread_handle;
1174       _sc_logs[i] = nullptr;
1175       i++;
1176 
1177       JavaThread *ct = make_thread(compiler_t, thread_handle, _sc1_compile_queue, _compilers[0], THREAD);
1178       assert(ct != nullptr, "should have been handled for initial thread");
1179       print_compiler_thread(ct);
1180     }
1181     if (_c2_count > 0) { // C2 is present
1182       os::snprintf_checked(name_buffer, sizeof(name_buffer), "C%d SC CompilerThread", 2);
1183       Handle thread_oop = create_thread_oop(name_buffer, CHECK);
1184       jobject thread_handle = JNIHandles::make_global(thread_oop);
1185       _sc_objects[i] = thread_handle;
1186       _sc_logs[i] = nullptr;
1187 
1188       JavaThread *ct = make_thread(compiler_t, thread_handle, _sc2_compile_queue, _compilers[1], THREAD);
1189       assert(ct != nullptr, "should have been handled for initial thread");
1190       print_compiler_thread(ct);
1191     }
1192   }
1193 
1194   if (UsePerfData) {
1195     PerfDataManager::create_constant(SUN_CI, "threads", PerfData::U_Bytes, _c1_count + _c2_count + _c3_count, CHECK);
1196   }
1197 
1198 #if defined(ASSERT) && COMPILER2_OR_JVMCI
1199   if (DeoptimizeObjectsALot) {
1200     // Initialize and start the object deoptimizer threads
1201     const int total_count = DeoptimizeObjectsALotThreadCountSingle + DeoptimizeObjectsALotThreadCountAll;
1202     for (int count = 0; count < total_count; count++) {
1203       Handle thread_oop = JavaThread::create_system_thread_object("Deoptimize objects a lot single mode", CHECK);
1204       jobject thread_handle = JNIHandles::make_local(THREAD, thread_oop());
1205       make_thread(deoptimizer_t, thread_handle, nullptr, nullptr, THREAD);
1206     }
1207   }
1208 #endif // defined(ASSERT) && COMPILER2_OR_JVMCI
1209 }
1210 
1211 void CompileBroker::init_training_replay() {
1212   // Ensure any exceptions lead to vm_exit_during_initialization.
1213   EXCEPTION_MARK;
1214   if (TrainingData::have_data()) {
1215     Handle thread_oop = create_thread_oop("Training replay thread", CHECK);
1216     jobject thread_handle = JNIHandles::make_local(THREAD, thread_oop());
1217     make_thread(training_replay_t, thread_handle, nullptr, nullptr, THREAD);
1218   }
1219 }
1220 
1221 void CompileBroker::possibly_add_compiler_threads(JavaThread* THREAD) {
1222 
1223   int old_c2_count = 0, new_c2_count = 0, old_c1_count = 0, new_c1_count = 0;
1224   const int c2_tasks_per_thread = 2, c1_tasks_per_thread = 4;
1225 
1226   // Quick check if we already have enough compiler threads without taking the lock.
1227   // Numbers may change concurrently, so we read them again after we have the lock.
1228   if (_c2_compile_queue != nullptr) {
1229     old_c2_count = get_c2_thread_count();
1230     new_c2_count = MIN2(_c2_count, _c2_compile_queue->size() / c2_tasks_per_thread);
1231   }
1232   if (_c1_compile_queue != nullptr) {
1233     old_c1_count = get_c1_thread_count();
1234     new_c1_count = MIN2(_c1_count, _c1_compile_queue->size() / c1_tasks_per_thread);
1235   }
1236   if (new_c2_count <= old_c2_count && new_c1_count <= old_c1_count) return;
1237 
1238   // Now, we do the more expensive operations.
1239   julong free_memory = os::free_memory();
1240   // If SegmentedCodeCache is off, both values refer to the single heap (with type CodeBlobType::All).

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

1535     // <RESULT, QUEUE> :
1536     //     <0, 1> : in compile queue, but not yet compiled
1537     //     <1, 1> : compiled but queue bit not cleared
1538     //     <1, 0> : compiled and queue bit cleared
1539     // Because we first check the queue bits then check the result bits,
1540     // we are assured that we cannot introduce a duplicate task.
1541     // Note that if we did the tests in the reverse order (i.e. check
1542     // result then check queued bit), we could get the result bit before
1543     // the compilation completed, and the queue bit after the compilation
1544     // completed, and end up introducing a "duplicate" (redundant) task.
1545     // In that case, the compiler thread should first check if a method
1546     // has already been compiled before trying to compile it.
1547     // NOTE: in the event that there are multiple compiler threads and
1548     // there is de-optimization/recompilation, things will get hairy,
1549     // and in that case it's best to protect both the testing (here) of
1550     // these bits, and their updating (here and elsewhere) under a
1551     // common lock.
1552     task = create_compile_task(queue,
1553                                compile_id, method,
1554                                osr_bci, comp_level,
1555                                hot_method, hot_count, scc_entry, compile_reason,
1556                                requires_online_compilation, blocking);
1557 
1558     if (task->is_scc() && (_sc_count > 0)) {
1559       // Put it on SC queue
1560       queue = is_c1_compile(comp_level) ? _sc1_compile_queue : _sc2_compile_queue;
1561     }
1562 
1563     if (UseLockFreeCompileQueues) {
1564       assert(queue->lock()->owned_by_self() == false, "");
1565       queue->add_pending(task);
1566     } else {
1567       queue->add(task);
1568     }
1569   }
1570 
1571   if (blocking) {
1572     wait_for_completion(task);
1573   }
1574 }
1575 
1576 SCCEntry* CompileBroker::find_scc_entry(const methodHandle& method, int osr_bci, int comp_level,
1577                                         CompileTask::CompileReason compile_reason,
1578                                         bool requires_online_compilation) {
1579   SCCEntry* scc_entry = nullptr;
1580   if (osr_bci == InvocationEntryBci && !requires_online_compilation && SCCache::is_on_for_read()) {
1581     // Check for cached code.
1582     if (compile_reason == CompileTask::Reason_Preload) {
1583       scc_entry = method->scc_entry();
1584       assert(scc_entry != nullptr && scc_entry->for_preload(), "sanity");
1585     } else {
1586       scc_entry = SCCache::find_code_entry(method, comp_level);
1587     }
1588   }
1589   return scc_entry;
1590 }
1591 
1592 nmethod* CompileBroker::compile_method(const methodHandle& method, int osr_bci,
1593                                        int comp_level,
1594                                        const methodHandle& hot_method, int hot_count,
1595                                        bool requires_online_compilation,
1596                                        CompileTask::CompileReason compile_reason,
1597                                        TRAPS) {
1598   // Do nothing if compilebroker is not initialized or compiles are submitted on level none
1599   if (!_initialized || comp_level == CompLevel_none) {
1600     return nullptr;
1601   }
1602 
1603 #if INCLUDE_JVMCI
1604   if (EnableJVMCI && UseJVMCICompiler &&
1605       comp_level == CompLevel_full_optimization && !AOTLinkedClassBulkLoader::class_preloading_finished()) {
1606     return nullptr;
1607   }
1608 #endif
1609 
1610   AbstractCompiler *comp = CompileBroker::compiler(comp_level);
1611   assert(comp != nullptr, "Ensure we have a compiler");
1612 
1613 #if INCLUDE_JVMCI
1614   if (comp->is_jvmci() && !JVMCI::can_initialize_JVMCI()) {
1615     // JVMCI compilation is not yet initializable.
1616     return nullptr;
1617   }
1618 #endif
1619 
1620   DirectiveSet* directive = DirectivesStack::getMatchingDirective(method, comp);
1621   // CompileBroker::compile_method can trap and can have pending async exception.
1622   nmethod* nm = CompileBroker::compile_method(method, osr_bci, comp_level, hot_method, hot_count, requires_online_compilation, compile_reason, directive, THREAD);
1623   DirectivesStack::release(directive);
1624   return nm;
1625 }
1626 
1627 nmethod* CompileBroker::compile_method(const methodHandle& method, int osr_bci,
1628                                          int comp_level,
1629                                          const methodHandle& hot_method, int hot_count,
1630                                          bool requires_online_compilation,
1631                                          CompileTask::CompileReason compile_reason,
1632                                          DirectiveSet* directive,
1633                                          TRAPS) {
1634 
1635   // make sure arguments make sense
1636   assert(method->method_holder()->is_instance_klass(), "not an instance method");
1637   assert(osr_bci == InvocationEntryBci || (0 <= osr_bci && osr_bci < method->code_size()), "bci out of range");
1638   assert(!method->is_abstract() && (osr_bci == InvocationEntryBci || !method->is_native()), "cannot compile abstract/native methods");
1639   assert(!method->method_holder()->is_not_initialized()   ||
1640          compile_reason == CompileTask::Reason_Preload    ||
1641          compile_reason == CompileTask::Reason_Precompile ||
1642          compile_reason == CompileTask::Reason_PrecompileForPreload, "method holder must be initialized");
1643   // return quickly if possible
1644 
1645   if (PrecompileOnlyAndExit && !CompileTask::reason_is_precompiled(compile_reason)) {
1646     return nullptr;
1647   }
1648 
1649   // lock, make sure that the compilation
1650   // isn't prohibited in a straightforward way.
1651   AbstractCompiler* comp = CompileBroker::compiler(comp_level);
1652   if (comp == nullptr || compilation_is_prohibited(method, osr_bci, comp_level, directive->ExcludeOption)) {
1653     return nullptr;
1654   }
1655 
1656   if (osr_bci == InvocationEntryBci) {
1657     // standard compilation
1658     nmethod* method_code = method->code();
1659     if (method_code != nullptr) {
1660       if (compilation_is_complete(method(), osr_bci, comp_level, requires_online_compilation, compile_reason)) {
1661         return method_code;
1662       }
1663     }
1664     if (method->is_not_compilable(comp_level)) {
1665       return nullptr;
1666     }
1667   } else {
1668     // osr compilation
1669     // We accept a higher level osr method
1670     nmethod* nm = method->lookup_osr_nmethod_for(osr_bci, comp_level, false);
1671     if (nm != nullptr) return nm;
1672     if (method->is_not_osr_compilable(comp_level)) return nullptr;
1673   }
1674 
1675   assert(!HAS_PENDING_EXCEPTION, "No exception should be present");
1676   // some prerequisites that are compiler specific
1677   if (compile_reason != CompileTask::Reason_Preload &&
1678       !CompileTask::reason_is_precompiled(compile_reason) &&
1679      (comp->is_c2() || comp->is_jvmci())) {
1680     InternalOOMEMark iom(THREAD);
1681     method->constants()->resolve_string_constants(CHECK_AND_CLEAR_NONASYNC_NULL);
1682     // Resolve all classes seen in the signature of the method
1683     // we are compiling.
1684     Method::load_signature_classes(method, CHECK_AND_CLEAR_NONASYNC_NULL);
1685   }
1686 
1687   // If the method is native, do the lookup in the thread requesting
1688   // the compilation. Native lookups can load code, which is not
1689   // permitted during compilation.
1690   //
1691   // Note: A native method implies non-osr compilation which is
1692   //       checked with an assertion at the entry of this method.
1693   if (method->is_native() && !method->is_method_handle_intrinsic()) {
1694     address adr = NativeLookup::lookup(method, THREAD);
1695     if (HAS_PENDING_EXCEPTION) {
1696       // In case of an exception looking up the method, we just forget
1697       // about it. The interpreter will kick-in and throw the exception.
1698       method->set_not_compilable("NativeLookup::lookup failed"); // implies is_not_osr_compilable()
1699       CLEAR_PENDING_EXCEPTION;

1714   }
1715 
1716   // do the compilation
1717   if (method->is_native()) {
1718     if (!PreferInterpreterNativeStubs || method->is_method_handle_intrinsic()) {
1719       // To properly handle the appendix argument for out-of-line calls we are using a small trampoline that
1720       // pops off the appendix argument and jumps to the target (see gen_special_dispatch in SharedRuntime).
1721       //
1722       // Since normal compiled-to-compiled calls are not able to handle such a thing we MUST generate an adapter
1723       // in this case.  If we can't generate one and use it we can not execute the out-of-line method handle calls.
1724       AdapterHandlerLibrary::create_native_wrapper(method);
1725     } else {
1726       return nullptr;
1727     }
1728   } else {
1729     // If the compiler is shut off due to code cache getting full
1730     // fail out now so blocking compiles dont hang the java thread
1731     if (!should_compile_new_jobs()) {
1732       return nullptr;
1733     }
1734     bool is_blocking = ReplayCompiles                                             ||
1735                        !directive->BackgroundCompilationOption                    ||
1736                        (PreloadBlocking && (compile_reason == CompileTask::Reason_Preload));
1737     compile_method_base(method, osr_bci, comp_level, hot_method, hot_count, compile_reason, requires_online_compilation, is_blocking, THREAD);
1738   }
1739 
1740   // return requested nmethod
1741   // We accept a higher level osr method
1742   if (osr_bci == InvocationEntryBci) {
1743     return method->code();
1744   }
1745   return method->lookup_osr_nmethod_for(osr_bci, comp_level, false);
1746 }
1747 
1748 
1749 // ------------------------------------------------------------------
1750 // CompileBroker::compilation_is_complete
1751 //
1752 // See if compilation of this method is already complete.
1753 bool CompileBroker::compilation_is_complete(Method*                    method,
1754                                             int                        osr_bci,
1755                                             int                        comp_level,
1756                                             bool                       online_only,
1757                                             CompileTask::CompileReason compile_reason) {
1758   if (compile_reason == CompileTask::Reason_Precompile ||
1759       compile_reason == CompileTask::Reason_PrecompileForPreload) {
1760     return false; // FIXME: any restrictions?
1761   }
1762   bool is_osr = (osr_bci != standard_entry_bci);
1763   if (is_osr) {
1764     if (method->is_not_osr_compilable(comp_level)) {
1765       return true;
1766     } else {
1767       nmethod* result = method->lookup_osr_nmethod_for(osr_bci, comp_level, true);
1768       return (result != nullptr);
1769     }
1770   } else {
1771     if (method->is_not_compilable(comp_level)) {
1772       return true;
1773     } else {
1774       nmethod* result = method->code();
1775       if (result == nullptr) {
1776         return false;
1777       }
1778       if (online_only && result->is_scc()) {
1779         return false;
1780       }
1781       bool same_level = (comp_level == result->comp_level());
1782       if (result->has_clinit_barriers()) {
1783         return !same_level; // Allow replace preloaded code with new code of the same level
1784       }
1785       return same_level;
1786     }
1787   }
1788 }
1789 
1790 
1791 /**
1792  * See if this compilation is already requested.
1793  *
1794  * Implementation note: there is only a single "is in queue" bit
1795  * for each method.  This means that the check below is overly
1796  * conservative in the sense that an osr compilation in the queue
1797  * will block a normal compilation from entering the queue (and vice
1798  * versa).  This can be remedied by a full queue search to disambiguate
1799  * cases.  If it is deemed profitable, this may be done.
1800  */
1801 bool CompileBroker::compilation_is_in_queue(const methodHandle& method) {
1802   return method->queued_for_compilation();
1803 }
1804 
1805 // ------------------------------------------------------------------

1865     if (CIStart <= id && id < CIStop) {
1866       return id;
1867     }
1868   }
1869 
1870   // Method was not in the appropriate compilation range.
1871   method->set_not_compilable_quietly("Not in requested compile id range");
1872   return 0;
1873 #else
1874   // CICountOSR is a develop flag and set to 'false' by default. In a product built,
1875   // only _compilation_id is incremented.
1876   return Atomic::add(&_compilation_id, 1);
1877 #endif
1878 }
1879 
1880 // ------------------------------------------------------------------
1881 // CompileBroker::assign_compile_id_unlocked
1882 //
1883 // Public wrapper for assign_compile_id that acquires the needed locks
1884 int CompileBroker::assign_compile_id_unlocked(Thread* thread, const methodHandle& method, int osr_bci) {

1885   return assign_compile_id(method, osr_bci);
1886 }
1887 
1888 // ------------------------------------------------------------------
1889 // CompileBroker::create_compile_task
1890 //
1891 // Create a CompileTask object representing the current request for
1892 // compilation.  Add this task to the queue.
1893 CompileTask* CompileBroker::create_compile_task(CompileQueue*       queue,
1894                                                 int                 compile_id,
1895                                                 const methodHandle& method,
1896                                                 int                 osr_bci,
1897                                                 int                 comp_level,
1898                                                 const methodHandle& hot_method,
1899                                                 int                 hot_count,
1900                                                 SCCEntry*           scc_entry,
1901                                                 CompileTask::CompileReason compile_reason,
1902                                                 bool                requires_online_compilation,
1903                                                 bool                blocking) {
1904   CompileTask* new_task = CompileTask::allocate();
1905   new_task->initialize(compile_id, method, osr_bci, comp_level,
1906                        hot_method, hot_count, scc_entry, compile_reason, queue,
1907                        requires_online_compilation, blocking);

1908   return new_task;
1909 }
1910 
1911 #if INCLUDE_JVMCI
1912 // The number of milliseconds to wait before checking if
1913 // JVMCI compilation has made progress.
1914 static const long JVMCI_COMPILATION_PROGRESS_WAIT_TIMESLICE = 1000;
1915 
1916 // The number of JVMCI compilation progress checks that must fail
1917 // before unblocking a thread waiting for a blocking compilation.
1918 static const int JVMCI_COMPILATION_PROGRESS_WAIT_ATTEMPTS = 10;
1919 
1920 /**
1921  * Waits for a JVMCI compiler to complete a given task. This thread
1922  * waits until either the task completes or it sees no JVMCI compilation
1923  * progress for N consecutive milliseconds where N is
1924  * JVMCI_COMPILATION_PROGRESS_WAIT_TIMESLICE *
1925  * JVMCI_COMPILATION_PROGRESS_WAIT_ATTEMPTS.
1926  *
1927  * @return true if this thread needs to free/recycle the task

2006   }
2007 
2008   if (free_task) {
2009     if (is_compilation_disabled_forever()) {
2010       CompileTask::free(task);
2011       return;
2012     }
2013 
2014     // It is harmless to check this status without the lock, because
2015     // completion is a stable property (until the task object is recycled).
2016     assert(task->is_complete(), "Compilation should have completed");
2017 
2018     // By convention, the waiter is responsible for recycling a
2019     // blocking CompileTask. Since there is only one waiter ever
2020     // waiting on a CompileTask, we know that no one else will
2021     // be using this CompileTask; we can free it.
2022     CompileTask::free(task);
2023   }
2024 }
2025 
2026 void CompileBroker::wait_for_no_active_tasks() {
2027   CompileTask::wait_for_no_active_tasks();
2028 }
2029 
2030 /**
2031  * Initialize compiler thread(s) + compiler object(s). The postcondition
2032  * of this function is that the compiler runtimes are initialized and that
2033  * compiler threads can start compiling.
2034  */
2035 bool CompileBroker::init_compiler_runtime() {
2036   CompilerThread* thread = CompilerThread::current();
2037   AbstractCompiler* comp = thread->compiler();
2038   // Final sanity check - the compiler object must exist
2039   guarantee(comp != nullptr, "Compiler object must exist");
2040 
2041   {
2042     // Must switch to native to allocate ci_env
2043     ThreadToNativeFromVM ttn(thread);
2044     ciEnv ci_env((CompileTask*)nullptr);
2045     // Cache Jvmti state
2046     ci_env.cache_jvmti_state();
2047     // Cache DTrace flags
2048     ci_env.cache_dtrace_flags();
2049 
2050     // Switch back to VM state to do compiler initialization
2051     ThreadInVMfromNative tv(thread);
2052 

2053     comp->initialize();
2054   }
2055 
2056   if (comp->is_failed()) {
2057     disable_compilation_forever();
2058     // If compiler initialization failed, no compiler thread that is specific to a
2059     // particular compiler runtime will ever start to compile methods.
2060     shutdown_compiler_runtime(comp, thread);
2061     return false;
2062   }
2063 
2064   // C1 specific check
2065   if (comp->is_c1() && (thread->get_buffer_blob() == nullptr)) {
2066     warning("Initialization of %s thread failed (no space to run compilers)", thread->name());
2067     return false;
2068   }
2069 
2070   return true;
2071 }
2072 
2073 void CompileBroker::free_buffer_blob_if_allocated(CompilerThread* thread) {
2074   BufferBlob* blob = thread->get_buffer_blob();
2075   if (blob != nullptr) {
2076     blob->purge();
2077     MutexLocker mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
2078     CodeCache::free(blob);
2079   }
2080 }
2081 
2082 /**
2083  * If C1 and/or C2 initialization failed, we shut down all compilation.
2084  * We do this to keep things simple. This can be changed if it ever turns
2085  * out to be a problem.
2086  */
2087 void CompileBroker::shutdown_compiler_runtime(AbstractCompiler* comp, CompilerThread* thread) {
2088   free_buffer_blob_if_allocated(thread);
2089 
2090   log_info(compilation)("shutdown_compiler_runtime: " INTPTR_FORMAT, p2i(thread));
2091 
2092   if (comp->should_perform_shutdown()) {
2093     // There are two reasons for shutting down the compiler
2094     // 1) compiler runtime initialization failed
2095     // 2) The code cache is full and the following flag is set: -XX:-UseCodeCacheFlushing
2096     warning("%s initialization failed. Shutting down all compilers", comp->name());
2097 
2098     // Only one thread per compiler runtime object enters here
2099     // Set state to shut down
2100     comp->set_shut_down();
2101 
2102     // Delete all queued compilation tasks to make compiler threads exit faster.
2103     if (_c1_compile_queue != nullptr) {
2104       _c1_compile_queue->free_all();
2105     }
2106 
2107     if (_c2_compile_queue != nullptr) {
2108       _c2_compile_queue->free_all();
2109     }
2110 
2111     if (_c3_compile_queue != nullptr) {
2112       _c3_compile_queue->free_all();
2113     }
2114 
2115     // Set flags so that we continue execution with using interpreter only.
2116     UseCompiler    = false;
2117     UseInterpreter = true;
2118 
2119     // We could delete compiler runtimes also. However, there are references to
2120     // the compiler runtime(s) (e.g.,  nmethod::is_compiled_by_c1()) which then
2121     // fail. This can be done later if necessary.
2122   }
2123 }
2124 
2125 /**
2126  * Helper function to create new or reuse old CompileLog.
2127  */
2128 CompileLog* CompileBroker::get_log(CompilerThread* ct) {
2129   if (!LogCompilation) return nullptr;
2130 
2131   AbstractCompiler *compiler = ct->compiler();
2132   bool jvmci = JVMCI_ONLY( compiler->is_jvmci() ||) false;
2133   bool c1 = compiler->is_c1();
2134   jobject* compiler_objects = c1 ? _compiler1_objects : (_c3_count == 0 ? _compiler2_objects : (jvmci ? _compiler2_objects : _compiler3_objects));
2135   assert(compiler_objects != nullptr, "must be initialized at this point");
2136   CompileLog** logs = c1 ? _compiler1_logs : (_c3_count == 0 ? _compiler2_logs : (jvmci ? _compiler2_logs : _compiler3_logs));
2137   assert(logs != nullptr, "must be initialized at this point");
2138   int count = c1 ? _c1_count : (_c3_count == 0 ? _c2_count : (jvmci ? _c2_count : _c3_count));
2139 
2140   if (ct->queue() == _sc1_compile_queue || ct->queue() == _sc2_compile_queue) {
2141     compiler_objects = _sc_objects;
2142     logs  = _sc_logs;
2143     count = _sc_count;
2144   }
2145   // Find Compiler number by its threadObj.
2146   oop compiler_obj = ct->threadObj();
2147   int compiler_number = 0;
2148   bool found = false;
2149   for (; compiler_number < count; compiler_number++) {
2150     if (JNIHandles::resolve_non_null(compiler_objects[compiler_number]) == compiler_obj) {
2151       found = true;
2152       break;
2153     }
2154   }
2155   assert(found, "Compiler must exist at this point");
2156 
2157   // Determine pointer for this thread's log.
2158   CompileLog** log_ptr = &logs[compiler_number];
2159 
2160   // Return old one if it exists.
2161   CompileLog* log = *log_ptr;
2162   if (log != nullptr) {
2163     ct->init_log(log);
2164     return log;

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

2446 
2447 // Acquires Compilation_lock and waits for it to be notified
2448 // as long as WhiteBox::compilation_locked is true.
2449 static void whitebox_lock_compilation() {
2450   MonitorLocker locker(Compilation_lock, Mutex::_no_safepoint_check_flag);
2451   while (WhiteBox::compilation_locked) {
2452     locker.wait();
2453   }
2454 }
2455 
2456 // ------------------------------------------------------------------
2457 // CompileBroker::invoke_compiler_on_method
2458 //
2459 // Compile a method.
2460 //
2461 void CompileBroker::invoke_compiler_on_method(CompileTask* task) {
2462   task->print_ul();
2463   elapsedTimer time;
2464 
2465   DirectiveSet* directive = task->directive();




2466 
2467   CompilerThread* thread = CompilerThread::current();
2468   ResourceMark rm(thread);
2469 
2470   if (CompilationLog::log() != nullptr) {
2471     CompilationLog::log()->log_compile(thread, task);
2472   }
2473 
2474   // Common flags.
2475   int compile_id = task->compile_id();
2476   int osr_bci = task->osr_bci();
2477   bool is_osr = (osr_bci != standard_entry_bci);
2478   bool should_log = (thread->log() != nullptr);
2479   bool should_break = false;
2480   bool should_print_compilation = PrintCompilation || directive->PrintCompilationOption;
2481   const int task_level = task->comp_level();
2482   AbstractCompiler* comp = task->compiler();
2483   {
2484     // create the handle inside it's own block so it can't
2485     // accidentally be referenced once the thread transitions to
2486     // native.  The NoHandleMark before the transition should catch
2487     // any cases where this occurs in the future.
2488     methodHandle method(thread, task->method());
2489 
2490     assert(!method->is_native(), "no longer compile natives");
2491 
2492     // Update compile information when using perfdata.
2493     if (UsePerfData) {
2494       update_compile_perf_data(thread, method, is_osr);
2495     }
2496 
2497     DTRACE_METHOD_COMPILE_BEGIN_PROBE(method, compiler_name(task_level));
2498   }
2499 
2500   should_break = directive->BreakAtCompileOption || task->check_break_at_flags();

2605 
2606     if (comp == nullptr) {
2607       ci_env.record_method_not_compilable("no compiler");
2608     } else if (!ci_env.failing()) {
2609       if (WhiteBoxAPI && WhiteBox::compilation_locked) {
2610         whitebox_lock_compilation();
2611       }
2612       comp->compile_method(&ci_env, target, osr_bci, true, directive);
2613 
2614       /* Repeat compilation without installing code for profiling purposes */
2615       int repeat_compilation_count = directive->RepeatCompilationOption;
2616       while (repeat_compilation_count > 0) {
2617         ResourceMark rm(thread);
2618         task->print_ul("NO CODE INSTALLED");
2619         comp->compile_method(&ci_env, target, osr_bci, false, directive);
2620         repeat_compilation_count--;
2621       }
2622     }
2623 
2624 
2625     if (!ci_env.failing() && !task->is_success() && !task->is_precompiled()) {
2626       assert(ci_env.failure_reason() != nullptr, "expect failure reason");
2627       assert(false, "compiler should always document failure: %s", ci_env.failure_reason());
2628       // The compiler elected, without comment, not to register a result.
2629       // Do not attempt further compilations of this method.
2630       ci_env.record_method_not_compilable("compile failed");
2631     }
2632 
2633     // Copy this bit to the enclosing block:
2634     compilable = ci_env.compilable();
2635 
2636     if (ci_env.failing()) {
2637       // Duplicate the failure reason string, so that it outlives ciEnv
2638       failure_reason = os::strdup(ci_env.failure_reason(), mtCompiler);
2639       failure_reason_on_C_heap = true;
2640       retry_message = ci_env.retry_message();
2641       ci_env.report_failure(failure_reason);
2642     }
2643 
2644     if (ci_env.failing()) {
2645       handle_compile_error(thread, task, &ci_env, compilable, failure_reason);
2646     }
2647     if (event.should_commit()) {
2648       post_compilation_event(event, task);
2649     }
2650   }
2651 
2652   if (failure_reason != nullptr) {
2653     task->set_failure_reason(failure_reason, failure_reason_on_C_heap);
2654     if (CompilationLog::log() != nullptr) {
2655       CompilationLog::log()->log_failure(thread, task, failure_reason, retry_message);
2656     }
2657     if (PrintCompilation || directive->PrintCompilationOption) {
2658       FormatBufferResource msg = retry_message != nullptr ?
2659         FormatBufferResource("COMPILE SKIPPED: %s (%s)", failure_reason, retry_message) :
2660         FormatBufferResource("COMPILE SKIPPED: %s",      failure_reason);
2661       task->print(tty, msg);
2662     }
2663   }
2664 
2665   task->mark_finished(os::elapsed_counter());
2666   DirectivesStack::release(directive);
2667 
2668   methodHandle method(thread, task->method());
2669 
2670   DTRACE_METHOD_COMPILE_END_PROBE(method, compiler_name(task_level), task->is_success());
2671 
2672   collect_statistics(thread, time, task);
2673 
2674   if (PrintCompilation && PrintCompilation2) {
2675     tty->print("%7d ", (int) tty->time_stamp().milliseconds());  // print timestamp
2676     tty->print("%4d ", compile_id);    // print compilation number
2677     tty->print("%s ", (is_osr ? "%" : (task->is_scc() ? "A" : " ")));
2678     if (task->is_success()) {
2679       tty->print("size: %d(%d) ", task->nm_total_size(), task->nm_insts_size());
2680     }
2681     tty->print_cr("time: %d inlined: %d bytes", (int)time.milliseconds(), task->num_inlined_bytecodes());
2682   }
2683 
2684   Log(compilation, codecache) log;
2685   if (log.is_debug()) {
2686     LogStream ls(log.debug());
2687     codecache_print(&ls, /* detailed= */ false);
2688   }
2689   if (PrintCodeCacheOnCompilation) {
2690     codecache_print(/* detailed= */ false);
2691   }
2692   // Disable compilation, if required.
2693   switch (compilable) {
2694   case ciEnv::MethodCompilable_never:
2695     if (is_osr)
2696       method->set_not_osr_compilable_quietly("MethodCompilable_never");
2697     else
2698       method->set_not_compilable_quietly("MethodCompilable_never");
2699     break;
2700   case ciEnv::MethodCompilable_not_at_tier:
2701     if (is_osr)
2702       method->set_not_osr_compilable_quietly("MethodCompilable_not_at_tier", task_level);
2703     else
2704       method->set_not_compilable_quietly("MethodCompilable_not_at_tier", task_level);
2705     break;
2706   }
2707 
2708   // Note that the queued_for_compilation bits are cleared without
2709   // protection of a mutex. [They were set by the requester thread,
2710   // when adding the task to the compile queue -- at which time the
2711   // compile queue lock was held. Subsequently, we acquired the compile
2712   // queue lock to get this task off the compile queue; thus (to belabour
2713   // the point somewhat) our clearing of the bits must be occurring
2714   // only after the setting of the bits. See also 14012000 above.
2715   method->clear_queued_for_compilation();
2716   method->set_pending_queue_processed(false);
2717 
2718   if (should_print_compilation) {
2719     ResourceMark rm;
2720     task->print_tty();
2721   }
2722 }
2723 
2724 /**
2725  * The CodeCache is full. Print warning and disable compilation.
2726  * Schedule code cache cleaning so compilation can continue later.
2727  * This function needs to be called only from CodeCache::allocate(),
2728  * since we currently handle a full code cache uniformly.
2729  */
2730 void CompileBroker::handle_full_code_cache(CodeBlobType code_blob_type) {
2731   UseInterpreter = true;
2732   if (UseCompiler || AlwaysCompileLoopMethods ) {
2733     if (xtty != nullptr) {
2734       stringStream s;
2735       // Dump code cache state into a buffer before locking the tty,
2736       // because log_state() will use locks causing lock conflicts.
2737       CodeCache::log_state(&s);
2738       // Lock to prevent tearing
2739       ttyLocker ttyl;
2740       xtty->begin_elem("code_cache_full");
2741       xtty->print("%s", s.freeze());

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

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

3179 
3180   tty->cr();
3181   tty->print_cr("Accumulated compiler times");
3182   tty->print_cr("----------------------------------------------------------");
3183                //0000000000111111111122222222223333333333444444444455555555556666666666
3184                //0123456789012345678901234567890123456789012345678901234567890123456789
3185   tty->print_cr("  Total compilation time   : %7.3f s", total_compilation.seconds());
3186   tty->print_cr("    Standard compilation   : %7.3f s, Average : %2.3f s",
3187                 standard_compilation.seconds(),
3188                 standard_compile_count == 0 ? 0.0 : standard_compilation.seconds() / standard_compile_count);
3189   tty->print_cr("    Bailed out compilation : %7.3f s, Average : %2.3f s",
3190                 CompileBroker::_t_bailedout_compilation.seconds(),
3191                 total_bailout_count == 0 ? 0.0 : CompileBroker::_t_bailedout_compilation.seconds() / total_bailout_count);
3192   tty->print_cr("    On stack replacement   : %7.3f s, Average : %2.3f s",
3193                 osr_compilation.seconds(),
3194                 osr_compile_count == 0 ? 0.0 : osr_compilation.seconds() / osr_compile_count);
3195   tty->print_cr("    Invalidated            : %7.3f s, Average : %2.3f s",
3196                 CompileBroker::_t_invalidated_compilation.seconds(),
3197                 total_invalidated_count == 0 ? 0.0 : CompileBroker::_t_invalidated_compilation.seconds() / total_invalidated_count);
3198 
3199   if (StoreCachedCode || LoadCachedCode) { // Check flags because SC cache could be closed already
3200     tty->cr();
3201     SCCache::print_timers_on(tty);
3202   }
3203   AbstractCompiler *comp = compiler(CompLevel_simple);
3204   if (comp != nullptr) {
3205     tty->cr();
3206     comp->print_timers();
3207   }
3208   comp = compiler(CompLevel_full_optimization);
3209   if (comp != nullptr) {
3210     tty->cr();
3211     comp->print_timers();
3212   }
3213   comp = _compilers[2];
3214   if (comp != nullptr) {
3215     tty->cr();
3216     comp->print_timers();
3217   }
3218 #if INCLUDE_JVMCI
3219   if (EnableJVMCI) {
3220     JVMCICompiler *jvmci_comp = JVMCICompiler::instance(false, JavaThread::current_or_null());
3221     if (jvmci_comp != nullptr && jvmci_comp != comp) {
3222       tty->cr();
3223       jvmci_comp->print_timers();
3224     }
3225   }
3226 #endif
3227 
3228   tty->cr();
3229   tty->print_cr("  Total compiled methods    : %8u methods", total_compile_count);
3230   tty->print_cr("    Standard compilation    : %8u methods", standard_compile_count);
3231   tty->print_cr("    On stack replacement    : %8u methods", osr_compile_count);
3232   uint tcb = osr_bytes_compiled + standard_bytes_compiled;
3233   tty->print_cr("  Total compiled bytecodes  : %8u bytes", tcb);
3234   tty->print_cr("    Standard compilation    : %8u bytes", standard_bytes_compiled);
3235   tty->print_cr("    On stack replacement    : %8u bytes", osr_bytes_compiled);
3236   double tcs = total_compilation.seconds();
3237   uint bps = tcs == 0.0 ? 0 : (uint)(tcb / tcs);
< prev index next >