1 /*
   2  * Copyright (c) 1999, 2024, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "precompiled.hpp"
  26 #include "cds/classPrelinker.hpp"
  27 #include "classfile/javaClasses.inline.hpp"
  28 #include "classfile/symbolTable.hpp"
  29 #include "classfile/vmClasses.hpp"
  30 #include "classfile/vmSymbols.hpp"
  31 #include "code/codeCache.hpp"
  32 #include "code/codeHeapState.hpp"
  33 #include "code/dependencyContext.hpp"
  34 #include "code/SCCache.hpp"
  35 #include "compiler/compilationLog.hpp"
  36 #include "compiler/compilationMemoryStatistic.hpp"
  37 #include "compiler/compilationPolicy.hpp"
  38 #include "compiler/compileBroker.hpp"
  39 #include "compiler/compilerDefinitions.inline.hpp"
  40 #include "compiler/compileLog.hpp"
  41 #include "compiler/compilerEvent.hpp"
  42 #include "compiler/compilerOracle.hpp"
  43 #include "compiler/directivesParser.hpp"
  44 #include "interpreter/linkResolver.hpp"
  45 #include "jvm.h"
  46 #include "jfr/jfrEvents.hpp"
  47 #include "logging/log.hpp"
  48 #include "logging/logStream.hpp"
  49 #include "memory/allocation.inline.hpp"
  50 #include "memory/resourceArea.hpp"
  51 #include "memory/universe.hpp"
  52 #include "oops/methodData.hpp"
  53 #include "oops/method.inline.hpp"
  54 #include "oops/oop.inline.hpp"
  55 #include "prims/jvmtiExport.hpp"
  56 #include "prims/nativeLookup.hpp"
  57 #include "prims/whitebox.hpp"
  58 #include "runtime/atomic.hpp"
  59 #include "runtime/escapeBarrier.hpp"
  60 #include "runtime/globals_extension.hpp"
  61 #include "runtime/handles.inline.hpp"
  62 #include "runtime/init.hpp"
  63 #include "runtime/interfaceSupport.inline.hpp"
  64 #include "runtime/java.hpp"
  65 #include "runtime/javaCalls.hpp"
  66 #include "runtime/jniHandles.inline.hpp"
  67 #include "runtime/os.hpp"
  68 #include "runtime/perfData.hpp"
  69 #include "runtime/safepointVerifiers.hpp"
  70 #include "runtime/sharedRuntime.hpp"
  71 #include "runtime/threads.hpp"
  72 #include "runtime/threadSMR.inline.hpp"
  73 #include "runtime/timerTrace.hpp"
  74 #include "runtime/vframe.inline.hpp"
  75 #include "services/management.hpp"
  76 #include "utilities/debug.hpp"
  77 #include "utilities/dtrace.hpp"
  78 #include "utilities/events.hpp"
  79 #include "utilities/formatBuffer.hpp"
  80 #include "utilities/macros.hpp"
  81 #ifdef COMPILER1
  82 #include "c1/c1_Compiler.hpp"
  83 #endif
  84 #ifdef COMPILER2
  85 #include "opto/c2compiler.hpp"
  86 #endif
  87 #if INCLUDE_JVMCI
  88 #include "jvmci/jvmciEnv.hpp"
  89 #include "jvmci/jvmciRuntime.hpp"
  90 #endif
  91 
  92 #ifdef DTRACE_ENABLED
  93 
  94 // Only bother with this argument setup if dtrace is available
  95 
  96 #define DTRACE_METHOD_COMPILE_BEGIN_PROBE(method, comp_name)             \
  97   {                                                                      \
  98     Symbol* klass_name = (method)->klass_name();                         \
  99     Symbol* name = (method)->name();                                     \
 100     Symbol* signature = (method)->signature();                           \
 101     HOTSPOT_METHOD_COMPILE_BEGIN(                                        \
 102       (char *) comp_name, strlen(comp_name),                             \
 103       (char *) klass_name->bytes(), klass_name->utf8_length(),           \
 104       (char *) name->bytes(), name->utf8_length(),                       \
 105       (char *) signature->bytes(), signature->utf8_length());            \
 106   }
 107 
 108 #define DTRACE_METHOD_COMPILE_END_PROBE(method, comp_name, success)      \
 109   {                                                                      \
 110     Symbol* klass_name = (method)->klass_name();                         \
 111     Symbol* name = (method)->name();                                     \
 112     Symbol* signature = (method)->signature();                           \
 113     HOTSPOT_METHOD_COMPILE_END(                                          \
 114       (char *) comp_name, strlen(comp_name),                             \
 115       (char *) klass_name->bytes(), klass_name->utf8_length(),           \
 116       (char *) name->bytes(), name->utf8_length(),                       \
 117       (char *) signature->bytes(), signature->utf8_length(), (success)); \
 118   }
 119 
 120 #else //  ndef DTRACE_ENABLED
 121 
 122 #define DTRACE_METHOD_COMPILE_BEGIN_PROBE(method, comp_name)
 123 #define DTRACE_METHOD_COMPILE_END_PROBE(method, comp_name, success)
 124 
 125 #endif // ndef DTRACE_ENABLED
 126 
 127 bool CompileBroker::_initialized = false;
 128 volatile bool CompileBroker::_should_block = false;
 129 volatile int  CompileBroker::_print_compilation_warning = 0;
 130 volatile jint CompileBroker::_should_compile_new_jobs = run_compilation;
 131 
 132 // The installed compiler(s)
 133 AbstractCompiler* CompileBroker::_compilers[3];
 134 
 135 // The maximum numbers of compiler threads to be determined during startup.
 136 int CompileBroker::_c1_count = 0;
 137 int CompileBroker::_c2_count = 0;
 138 int CompileBroker::_c3_count = 0;
 139 int CompileBroker::_sc_count = 0;
 140 
 141 // An array of compiler names as Java String objects
 142 jobject* CompileBroker::_compiler1_objects = nullptr;
 143 jobject* CompileBroker::_compiler2_objects = nullptr;
 144 jobject* CompileBroker::_compiler3_objects = nullptr;
 145 jobject* CompileBroker::_sc_objects = nullptr;
 146 
 147 CompileLog** CompileBroker::_compiler1_logs = nullptr;
 148 CompileLog** CompileBroker::_compiler2_logs = nullptr;
 149 CompileLog** CompileBroker::_compiler3_logs = nullptr;
 150 CompileLog** CompileBroker::_sc_logs = nullptr;
 151 
 152 // These counters are used to assign an unique ID to each compilation.
 153 volatile jint CompileBroker::_compilation_id     = 0;
 154 volatile jint CompileBroker::_osr_compilation_id = 0;
 155 volatile jint CompileBroker::_native_compilation_id = 0;
 156 
 157 // Performance counters
 158 PerfCounter* CompileBroker::_perf_total_compilation = nullptr;
 159 PerfCounter* CompileBroker::_perf_osr_compilation = nullptr;
 160 PerfCounter* CompileBroker::_perf_standard_compilation = nullptr;
 161 
 162 PerfCounter* CompileBroker::_perf_total_bailout_count = nullptr;
 163 PerfCounter* CompileBroker::_perf_total_invalidated_count = nullptr;
 164 PerfCounter* CompileBroker::_perf_total_compile_count = nullptr;
 165 PerfCounter* CompileBroker::_perf_total_osr_compile_count = nullptr;
 166 PerfCounter* CompileBroker::_perf_total_standard_compile_count = nullptr;
 167 
 168 PerfCounter* CompileBroker::_perf_sum_osr_bytes_compiled = nullptr;
 169 PerfCounter* CompileBroker::_perf_sum_standard_bytes_compiled = nullptr;
 170 PerfCounter* CompileBroker::_perf_sum_nmethod_size = nullptr;
 171 PerfCounter* CompileBroker::_perf_sum_nmethod_code_size = nullptr;
 172 
 173 PerfStringVariable* CompileBroker::_perf_last_method = nullptr;
 174 PerfStringVariable* CompileBroker::_perf_last_failed_method = nullptr;
 175 PerfStringVariable* CompileBroker::_perf_last_invalidated_method = nullptr;
 176 PerfVariable*       CompileBroker::_perf_last_compile_type = nullptr;
 177 PerfVariable*       CompileBroker::_perf_last_compile_size = nullptr;
 178 PerfVariable*       CompileBroker::_perf_last_failed_type = nullptr;
 179 PerfVariable*       CompileBroker::_perf_last_invalidated_type = nullptr;
 180 
 181 // Timers and counters for generating statistics
 182 elapsedTimer CompileBroker::_t_total_compilation;
 183 elapsedTimer CompileBroker::_t_osr_compilation;
 184 elapsedTimer CompileBroker::_t_standard_compilation;
 185 elapsedTimer CompileBroker::_t_invalidated_compilation;
 186 elapsedTimer CompileBroker::_t_bailedout_compilation;
 187 
 188 uint CompileBroker::_total_bailout_count            = 0;
 189 uint CompileBroker::_total_invalidated_count        = 0;
 190 uint CompileBroker::_total_not_entrant_count        = 0;
 191 uint CompileBroker::_total_compile_count            = 0;
 192 uint CompileBroker::_total_osr_compile_count        = 0;
 193 uint CompileBroker::_total_standard_compile_count   = 0;
 194 uint CompileBroker::_total_compiler_stopped_count   = 0;
 195 uint CompileBroker::_total_compiler_restarted_count = 0;
 196 
 197 uint CompileBroker::_sum_osr_bytes_compiled         = 0;
 198 uint CompileBroker::_sum_standard_bytes_compiled    = 0;
 199 uint CompileBroker::_sum_nmethod_size               = 0;
 200 uint CompileBroker::_sum_nmethod_code_size          = 0;
 201 
 202 jlong CompileBroker::_peak_compilation_time        = 0;
 203 
 204 CompilerStatistics CompileBroker::_stats_per_level[CompLevel_full_optimization];
 205 CompilerStatistics CompileBroker::_scc_stats;
 206 CompilerStatistics CompileBroker::_scc_stats_per_level[CompLevel_full_optimization + 1];
 207 
 208 CompileQueue* CompileBroker::_c3_compile_queue     = nullptr;
 209 CompileQueue* CompileBroker::_c2_compile_queue     = nullptr;
 210 CompileQueue* CompileBroker::_c1_compile_queue     = nullptr;
 211 CompileQueue* CompileBroker::_sc1_compile_queue    = nullptr;
 212 CompileQueue* CompileBroker::_sc2_compile_queue    = nullptr;
 213 
 214 bool compileBroker_init() {
 215   if (LogEvents) {
 216     CompilationLog::init();
 217   }
 218 
 219   // init directives stack, adding default directive
 220   DirectivesStack::init();
 221 
 222   if (DirectivesParser::has_file()) {
 223     return DirectivesParser::parse_from_flag();
 224   } else if (CompilerDirectivesPrint) {
 225     // Print default directive even when no other was added
 226     DirectivesStack::print(tty);
 227   }
 228 
 229   return true;
 230 }
 231 
 232 CompileTaskWrapper::CompileTaskWrapper(CompileTask* task) {
 233   CompilerThread* thread = CompilerThread::current();
 234   thread->set_task(task);
 235   CompileLog*     log  = thread->log();
 236   if (log != nullptr && !task->is_unloaded())  task->log_task_start(log);
 237 }
 238 
 239 CompileTaskWrapper::~CompileTaskWrapper() {
 240   CompilerThread* thread = CompilerThread::current();
 241   CompileTask* task = thread->task();
 242   CompileLog*  log  = thread->log();
 243   AbstractCompiler* comp = thread->compiler();
 244   if (log != nullptr && !task->is_unloaded())  task->log_task_done(log);
 245   thread->set_task(nullptr);
 246   thread->set_env(nullptr);
 247   if (task->is_blocking()) {
 248     bool free_task = false;
 249     {
 250       MutexLocker notifier(thread, task->lock());
 251       task->mark_complete();
 252 #if INCLUDE_JVMCI
 253       if (comp->is_jvmci()) {
 254         if (!task->has_waiter()) {
 255           // The waiting thread timed out and thus did not free the task.
 256           free_task = true;
 257         }
 258         task->set_blocking_jvmci_compile_state(nullptr);
 259       }
 260 #endif
 261       if (!free_task) {
 262         // Notify the waiting thread that the compilation has completed
 263         // so that it can free the task.
 264         task->lock()->notify_all();
 265       }
 266     }
 267     if (free_task) {
 268       // The task can only be freed once the task lock is released.
 269       CompileTask::free(task);
 270     }
 271   } else {
 272     task->mark_complete();
 273 
 274     // By convention, the compiling thread is responsible for
 275     // recycling a non-blocking CompileTask.
 276     CompileTask::free(task);
 277   }
 278 }
 279 
 280 /**
 281  * Check if a CompilerThread can be removed and update count if requested.
 282  */
 283 bool CompileBroker::can_remove(CompilerThread *ct, bool do_it) {
 284   assert(UseDynamicNumberOfCompilerThreads, "or shouldn't be here");
 285   if (!ReduceNumberOfCompilerThreads) return false;
 286 
 287   if (CompilationPolicy::have_recompilation_work()) return false;
 288 
 289   AbstractCompiler *compiler = ct->compiler();
 290   int compiler_count = compiler->num_compiler_threads();
 291   bool c1 = compiler->is_c1();
 292 
 293   // Keep at least 1 compiler thread of each type.
 294   if (compiler_count < 2) return false;
 295 
 296   // Keep thread alive for at least some time.
 297   if (ct->idle_time_millis() < (c1 ? 500 : 100)) return false;
 298 
 299 #if INCLUDE_JVMCI
 300   if (compiler->is_jvmci() && !UseJVMCINativeLibrary) {
 301     // Handles for JVMCI thread objects may get released concurrently.
 302     if (do_it) {
 303       assert(CompileThread_lock->owner() == ct, "must be holding lock");
 304     } else {
 305       // Skip check if it's the last thread and let caller check again.
 306       return true;
 307     }
 308   }
 309 #endif
 310 
 311   // We only allow the last compiler thread of each type to get removed.
 312   jobject last_compiler = c1 ? compiler1_object(compiler_count - 1)
 313                              : compiler2_object(compiler_count - 1);
 314   if (ct->threadObj() == JNIHandles::resolve_non_null(last_compiler)) {
 315     if (do_it) {
 316       assert_locked_or_safepoint(CompileThread_lock); // Update must be consistent.
 317       compiler->set_num_compiler_threads(compiler_count - 1);
 318 #if INCLUDE_JVMCI
 319       if (compiler->is_jvmci() && !UseJVMCINativeLibrary) {
 320         // Old j.l.Thread object can die when no longer referenced elsewhere.
 321         JNIHandles::destroy_global(compiler2_object(compiler_count - 1));
 322         _compiler2_objects[compiler_count - 1] = nullptr;
 323       }
 324 #endif
 325     }
 326     return true;
 327   }
 328   return false;
 329 }
 330 
 331 /**
 332  * Add a CompileTask to a CompileQueue.
 333  */
 334 void CompileQueue::add(CompileTask* task) {
 335   assert(_lock->owned_by_self(), "must own lock");
 336 
 337   task->set_next(nullptr);
 338   task->set_prev(nullptr);
 339 
 340   if (_last == nullptr) {
 341     // The compile queue is empty.
 342     assert(_first == nullptr, "queue is empty");
 343     _first = task;
 344     _last = task;
 345   } else {
 346     // Append the task to the queue.
 347     assert(_last->next() == nullptr, "not last");
 348     _last->set_next(task);
 349     task->set_prev(_last);
 350     _last = task;
 351   }
 352   ++_size;
 353   ++_total_added;
 354   if (_size > _peak_size) {
 355     _peak_size = _size;
 356   }
 357 
 358   // Mark the method as being in the compile queue.
 359   task->method()->set_queued_for_compilation();
 360 
 361   task->mark_queued(os::elapsed_counter());
 362 
 363   if (CIPrintCompileQueue) {
 364     print_tty();
 365   }
 366 
 367   if (LogCompilation && xtty != nullptr) {
 368     task->log_task_queued();
 369   }
 370 
 371   if (TrainingData::need_data()) {
 372     CompileTrainingData* tdata = CompileTrainingData::make(task);
 373     if (tdata != nullptr) {
 374       tdata->record_compilation_queued(task);
 375       task->set_training_data(tdata);
 376     }
 377   }
 378 
 379   // Notify CompilerThreads that a task is available.
 380   _lock->notify_all();
 381 }
 382 
 383 void CompileQueue::add_pending(CompileTask* task) {
 384   assert(_lock->owned_by_self() == false, "must NOT own lock");
 385   assert(UseLockFreeCompileQueues, "");
 386   task->method()->set_queued_for_compilation();
 387   _queue.push(*task);
 388   // FIXME: additional coordination needed? e.g., is it possible for compiler thread to block w/o processing pending tasks?
 389   if (is_empty()) {
 390     MutexLocker ml(_lock);
 391     _lock->notify_all();
 392   }
 393 }
 394 
 395 void CompileQueue::transfer_pending() {
 396   assert(_lock->owned_by_self(), "must own lock");
 397   while (!_queue.empty()) {
 398     CompileTask* task = _queue.pop();
 399 //    guarantee(task->method()->queued_for_compilation(), "");
 400     task->method()->set_queued_for_compilation(); // FIXME
 401     if (task->method()->pending_queue_processed()) {
 402       task->set_next(_first_stale);
 403       task->set_prev(nullptr);
 404       _first_stale = task;
 405       continue; // skip
 406     } else {
 407       // Mark the method as being in the compile queue.
 408       task->method()->set_pending_queue_processed();
 409     }
 410     if (CompileBroker::compilation_is_complete(task->method(), task->osr_bci(), task->comp_level(),
 411                                                task->requires_online_compilation(), task->compile_reason())) {
 412       task->set_next(_first_stale);
 413       task->set_prev(nullptr);
 414       _first_stale = task;
 415       continue; // skip
 416     }
 417     add(task);
 418   }
 419 }
 420 
 421 /**
 422  * Empties compilation queue by putting all compilation tasks onto
 423  * a freelist. Furthermore, the method wakes up all threads that are
 424  * waiting on a compilation task to finish. This can happen if background
 425  * compilation is disabled.
 426  */
 427 void CompileQueue::free_all() {
 428   MutexLocker mu(_lock);
 429   transfer_pending();
 430 
 431   CompileTask* next = _first;
 432 
 433   // Iterate over all tasks in the compile queue
 434   while (next != nullptr) {
 435     CompileTask* current = next;
 436     next = current->next();
 437     {
 438       // Wake up thread that blocks on the compile task.
 439       MutexLocker ct_lock(current->lock());
 440       current->lock()->notify();
 441     }
 442     // Put the task back on the freelist.
 443     CompileTask::free(current);
 444   }
 445   _first = nullptr;
 446   _last = nullptr;
 447 
 448   // Wake up all threads that block on the queue.
 449   _lock->notify_all();
 450 }
 451 
 452 /**
 453  * Get the next CompileTask from a CompileQueue
 454  */
 455 CompileTask* CompileQueue::get(CompilerThread* thread) {
 456   // save methods from RedefineClasses across safepoint
 457   // across compile queue lock below.
 458   methodHandle save_method;
 459   methodHandle save_hot_method;
 460 
 461   MonitorLocker locker(_lock);
 462   transfer_pending();
 463 
 464   CompilationPolicy::sample_load_average();
 465 
 466   // If _first is null we have no more compile jobs. There are two reasons for
 467   // having no compile jobs: First, we compiled everything we wanted. Second,
 468   // we ran out of code cache so compilation has been disabled. In the latter
 469   // case we perform code cache sweeps to free memory such that we can re-enable
 470   // compilation.
 471   while (_first == nullptr) {
 472     // Exit loop if compilation is disabled forever
 473     if (CompileBroker::is_compilation_disabled_forever()) {
 474       return nullptr;
 475     }
 476 
 477     AbstractCompiler* compiler = thread->compiler();
 478     guarantee(compiler != nullptr, "Compiler object must exist");
 479     compiler->on_empty_queue(this, thread);
 480     if (_first != nullptr) {
 481       // The call to on_empty_queue may have temporarily unlocked the MCQ lock
 482       // so check again whether any tasks were added to the queue.
 483       break;
 484     }
 485 
 486     // If there are no compilation tasks and we can compile new jobs
 487     // (i.e., there is enough free space in the code cache) there is
 488     // no need to invoke the GC.
 489     // We need a timed wait here, since compiler threads can exit if compilation
 490     // is disabled forever. We use 5 seconds wait time; the exiting of compiler threads
 491     // is not critical and we do not want idle compiler threads to wake up too often.
 492     locker.wait(5*1000);
 493 
 494     transfer_pending(); // reacquired lock
 495 
 496     if (CompilationPolicy::have_recompilation_work()) return nullptr;
 497 
 498     if (UseDynamicNumberOfCompilerThreads && _first == nullptr) {
 499       // Still nothing to compile. Give caller a chance to stop this thread.
 500       if (CompileBroker::can_remove(CompilerThread::current(), false)) return nullptr;
 501     }
 502   }
 503 
 504   if (CompileBroker::is_compilation_disabled_forever()) {
 505     return nullptr;
 506   }
 507 
 508   CompileTask* task;
 509   {
 510     NoSafepointVerifier nsv;
 511     task = CompilationPolicy::select_task(this, thread);
 512     if (task != nullptr) {
 513       task = task->select_for_compilation();
 514     }
 515   }
 516 
 517   if (task != nullptr) {
 518     // Save method pointers across unlock safepoint.  The task is removed from
 519     // the compilation queue, which is walked during RedefineClasses.
 520     Thread* thread = Thread::current();
 521     save_method = methodHandle(thread, task->method());
 522     save_hot_method = methodHandle(thread, task->hot_method());
 523 
 524     remove(task);
 525   }
 526   purge_stale_tasks(); // may temporarily release MCQ lock
 527   return task;
 528 }
 529 
 530 // Clean & deallocate stale compile tasks.
 531 // Temporarily releases MethodCompileQueue lock.
 532 void CompileQueue::purge_stale_tasks() {
 533   assert(_lock->owned_by_self(), "must own lock");
 534   if (_first_stale != nullptr) {
 535     // Stale tasks are purged when MCQ lock is released,
 536     // but _first_stale updates are protected by MCQ lock.
 537     // Once task processing starts and MCQ lock is released,
 538     // other compiler threads can reuse _first_stale.
 539     CompileTask* head = _first_stale;
 540     _first_stale = nullptr;
 541     {
 542       MutexUnlocker ul(_lock);
 543       for (CompileTask* task = head; task != nullptr; ) {
 544         CompileTask* next_task = task->next();
 545         CompileTaskWrapper ctw(task); // Frees the task
 546         task->set_failure_reason("stale task");
 547         task = next_task;
 548       }
 549     }
 550     transfer_pending(); // transfer pending after reacquiring MCQ lock
 551   }
 552 }
 553 
 554 void CompileQueue::remove(CompileTask* task) {
 555   assert(_lock->owned_by_self(), "must own lock");
 556   if (task->prev() != nullptr) {
 557     task->prev()->set_next(task->next());
 558   } else {
 559     // max is the first element
 560     assert(task == _first, "Sanity");
 561     _first = task->next();
 562   }
 563 
 564   if (task->next() != nullptr) {
 565     task->next()->set_prev(task->prev());
 566   } else {
 567     // max is the last element
 568     assert(task == _last, "Sanity");
 569     _last = task->prev();
 570   }
 571   --_size;
 572   ++_total_removed;
 573 }
 574 
 575 void CompileQueue::remove_and_mark_stale(CompileTask* task) {
 576   assert(_lock->owned_by_self(), "must own lock");
 577   remove(task);
 578 
 579   // Enqueue the task for reclamation (should be done outside MCQ lock)
 580   task->set_next(_first_stale);
 581   task->set_prev(nullptr);
 582   _first_stale = task;
 583 }
 584 
 585 // methods in the compile queue need to be marked as used on the stack
 586 // so that they don't get reclaimed by Redefine Classes
 587 void CompileQueue::mark_on_stack() {
 588   CompileTask* task = _first;
 589   while (task != nullptr) {
 590     task->mark_on_stack();
 591     task = task->next();
 592   }
 593 }
 594 
 595 
 596 CompileQueue* CompileBroker::compile_queue(int comp_level, bool is_scc) {
 597   if (is_c2_compile(comp_level)) return (is_scc ? _sc2_compile_queue : _c2_compile_queue);
 598   if (is_c1_compile(comp_level)) return (is_scc ? _sc1_compile_queue : _c1_compile_queue);
 599   return nullptr;
 600 }
 601 
 602 CompileQueue* CompileBroker::c1_compile_queue() {
 603   return _c1_compile_queue;
 604 }
 605 
 606 CompileQueue* CompileBroker::c2_compile_queue() {
 607   return _c2_compile_queue;
 608 }
 609 
 610 void CompileBroker::print_compile_queues(outputStream* st) {
 611   st->print_cr("Current compiles: ");
 612 
 613   char buf[2000];
 614   int buflen = sizeof(buf);
 615   Threads::print_threads_compiling(st, buf, buflen, /* short_form = */ true);
 616 
 617   st->cr();
 618   if (_c1_compile_queue != nullptr) {
 619     _c1_compile_queue->print(st);
 620   }
 621   if (_c2_compile_queue != nullptr) {
 622     _c2_compile_queue->print(st);
 623   }
 624   if (_c3_compile_queue != nullptr) {
 625     _c3_compile_queue->print(st);
 626   }
 627   if (_sc1_compile_queue != nullptr) {
 628     _sc1_compile_queue->print(st);
 629   }
 630   if (_sc2_compile_queue != nullptr) {
 631     _sc2_compile_queue->print(st);
 632   }
 633 }
 634 
 635 void CompileQueue::print(outputStream* st) {
 636   assert_locked_or_safepoint(_lock);
 637   st->print_cr("%s:", name());
 638   CompileTask* task = _first;
 639   if (task == nullptr) {
 640     st->print_cr("Empty");
 641   } else {
 642     while (task != nullptr) {
 643       task->print(st, nullptr, true, true);
 644       task = task->next();
 645     }
 646   }
 647   st->cr();
 648 }
 649 
 650 void CompileQueue::print_tty() {
 651   stringStream ss;
 652   // Dump the compile queue into a buffer before locking the tty
 653   print(&ss);
 654   {
 655     ttyLocker ttyl;
 656     tty->print("%s", ss.freeze());
 657   }
 658 }
 659 
 660 CompilerCounters::CompilerCounters() {
 661   _current_method[0] = '\0';
 662   _compile_type = CompileBroker::no_compile;
 663 }
 664 
 665 #if INCLUDE_JFR && COMPILER2_OR_JVMCI
 666 // It appends new compiler phase names to growable array phase_names(a new CompilerPhaseType mapping
 667 // in compiler/compilerEvent.cpp) and registers it with its serializer.
 668 //
 669 // c2 uses explicit CompilerPhaseType idToPhase mapping in opto/phasetype.hpp,
 670 // so if c2 is used, it should be always registered first.
 671 // This function is called during vm initialization.
 672 static void register_jfr_phasetype_serializer(CompilerType compiler_type) {
 673   ResourceMark rm;
 674   static bool first_registration = true;
 675   if (compiler_type == compiler_jvmci) {
 676     CompilerEvent::PhaseEvent::get_phase_id("NOT_A_PHASE_NAME", false, false, false);
 677     first_registration = false;
 678 #ifdef COMPILER2
 679   } else if (compiler_type == compiler_c2) {
 680     assert(first_registration, "invariant"); // c2 must be registered first.
 681     for (int i = 0; i < PHASE_NUM_TYPES; i++) {
 682       const char* phase_name = CompilerPhaseTypeHelper::to_description((CompilerPhaseType) i);
 683       CompilerEvent::PhaseEvent::get_phase_id(phase_name, false, false, false);
 684     }
 685     first_registration = false;
 686 #endif // COMPILER2
 687   }
 688 }
 689 #endif // INCLUDE_JFR && COMPILER2_OR_JVMCI
 690 
 691 // ------------------------------------------------------------------
 692 // CompileBroker::compilation_init
 693 //
 694 // Initialize the Compilation object
 695 void CompileBroker::compilation_init(JavaThread* THREAD) {
 696   // No need to initialize compilation system if we do not use it.
 697   if (!UseCompiler) {
 698     return;
 699   }
 700   // Set the interface to the current compiler(s).
 701   _c1_count = CompilationPolicy::c1_count();
 702   _c2_count = CompilationPolicy::c2_count();
 703   _c3_count = CompilationPolicy::c3_count();
 704   _sc_count = CompilationPolicy::sc_count();
 705 
 706 #if INCLUDE_JVMCI
 707   if (EnableJVMCI) {
 708     // This is creating a JVMCICompiler singleton.
 709     JVMCICompiler* jvmci = new JVMCICompiler();
 710 
 711     if (UseJVMCICompiler) {
 712       _compilers[1] = jvmci;
 713       if (FLAG_IS_DEFAULT(JVMCIThreads)) {
 714         if (BootstrapJVMCI) {
 715           // JVMCI will bootstrap so give it more threads
 716           _c2_count = MIN2(32, os::active_processor_count());
 717         }
 718       } else {
 719         _c2_count = JVMCIThreads;
 720       }
 721       if (FLAG_IS_DEFAULT(JVMCIHostThreads)) {
 722       } else {
 723 #ifdef COMPILER1
 724         _c1_count = JVMCIHostThreads;
 725 #endif // COMPILER1
 726       }
 727 #ifdef COMPILER2
 728       if (SCCache::is_on() && (_c3_count > 0)) {
 729         _compilers[2] = new C2Compiler();
 730       }
 731 #endif
 732     }
 733   }
 734 #endif // INCLUDE_JVMCI
 735 
 736 #ifdef COMPILER1
 737   if (_c1_count > 0) {
 738     _compilers[0] = new Compiler();
 739   }
 740 #endif // COMPILER1
 741 
 742 #ifdef COMPILER2
 743   if (true JVMCI_ONLY( && !UseJVMCICompiler)) {
 744     if (_c2_count > 0) {
 745       _compilers[1] = new C2Compiler();
 746       // Register c2 first as c2 CompilerPhaseType idToPhase mapping is explicit.
 747       // idToPhase mapping for c2 is in opto/phasetype.hpp
 748       JFR_ONLY(register_jfr_phasetype_serializer(compiler_c2);)
 749     }
 750   }
 751 #endif // COMPILER2
 752 
 753 #if INCLUDE_JVMCI
 754    // Register after c2 registration.
 755    // JVMCI CompilerPhaseType idToPhase mapping is dynamic.
 756    if (EnableJVMCI) {
 757      JFR_ONLY(register_jfr_phasetype_serializer(compiler_jvmci);)
 758    }
 759 #endif // INCLUDE_JVMCI
 760 
 761   if (CompilerOracle::should_collect_memstat()) {
 762     CompilationMemoryStatistic::initialize();
 763   }
 764 
 765   // Start the compiler thread(s)
 766   init_compiler_threads();
 767   // totalTime performance counter is always created as it is required
 768   // by the implementation of java.lang.management.CompilationMXBean.
 769   {
 770     // Ensure OOM leads to vm_exit_during_initialization.
 771     EXCEPTION_MARK;
 772     _perf_total_compilation =
 773                  PerfDataManager::create_counter(JAVA_CI, "totalTime",
 774                                                  PerfData::U_Ticks, CHECK);
 775   }
 776 
 777   if (UsePerfData) {
 778 
 779     EXCEPTION_MARK;
 780 
 781     // create the jvmstat performance counters
 782     _perf_osr_compilation =
 783                  PerfDataManager::create_counter(SUN_CI, "osrTime",
 784                                                  PerfData::U_Ticks, CHECK);
 785 
 786     _perf_standard_compilation =
 787                  PerfDataManager::create_counter(SUN_CI, "standardTime",
 788                                                  PerfData::U_Ticks, CHECK);
 789 
 790     _perf_total_bailout_count =
 791                  PerfDataManager::create_counter(SUN_CI, "totalBailouts",
 792                                                  PerfData::U_Events, CHECK);
 793 
 794     _perf_total_invalidated_count =
 795                  PerfDataManager::create_counter(SUN_CI, "totalInvalidates",
 796                                                  PerfData::U_Events, CHECK);
 797 
 798     _perf_total_compile_count =
 799                  PerfDataManager::create_counter(SUN_CI, "totalCompiles",
 800                                                  PerfData::U_Events, CHECK);
 801     _perf_total_osr_compile_count =
 802                  PerfDataManager::create_counter(SUN_CI, "osrCompiles",
 803                                                  PerfData::U_Events, CHECK);
 804 
 805     _perf_total_standard_compile_count =
 806                  PerfDataManager::create_counter(SUN_CI, "standardCompiles",
 807                                                  PerfData::U_Events, CHECK);
 808 
 809     _perf_sum_osr_bytes_compiled =
 810                  PerfDataManager::create_counter(SUN_CI, "osrBytes",
 811                                                  PerfData::U_Bytes, CHECK);
 812 
 813     _perf_sum_standard_bytes_compiled =
 814                  PerfDataManager::create_counter(SUN_CI, "standardBytes",
 815                                                  PerfData::U_Bytes, CHECK);
 816 
 817     _perf_sum_nmethod_size =
 818                  PerfDataManager::create_counter(SUN_CI, "nmethodSize",
 819                                                  PerfData::U_Bytes, CHECK);
 820 
 821     _perf_sum_nmethod_code_size =
 822                  PerfDataManager::create_counter(SUN_CI, "nmethodCodeSize",
 823                                                  PerfData::U_Bytes, CHECK);
 824 
 825     _perf_last_method =
 826                  PerfDataManager::create_string_variable(SUN_CI, "lastMethod",
 827                                        CompilerCounters::cmname_buffer_length,
 828                                        "", CHECK);
 829 
 830     _perf_last_failed_method =
 831             PerfDataManager::create_string_variable(SUN_CI, "lastFailedMethod",
 832                                        CompilerCounters::cmname_buffer_length,
 833                                        "", CHECK);
 834 
 835     _perf_last_invalidated_method =
 836         PerfDataManager::create_string_variable(SUN_CI, "lastInvalidatedMethod",
 837                                      CompilerCounters::cmname_buffer_length,
 838                                      "", CHECK);
 839 
 840     _perf_last_compile_type =
 841              PerfDataManager::create_variable(SUN_CI, "lastType",
 842                                               PerfData::U_None,
 843                                               (jlong)CompileBroker::no_compile,
 844                                               CHECK);
 845 
 846     _perf_last_compile_size =
 847              PerfDataManager::create_variable(SUN_CI, "lastSize",
 848                                               PerfData::U_Bytes,
 849                                               (jlong)CompileBroker::no_compile,
 850                                               CHECK);
 851 
 852 
 853     _perf_last_failed_type =
 854              PerfDataManager::create_variable(SUN_CI, "lastFailedType",
 855                                               PerfData::U_None,
 856                                               (jlong)CompileBroker::no_compile,
 857                                               CHECK);
 858 
 859     _perf_last_invalidated_type =
 860          PerfDataManager::create_variable(SUN_CI, "lastInvalidatedType",
 861                                           PerfData::U_None,
 862                                           (jlong)CompileBroker::no_compile,
 863                                           CHECK);
 864   }
 865 
 866   log_info(scc, init)("CompileBroker is initialized");
 867   _initialized = true;
 868 }
 869 
 870 Handle CompileBroker::create_thread_oop(const char* name, TRAPS) {
 871   Handle thread_oop = JavaThread::create_system_thread_object(name, CHECK_NH);
 872   return thread_oop;
 873 }
 874 
 875 void TrainingReplayThread::training_replay_thread_entry(JavaThread* thread, TRAPS) {
 876   CompilationPolicy::replay_training_at_init_loop(thread);
 877 }
 878 
 879 #if defined(ASSERT) && COMPILER2_OR_JVMCI
 880 // Stress testing. Dedicated threads revert optimizations based on escape analysis concurrently to
 881 // the running java application.  Configured with vm options DeoptimizeObjectsALot*.
 882 class DeoptimizeObjectsALotThread : public JavaThread {
 883 
 884   static void deopt_objs_alot_thread_entry(JavaThread* thread, TRAPS);
 885   void deoptimize_objects_alot_loop_single();
 886   void deoptimize_objects_alot_loop_all();
 887 
 888 public:
 889   DeoptimizeObjectsALotThread() : JavaThread(&deopt_objs_alot_thread_entry) { }
 890 
 891   bool is_hidden_from_external_view() const      { return true; }
 892 };
 893 
 894 // Entry for DeoptimizeObjectsALotThread. The threads are started in
 895 // CompileBroker::init_compiler_threads() iff DeoptimizeObjectsALot is enabled
 896 void DeoptimizeObjectsALotThread::deopt_objs_alot_thread_entry(JavaThread* thread, TRAPS) {
 897     DeoptimizeObjectsALotThread* dt = ((DeoptimizeObjectsALotThread*) thread);
 898     bool enter_single_loop;
 899     {
 900       MonitorLocker ml(dt, EscapeBarrier_lock, Mutex::_no_safepoint_check_flag);
 901       static int single_thread_count = 0;
 902       enter_single_loop = single_thread_count++ < DeoptimizeObjectsALotThreadCountSingle;
 903     }
 904     if (enter_single_loop) {
 905       dt->deoptimize_objects_alot_loop_single();
 906     } else {
 907       dt->deoptimize_objects_alot_loop_all();
 908     }
 909   }
 910 
 911 // Execute EscapeBarriers in an endless loop to revert optimizations based on escape analysis. Each
 912 // barrier targets a single thread which is selected round robin.
 913 void DeoptimizeObjectsALotThread::deoptimize_objects_alot_loop_single() {
 914   HandleMark hm(this);
 915   while (true) {
 916     for (JavaThreadIteratorWithHandle jtiwh; JavaThread *deoptee_thread = jtiwh.next(); ) {
 917       { // Begin new scope for escape barrier
 918         HandleMarkCleaner hmc(this);
 919         ResourceMark rm(this);
 920         EscapeBarrier eb(true, this, deoptee_thread);
 921         eb.deoptimize_objects(100);
 922       }
 923       // Now sleep after the escape barriers destructor resumed deoptee_thread.
 924       sleep(DeoptimizeObjectsALotInterval);
 925     }
 926   }
 927 }
 928 
 929 // Execute EscapeBarriers in an endless loop to revert optimizations based on escape analysis. Each
 930 // barrier targets all java threads in the vm at once.
 931 void DeoptimizeObjectsALotThread::deoptimize_objects_alot_loop_all() {
 932   HandleMark hm(this);
 933   while (true) {
 934     { // Begin new scope for escape barrier
 935       HandleMarkCleaner hmc(this);
 936       ResourceMark rm(this);
 937       EscapeBarrier eb(true, this);
 938       eb.deoptimize_objects_all_threads();
 939     }
 940     // Now sleep after the escape barriers destructor resumed the java threads.
 941     sleep(DeoptimizeObjectsALotInterval);
 942   }
 943 }
 944 #endif // defined(ASSERT) && COMPILER2_OR_JVMCI
 945 
 946 
 947 JavaThread* CompileBroker::make_thread(ThreadType type, jobject thread_handle, CompileQueue* queue, AbstractCompiler* comp, JavaThread* THREAD) {
 948   Handle thread_oop(THREAD, JNIHandles::resolve_non_null(thread_handle));
 949 
 950   if (java_lang_Thread::thread(thread_oop()) != nullptr) {
 951     assert(type == compiler_t, "should only happen with reused compiler threads");
 952     // The compiler thread hasn't actually exited yet so don't try to reuse it
 953     return nullptr;
 954   }
 955 
 956   JavaThread* new_thread = nullptr;
 957   switch (type) {
 958     case compiler_t:
 959       assert(comp != nullptr, "Compiler instance missing.");
 960       if (!InjectCompilerCreationFailure || comp->num_compiler_threads() == 0) {
 961         CompilerCounters* counters = new CompilerCounters();
 962         new_thread = new CompilerThread(queue, counters);
 963       }
 964       break;
 965 #if defined(ASSERT) && COMPILER2_OR_JVMCI
 966     case deoptimizer_t:
 967       new_thread = new DeoptimizeObjectsALotThread();
 968       break;
 969 #endif // ASSERT
 970     case training_replay_t:
 971       new_thread = new TrainingReplayThread();
 972       break;
 973     default:
 974       ShouldNotReachHere();
 975   }
 976 
 977   // At this point the new CompilerThread data-races with this startup
 978   // thread (which is the main thread and NOT the VM thread).
 979   // This means Java bytecodes being executed at startup can
 980   // queue compile jobs which will run at whatever default priority the
 981   // newly created CompilerThread runs at.
 982 
 983 
 984   // At this point it may be possible that no osthread was created for the
 985   // JavaThread due to lack of resources. We will handle that failure below.
 986   // Also check new_thread so that static analysis is happy.
 987   if (new_thread != nullptr && new_thread->osthread() != nullptr) {
 988 
 989     if (type == compiler_t) {
 990       CompilerThread::cast(new_thread)->set_compiler(comp);
 991     }
 992 
 993     // Note that we cannot call os::set_priority because it expects Java
 994     // priorities and we are *explicitly* using OS priorities so that it's
 995     // possible to set the compiler thread priority higher than any Java
 996     // thread.
 997 
 998     int native_prio = CompilerThreadPriority;
 999     if (native_prio == -1) {
1000       if (UseCriticalCompilerThreadPriority) {
1001         native_prio = os::java_to_os_priority[CriticalPriority];
1002       } else {
1003         native_prio = os::java_to_os_priority[NearMaxPriority];
1004       }
1005     }
1006     os::set_native_priority(new_thread, native_prio);
1007 
1008     // Note that this only sets the JavaThread _priority field, which by
1009     // definition is limited to Java priorities and not OS priorities.
1010     JavaThread::start_internal_daemon(THREAD, new_thread, thread_oop, NearMaxPriority);
1011 
1012   } else { // osthread initialization failure
1013     if (UseDynamicNumberOfCompilerThreads && type == compiler_t
1014         && comp->num_compiler_threads() > 0) {
1015       // The new thread is not known to Thread-SMR yet so we can just delete.
1016       delete new_thread;
1017       return nullptr;
1018     } else {
1019       vm_exit_during_initialization("java.lang.OutOfMemoryError",
1020                                     os::native_thread_creation_failed_msg());
1021     }
1022   }
1023 
1024   os::naked_yield(); // make sure that the compiler thread is started early (especially helpful on SOLARIS)
1025 
1026   return new_thread;
1027 }
1028 
1029 static bool trace_compiler_threads() {
1030   LogTarget(Debug, jit, thread) lt;
1031   return TraceCompilerThreads || lt.is_enabled();
1032 }
1033 
1034 static jobject create_compiler_thread(AbstractCompiler* compiler, int i, TRAPS) {
1035   char name_buffer[256];
1036   os::snprintf_checked(name_buffer, sizeof(name_buffer), "%s CompilerThread%d", compiler->name(), i);
1037   Handle thread_oop = JavaThread::create_system_thread_object(name_buffer, CHECK_NULL);
1038   return JNIHandles::make_global(thread_oop);
1039 }
1040 
1041 static void print_compiler_threads(stringStream& msg) {
1042   if (TraceCompilerThreads) {
1043     tty->print_cr("%7d %s", (int)tty->time_stamp().milliseconds(), msg.as_string());
1044   }
1045   LogTarget(Debug, jit, thread) lt;
1046   if (lt.is_enabled()) {
1047     LogStream ls(lt);
1048     ls.print_cr("%s", msg.as_string());
1049   }
1050 }
1051 
1052 static void print_compiler_thread(JavaThread *ct) {
1053   if (trace_compiler_threads()) {
1054     ResourceMark rm;
1055     ThreadsListHandle tlh;  // name() depends on the TLH.
1056     assert(tlh.includes(ct), "ct=" INTPTR_FORMAT " exited unexpectedly.", p2i(ct));
1057     stringStream msg;
1058     msg.print("Added initial compiler thread %s", ct->name());
1059     print_compiler_threads(msg);
1060   }
1061 }
1062 
1063 void CompileBroker::init_compiler_threads() {
1064   // Ensure any exceptions lead to vm_exit_during_initialization.
1065   EXCEPTION_MARK;
1066 #if !defined(ZERO)
1067   assert(_c2_count > 0 || _c1_count > 0, "No compilers?");
1068 #endif // !ZERO
1069   // Initialize the compilation queue
1070   if (_c2_count > 0) {
1071     const char* name = JVMCI_ONLY(UseJVMCICompiler ? "JVMCI compile queue" :) "C2 compile queue";
1072     _c2_compile_queue  = new CompileQueue(name, MethodCompileQueueC2_lock);
1073     _compiler2_objects = NEW_C_HEAP_ARRAY(jobject, _c2_count, mtCompiler);
1074     _compiler2_logs = NEW_C_HEAP_ARRAY(CompileLog*, _c2_count, mtCompiler);
1075   }
1076   if (_c1_count > 0) {
1077     _c1_compile_queue  = new CompileQueue("C1 compile queue", MethodCompileQueueC1_lock);
1078     _compiler1_objects = NEW_C_HEAP_ARRAY(jobject, _c1_count, mtCompiler);
1079     _compiler1_logs = NEW_C_HEAP_ARRAY(CompileLog*, _c1_count, mtCompiler);
1080   }
1081 
1082   if (_c3_count > 0) {
1083     const char* name = "C2 compile queue";
1084     _c3_compile_queue  = new CompileQueue(name, MethodCompileQueueC3_lock);
1085     _compiler3_objects = NEW_C_HEAP_ARRAY(jobject, _c3_count, mtCompiler);
1086     _compiler3_logs = NEW_C_HEAP_ARRAY(CompileLog*, _c3_count, mtCompiler);
1087   }
1088   if (_sc_count > 0) {
1089     if (_c1_count > 0) { // C1 is present
1090       _sc1_compile_queue  = new CompileQueue("C1 SC compile queue", MethodCompileQueueSC1_lock);
1091     }
1092     if (_c2_count > 0) { // C2 is present
1093       _sc2_compile_queue  = new CompileQueue("C2 SC compile queue", MethodCompileQueueSC2_lock);
1094     }
1095     _sc_objects = NEW_C_HEAP_ARRAY(jobject, _sc_count, mtCompiler);
1096     _sc_logs = NEW_C_HEAP_ARRAY(CompileLog*, _sc_count, mtCompiler);
1097   }
1098   char name_buffer[256];
1099 
1100   for (int i = 0; i < _c2_count; i++) {
1101     // Create a name for our thread.
1102     jobject thread_handle = create_compiler_thread(_compilers[1], i, CHECK);
1103     _compiler2_objects[i] = thread_handle;
1104     _compiler2_logs[i] = nullptr;
1105 
1106     if (!UseDynamicNumberOfCompilerThreads || i == 0) {
1107       JavaThread *ct = make_thread(compiler_t, thread_handle, _c2_compile_queue, _compilers[1], THREAD);
1108       assert(ct != nullptr, "should have been handled for initial thread");
1109       _compilers[1]->set_num_compiler_threads(i + 1);
1110       print_compiler_thread(ct);
1111     }
1112   }
1113 
1114   for (int i = 0; i < _c1_count; i++) {
1115     // Create a name for our thread.
1116     jobject thread_handle = create_compiler_thread(_compilers[0], i, CHECK);
1117     _compiler1_objects[i] = thread_handle;
1118     _compiler1_logs[i] = nullptr;
1119 
1120     if (!UseDynamicNumberOfCompilerThreads || i == 0) {
1121       JavaThread *ct = make_thread(compiler_t, thread_handle, _c1_compile_queue, _compilers[0], THREAD);
1122       assert(ct != nullptr, "should have been handled for initial thread");
1123       _compilers[0]->set_num_compiler_threads(i + 1);
1124       print_compiler_thread(ct);
1125     }
1126   }
1127 
1128   for (int i = 0; i < _c3_count; i++) {
1129     // Create a name for our thread.
1130     os::snprintf_checked(name_buffer, sizeof(name_buffer), "C2 CompilerThread%d", i);
1131     Handle thread_oop = create_thread_oop(name_buffer, CHECK);
1132     jobject thread_handle = JNIHandles::make_global(thread_oop);
1133     _compiler3_objects[i] = thread_handle;
1134     _compiler3_logs[i] = nullptr;
1135 
1136     JavaThread *ct = make_thread(compiler_t, thread_handle, _c3_compile_queue, _compilers[2], THREAD);
1137     assert(ct != nullptr, "should have been handled for initial thread");
1138     _compilers[2]->set_num_compiler_threads(i + 1);
1139     print_compiler_thread(ct);
1140   }
1141 
1142   if (_sc_count > 0) {
1143     int i = 0;
1144     if (_c1_count > 0) { // C1 is present
1145       os::snprintf_checked(name_buffer, sizeof(name_buffer), "C%d SC CompilerThread", 1);
1146       Handle thread_oop = create_thread_oop(name_buffer, CHECK);
1147       jobject thread_handle = JNIHandles::make_global(thread_oop);
1148       _sc_objects[i] = thread_handle;
1149       _sc_logs[i] = nullptr;
1150       i++;
1151 
1152       JavaThread *ct = make_thread(compiler_t, thread_handle, _sc1_compile_queue, _compilers[0], THREAD);
1153       assert(ct != nullptr, "should have been handled for initial thread");
1154       print_compiler_thread(ct);
1155     }
1156     if (_c2_count > 0) { // C2 is present
1157       os::snprintf_checked(name_buffer, sizeof(name_buffer), "C%d SC CompilerThread", 2);
1158       Handle thread_oop = create_thread_oop(name_buffer, CHECK);
1159       jobject thread_handle = JNIHandles::make_global(thread_oop);
1160       _sc_objects[i] = thread_handle;
1161       _sc_logs[i] = nullptr;
1162 
1163       JavaThread *ct = make_thread(compiler_t, thread_handle, _sc2_compile_queue, _compilers[1], THREAD);
1164       assert(ct != nullptr, "should have been handled for initial thread");
1165       print_compiler_thread(ct);
1166     }
1167   }
1168 
1169   if (UsePerfData) {
1170     PerfDataManager::create_constant(SUN_CI, "threads", PerfData::U_Bytes, _c1_count + _c2_count + _c3_count, CHECK);
1171   }
1172 
1173 #if defined(ASSERT) && COMPILER2_OR_JVMCI
1174   if (DeoptimizeObjectsALot) {
1175     // Initialize and start the object deoptimizer threads
1176     const int total_count = DeoptimizeObjectsALotThreadCountSingle + DeoptimizeObjectsALotThreadCountAll;
1177     for (int count = 0; count < total_count; count++) {
1178       Handle thread_oop = JavaThread::create_system_thread_object("Deoptimize objects a lot single mode", CHECK);
1179       jobject thread_handle = JNIHandles::make_local(THREAD, thread_oop());
1180       make_thread(deoptimizer_t, thread_handle, nullptr, nullptr, THREAD);
1181     }
1182   }
1183 #endif // defined(ASSERT) && COMPILER2_OR_JVMCI
1184   if (UseConcurrentTrainingReplay) {
1185     Handle thread_oop = create_thread_oop("Training replay thread", CHECK);
1186     jobject thread_handle = JNIHandles::make_local(THREAD, thread_oop());
1187     make_thread(training_replay_t, thread_handle, nullptr, nullptr, THREAD);
1188   }
1189 }
1190 
1191 void CompileBroker::possibly_add_compiler_threads(JavaThread* THREAD) {
1192 
1193   julong free_memory = os::free_memory();
1194   // If SegmentedCodeCache is off, both values refer to the single heap (with type CodeBlobType::All).
1195   size_t available_cc_np  = CodeCache::unallocated_capacity(CodeBlobType::MethodNonProfiled),
1196          available_cc_p   = CodeCache::unallocated_capacity(CodeBlobType::MethodProfiled);
1197 
1198   // Only do attempt to start additional threads if the lock is free.
1199   if (!CompileThread_lock->try_lock()) return;
1200 
1201   if (_c2_compile_queue != nullptr) {
1202     int old_c2_count = _compilers[1]->num_compiler_threads();
1203     int new_c2_count = MIN4(_c2_count,
1204         _c2_compile_queue->size() / 2,
1205         (int)(free_memory / (200*M)),
1206         (int)(available_cc_np / (128*K)));
1207 
1208     for (int i = old_c2_count; i < new_c2_count; i++) {
1209 #if INCLUDE_JVMCI
1210       if (UseJVMCICompiler && !UseJVMCINativeLibrary && _compiler2_objects[i] == nullptr) {
1211         // Native compiler threads as used in C1/C2 can reuse the j.l.Thread objects as their
1212         // existence is completely hidden from the rest of the VM (and those compiler threads can't
1213         // call Java code to do the creation anyway).
1214         //
1215         // For pure Java JVMCI we have to create new j.l.Thread objects as they are visible and we
1216         // can see unexpected thread lifecycle transitions if we bind them to new JavaThreads.  For
1217         // native library JVMCI it's preferred to use the C1/C2 strategy as this avoids unnecessary
1218         // coupling with Java.
1219         if (!THREAD->can_call_java()) break;
1220         char name_buffer[256];
1221         os::snprintf_checked(name_buffer, sizeof(name_buffer), "%s CompilerThread%d", _compilers[1]->name(), i);
1222         Handle thread_oop;
1223         {
1224           // We have to give up the lock temporarily for the Java calls.
1225           MutexUnlocker mu(CompileThread_lock);
1226           thread_oop = JavaThread::create_system_thread_object(name_buffer, THREAD);
1227         }
1228         if (HAS_PENDING_EXCEPTION) {
1229           if (trace_compiler_threads()) {
1230             ResourceMark rm;
1231             stringStream msg;
1232             msg.print_cr("JVMCI compiler thread creation failed:");
1233             PENDING_EXCEPTION->print_on(&msg);
1234             print_compiler_threads(msg);
1235           }
1236           CLEAR_PENDING_EXCEPTION;
1237           break;
1238         }
1239         // Check if another thread has beaten us during the Java calls.
1240         if (_compilers[1]->num_compiler_threads() != i) break;
1241         jobject thread_handle = JNIHandles::make_global(thread_oop);
1242         assert(compiler2_object(i) == nullptr, "Old one must be released!");
1243         _compiler2_objects[i] = thread_handle;
1244       }
1245 #endif
1246       guarantee(compiler2_object(i) != nullptr, "Thread oop must exist");
1247       JavaThread *ct = make_thread(compiler_t, compiler2_object(i), _c2_compile_queue, _compilers[1], THREAD);
1248       if (ct == nullptr) break;
1249       _compilers[1]->set_num_compiler_threads(i + 1);
1250       if (trace_compiler_threads()) {
1251         ResourceMark rm;
1252         ThreadsListHandle tlh;  // name() depends on the TLH.
1253         assert(tlh.includes(ct), "ct=" INTPTR_FORMAT " exited unexpectedly.", p2i(ct));
1254         stringStream msg;
1255         msg.print("Added compiler thread %s (free memory: %dMB, available non-profiled code cache: %dMB)",
1256                   ct->name(), (int)(free_memory/M), (int)(available_cc_np/M));
1257         print_compiler_threads(msg);
1258       }
1259     }
1260   }
1261 
1262   if (_c1_compile_queue != nullptr) {
1263     int old_c1_count = _compilers[0]->num_compiler_threads();
1264     int new_c1_count = MIN4(_c1_count,
1265         _c1_compile_queue->size() / 4,
1266         (int)(free_memory / (100*M)),
1267         (int)(available_cc_p / (128*K)));
1268 
1269     for (int i = old_c1_count; i < new_c1_count; i++) {
1270       JavaThread *ct = make_thread(compiler_t, compiler1_object(i), _c1_compile_queue, _compilers[0], THREAD);
1271       if (ct == nullptr) break;
1272       _compilers[0]->set_num_compiler_threads(i + 1);
1273       if (trace_compiler_threads()) {
1274         ResourceMark rm;
1275         ThreadsListHandle tlh;  // name() depends on the TLH.
1276         assert(tlh.includes(ct), "ct=" INTPTR_FORMAT " exited unexpectedly.", p2i(ct));
1277         stringStream msg;
1278         msg.print("Added compiler thread %s (free memory: %dMB, available profiled code cache: %dMB)",
1279                   ct->name(), (int)(free_memory/M), (int)(available_cc_p/M));
1280         print_compiler_threads(msg);
1281       }
1282     }
1283   }
1284 
1285   CompileThread_lock->unlock();
1286 }
1287 
1288 
1289 /**
1290  * Set the methods on the stack as on_stack so that redefine classes doesn't
1291  * reclaim them. This method is executed at a safepoint.
1292  */
1293 void CompileBroker::mark_on_stack() {
1294   assert(SafepointSynchronize::is_at_safepoint(), "sanity check");
1295   // Since we are at a safepoint, we do not need a lock to access
1296   // the compile queues.
1297   if (_c3_compile_queue != nullptr) {
1298     _c3_compile_queue->mark_on_stack();
1299   }
1300   if (_c2_compile_queue != nullptr) {
1301     _c2_compile_queue->mark_on_stack();
1302   }
1303   if (_c1_compile_queue != nullptr) {
1304     _c1_compile_queue->mark_on_stack();
1305   }
1306   if (_sc1_compile_queue != nullptr) {
1307     _sc1_compile_queue->mark_on_stack();
1308   }
1309   if (_sc2_compile_queue != nullptr) {
1310     _sc2_compile_queue->mark_on_stack();
1311   }
1312 }
1313 
1314 // ------------------------------------------------------------------
1315 // CompileBroker::compile_method
1316 //
1317 // Request compilation of a method.
1318 void CompileBroker::compile_method_base(const methodHandle& method,
1319                                         int osr_bci,
1320                                         int comp_level,
1321                                         const methodHandle& hot_method,
1322                                         int hot_count,
1323                                         CompileTask::CompileReason compile_reason,
1324                                         bool requires_online_compilation,
1325                                         bool blocking,
1326                                         Thread* thread) {
1327   guarantee(!method->is_abstract(), "cannot compile abstract methods");
1328   assert(method->method_holder()->is_instance_klass(),
1329          "sanity check");
1330   assert(!method->method_holder()->is_not_initialized()   ||
1331          compile_reason == CompileTask::Reason_Preload    ||
1332          compile_reason == CompileTask::Reason_Precompile ||
1333          compile_reason == CompileTask::Reason_PrecompileForPreload, "method holder must be initialized");
1334   assert(!method->is_method_handle_intrinsic(), "do not enqueue these guys");
1335 
1336   if (CIPrintRequests) {
1337     tty->print("request: ");
1338     method->print_short_name(tty);
1339     if (osr_bci != InvocationEntryBci) {
1340       tty->print(" osr_bci: %d", osr_bci);
1341     }
1342     tty->print(" level: %d comment: %s count: %d", comp_level, CompileTask::reason_name(compile_reason), hot_count);
1343     if (!hot_method.is_null()) {
1344       tty->print(" hot: ");
1345       if (hot_method() != method()) {
1346           hot_method->print_short_name(tty);
1347       } else {
1348         tty->print("yes");
1349       }
1350     }
1351     tty->cr();
1352   }
1353 
1354   // A request has been made for compilation.  Before we do any
1355   // real work, check to see if the method has been compiled
1356   // in the meantime with a definitive result.
1357   if (compilation_is_complete(method(), osr_bci, comp_level, requires_online_compilation, compile_reason)) {
1358     return;
1359   }
1360 
1361 #ifndef PRODUCT
1362   if (osr_bci != -1 && !FLAG_IS_DEFAULT(OSROnlyBCI)) {
1363     if ((OSROnlyBCI > 0) ? (OSROnlyBCI != osr_bci) : (-OSROnlyBCI == osr_bci)) {
1364       // Positive OSROnlyBCI means only compile that bci.  Negative means don't compile that BCI.
1365       return;
1366     }
1367   }
1368 #endif
1369 
1370   // If this method is already in the compile queue, then
1371   // we do not block the current thread.
1372   if (compilation_is_in_queue(method)) {
1373     // We may want to decay our counter a bit here to prevent
1374     // multiple denied requests for compilation.  This is an
1375     // open compilation policy issue. Note: The other possibility,
1376     // in the case that this is a blocking compile request, is to have
1377     // all subsequent blocking requesters wait for completion of
1378     // ongoing compiles. Note that in this case we'll need a protocol
1379     // for freeing the associated compile tasks. [Or we could have
1380     // a single static monitor on which all these waiters sleep.]
1381     return;
1382   }
1383 
1384   // Tiered policy requires MethodCounters to exist before adding a method to
1385   // the queue. Create if we don't have them yet.
1386   if (compile_reason != CompileTask::Reason_Preload) {
1387     method->get_method_counters(thread);
1388   }
1389 
1390   SCCEntry* scc_entry = find_scc_entry(method, osr_bci, comp_level, compile_reason, requires_online_compilation);
1391   bool is_scc = (scc_entry != nullptr);
1392 
1393   // Outputs from the following MutexLocker block:
1394   CompileTask* task = nullptr;
1395   CompileQueue* queue;
1396 #if INCLUDE_JVMCI
1397   if (is_c2_compile(comp_level) && compiler2()->is_jvmci() && compiler3() != nullptr &&
1398       ((JVMCICompiler*)compiler2())->force_comp_at_level_simple(method)) {
1399     assert(_c3_compile_queue != nullptr, "sanity");
1400     queue = _c3_compile_queue; // JVMCI compiler's methods compilation
1401   } else
1402 #endif
1403   queue = compile_queue(comp_level, is_scc);
1404 
1405   // Acquire our lock.
1406   {
1407     ConditionalMutexLocker locker(thread, queue->lock(), !UseLockFreeCompileQueues);
1408 
1409     // Make sure the method has not slipped into the queues since
1410     // last we checked; note that those checks were "fast bail-outs".
1411     // Here we need to be more careful, see 14012000 below.
1412     if (compilation_is_in_queue(method)) {
1413       return;
1414     }
1415 
1416     // We need to check again to see if the compilation has
1417     // completed.  A previous compilation may have registered
1418     // some result.
1419     if (compilation_is_complete(method(), osr_bci, comp_level, requires_online_compilation, compile_reason)) {
1420       return;
1421     }
1422 
1423     // We now know that this compilation is not pending, complete,
1424     // or prohibited.  Assign a compile_id to this compilation
1425     // and check to see if it is in our [Start..Stop) range.
1426     int compile_id = assign_compile_id(method, osr_bci);
1427     if (compile_id == 0) {
1428       // The compilation falls outside the allowed range.
1429       return;
1430     }
1431 
1432 #if INCLUDE_JVMCI
1433     if (UseJVMCICompiler && blocking) {
1434       // Don't allow blocking compiles for requests triggered by JVMCI.
1435       if (thread->is_Compiler_thread()) {
1436         blocking = false;
1437       }
1438 
1439       // In libjvmci, JVMCI initialization should not deadlock with other threads
1440       if (!UseJVMCINativeLibrary) {
1441         // Don't allow blocking compiles if inside a class initializer or while performing class loading
1442         vframeStream vfst(JavaThread::cast(thread));
1443         for (; !vfst.at_end(); vfst.next()) {
1444           if (vfst.method()->is_static_initializer() ||
1445               (vfst.method()->method_holder()->is_subclass_of(vmClasses::ClassLoader_klass()) &&
1446                   vfst.method()->name() == vmSymbols::loadClass_name())) {
1447             blocking = false;
1448             break;
1449           }
1450         }
1451 
1452         // Don't allow blocking compilation requests to JVMCI
1453         // if JVMCI itself is not yet initialized
1454         if (!JVMCI::is_compiler_initialized() && compiler(comp_level)->is_jvmci()) {
1455           blocking = false;
1456         }
1457       }
1458 
1459       // Don't allow blocking compilation requests if we are in JVMCIRuntime::shutdown
1460       // to avoid deadlock between compiler thread(s) and threads run at shutdown
1461       // such as the DestroyJavaVM thread.
1462       if (JVMCI::in_shutdown()) {
1463         blocking = false;
1464       }
1465     }
1466 #endif // INCLUDE_JVMCI
1467 
1468     // We will enter the compilation in the queue.
1469     // 14012000: Note that this sets the queued_for_compile bits in
1470     // the target method. We can now reason that a method cannot be
1471     // queued for compilation more than once, as follows:
1472     // Before a thread queues a task for compilation, it first acquires
1473     // the compile queue lock, then checks if the method's queued bits
1474     // are set or it has already been compiled. Thus there can not be two
1475     // instances of a compilation task for the same method on the
1476     // compilation queue. Consider now the case where the compilation
1477     // thread has already removed a task for that method from the queue
1478     // and is in the midst of compiling it. In this case, the
1479     // queued_for_compile bits must be set in the method (and these
1480     // will be visible to the current thread, since the bits were set
1481     // under protection of the compile queue lock, which we hold now.
1482     // When the compilation completes, the compiler thread first sets
1483     // the compilation result and then clears the queued_for_compile
1484     // bits. Neither of these actions are protected by a barrier (or done
1485     // under the protection of a lock), so the only guarantee we have
1486     // (on machines with TSO (Total Store Order)) is that these values
1487     // will update in that order. As a result, the only combinations of
1488     // these bits that the current thread will see are, in temporal order:
1489     // <RESULT, QUEUE> :
1490     //     <0, 1> : in compile queue, but not yet compiled
1491     //     <1, 1> : compiled but queue bit not cleared
1492     //     <1, 0> : compiled and queue bit cleared
1493     // Because we first check the queue bits then check the result bits,
1494     // we are assured that we cannot introduce a duplicate task.
1495     // Note that if we did the tests in the reverse order (i.e. check
1496     // result then check queued bit), we could get the result bit before
1497     // the compilation completed, and the queue bit after the compilation
1498     // completed, and end up introducing a "duplicate" (redundant) task.
1499     // In that case, the compiler thread should first check if a method
1500     // has already been compiled before trying to compile it.
1501     // NOTE: in the event that there are multiple compiler threads and
1502     // there is de-optimization/recompilation, things will get hairy,
1503     // and in that case it's best to protect both the testing (here) of
1504     // these bits, and their updating (here and elsewhere) under a
1505     // common lock.
1506     task = create_compile_task(queue,
1507                                compile_id, method,
1508                                osr_bci, comp_level,
1509                                hot_method, hot_count, scc_entry, compile_reason,
1510                                requires_online_compilation, blocking);
1511 
1512     if (task->is_scc() && (_sc_count > 0)) {
1513       // Put it on SC queue
1514       queue = is_c1_compile(comp_level) ? _sc1_compile_queue : _sc2_compile_queue;
1515     }
1516 
1517     if (UseLockFreeCompileQueues) {
1518       assert(queue->lock()->owned_by_self() == false, "");
1519       queue->add_pending(task);
1520     } else {
1521       queue->add(task);
1522     }
1523   }
1524 
1525   if (blocking) {
1526     wait_for_completion(task);
1527   }
1528 }
1529 
1530 SCCEntry* CompileBroker::find_scc_entry(const methodHandle& method, int osr_bci, int comp_level,
1531                                         CompileTask::CompileReason compile_reason,
1532                                         bool requires_online_compilation) {
1533   SCCEntry* scc_entry = nullptr;
1534   if (_sc_count > 0 && osr_bci == InvocationEntryBci && !requires_online_compilation && SCCache::is_on_for_read()) {
1535     // Check for cached code.
1536     if (compile_reason == CompileTask::Reason_Preload) {
1537       scc_entry = method->scc_entry();
1538       assert(scc_entry != nullptr && scc_entry->for_preload(), "sanity");
1539     } else {
1540       scc_entry = SCCache::find_code_entry(method, comp_level);
1541     }
1542   }
1543   return scc_entry;
1544 }
1545 
1546 nmethod* CompileBroker::compile_method(const methodHandle& method, int osr_bci,
1547                                        int comp_level,
1548                                        const methodHandle& hot_method, int hot_count,
1549                                        bool requires_online_compilation,
1550                                        CompileTask::CompileReason compile_reason,
1551                                        TRAPS) {
1552   // Do nothing if compilebroker is not initialized or compiles are submitted on level none
1553   if (!_initialized || comp_level == CompLevel_none) {
1554     return nullptr;
1555   }
1556 
1557 #if INCLUDE_JVMCI
1558   if (EnableJVMCI && UseJVMCICompiler &&
1559       comp_level == CompLevel_full_optimization && !ClassPrelinker::class_preloading_finished()) {
1560     return nullptr;
1561   }
1562 #endif
1563 
1564   AbstractCompiler *comp = CompileBroker::compiler(comp_level);
1565   assert(comp != nullptr, "Ensure we have a compiler");
1566 
1567 #if INCLUDE_JVMCI
1568   if (comp->is_jvmci() && !JVMCI::can_initialize_JVMCI()) {
1569     // JVMCI compilation is not yet initializable.
1570     return nullptr;
1571   }
1572 #endif
1573 
1574   DirectiveSet* directive = DirectivesStack::getMatchingDirective(method, comp);
1575   // CompileBroker::compile_method can trap and can have pending async exception.
1576   nmethod* nm = CompileBroker::compile_method(method, osr_bci, comp_level, hot_method, hot_count, requires_online_compilation, compile_reason, directive, THREAD);
1577   DirectivesStack::release(directive);
1578   return nm;
1579 }
1580 
1581 nmethod* CompileBroker::compile_method(const methodHandle& method, int osr_bci,
1582                                          int comp_level,
1583                                          const methodHandle& hot_method, int hot_count,
1584                                          bool requires_online_compilation,
1585                                          CompileTask::CompileReason compile_reason,
1586                                          DirectiveSet* directive,
1587                                          TRAPS) {
1588 
1589   // make sure arguments make sense
1590   assert(method->method_holder()->is_instance_klass(), "not an instance method");
1591   assert(osr_bci == InvocationEntryBci || (0 <= osr_bci && osr_bci < method->code_size()), "bci out of range");
1592   assert(!method->is_abstract() && (osr_bci == InvocationEntryBci || !method->is_native()), "cannot compile abstract/native methods");
1593   assert(!method->method_holder()->is_not_initialized()   ||
1594          compile_reason == CompileTask::Reason_Preload    ||
1595          compile_reason == CompileTask::Reason_Precompile ||
1596          compile_reason == CompileTask::Reason_PrecompileForPreload, "method holder must be initialized");
1597   // return quickly if possible
1598 
1599   // lock, make sure that the compilation
1600   // isn't prohibited in a straightforward way.
1601   AbstractCompiler* comp = CompileBroker::compiler(comp_level);
1602   if (comp == nullptr || compilation_is_prohibited(method, osr_bci, comp_level, directive->ExcludeOption)) {
1603     return nullptr;
1604   }
1605 
1606   if (osr_bci == InvocationEntryBci) {
1607     // standard compilation
1608     CompiledMethod* method_code = method->code();
1609     if (method_code != nullptr && method_code->is_nmethod()) {
1610       if (compilation_is_complete(method(), osr_bci, comp_level, requires_online_compilation, compile_reason)) {
1611         return (nmethod*) method_code;
1612       }
1613     }
1614     if (method->is_not_compilable(comp_level)) {
1615       return nullptr;
1616     }
1617   } else {
1618     // osr compilation
1619     // We accept a higher level osr method
1620     nmethod* nm = method->lookup_osr_nmethod_for(osr_bci, comp_level, false);
1621     if (nm != nullptr) return nm;
1622     if (method->is_not_osr_compilable(comp_level)) return nullptr;
1623   }
1624 
1625   assert(!HAS_PENDING_EXCEPTION, "No exception should be present");
1626   // some prerequisites that are compiler specific
1627   if (compile_reason != CompileTask::Reason_Preload && (comp->is_c2() || comp->is_jvmci())) {
1628     method->constants()->resolve_string_constants(CHECK_AND_CLEAR_NONASYNC_NULL);
1629     // Resolve all classes seen in the signature of the method
1630     // we are compiling.
1631     Method::load_signature_classes(method, CHECK_AND_CLEAR_NONASYNC_NULL);
1632   }
1633 
1634   // If the method is native, do the lookup in the thread requesting
1635   // the compilation. Native lookups can load code, which is not
1636   // permitted during compilation.
1637   //
1638   // Note: A native method implies non-osr compilation which is
1639   //       checked with an assertion at the entry of this method.
1640   if (method->is_native() && !method->is_method_handle_intrinsic()) {
1641     address adr = NativeLookup::lookup(method, THREAD);
1642     if (HAS_PENDING_EXCEPTION) {
1643       // In case of an exception looking up the method, we just forget
1644       // about it. The interpreter will kick-in and throw the exception.
1645       method->set_not_compilable("NativeLookup::lookup failed"); // implies is_not_osr_compilable()
1646       CLEAR_PENDING_EXCEPTION;
1647       return nullptr;
1648     }
1649     assert(method->has_native_function(), "must have native code by now");
1650   }
1651 
1652   // RedefineClasses() has replaced this method; just return
1653   if (method->is_old()) {
1654     return nullptr;
1655   }
1656 
1657   // JVMTI -- post_compile_event requires jmethod_id() that may require
1658   // a lock the compiling thread can not acquire. Prefetch it here.
1659   if (JvmtiExport::should_post_compiled_method_load()) {
1660     method->jmethod_id();
1661   }
1662 
1663   // do the compilation
1664   if (method->is_native()) {
1665     if (!PreferInterpreterNativeStubs || method->is_method_handle_intrinsic()) {
1666 #if defined(X86) && !defined(ZERO)
1667       // The following native methods:
1668       //
1669       // java.lang.Float.intBitsToFloat
1670       // java.lang.Float.floatToRawIntBits
1671       // java.lang.Double.longBitsToDouble
1672       // java.lang.Double.doubleToRawLongBits
1673       //
1674       // are called through the interpreter even if interpreter native stubs
1675       // are not preferred (i.e., calling through adapter handlers is preferred).
1676       // The reason is that on x86_32 signaling NaNs (sNaNs) are not preserved
1677       // if the version of the methods from the native libraries is called.
1678       // As the interpreter and the C2-intrinsified version of the methods preserves
1679       // sNaNs, that would result in an inconsistent way of handling of sNaNs.
1680       if ((UseSSE >= 1 &&
1681           (method->intrinsic_id() == vmIntrinsics::_intBitsToFloat ||
1682            method->intrinsic_id() == vmIntrinsics::_floatToRawIntBits)) ||
1683           (UseSSE >= 2 &&
1684            (method->intrinsic_id() == vmIntrinsics::_longBitsToDouble ||
1685             method->intrinsic_id() == vmIntrinsics::_doubleToRawLongBits))) {
1686         return nullptr;
1687       }
1688 #endif // X86 && !ZERO
1689 
1690       // To properly handle the appendix argument for out-of-line calls we are using a small trampoline that
1691       // pops off the appendix argument and jumps to the target (see gen_special_dispatch in SharedRuntime).
1692       //
1693       // Since normal compiled-to-compiled calls are not able to handle such a thing we MUST generate an adapter
1694       // in this case.  If we can't generate one and use it we can not execute the out-of-line method handle calls.
1695       AdapterHandlerLibrary::create_native_wrapper(method);
1696     } else {
1697       return nullptr;
1698     }
1699   } else {
1700     // If the compiler is shut off due to code cache getting full
1701     // fail out now so blocking compiles dont hang the java thread
1702     if (!should_compile_new_jobs()) {
1703       return nullptr;
1704     }
1705     bool is_blocking = ReplayCompiles                                             ||
1706                        !directive->BackgroundCompilationOption                    ||
1707                        (compile_reason == CompileTask::Reason_Precompile)         ||
1708                        (compile_reason == CompileTask::Reason_PrecompileForPreload);
1709 	  compile_method_base(method, osr_bci, comp_level, hot_method, hot_count, compile_reason, requires_online_compilation, is_blocking, THREAD);
1710   }
1711 
1712   // return requested nmethod
1713   // We accept a higher level osr method
1714   if (osr_bci == InvocationEntryBci) {
1715     CompiledMethod* code = method->code();
1716     if (code == nullptr) {
1717       return (nmethod*) code;
1718     } else {
1719       return code->as_nmethod_or_null();
1720     }
1721   }
1722   return method->lookup_osr_nmethod_for(osr_bci, comp_level, false);
1723 }
1724 
1725 
1726 // ------------------------------------------------------------------
1727 // CompileBroker::compilation_is_complete
1728 //
1729 // See if compilation of this method is already complete.
1730 bool CompileBroker::compilation_is_complete(Method*                    method,
1731                                             int                        osr_bci,
1732                                             int                        comp_level,
1733                                             bool                       online_only,
1734                                             CompileTask::CompileReason compile_reason) {
1735   if (compile_reason == CompileTask::Reason_Precompile ||
1736       compile_reason == CompileTask::Reason_PrecompileForPreload) {
1737     return false; // FIXME: any restrictions?
1738   }
1739   bool is_osr = (osr_bci != standard_entry_bci);
1740   if (is_osr) {
1741     if (method->is_not_osr_compilable(comp_level)) {
1742       return true;
1743     } else {
1744       nmethod* result = method->lookup_osr_nmethod_for(osr_bci, comp_level, true);
1745       return (result != nullptr);
1746     }
1747   } else {
1748     if (method->is_not_compilable(comp_level)) {
1749       return true;
1750     } else {
1751       CompiledMethod* result = method->code();
1752       if (result == nullptr) {
1753         return false;
1754       }
1755       if (online_only && result->is_scc()) {
1756         return false;
1757       }
1758       bool same_level = (comp_level == result->comp_level());
1759       if (result->has_clinit_barriers()) {
1760         return !same_level; // Allow replace preloaded code with new code of the same level
1761       }
1762       return same_level;
1763     }
1764   }
1765 }
1766 
1767 
1768 /**
1769  * See if this compilation is already requested.
1770  *
1771  * Implementation note: there is only a single "is in queue" bit
1772  * for each method.  This means that the check below is overly
1773  * conservative in the sense that an osr compilation in the queue
1774  * will block a normal compilation from entering the queue (and vice
1775  * versa).  This can be remedied by a full queue search to disambiguate
1776  * cases.  If it is deemed profitable, this may be done.
1777  */
1778 bool CompileBroker::compilation_is_in_queue(const methodHandle& method) {
1779   return method->queued_for_compilation();
1780 }
1781 
1782 // ------------------------------------------------------------------
1783 // CompileBroker::compilation_is_prohibited
1784 //
1785 // See if this compilation is not allowed.
1786 bool CompileBroker::compilation_is_prohibited(const methodHandle& method, int osr_bci, int comp_level, bool excluded) {
1787   bool is_native = method->is_native();
1788   // Some compilers may not support the compilation of natives.
1789   AbstractCompiler *comp = compiler(comp_level);
1790   if (is_native && (!CICompileNatives || comp == nullptr)) {
1791     method->set_not_compilable_quietly("native methods not supported", comp_level);
1792     return true;
1793   }
1794 
1795   bool is_osr = (osr_bci != standard_entry_bci);
1796   // Some compilers may not support on stack replacement.
1797   if (is_osr && (!CICompileOSR || comp == nullptr)) {
1798     method->set_not_osr_compilable("OSR not supported", comp_level);
1799     return true;
1800   }
1801 
1802   // The method may be explicitly excluded by the user.
1803   double scale;
1804   if (excluded || (CompilerOracle::has_option_value(method, CompileCommand::CompileThresholdScaling, scale) && scale == 0)) {
1805     bool quietly = CompilerOracle::be_quiet();
1806     if (PrintCompilation && !quietly) {
1807       // This does not happen quietly...
1808       ResourceMark rm;
1809       tty->print("### Excluding %s:%s",
1810                  method->is_native() ? "generation of native wrapper" : "compile",
1811                  (method->is_static() ? " static" : ""));
1812       method->print_short_name(tty);
1813       tty->cr();
1814     }
1815     method->set_not_compilable("excluded by CompileCommand", comp_level, !quietly);
1816   }
1817 
1818   return false;
1819 }
1820 
1821 /**
1822  * Generate serialized IDs for compilation requests. If certain debugging flags are used
1823  * and the ID is not within the specified range, the method is not compiled and 0 is returned.
1824  * The function also allows to generate separate compilation IDs for OSR compilations.
1825  */
1826 int CompileBroker::assign_compile_id(const methodHandle& method, int osr_bci) {
1827 #ifdef ASSERT
1828   bool is_osr = (osr_bci != standard_entry_bci);
1829   int id;
1830   if (method->is_native()) {
1831     assert(!is_osr, "can't be osr");
1832     // Adapters, native wrappers and method handle intrinsics
1833     // should be generated always.
1834     return Atomic::add(CICountNative ? &_native_compilation_id : &_compilation_id, 1);
1835   } else if (CICountOSR && is_osr) {
1836     id = Atomic::add(&_osr_compilation_id, 1);
1837     if (CIStartOSR <= id && id < CIStopOSR) {
1838       return id;
1839     }
1840   } else {
1841     id = Atomic::add(&_compilation_id, 1);
1842     if (CIStart <= id && id < CIStop) {
1843       return id;
1844     }
1845   }
1846 
1847   // Method was not in the appropriate compilation range.
1848   method->set_not_compilable_quietly("Not in requested compile id range");
1849   return 0;
1850 #else
1851   // CICountOSR is a develop flag and set to 'false' by default. In a product built,
1852   // only _compilation_id is incremented.
1853   return Atomic::add(&_compilation_id, 1);
1854 #endif
1855 }
1856 
1857 // ------------------------------------------------------------------
1858 // CompileBroker::assign_compile_id_unlocked
1859 //
1860 // Public wrapper for assign_compile_id that acquires the needed locks
1861 int CompileBroker::assign_compile_id_unlocked(Thread* thread, const methodHandle& method, int osr_bci) {
1862   return assign_compile_id(method, osr_bci);
1863 }
1864 
1865 // ------------------------------------------------------------------
1866 // CompileBroker::create_compile_task
1867 //
1868 // Create a CompileTask object representing the current request for
1869 // compilation.  Add this task to the queue.
1870 CompileTask* CompileBroker::create_compile_task(CompileQueue*       queue,
1871                                                 int                 compile_id,
1872                                                 const methodHandle& method,
1873                                                 int                 osr_bci,
1874                                                 int                 comp_level,
1875                                                 const methodHandle& hot_method,
1876                                                 int                 hot_count,
1877                                                 SCCEntry*           scc_entry,
1878                                                 CompileTask::CompileReason compile_reason,
1879                                                 bool                requires_online_compilation,
1880                                                 bool                blocking) {
1881   CompileTask* new_task = CompileTask::allocate();
1882   new_task->initialize(compile_id, method, osr_bci, comp_level,
1883                        hot_method, hot_count, scc_entry, compile_reason, queue,
1884                        requires_online_compilation, blocking);
1885   return new_task;
1886 }
1887 
1888 #if INCLUDE_JVMCI
1889 // The number of milliseconds to wait before checking if
1890 // JVMCI compilation has made progress.
1891 static const long JVMCI_COMPILATION_PROGRESS_WAIT_TIMESLICE = 1000;
1892 
1893 // The number of JVMCI compilation progress checks that must fail
1894 // before unblocking a thread waiting for a blocking compilation.
1895 static const int JVMCI_COMPILATION_PROGRESS_WAIT_ATTEMPTS = 10;
1896 
1897 /**
1898  * Waits for a JVMCI compiler to complete a given task. This thread
1899  * waits until either the task completes or it sees no JVMCI compilation
1900  * progress for N consecutive milliseconds where N is
1901  * JVMCI_COMPILATION_PROGRESS_WAIT_TIMESLICE *
1902  * JVMCI_COMPILATION_PROGRESS_WAIT_ATTEMPTS.
1903  *
1904  * @return true if this thread needs to free/recycle the task
1905  */
1906 bool CompileBroker::wait_for_jvmci_completion(JVMCICompiler* jvmci, CompileTask* task, JavaThread* thread) {
1907   assert(UseJVMCICompiler, "sanity");
1908   MonitorLocker ml(thread, task->lock());
1909   int progress_wait_attempts = 0;
1910   jint thread_jvmci_compilation_ticks = 0;
1911   jint global_jvmci_compilation_ticks = jvmci->global_compilation_ticks();
1912   while (!task->is_complete() && !is_compilation_disabled_forever() &&
1913          ml.wait(JVMCI_COMPILATION_PROGRESS_WAIT_TIMESLICE)) {
1914     JVMCICompileState* jvmci_compile_state = task->blocking_jvmci_compile_state();
1915 
1916     bool progress;
1917     if (jvmci_compile_state != nullptr) {
1918       jint ticks = jvmci_compile_state->compilation_ticks();
1919       progress = (ticks - thread_jvmci_compilation_ticks) != 0;
1920       JVMCI_event_1("waiting on compilation %d [ticks=%d]", task->compile_id(), ticks);
1921       thread_jvmci_compilation_ticks = ticks;
1922     } else {
1923       // Still waiting on JVMCI compiler queue. This thread may be holding a lock
1924       // that all JVMCI compiler threads are blocked on. We use the global JVMCI
1925       // compilation ticks to determine whether JVMCI compilation
1926       // is still making progress through the JVMCI compiler queue.
1927       jint ticks = jvmci->global_compilation_ticks();
1928       progress = (ticks - global_jvmci_compilation_ticks) != 0;
1929       JVMCI_event_1("waiting on compilation %d to be queued [ticks=%d]", task->compile_id(), ticks);
1930       global_jvmci_compilation_ticks = ticks;
1931     }
1932 
1933     if (!progress) {
1934       if (++progress_wait_attempts == JVMCI_COMPILATION_PROGRESS_WAIT_ATTEMPTS) {
1935         if (PrintCompilation) {
1936           task->print(tty, "wait for blocking compilation timed out");
1937         }
1938         JVMCI_event_1("waiting on compilation %d timed out", task->compile_id());
1939         break;
1940       }
1941     } else {
1942       progress_wait_attempts = 0;
1943     }
1944   }
1945   task->clear_waiter();
1946   return task->is_complete();
1947 }
1948 #endif
1949 
1950 /**
1951  *  Wait for the compilation task to complete.
1952  */
1953 void CompileBroker::wait_for_completion(CompileTask* task) {
1954   if (CIPrintCompileQueue) {
1955     ttyLocker ttyl;
1956     tty->print_cr("BLOCKING FOR COMPILE");
1957   }
1958 
1959   assert(task->is_blocking(), "can only wait on blocking task");
1960 
1961   JavaThread* thread = JavaThread::current();
1962 
1963   methodHandle method(thread, task->method());
1964   bool free_task;
1965 #if INCLUDE_JVMCI
1966   AbstractCompiler* comp = compiler(task->comp_level());
1967   if (!UseJVMCINativeLibrary && comp->is_jvmci() && !task->should_wait_for_compilation()) {
1968     // It may return before compilation is completed.
1969     // Note that libjvmci should not pre-emptively unblock
1970     // a thread waiting for a compilation as it does not call
1971     // Java code and so is not deadlock prone like jarjvmci.
1972     free_task = wait_for_jvmci_completion((JVMCICompiler*) comp, task, thread);
1973   } else
1974 #endif
1975   {
1976     MonitorLocker ml(thread, task->lock());
1977     free_task = true;
1978     while (!task->is_complete() && !is_compilation_disabled_forever()) {
1979       ml.wait();
1980     }
1981   }
1982 
1983   if (free_task) {
1984     if (is_compilation_disabled_forever()) {
1985       CompileTask::free(task);
1986       return;
1987     }
1988 
1989     // It is harmless to check this status without the lock, because
1990     // completion is a stable property (until the task object is recycled).
1991     assert(task->is_complete(), "Compilation should have completed");
1992 
1993     // By convention, the waiter is responsible for recycling a
1994     // blocking CompileTask. Since there is only one waiter ever
1995     // waiting on a CompileTask, we know that no one else will
1996     // be using this CompileTask; we can free it.
1997     CompileTask::free(task);
1998   }
1999 }
2000 
2001 /**
2002  * Initialize compiler thread(s) + compiler object(s). The postcondition
2003  * of this function is that the compiler runtimes are initialized and that
2004  * compiler threads can start compiling.
2005  */
2006 bool CompileBroker::init_compiler_runtime() {
2007   CompilerThread* thread = CompilerThread::current();
2008   AbstractCompiler* comp = thread->compiler();
2009   // Final sanity check - the compiler object must exist
2010   guarantee(comp != nullptr, "Compiler object must exist");
2011 
2012   {
2013     // Must switch to native to allocate ci_env
2014     ThreadToNativeFromVM ttn(thread);
2015     ciEnv ci_env((CompileTask*)nullptr);
2016     // Cache Jvmti state
2017     ci_env.cache_jvmti_state();
2018     // Cache DTrace flags
2019     ci_env.cache_dtrace_flags();
2020 
2021     // Switch back to VM state to do compiler initialization
2022     ThreadInVMfromNative tv(thread);
2023 
2024     // Perform per-thread and global initializations
2025     {
2026       MutexLocker only_one (thread, CompileThread_lock);
2027       SCCache::init_table();
2028     }
2029     comp->initialize();
2030   }
2031 
2032   if (comp->is_failed()) {
2033     disable_compilation_forever();
2034     // If compiler initialization failed, no compiler thread that is specific to a
2035     // particular compiler runtime will ever start to compile methods.
2036     shutdown_compiler_runtime(comp, thread);
2037     return false;
2038   }
2039 
2040   // C1 specific check
2041   if (comp->is_c1() && (thread->get_buffer_blob() == nullptr)) {
2042     warning("Initialization of %s thread failed (no space to run compilers)", thread->name());
2043     return false;
2044   }
2045 
2046   return true;
2047 }
2048 
2049 void CompileBroker::free_buffer_blob_if_allocated(CompilerThread* thread) {
2050   BufferBlob* blob = thread->get_buffer_blob();
2051   if (blob != nullptr) {
2052     blob->purge(true /* free_code_cache_data */, true /* unregister_nmethod */);
2053     MutexLocker mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
2054     CodeCache::free(blob);
2055   }
2056 }
2057 
2058 /**
2059  * If C1 and/or C2 initialization failed, we shut down all compilation.
2060  * We do this to keep things simple. This can be changed if it ever turns
2061  * out to be a problem.
2062  */
2063 void CompileBroker::shutdown_compiler_runtime(AbstractCompiler* comp, CompilerThread* thread) {
2064   free_buffer_blob_if_allocated(thread);
2065 
2066   log_info(compilation)("shutdown_compiler_runtime: " INTPTR_FORMAT, p2i(thread));
2067 
2068   if (comp->should_perform_shutdown()) {
2069     // There are two reasons for shutting down the compiler
2070     // 1) compiler runtime initialization failed
2071     // 2) The code cache is full and the following flag is set: -XX:-UseCodeCacheFlushing
2072     warning("%s initialization failed. Shutting down all compilers", comp->name());
2073 
2074     // Only one thread per compiler runtime object enters here
2075     // Set state to shut down
2076     comp->set_shut_down();
2077 
2078     // Delete all queued compilation tasks to make compiler threads exit faster.
2079     if (_c1_compile_queue != nullptr) {
2080       _c1_compile_queue->free_all();
2081     }
2082 
2083     if (_c2_compile_queue != nullptr) {
2084       _c2_compile_queue->free_all();
2085     }
2086 
2087     if (_c3_compile_queue != nullptr) {
2088       _c3_compile_queue->free_all();
2089     }
2090 
2091     // Set flags so that we continue execution with using interpreter only.
2092     UseCompiler    = false;
2093     UseInterpreter = true;
2094 
2095     // We could delete compiler runtimes also. However, there are references to
2096     // the compiler runtime(s) (e.g.,  nmethod::is_compiled_by_c1()) which then
2097     // fail. This can be done later if necessary.
2098   }
2099 }
2100 
2101 /**
2102  * Helper function to create new or reuse old CompileLog.
2103  */
2104 CompileLog* CompileBroker::get_log(CompilerThread* ct) {
2105   if (!LogCompilation) return nullptr;
2106 
2107   AbstractCompiler *compiler = ct->compiler();
2108   bool jvmci = JVMCI_ONLY( compiler->is_jvmci() ||) false;
2109   bool c1 = compiler->is_c1();
2110   jobject* compiler_objects = c1 ? _compiler1_objects : (_c3_count == 0 ? _compiler2_objects : (jvmci ? _compiler2_objects : _compiler3_objects));
2111   assert(compiler_objects != nullptr, "must be initialized at this point");
2112   CompileLog** logs = c1 ? _compiler1_logs : (_c3_count == 0 ? _compiler2_logs : (jvmci ? _compiler2_logs : _compiler3_logs));
2113   assert(logs != nullptr, "must be initialized at this point");
2114   int count = c1 ? _c1_count : (_c3_count == 0 ? _c2_count : (jvmci ? _c2_count : _c3_count));
2115 
2116   if (ct->queue() == _sc1_compile_queue || ct->queue() == _sc2_compile_queue) {
2117     compiler_objects = _sc_objects;
2118     logs  = _sc_logs;
2119     count = _sc_count;
2120   }
2121   // Find Compiler number by its threadObj.
2122   oop compiler_obj = ct->threadObj();
2123   int compiler_number = 0;
2124   bool found = false;
2125   for (; compiler_number < count; compiler_number++) {
2126     if (JNIHandles::resolve_non_null(compiler_objects[compiler_number]) == compiler_obj) {
2127       found = true;
2128       break;
2129     }
2130   }
2131   assert(found, "Compiler must exist at this point");
2132 
2133   // Determine pointer for this thread's log.
2134   CompileLog** log_ptr = &logs[compiler_number];
2135 
2136   // Return old one if it exists.
2137   CompileLog* log = *log_ptr;
2138   if (log != nullptr) {
2139     ct->init_log(log);
2140     return log;
2141   }
2142 
2143   // Create a new one and remember it.
2144   init_compiler_thread_log();
2145   log = ct->log();
2146   *log_ptr = log;
2147   return log;
2148 }
2149 
2150 // ------------------------------------------------------------------
2151 // CompileBroker::compiler_thread_loop
2152 //
2153 // The main loop run by a CompilerThread.
2154 void CompileBroker::compiler_thread_loop() {
2155   CompilerThread* thread = CompilerThread::current();
2156   CompileQueue* queue = thread->queue();
2157   // For the thread that initializes the ciObjectFactory
2158   // this resource mark holds all the shared objects
2159   ResourceMark rm;
2160 
2161   // First thread to get here will initialize the compiler interface
2162 
2163   {
2164     ASSERT_IN_VM;
2165     MutexLocker only_one (thread, CompileThread_lock);
2166     if (!ciObjectFactory::is_initialized()) {
2167       ciObjectFactory::initialize();
2168     }
2169   }
2170 
2171   // Open a log.
2172   CompileLog* log = get_log(thread);
2173   if (log != nullptr) {
2174     log->begin_elem("start_compile_thread name='%s' thread='" UINTX_FORMAT "' process='%d'",
2175                     thread->name(),
2176                     os::current_thread_id(),
2177                     os::current_process_id());
2178     log->stamp();
2179     log->end_elem();
2180   }
2181 
2182   // If compiler thread/runtime initialization fails, exit the compiler thread
2183   if (!init_compiler_runtime()) {
2184     return;
2185   }
2186 
2187   thread->start_idle_timer();
2188 
2189   // Poll for new compilation tasks as long as the JVM runs. Compilation
2190   // should only be disabled if something went wrong while initializing the
2191   // compiler runtimes. This, in turn, should not happen. The only known case
2192   // when compiler runtime initialization fails is if there is not enough free
2193   // space in the code cache to generate the necessary stubs, etc.
2194   while (!is_compilation_disabled_forever()) {
2195     // We need this HandleMark to avoid leaking VM handles.
2196     HandleMark hm(thread);
2197 
2198     CompilationPolicy::recompilation_step(RecompilationWorkUnitSize, thread);
2199 
2200     CompileTask* task = queue->get(thread);
2201 
2202     if (task == nullptr) {
2203       if (UseDynamicNumberOfCompilerThreads) {
2204         // Access compiler_count under lock to enforce consistency.
2205         MutexLocker only_one(CompileThread_lock);
2206         if (can_remove(thread, true)) {
2207           if (trace_compiler_threads()) {
2208             ResourceMark rm;
2209             stringStream msg;
2210             msg.print("Removing compiler thread %s after " JLONG_FORMAT " ms idle time",
2211                       thread->name(), thread->idle_time_millis());
2212             print_compiler_threads(msg);
2213           }
2214 
2215           // Notify compiler that the compiler thread is about to stop
2216           thread->compiler()->stopping_compiler_thread(thread);
2217 
2218           free_buffer_blob_if_allocated(thread);
2219           return; // Stop this thread.
2220         }
2221       }
2222     } else {
2223       // Assign the task to the current thread.  Mark this compilation
2224       // thread as active for the profiler.
2225       // CompileTaskWrapper also keeps the Method* from being deallocated if redefinition
2226       // occurs after fetching the compile task off the queue.
2227       CompileTaskWrapper ctw(task);
2228       methodHandle method(thread, task->method());
2229 
2230       // Never compile a method if breakpoints are present in it
2231       if (method()->number_of_breakpoints() == 0) {
2232         // Compile the method.
2233         if ((UseCompiler || AlwaysCompileLoopMethods) && CompileBroker::should_compile_new_jobs()) {
2234           invoke_compiler_on_method(task);
2235           thread->start_idle_timer();
2236         } else {
2237           // After compilation is disabled, remove remaining methods from queue
2238           method->clear_queued_for_compilation();
2239           method->set_pending_queue_processed(false);
2240           task->set_failure_reason("compilation is disabled");
2241         }
2242       } else {
2243         task->set_failure_reason("breakpoints are present");
2244       }
2245 
2246       if (UseDynamicNumberOfCompilerThreads) {
2247         possibly_add_compiler_threads(thread);
2248         assert(!thread->has_pending_exception(), "should have been handled");
2249       }
2250     }
2251   }
2252 
2253   // Shut down compiler runtime
2254   shutdown_compiler_runtime(thread->compiler(), thread);
2255 }
2256 
2257 // ------------------------------------------------------------------
2258 // CompileBroker::init_compiler_thread_log
2259 //
2260 // Set up state required by +LogCompilation.
2261 void CompileBroker::init_compiler_thread_log() {
2262     CompilerThread* thread = CompilerThread::current();
2263     char  file_name[4*K];
2264     FILE* fp = nullptr;
2265     intx thread_id = os::current_thread_id();
2266     for (int try_temp_dir = 1; try_temp_dir >= 0; try_temp_dir--) {
2267       const char* dir = (try_temp_dir ? os::get_temp_directory() : nullptr);
2268       if (dir == nullptr) {
2269         jio_snprintf(file_name, sizeof(file_name), "hs_c" UINTX_FORMAT "_pid%u.log",
2270                      thread_id, os::current_process_id());
2271       } else {
2272         jio_snprintf(file_name, sizeof(file_name),
2273                      "%s%shs_c" UINTX_FORMAT "_pid%u.log", dir,
2274                      os::file_separator(), thread_id, os::current_process_id());
2275       }
2276 
2277       fp = os::fopen(file_name, "wt");
2278       if (fp != nullptr) {
2279         if (LogCompilation && Verbose) {
2280           tty->print_cr("Opening compilation log %s", file_name);
2281         }
2282         CompileLog* log = new(mtCompiler) CompileLog(file_name, fp, thread_id);
2283         if (log == nullptr) {
2284           fclose(fp);
2285           return;
2286         }
2287         thread->init_log(log);
2288 
2289         if (xtty != nullptr) {
2290           ttyLocker ttyl;
2291           // Record any per thread log files
2292           xtty->elem("thread_logfile thread='" INTX_FORMAT "' filename='%s'", thread_id, file_name);
2293         }
2294         return;
2295       }
2296     }
2297     warning("Cannot open log file: %s", file_name);
2298 }
2299 
2300 void CompileBroker::log_metaspace_failure() {
2301   const char* message = "some methods may not be compiled because metaspace "
2302                         "is out of memory";
2303   if (CompilationLog::log() != nullptr) {
2304     CompilationLog::log()->log_metaspace_failure(message);
2305   }
2306   if (PrintCompilation) {
2307     tty->print_cr("COMPILE PROFILING SKIPPED: %s", message);
2308   }
2309 }
2310 
2311 
2312 // ------------------------------------------------------------------
2313 // CompileBroker::set_should_block
2314 //
2315 // Set _should_block.
2316 // Call this from the VM, with Threads_lock held and a safepoint requested.
2317 void CompileBroker::set_should_block() {
2318   assert(Threads_lock->owner() == Thread::current(), "must have threads lock");
2319   assert(SafepointSynchronize::is_at_safepoint(), "must be at a safepoint already");
2320 #ifndef PRODUCT
2321   if (PrintCompilation && (Verbose || WizardMode))
2322     tty->print_cr("notifying compiler thread pool to block");
2323 #endif
2324   _should_block = true;
2325 }
2326 
2327 // ------------------------------------------------------------------
2328 // CompileBroker::maybe_block
2329 //
2330 // Call this from the compiler at convenient points, to poll for _should_block.
2331 void CompileBroker::maybe_block() {
2332   if (_should_block) {
2333 #ifndef PRODUCT
2334     if (PrintCompilation && (Verbose || WizardMode))
2335       tty->print_cr("compiler thread " INTPTR_FORMAT " poll detects block request", p2i(Thread::current()));
2336 #endif
2337     ThreadInVMfromNative tivfn(JavaThread::current());
2338   }
2339 }
2340 
2341 // wrapper for CodeCache::print_summary()
2342 static void codecache_print(bool detailed)
2343 {
2344   stringStream s;
2345   // Dump code cache  into a buffer before locking the tty,
2346   {
2347     MutexLocker mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
2348     CodeCache::print_summary(&s, detailed);
2349   }
2350   ttyLocker ttyl;
2351   tty->print("%s", s.freeze());
2352 }
2353 
2354 // wrapper for CodeCache::print_summary() using outputStream
2355 static void codecache_print(outputStream* out, bool detailed) {
2356   stringStream s;
2357 
2358   // Dump code cache into a buffer
2359   {
2360     MutexLocker mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
2361     CodeCache::print_summary(&s, detailed);
2362   }
2363 
2364   char* remaining_log = s.as_string();
2365   while (*remaining_log != '\0') {
2366     char* eol = strchr(remaining_log, '\n');
2367     if (eol == nullptr) {
2368       out->print_cr("%s", remaining_log);
2369       remaining_log = remaining_log + strlen(remaining_log);
2370     } else {
2371       *eol = '\0';
2372       out->print_cr("%s", remaining_log);
2373       remaining_log = eol + 1;
2374     }
2375   }
2376 }
2377 
2378 void CompileBroker::handle_compile_error(CompilerThread* thread, CompileTask* task, ciEnv* ci_env,
2379                                          int compilable, const char* failure_reason) {
2380   if (!AbortVMOnCompilationFailure) {
2381     return;
2382   }
2383   if (compilable == ciEnv::MethodCompilable_not_at_tier) {
2384     fatal("Not compilable at tier %d: %s", task->comp_level(), failure_reason);
2385   }
2386   if (compilable == ciEnv::MethodCompilable_never) {
2387     fatal("Never compilable: %s", failure_reason);
2388   }
2389 }
2390 
2391 static void post_compilation_event(EventCompilation& event, CompileTask* task) {
2392   assert(task != nullptr, "invariant");
2393   CompilerEvent::CompilationEvent::post(event,
2394                                         task->compile_id(),
2395                                         task->compiler()->type(),
2396                                         task->method(),
2397                                         task->comp_level(),
2398                                         task->is_success(),
2399                                         task->osr_bci() != CompileBroker::standard_entry_bci,
2400                                         task->nm_total_size(),
2401                                         task->num_inlined_bytecodes());
2402 }
2403 
2404 int DirectivesStack::_depth = 0;
2405 CompilerDirectives* DirectivesStack::_top = nullptr;
2406 CompilerDirectives* DirectivesStack::_bottom = nullptr;
2407 
2408 // Acquires Compilation_lock and waits for it to be notified
2409 // as long as WhiteBox::compilation_locked is true.
2410 static void whitebox_lock_compilation() {
2411   MonitorLocker locker(Compilation_lock, Mutex::_no_safepoint_check_flag);
2412   while (WhiteBox::compilation_locked) {
2413     locker.wait();
2414   }
2415 }
2416 
2417 // ------------------------------------------------------------------
2418 // CompileBroker::invoke_compiler_on_method
2419 //
2420 // Compile a method.
2421 //
2422 void CompileBroker::invoke_compiler_on_method(CompileTask* task) {
2423   task->print_ul();
2424   elapsedTimer time;
2425 
2426   DirectiveSet* directive = task->directive();
2427 
2428   CompilerThread* thread = CompilerThread::current();
2429   ResourceMark rm(thread);
2430 
2431   if (CompilationLog::log() != nullptr) {
2432     CompilationLog::log()->log_compile(thread, task);
2433   }
2434 
2435   // Common flags.
2436   int compile_id = task->compile_id();
2437   int osr_bci = task->osr_bci();
2438   bool is_osr = (osr_bci != standard_entry_bci);
2439   bool should_log = (thread->log() != nullptr);
2440   bool should_break = false;
2441   const int task_level = task->comp_level();
2442   AbstractCompiler* comp = task->compiler();
2443   CompileTrainingData* tdata = task->training_data();
2444   assert(tdata == nullptr || TrainingData::need_data(), "");
2445   {
2446     // create the handle inside it's own block so it can't
2447     // accidentally be referenced once the thread transitions to
2448     // native.  The NoHandleMark before the transition should catch
2449     // any cases where this occurs in the future.
2450     methodHandle method(thread, task->method());
2451 
2452     assert(!method->is_native(), "no longer compile natives");
2453 
2454     // Update compile information when using perfdata.
2455     if (UsePerfData) {
2456       update_compile_perf_data(thread, method, is_osr);
2457     }
2458 
2459     DTRACE_METHOD_COMPILE_BEGIN_PROBE(method, compiler_name(task_level));
2460   }
2461 
2462   if (tdata != nullptr) {
2463     tdata->record_compilation_start(task);
2464   }
2465 
2466   should_break = directive->BreakAtCompileOption || task->check_break_at_flags();
2467   if (should_log && !directive->LogOption) {
2468     should_log = false;
2469   }
2470 
2471   // Allocate a new set of JNI handles.
2472   JNIHandleMark jhm(thread);
2473   Method* target_handle = task->method();
2474   int compilable = ciEnv::MethodCompilable;
2475   const char* failure_reason = nullptr;
2476   bool failure_reason_on_C_heap = false;
2477   const char* retry_message = nullptr;
2478 
2479 #if INCLUDE_JVMCI
2480   if (UseJVMCICompiler && comp != nullptr && comp->is_jvmci()) {
2481     JVMCICompiler* jvmci = (JVMCICompiler*) comp;
2482 
2483     TraceTime t1("compilation", &time);
2484     EventCompilation event;
2485     JVMCICompileState compile_state(task, jvmci);
2486     JVMCIRuntime *runtime = nullptr;
2487 
2488     if (JVMCI::in_shutdown()) {
2489       failure_reason = "in JVMCI shutdown";
2490       retry_message = "not retryable";
2491       compilable = ciEnv::MethodCompilable_never;
2492     } else if (compile_state.target_method_is_old()) {
2493       // Skip redefined methods
2494       failure_reason = "redefined method";
2495       retry_message = "not retryable";
2496       compilable = ciEnv::MethodCompilable_never;
2497     } else {
2498       JVMCIEnv env(thread, &compile_state, __FILE__, __LINE__);
2499       if (env.init_error() != JNI_OK) {
2500         const char* msg = env.init_error_msg();
2501         failure_reason = os::strdup(err_msg("Error attaching to libjvmci (err: %d, %s)",
2502                                     env.init_error(), msg == nullptr ? "unknown" : msg), mtJVMCI);
2503         bool reason_on_C_heap = true;
2504         // In case of JNI_ENOMEM, there's a good chance a subsequent attempt to create libjvmci or attach to it
2505         // might succeed. Other errors most likely indicate a non-recoverable error in the JVMCI runtime.
2506         bool retryable = env.init_error() == JNI_ENOMEM;
2507         compile_state.set_failure(retryable, failure_reason, reason_on_C_heap);
2508       }
2509       if (failure_reason == nullptr) {
2510         if (WhiteBoxAPI && WhiteBox::compilation_locked) {
2511           // Must switch to native to block
2512           ThreadToNativeFromVM ttn(thread);
2513           whitebox_lock_compilation();
2514         }
2515         methodHandle method(thread, target_handle);
2516         runtime = env.runtime();
2517         runtime->compile_method(&env, jvmci, method, osr_bci);
2518 
2519         failure_reason = compile_state.failure_reason();
2520         failure_reason_on_C_heap = compile_state.failure_reason_on_C_heap();
2521         if (!compile_state.retryable()) {
2522           retry_message = "not retryable";
2523           compilable = ciEnv::MethodCompilable_not_at_tier;
2524         }
2525         if (!task->is_success()) {
2526           assert(failure_reason != nullptr, "must specify failure_reason");
2527         }
2528       }
2529     }
2530     if (!task->is_success() && !JVMCI::in_shutdown()) {
2531       handle_compile_error(thread, task, nullptr, compilable, failure_reason);
2532     }
2533     if (event.should_commit()) {
2534       post_compilation_event(event, task);
2535     }
2536 
2537     if (runtime != nullptr) {
2538       runtime->post_compile(thread);
2539     }
2540   } else
2541 #endif // INCLUDE_JVMCI
2542   {
2543     NoHandleMark  nhm;
2544     ThreadToNativeFromVM ttn(thread);
2545 
2546     ciEnv ci_env(task);
2547     if (should_break) {
2548       ci_env.set_break_at_compile(true);
2549     }
2550     if (should_log) {
2551       ci_env.set_log(thread->log());
2552     }
2553     assert(thread->env() == &ci_env, "set by ci_env");
2554     // The thread-env() field is cleared in ~CompileTaskWrapper.
2555 
2556     // Cache Jvmti state
2557     bool method_is_old = ci_env.cache_jvmti_state();
2558 
2559     // Skip redefined methods
2560     if (method_is_old) {
2561       ci_env.record_method_not_compilable("redefined method", true);
2562     }
2563 
2564     // Cache DTrace flags
2565     ci_env.cache_dtrace_flags();
2566 
2567     ciMethod* target = ci_env.get_method_from_handle(target_handle);
2568 
2569     TraceTime t1("compilation", &time);
2570     EventCompilation event;
2571 
2572     bool install_code = true;
2573     if (comp == nullptr) {
2574       ci_env.record_method_not_compilable("no compiler");
2575     } else if (!ci_env.failing()) {
2576       if (WhiteBoxAPI && WhiteBox::compilation_locked) {
2577         whitebox_lock_compilation();
2578       }
2579       if (StoreCachedCode && task->is_precompiled()) {
2580         install_code = false; // not suitable in the current context
2581       }
2582       comp->compile_method(&ci_env, target, osr_bci, install_code, directive);
2583 
2584       /* Repeat compilation without installing code for profiling purposes */
2585       int repeat_compilation_count = directive->RepeatCompilationOption;
2586       while (repeat_compilation_count > 0) {
2587         ResourceMark rm(thread);
2588         task->print_ul("NO CODE INSTALLED");
2589         comp->compile_method(&ci_env, target, osr_bci, false, directive);
2590         repeat_compilation_count--;
2591       }
2592     }
2593 
2594     DirectivesStack::release(directive);
2595 
2596     if (!ci_env.failing() && !task->is_success() && install_code) {
2597       assert(ci_env.failure_reason() != nullptr, "expect failure reason");
2598       assert(false, "compiler should always document failure: %s", ci_env.failure_reason());
2599       // The compiler elected, without comment, not to register a result.
2600       // Do not attempt further compilations of this method.
2601       ci_env.record_method_not_compilable("compile failed");
2602     }
2603 
2604     // Copy this bit to the enclosing block:
2605     compilable = ci_env.compilable();
2606 
2607     if (ci_env.failing()) {
2608       failure_reason = ci_env.failure_reason();
2609       retry_message = ci_env.retry_message();
2610       ci_env.report_failure(failure_reason);
2611     }
2612 
2613     if (ci_env.failing()) {
2614       handle_compile_error(thread, task, &ci_env, compilable, failure_reason);
2615     }
2616     if (event.should_commit()) {
2617       post_compilation_event(event, task);
2618     }
2619   }
2620 
2621   if (failure_reason != nullptr) {
2622     task->set_failure_reason(failure_reason, failure_reason_on_C_heap);
2623     if (CompilationLog::log() != nullptr) {
2624       CompilationLog::log()->log_failure(thread, task, failure_reason, retry_message);
2625     }
2626     if (PrintCompilation) {
2627       FormatBufferResource msg = retry_message != nullptr ?
2628         FormatBufferResource("COMPILE SKIPPED: %s (%s)", failure_reason, retry_message) :
2629         FormatBufferResource("COMPILE SKIPPED: %s",      failure_reason);
2630       task->print(tty, msg);
2631     }
2632   }
2633 
2634   if (tdata != nullptr) {
2635     tdata->record_compilation_end(task);
2636   }
2637 
2638   if (directive->PrintCompilationOption) {
2639     ResourceMark rm;
2640     task->print_tty();
2641   }
2642 
2643   methodHandle method(thread, task->method());
2644 
2645   DTRACE_METHOD_COMPILE_END_PROBE(method, compiler_name(task_level), task->is_success());
2646 
2647   collect_statistics(thread, time, task);
2648 
2649   if (PrintCompilation && PrintCompilation2) {
2650     tty->print("%7d ", (int) tty->time_stamp().milliseconds());  // print timestamp
2651     tty->print("%4d ", compile_id);    // print compilation number
2652     tty->print("%s ", (is_osr ? "%" : (task->is_scc() ? "A" : " ")));
2653     if (task->is_success()) {
2654       tty->print("size: %d(%d) ", task->nm_total_size(), task->nm_insts_size());
2655     }
2656     tty->print_cr("time: %d inlined: %d bytes", (int)time.milliseconds(), task->num_inlined_bytecodes());
2657   }
2658 
2659   Log(compilation, codecache) log;
2660   if (log.is_debug()) {
2661     LogStream ls(log.debug());
2662     codecache_print(&ls, /* detailed= */ false);
2663   }
2664   if (PrintCodeCacheOnCompilation) {
2665     codecache_print(/* detailed= */ false);
2666   }
2667   // Disable compilation, if required.
2668   switch (compilable) {
2669   case ciEnv::MethodCompilable_never:
2670     if (is_osr)
2671       method->set_not_osr_compilable_quietly("MethodCompilable_never");
2672     else
2673       method->set_not_compilable_quietly("MethodCompilable_never");
2674     break;
2675   case ciEnv::MethodCompilable_not_at_tier:
2676     if (is_osr)
2677       method->set_not_osr_compilable_quietly("MethodCompilable_not_at_tier", task_level);
2678     else
2679       method->set_not_compilable_quietly("MethodCompilable_not_at_tier", task_level);
2680     break;
2681   }
2682 
2683   // Note that the queued_for_compilation bits are cleared without
2684   // protection of a mutex. [They were set by the requester thread,
2685   // when adding the task to the compile queue -- at which time the
2686   // compile queue lock was held. Subsequently, we acquired the compile
2687   // queue lock to get this task off the compile queue; thus (to belabour
2688   // the point somewhat) our clearing of the bits must be occurring
2689   // only after the setting of the bits. See also 14012000 above.
2690   method->clear_queued_for_compilation();
2691   method->set_pending_queue_processed(false);
2692 }
2693 
2694 /**
2695  * The CodeCache is full. Print warning and disable compilation.
2696  * Schedule code cache cleaning so compilation can continue later.
2697  * This function needs to be called only from CodeCache::allocate(),
2698  * since we currently handle a full code cache uniformly.
2699  */
2700 void CompileBroker::handle_full_code_cache(CodeBlobType code_blob_type) {
2701   UseInterpreter = true;
2702   if (UseCompiler || AlwaysCompileLoopMethods ) {
2703     if (xtty != nullptr) {
2704       stringStream s;
2705       // Dump code cache state into a buffer before locking the tty,
2706       // because log_state() will use locks causing lock conflicts.
2707       CodeCache::log_state(&s);
2708       // Lock to prevent tearing
2709       ttyLocker ttyl;
2710       xtty->begin_elem("code_cache_full");
2711       xtty->print("%s", s.freeze());
2712       xtty->stamp();
2713       xtty->end_elem();
2714     }
2715 
2716 #ifndef PRODUCT
2717     if (ExitOnFullCodeCache) {
2718       codecache_print(/* detailed= */ true);
2719       before_exit(JavaThread::current());
2720       exit_globals(); // will delete tty
2721       vm_direct_exit(1);
2722     }
2723 #endif
2724     if (UseCodeCacheFlushing) {
2725       // Since code cache is full, immediately stop new compiles
2726       if (CompileBroker::set_should_compile_new_jobs(CompileBroker::stop_compilation)) {
2727         log_info(codecache)("Code cache is full - disabling compilation");
2728       }
2729     } else {
2730       disable_compilation_forever();
2731     }
2732 
2733     CodeCache::report_codemem_full(code_blob_type, should_print_compiler_warning());
2734   }
2735 }
2736 
2737 // ------------------------------------------------------------------
2738 // CompileBroker::update_compile_perf_data
2739 //
2740 // Record this compilation for debugging purposes.
2741 void CompileBroker::update_compile_perf_data(CompilerThread* thread, const methodHandle& method, bool is_osr) {
2742   ResourceMark rm;
2743   char* method_name = method->name()->as_C_string();
2744   char current_method[CompilerCounters::cmname_buffer_length];
2745   size_t maxLen = CompilerCounters::cmname_buffer_length;
2746 
2747   const char* class_name = method->method_holder()->name()->as_C_string();
2748 
2749   size_t s1len = strlen(class_name);
2750   size_t s2len = strlen(method_name);
2751 
2752   // check if we need to truncate the string
2753   if (s1len + s2len + 2 > maxLen) {
2754 
2755     // the strategy is to lop off the leading characters of the
2756     // class name and the trailing characters of the method name.
2757 
2758     if (s2len + 2 > maxLen) {
2759       // lop of the entire class name string, let snprintf handle
2760       // truncation of the method name.
2761       class_name += s1len; // null string
2762     }
2763     else {
2764       // lop off the extra characters from the front of the class name
2765       class_name += ((s1len + s2len + 2) - maxLen);
2766     }
2767   }
2768 
2769   jio_snprintf(current_method, maxLen, "%s %s", class_name, method_name);
2770 
2771   int last_compile_type = normal_compile;
2772   if (CICountOSR && is_osr) {
2773     last_compile_type = osr_compile;
2774   } else if (CICountNative && method->is_native()) {
2775     last_compile_type = native_compile;
2776   }
2777 
2778   CompilerCounters* counters = thread->counters();
2779   counters->set_current_method(current_method);
2780   counters->set_compile_type((jlong) last_compile_type);
2781 }
2782 
2783 // ------------------------------------------------------------------
2784 // CompileBroker::collect_statistics
2785 //
2786 // Collect statistics about the compilation.
2787 
2788 void CompileBroker::collect_statistics(CompilerThread* thread, elapsedTimer time, CompileTask* task) {
2789   bool success = task->is_success();
2790   methodHandle method (thread, task->method());
2791   int compile_id = task->compile_id();
2792   bool is_osr = (task->osr_bci() != standard_entry_bci);
2793   const int comp_level = task->comp_level();
2794   CompilerCounters* counters = thread->counters();
2795 
2796   MutexLocker locker(CompileStatistics_lock);
2797 
2798   // _perf variables are production performance counters which are
2799   // updated regardless of the setting of the CITime and CITimeEach flags
2800   //
2801 
2802   // account all time, including bailouts and failures in this counter;
2803   // C1 and C2 counters are counting both successful and unsuccessful compiles
2804   _t_total_compilation.add(&time);
2805 
2806   if (!success) {
2807     _total_bailout_count++;
2808     if (UsePerfData) {
2809       _perf_last_failed_method->set_value(counters->current_method());
2810       _perf_last_failed_type->set_value(counters->compile_type());
2811       _perf_total_bailout_count->inc();
2812     }
2813     _t_bailedout_compilation.add(&time);
2814 
2815     if (CITime || log_is_enabled(Info, init)) {
2816       CompilerStatistics* stats = nullptr;
2817       if (task->is_scc()) {
2818         int level = task->preload() ? CompLevel_full_optimization : (comp_level - 1);
2819         stats = &_scc_stats_per_level[level];
2820       } else {
2821         stats = &_stats_per_level[comp_level-1];
2822       }
2823       stats->_bailout.update(time, 0);
2824     }
2825   } else if (!task->is_success()) {
2826     if (UsePerfData) {
2827       _perf_last_invalidated_method->set_value(counters->current_method());
2828       _perf_last_invalidated_type->set_value(counters->compile_type());
2829       _perf_total_invalidated_count->inc();
2830     }
2831     _total_invalidated_count++;
2832     _t_invalidated_compilation.add(&time);
2833 
2834     if (CITime || log_is_enabled(Info, init)) {
2835       CompilerStatistics* stats = nullptr;
2836       if (task->is_scc()) {
2837         int level = task->preload() ? CompLevel_full_optimization : (comp_level - 1);
2838         stats = &_scc_stats_per_level[level];
2839       } else {
2840         stats = &_stats_per_level[comp_level-1];
2841       }
2842       stats->_invalidated.update(time, 0);
2843     }
2844   } else {
2845     // Compilation succeeded
2846 
2847     // update compilation ticks - used by the implementation of
2848     // java.lang.management.CompilationMXBean
2849     _perf_total_compilation->inc(time.ticks());
2850     _peak_compilation_time = time.milliseconds() > _peak_compilation_time ? time.milliseconds() : _peak_compilation_time;
2851 
2852     if (CITime || log_is_enabled(Info, init)) {
2853       int bytes_compiled = method->code_size() + task->num_inlined_bytecodes();
2854       if (is_osr) {
2855         _t_osr_compilation.add(&time);
2856         _sum_osr_bytes_compiled += bytes_compiled;
2857       } else {
2858         _t_standard_compilation.add(&time);
2859         _sum_standard_bytes_compiled += method->code_size() + task->num_inlined_bytecodes();
2860       }
2861 
2862       // Collect statistic per compilation level
2863       if (task->is_scc()) {
2864         _scc_stats._standard.update(time, bytes_compiled);
2865         _scc_stats._nmethods_size += task->nm_total_size();
2866         _scc_stats._nmethods_code_size += task->nm_insts_size();
2867         int level = task->preload() ? CompLevel_full_optimization : (comp_level - 1);
2868         CompilerStatistics* stats = &_scc_stats_per_level[level];
2869         stats->_standard.update(time, bytes_compiled);
2870         stats->_nmethods_size += task->nm_total_size();
2871         stats->_nmethods_code_size += task->nm_insts_size();
2872       } else if (comp_level > CompLevel_none && comp_level <= CompLevel_full_optimization) {
2873         CompilerStatistics* stats = &_stats_per_level[comp_level-1];
2874         if (is_osr) {
2875           stats->_osr.update(time, bytes_compiled);
2876         } else {
2877           stats->_standard.update(time, bytes_compiled);
2878         }
2879         stats->_nmethods_size += task->nm_total_size();
2880         stats->_nmethods_code_size += task->nm_insts_size();
2881       } else {
2882         assert(false, "CompilerStatistics object does not exist for compilation level %d", comp_level);
2883       }
2884 
2885       // Collect statistic per compiler
2886       AbstractCompiler* comp = task->compiler();
2887       if (comp && !task->is_scc()) {
2888         CompilerStatistics* stats = comp->stats();
2889         if (is_osr) {
2890           stats->_osr.update(time, bytes_compiled);
2891         } else {
2892           stats->_standard.update(time, bytes_compiled);
2893         }
2894         stats->_nmethods_size += task->nm_total_size();
2895         stats->_nmethods_code_size += task->nm_insts_size();
2896       } else if (!task->is_scc()) { // if (!comp)
2897         assert(false, "Compiler object must exist");
2898       }
2899     }
2900 
2901     if (UsePerfData) {
2902       // save the name of the last method compiled
2903       _perf_last_method->set_value(counters->current_method());
2904       _perf_last_compile_type->set_value(counters->compile_type());
2905       _perf_last_compile_size->set_value(method->code_size() +
2906                                          task->num_inlined_bytecodes());
2907       if (is_osr) {
2908         _perf_osr_compilation->inc(time.ticks());
2909         _perf_sum_osr_bytes_compiled->inc(method->code_size() + task->num_inlined_bytecodes());
2910       } else {
2911         _perf_standard_compilation->inc(time.ticks());
2912         _perf_sum_standard_bytes_compiled->inc(method->code_size() + task->num_inlined_bytecodes());
2913       }
2914     }
2915 
2916     if (CITimeEach) {
2917       double compile_time = time.seconds();
2918       double bytes_per_sec = compile_time == 0.0 ? 0.0 : (double)(method->code_size() + task->num_inlined_bytecodes()) / compile_time;
2919       tty->print_cr("%3d   seconds: %6.3f bytes/sec : %f (bytes %d + %d inlined)",
2920                     compile_id, compile_time, bytes_per_sec, method->code_size(), task->num_inlined_bytecodes());
2921     }
2922 
2923     // Collect counts of successful compilations
2924     _sum_nmethod_size      += task->nm_total_size();
2925     _sum_nmethod_code_size += task->nm_insts_size();
2926     _total_compile_count++;
2927 
2928     if (UsePerfData) {
2929       _perf_sum_nmethod_size->inc(     task->nm_total_size());
2930       _perf_sum_nmethod_code_size->inc(task->nm_insts_size());
2931       _perf_total_compile_count->inc();
2932     }
2933 
2934     if (is_osr) {
2935       if (UsePerfData) _perf_total_osr_compile_count->inc();
2936       _total_osr_compile_count++;
2937     } else {
2938       if (UsePerfData) _perf_total_standard_compile_count->inc();
2939       _total_standard_compile_count++;
2940     }
2941   }
2942   // set the current method for the thread to null
2943   if (UsePerfData) counters->set_current_method("");
2944 }
2945 
2946 const char* CompileBroker::compiler_name(int comp_level) {
2947   AbstractCompiler *comp = CompileBroker::compiler(comp_level);
2948   if (comp == nullptr) {
2949     return "no compiler";
2950   } else {
2951     return (comp->name());
2952   }
2953 }
2954 
2955 jlong CompileBroker::total_compilation_ticks() {
2956   return _perf_total_compilation != nullptr ? _perf_total_compilation->get_value() : 0;
2957 }
2958 
2959 void CompileBroker::log_not_entrant(nmethod* nm) {
2960   _total_not_entrant_count++;
2961   if (CITime || log_is_enabled(Info, init)) {
2962     CompilerStatistics* stats = nullptr;
2963     int level = nm->comp_level();
2964     if (nm->is_scc()) {
2965       if (nm->preloaded()) {
2966         assert(level == CompLevel_full_optimization, "%d", level);
2967         level = CompLevel_full_optimization + 1;
2968       }
2969       stats = &_scc_stats_per_level[level - 1];
2970     } else {
2971       stats = &_stats_per_level[level - 1];
2972     }
2973     stats->_made_not_entrant._count++;
2974   }
2975 }
2976 
2977 void CompileBroker::print_times(const char* name, CompilerStatistics* stats) {
2978   tty->print_cr("  %s {speed: %6.3f bytes/s; standard: %6.3f s, %u bytes, %u methods; osr: %6.3f s, %u bytes, %u methods; nmethods_size: %u bytes; nmethods_code_size: %u bytes}",
2979                 name, stats->bytes_per_second(),
2980                 stats->_standard._time.seconds(), stats->_standard._bytes, stats->_standard._count,
2981                 stats->_osr._time.seconds(), stats->_osr._bytes, stats->_osr._count,
2982                 stats->_nmethods_size, stats->_nmethods_code_size);
2983 }
2984 
2985 static void print_helper(outputStream* st, const char* name, CompilerStatistics::Data data, bool print_time = true) {
2986   if (data._count > 0) {
2987     st->print("; %s: %4u methods", name, data._count);
2988     if (print_time) {
2989       st->print(" (in %.3fs)", data._time.seconds());
2990     }
2991   }
2992 }
2993 
2994 static void print_tier_helper(outputStream* st, const char* prefix, int tier, CompilerStatistics* stats) {
2995   st->print("    %s%d: %5u methods", prefix, tier, stats->_standard._count);
2996   if (stats->_standard._count > 0) {
2997     st->print(" (in %.3fs)", stats->_standard._time.seconds());
2998   }
2999   print_helper(st, "osr",     stats->_osr);
3000   print_helper(st, "bailout", stats->_bailout);
3001   print_helper(st, "invalid", stats->_invalidated);
3002   print_helper(st, "not_entrant", stats->_made_not_entrant, false);
3003   st->cr();
3004 }
3005 
3006 static void print_queue_info(outputStream* st, CompileQueue* queue) {
3007   if (queue != nullptr) {
3008     MutexLocker ml(queue->lock());
3009 
3010     uint  total_cnt = 0;
3011     uint active_cnt = 0;
3012     for (JavaThread* jt : *ThreadsSMRSupport::get_java_thread_list()) {
3013       guarantee(jt != nullptr, "");
3014       if (jt->is_Compiler_thread()) {
3015         CompilerThread* ct = (CompilerThread*)jt;
3016 
3017         guarantee(ct != nullptr, "");
3018         if (ct->queue() == queue) {
3019           ++total_cnt;
3020           CompileTask* task = ct->task();
3021           if (task != nullptr) {
3022             ++active_cnt;
3023           }
3024         }
3025       }
3026     }
3027 
3028     st->print("  %s (%d active / %d total threads): %u tasks",
3029               queue->name(), active_cnt, total_cnt, queue->size());
3030     if (queue->size() > 0) {
3031       uint counts[] = {0, 0, 0, 0, 0}; // T1 ... T5
3032       for (CompileTask* task = queue->first(); task != nullptr; task = task->next()) {
3033         int tier = task->comp_level();
3034         if (task->is_scc() && task->preload()) {
3035           assert(tier == CompLevel_full_optimization, "%d", tier);
3036           tier = CompLevel_full_optimization + 1;
3037         }
3038         counts[tier-1]++;
3039       }
3040       st->print(":");
3041       for (int tier = CompLevel_simple; tier <= CompilationPolicy::highest_compile_level() + 1; tier++) {
3042         uint cnt = counts[tier-1];
3043         if (cnt > 0) {
3044           st->print(" T%d: %u tasks;", tier, cnt);
3045         }
3046       }
3047     }
3048     st->cr();
3049 
3050 //    for (JavaThread* jt : *ThreadsSMRSupport::get_java_thread_list()) {
3051 //      guarantee(jt != nullptr, "");
3052 //      if (jt->is_Compiler_thread()) {
3053 //        CompilerThread* ct = (CompilerThread*)jt;
3054 //
3055 //        guarantee(ct != nullptr, "");
3056 //        if (ct->queue() == queue) {
3057 //          ResourceMark rm;
3058 //          CompileTask* task = ct->task();
3059 //          st->print("    %s: ", ct->name_raw());
3060 //          if (task != nullptr) {
3061 //            task->print(st, nullptr, true /*short_form*/, false /*cr*/);
3062 //          }
3063 //          st->cr();
3064 //        }
3065 //      }
3066 //    }
3067   }
3068 }
3069 void CompileBroker::print_statistics_on(outputStream* st) {
3070   st->print_cr("  Total: %u methods; %u bailouts, %u invalidated, %u non_entrant",
3071                _total_compile_count, _total_bailout_count, _total_invalidated_count, _total_not_entrant_count);
3072   for (int tier = CompLevel_simple; tier <= CompilationPolicy::highest_compile_level(); tier++) {
3073     print_tier_helper(st, "Tier", tier, &_stats_per_level[tier-1]);
3074   }
3075   st->cr();
3076 
3077   if (LoadCachedCode || StoreCachedCode) {
3078     for (int tier = CompLevel_simple; tier <= CompilationPolicy::highest_compile_level() + 1; tier++) {
3079       if (tier != CompLevel_full_profile) {
3080         print_tier_helper(st, "SC T", tier, &_scc_stats_per_level[tier - 1]);
3081       }
3082     }
3083     st->cr();
3084   }
3085 
3086   print_queue_info(st, _c1_compile_queue);
3087   print_queue_info(st, _c2_compile_queue);
3088   print_queue_info(st, _c3_compile_queue);
3089   print_queue_info(st, _sc1_compile_queue);
3090   print_queue_info(st, _sc2_compile_queue);
3091 }
3092 
3093 void CompileBroker::print_times(bool per_compiler, bool aggregate) {
3094   if (per_compiler) {
3095     if (aggregate) {
3096       tty->cr();
3097       tty->print_cr("[%dms] Individual compiler times (for compiled methods only)", (int)tty->time_stamp().milliseconds());
3098       tty->print_cr("------------------------------------------------");
3099       tty->cr();
3100     }
3101     for (unsigned int i = 0; i < sizeof(_compilers) / sizeof(AbstractCompiler*); i++) {
3102       AbstractCompiler* comp = _compilers[i];
3103       if (comp != nullptr) {
3104         print_times(comp->name(), comp->stats());
3105       }
3106     }
3107     if (_scc_stats._standard._count > 0) {
3108       print_times("SC", &_scc_stats);
3109     }
3110     if (aggregate) {
3111       tty->cr();
3112       tty->print_cr("Individual compilation Tier times (for compiled methods only)");
3113       tty->print_cr("------------------------------------------------");
3114       tty->cr();
3115     }
3116     char tier_name[256];
3117     for (int tier = CompLevel_simple; tier <= CompilationPolicy::highest_compile_level(); tier++) {
3118       CompilerStatistics* stats = &_stats_per_level[tier-1];
3119       os::snprintf_checked(tier_name, sizeof(tier_name), "Tier%d", tier);
3120       print_times(tier_name, stats);
3121     }
3122     for (int tier = CompLevel_simple; tier <= CompilationPolicy::highest_compile_level() + 1; tier++) {
3123       CompilerStatistics* stats = &_scc_stats_per_level[tier-1];
3124       if (stats->_standard._bytes > 0) {
3125         os::snprintf_checked(tier_name, sizeof(tier_name), "SC T%d", tier);
3126         print_times(tier_name, stats);
3127       }
3128     }
3129   }
3130 
3131   if (!aggregate) {
3132     return;
3133   }
3134 
3135   elapsedTimer standard_compilation = CompileBroker::_t_standard_compilation;
3136   elapsedTimer osr_compilation = CompileBroker::_t_osr_compilation;
3137   elapsedTimer total_compilation = CompileBroker::_t_total_compilation;
3138 
3139   uint standard_bytes_compiled = CompileBroker::_sum_standard_bytes_compiled;
3140   uint osr_bytes_compiled = CompileBroker::_sum_osr_bytes_compiled;
3141 
3142   uint standard_compile_count = CompileBroker::_total_standard_compile_count;
3143   uint osr_compile_count = CompileBroker::_total_osr_compile_count;
3144   uint total_compile_count = CompileBroker::_total_compile_count;
3145   uint total_bailout_count = CompileBroker::_total_bailout_count;
3146   uint total_invalidated_count = CompileBroker::_total_invalidated_count;
3147 
3148   uint nmethods_code_size = CompileBroker::_sum_nmethod_code_size;
3149   uint nmethods_size = CompileBroker::_sum_nmethod_size;
3150 
3151   tty->cr();
3152   tty->print_cr("Accumulated compiler times");
3153   tty->print_cr("----------------------------------------------------------");
3154                //0000000000111111111122222222223333333333444444444455555555556666666666
3155                //0123456789012345678901234567890123456789012345678901234567890123456789
3156   tty->print_cr("  Total compilation time   : %7.3f s", total_compilation.seconds());
3157   tty->print_cr("    Standard compilation   : %7.3f s, Average : %2.3f s",
3158                 standard_compilation.seconds(),
3159                 standard_compile_count == 0 ? 0.0 : standard_compilation.seconds() / standard_compile_count);
3160   tty->print_cr("    Bailed out compilation : %7.3f s, Average : %2.3f s",
3161                 CompileBroker::_t_bailedout_compilation.seconds(),
3162                 total_bailout_count == 0 ? 0.0 : CompileBroker::_t_bailedout_compilation.seconds() / total_bailout_count);
3163   tty->print_cr("    On stack replacement   : %7.3f s, Average : %2.3f s",
3164                 osr_compilation.seconds(),
3165                 osr_compile_count == 0 ? 0.0 : osr_compilation.seconds() / osr_compile_count);
3166   tty->print_cr("    Invalidated            : %7.3f s, Average : %2.3f s",
3167                 CompileBroker::_t_invalidated_compilation.seconds(),
3168                 total_invalidated_count == 0 ? 0.0 : CompileBroker::_t_invalidated_compilation.seconds() / total_invalidated_count);
3169 
3170   if (StoreCachedCode || LoadCachedCode) { // Check flags because SC cache could be closed already
3171     tty->cr();
3172     SCCache::print_timers_on(tty);
3173   }
3174   AbstractCompiler *comp = compiler(CompLevel_simple);
3175   if (comp != nullptr) {
3176     tty->cr();
3177     comp->print_timers();
3178   }
3179   comp = compiler(CompLevel_full_optimization);
3180   if (comp != nullptr) {
3181     tty->cr();
3182     comp->print_timers();
3183   }
3184   comp = _compilers[2];
3185   if (comp != nullptr) {
3186     tty->cr();
3187     comp->print_timers();
3188   }
3189 #if INCLUDE_JVMCI
3190   if (EnableJVMCI) {
3191     JVMCICompiler *jvmci_comp = JVMCICompiler::instance(false, JavaThread::current_or_null());
3192     if (jvmci_comp != nullptr && jvmci_comp != comp) {
3193       tty->cr();
3194       jvmci_comp->print_timers();
3195     }
3196   }
3197 #endif
3198 
3199   tty->cr();
3200   tty->print_cr("  Total compiled methods    : %8u methods", total_compile_count);
3201   tty->print_cr("    Standard compilation    : %8u methods", standard_compile_count);
3202   tty->print_cr("    On stack replacement    : %8u methods", osr_compile_count);
3203   uint tcb = osr_bytes_compiled + standard_bytes_compiled;
3204   tty->print_cr("  Total compiled bytecodes  : %8u bytes", tcb);
3205   tty->print_cr("    Standard compilation    : %8u bytes", standard_bytes_compiled);
3206   tty->print_cr("    On stack replacement    : %8u bytes", osr_bytes_compiled);
3207   double tcs = total_compilation.seconds();
3208   uint bps = tcs == 0.0 ? 0 : (uint)(tcb / tcs);
3209   tty->print_cr("  Average compilation speed : %8u bytes/s", bps);
3210   tty->cr();
3211   tty->print_cr("  nmethod code size         : %8u bytes", nmethods_code_size);
3212   tty->print_cr("  nmethod total size        : %8u bytes", nmethods_size);
3213 }
3214 
3215 // Print general/accumulated JIT information.
3216 void CompileBroker::print_info(outputStream *out) {
3217   if (out == nullptr) out = tty;
3218   out->cr();
3219   out->print_cr("======================");
3220   out->print_cr("   General JIT info   ");
3221   out->print_cr("======================");
3222   out->cr();
3223   out->print_cr("            JIT is : %7s",     should_compile_new_jobs() ? "on" : "off");
3224   out->print_cr("  Compiler threads : %7d",     (int)CICompilerCount);
3225   out->cr();
3226   out->print_cr("CodeCache overview");
3227   out->print_cr("--------------------------------------------------------");
3228   out->cr();
3229   out->print_cr("         Reserved size : " SIZE_FORMAT_W(7) " KB", CodeCache::max_capacity() / K);
3230   out->print_cr("        Committed size : " SIZE_FORMAT_W(7) " KB", CodeCache::capacity() / K);
3231   out->print_cr("  Unallocated capacity : " SIZE_FORMAT_W(7) " KB", CodeCache::unallocated_capacity() / K);
3232   out->cr();
3233 }
3234 
3235 // Note: tty_lock must not be held upon entry to this function.
3236 //       Print functions called from herein do "micro-locking" on tty_lock.
3237 //       That's a tradeoff which keeps together important blocks of output.
3238 //       At the same time, continuous tty_lock hold time is kept in check,
3239 //       preventing concurrently printing threads from stalling a long time.
3240 void CompileBroker::print_heapinfo(outputStream* out, const char* function, size_t granularity) {
3241   TimeStamp ts_total;
3242   TimeStamp ts_global;
3243   TimeStamp ts;
3244 
3245   bool allFun = !strcmp(function, "all");
3246   bool aggregate = !strcmp(function, "aggregate") || !strcmp(function, "analyze") || allFun;
3247   bool usedSpace = !strcmp(function, "UsedSpace") || allFun;
3248   bool freeSpace = !strcmp(function, "FreeSpace") || allFun;
3249   bool methodCount = !strcmp(function, "MethodCount") || allFun;
3250   bool methodSpace = !strcmp(function, "MethodSpace") || allFun;
3251   bool methodAge = !strcmp(function, "MethodAge") || allFun;
3252   bool methodNames = !strcmp(function, "MethodNames") || allFun;
3253   bool discard = !strcmp(function, "discard") || allFun;
3254 
3255   if (out == nullptr) {
3256     out = tty;
3257   }
3258 
3259   if (!(aggregate || usedSpace || freeSpace || methodCount || methodSpace || methodAge || methodNames || discard)) {
3260     out->print_cr("\n__ CodeHeapStateAnalytics: Function %s is not supported", function);
3261     out->cr();
3262     return;
3263   }
3264 
3265   ts_total.update(); // record starting point
3266 
3267   if (aggregate) {
3268     print_info(out);
3269   }
3270 
3271   // We hold the CodeHeapStateAnalytics_lock all the time, from here until we leave this function.
3272   // That prevents other threads from destroying (making inconsistent) our view on the CodeHeap.
3273   // When we request individual parts of the analysis via the jcmd interface, it is possible
3274   // that in between another thread (another jcmd user or the vm running into CodeCache OOM)
3275   // updated the aggregated data. We will then see a modified, but again consistent, view
3276   // on the CodeHeap. That's a tolerable tradeoff we have to accept because we can't hold
3277   // a lock across user interaction.
3278 
3279   // We should definitely acquire this lock before acquiring Compile_lock and CodeCache_lock.
3280   // CodeHeapStateAnalytics_lock may be held by a concurrent thread for a long time,
3281   // leading to an unnecessarily long hold time of the other locks we acquired before.
3282   ts.update(); // record starting point
3283   MutexLocker mu0(CodeHeapStateAnalytics_lock, Mutex::_safepoint_check_flag);
3284   out->print_cr("\n__ CodeHeapStateAnalytics lock wait took %10.3f seconds _________\n", ts.seconds());
3285 
3286   // Holding the CodeCache_lock protects from concurrent alterations of the CodeCache.
3287   // Unfortunately, such protection is not sufficient:
3288   // When a new nmethod is created via ciEnv::register_method(), the
3289   // Compile_lock is taken first. After some initializations,
3290   // nmethod::new_nmethod() takes over, grabbing the CodeCache_lock
3291   // immediately (after finalizing the oop references). To lock out concurrent
3292   // modifiers, we have to grab both locks as well in the described sequence.
3293   //
3294   // If we serve an "allFun" call, it is beneficial to hold CodeCache_lock and Compile_lock
3295   // for the entire duration of aggregation and printing. That makes sure we see
3296   // a consistent picture and do not run into issues caused by concurrent alterations.
3297   bool should_take_Compile_lock   = !SafepointSynchronize::is_at_safepoint() &&
3298                                     !Compile_lock->owned_by_self();
3299   bool should_take_CodeCache_lock = !SafepointSynchronize::is_at_safepoint() &&
3300                                     !CodeCache_lock->owned_by_self();
3301   bool take_global_lock_1   =  allFun && should_take_Compile_lock;
3302   bool take_global_lock_2   =  allFun && should_take_CodeCache_lock;
3303   bool take_function_lock_1 = !allFun && should_take_Compile_lock;
3304   bool take_function_lock_2 = !allFun && should_take_CodeCache_lock;
3305   bool take_global_locks    = take_global_lock_1 || take_global_lock_2;
3306   bool take_function_locks  = take_function_lock_1 || take_function_lock_2;
3307 
3308   ts_global.update(); // record starting point
3309 
3310   ConditionalMutexLocker mu1(Compile_lock, take_global_lock_1, Mutex::_safepoint_check_flag);
3311   ConditionalMutexLocker mu2(CodeCache_lock, take_global_lock_2, Mutex::_no_safepoint_check_flag);
3312   if (take_global_locks) {
3313     out->print_cr("\n__ Compile & CodeCache (global) lock wait took %10.3f seconds _________\n", ts_global.seconds());
3314     ts_global.update(); // record starting point
3315   }
3316 
3317   if (aggregate) {
3318     ts.update(); // record starting point
3319     ConditionalMutexLocker mu11(Compile_lock, take_function_lock_1,  Mutex::_safepoint_check_flag);
3320     ConditionalMutexLocker mu22(CodeCache_lock, take_function_lock_2, Mutex::_no_safepoint_check_flag);
3321     if (take_function_locks) {
3322       out->print_cr("\n__ Compile & CodeCache (function) lock wait took %10.3f seconds _________\n", ts.seconds());
3323     }
3324 
3325     ts.update(); // record starting point
3326     CodeCache::aggregate(out, granularity);
3327     if (take_function_locks) {
3328       out->print_cr("\n__ Compile & CodeCache (function) lock hold took %10.3f seconds _________\n", ts.seconds());
3329     }
3330   }
3331 
3332   if (usedSpace) CodeCache::print_usedSpace(out);
3333   if (freeSpace) CodeCache::print_freeSpace(out);
3334   if (methodCount) CodeCache::print_count(out);
3335   if (methodSpace) CodeCache::print_space(out);
3336   if (methodAge) CodeCache::print_age(out);
3337   if (methodNames) {
3338     if (allFun) {
3339       // print_names() can only be used safely if the locks have been continuously held
3340       // since aggregation begin. That is true only for function "all".
3341       CodeCache::print_names(out);
3342     } else {
3343       out->print_cr("\nCodeHeapStateAnalytics: Function 'MethodNames' is only available as part of function 'all'");
3344     }
3345   }
3346   if (discard) CodeCache::discard(out);
3347 
3348   if (take_global_locks) {
3349     out->print_cr("\n__ Compile & CodeCache (global) lock hold took %10.3f seconds _________\n", ts_global.seconds());
3350   }
3351   out->print_cr("\n__ CodeHeapStateAnalytics total duration %10.3f seconds _________\n", ts_total.seconds());
3352 }