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/cdsConfig.hpp"
  27 #include "cds/classPreloader.hpp"
  28 #include "classfile/javaClasses.inline.hpp"
  29 #include "classfile/symbolTable.hpp"
  30 #include "classfile/vmClasses.hpp"
  31 #include "classfile/vmSymbols.hpp"
  32 #include "code/codeCache.hpp"
  33 #include "code/codeHeapState.hpp"
  34 #include "code/dependencyContext.hpp"
  35 #include "code/SCCache.hpp"
  36 #include "compiler/compilationLog.hpp"
  37 #include "compiler/compilationMemoryStatistic.hpp"
  38 #include "compiler/compilationPolicy.hpp"
  39 #include "compiler/compileBroker.hpp"
  40 #include "compiler/compilerDefinitions.inline.hpp"
  41 #include "compiler/compileLog.hpp"
  42 #include "compiler/compilerEvent.hpp"
  43 #include "compiler/compilerOracle.hpp"
  44 #include "compiler/directivesParser.hpp"
  45 #include "interpreter/linkResolver.hpp"
  46 #include "jvm.h"
  47 #include "jfr/jfrEvents.hpp"
  48 #include "logging/log.hpp"
  49 #include "logging/logStream.hpp"
  50 #include "memory/allocation.inline.hpp"
  51 #include "memory/resourceArea.hpp"
  52 #include "memory/universe.hpp"
  53 #include "oops/methodData.hpp"
  54 #include "oops/method.inline.hpp"
  55 #include "oops/oop.inline.hpp"
  56 #include "prims/jvmtiExport.hpp"
  57 #include "prims/nativeLookup.hpp"
  58 #include "prims/whitebox.hpp"
  59 #include "runtime/atomic.hpp"
  60 #include "runtime/escapeBarrier.hpp"
  61 #include "runtime/globals_extension.hpp"
  62 #include "runtime/handles.inline.hpp"
  63 #include "runtime/init.hpp"
  64 #include "runtime/interfaceSupport.inline.hpp"
  65 #include "runtime/java.hpp"
  66 #include "runtime/javaCalls.hpp"
  67 #include "runtime/jniHandles.inline.hpp"
  68 #include "runtime/os.hpp"
  69 #include "runtime/perfData.hpp"
  70 #include "runtime/safepointVerifiers.hpp"
  71 #include "runtime/sharedRuntime.hpp"
  72 #include "runtime/threads.hpp"
  73 #include "runtime/threadSMR.inline.hpp"
  74 #include "runtime/timerTrace.hpp"
  75 #include "runtime/vframe.inline.hpp"
  76 #include "services/management.hpp"
  77 #include "utilities/debug.hpp"
  78 #include "utilities/dtrace.hpp"
  79 #include "utilities/events.hpp"
  80 #include "utilities/formatBuffer.hpp"
  81 #include "utilities/macros.hpp"
  82 #ifdef COMPILER1
  83 #include "c1/c1_Compiler.hpp"
  84 #endif
  85 #ifdef COMPILER2
  86 #include "opto/c2compiler.hpp"
  87 #endif
  88 #if INCLUDE_JVMCI
  89 #include "jvmci/jvmciEnv.hpp"
  90 #include "jvmci/jvmciRuntime.hpp"
  91 #endif
  92 
  93 #ifdef DTRACE_ENABLED
  94 
  95 // Only bother with this argument setup if dtrace is available
  96 
  97 #define DTRACE_METHOD_COMPILE_BEGIN_PROBE(method, comp_name)             \
  98   {                                                                      \
  99     Symbol* klass_name = (method)->klass_name();                         \
 100     Symbol* name = (method)->name();                                     \
 101     Symbol* signature = (method)->signature();                           \
 102     HOTSPOT_METHOD_COMPILE_BEGIN(                                        \
 103       (char *) comp_name, strlen(comp_name),                             \
 104       (char *) klass_name->bytes(), klass_name->utf8_length(),           \
 105       (char *) name->bytes(), name->utf8_length(),                       \
 106       (char *) signature->bytes(), signature->utf8_length());            \
 107   }
 108 
 109 #define DTRACE_METHOD_COMPILE_END_PROBE(method, comp_name, success)      \
 110   {                                                                      \
 111     Symbol* klass_name = (method)->klass_name();                         \
 112     Symbol* name = (method)->name();                                     \
 113     Symbol* signature = (method)->signature();                           \
 114     HOTSPOT_METHOD_COMPILE_END(                                          \
 115       (char *) comp_name, strlen(comp_name),                             \
 116       (char *) klass_name->bytes(), klass_name->utf8_length(),           \
 117       (char *) name->bytes(), name->utf8_length(),                       \
 118       (char *) signature->bytes(), signature->utf8_length(), (success)); \
 119   }
 120 
 121 #else //  ndef DTRACE_ENABLED
 122 
 123 #define DTRACE_METHOD_COMPILE_BEGIN_PROBE(method, comp_name)
 124 #define DTRACE_METHOD_COMPILE_END_PROBE(method, comp_name, success)
 125 
 126 #endif // ndef DTRACE_ENABLED
 127 
 128 bool CompileBroker::_initialized = false;
 129 bool CompileBroker::_replay_initialized = false;
 130 volatile bool CompileBroker::_should_block = false;
 131 volatile int  CompileBroker::_print_compilation_warning = 0;
 132 volatile jint CompileBroker::_should_compile_new_jobs = run_compilation;
 133 
 134 // The installed compiler(s)
 135 AbstractCompiler* CompileBroker::_compilers[3];
 136 
 137 // The maximum numbers of compiler threads to be determined during startup.
 138 int CompileBroker::_c1_count = 0;
 139 int CompileBroker::_c2_count = 0;
 140 int CompileBroker::_c3_count = 0;
 141 int CompileBroker::_sc_count = 0;
 142 
 143 // An array of compiler names as Java String objects
 144 jobject* CompileBroker::_compiler1_objects = nullptr;
 145 jobject* CompileBroker::_compiler2_objects = nullptr;
 146 jobject* CompileBroker::_compiler3_objects = nullptr;
 147 jobject* CompileBroker::_sc_objects = nullptr;
 148 
 149 CompileLog** CompileBroker::_compiler1_logs = nullptr;
 150 CompileLog** CompileBroker::_compiler2_logs = nullptr;
 151 CompileLog** CompileBroker::_compiler3_logs = nullptr;
 152 CompileLog** CompileBroker::_sc_logs = nullptr;
 153 
 154 // These counters are used to assign an unique ID to each compilation.
 155 volatile jint CompileBroker::_compilation_id     = 0;
 156 volatile jint CompileBroker::_osr_compilation_id = 0;
 157 volatile jint CompileBroker::_native_compilation_id = 0;
 158 
 159 // Performance counters
 160 PerfCounter* CompileBroker::_perf_total_compilation = nullptr;
 161 PerfCounter* CompileBroker::_perf_osr_compilation = nullptr;
 162 PerfCounter* CompileBroker::_perf_standard_compilation = nullptr;
 163 
 164 PerfCounter* CompileBroker::_perf_total_bailout_count = nullptr;
 165 PerfCounter* CompileBroker::_perf_total_invalidated_count = nullptr;
 166 PerfCounter* CompileBroker::_perf_total_compile_count = nullptr;
 167 PerfCounter* CompileBroker::_perf_total_osr_compile_count = nullptr;
 168 PerfCounter* CompileBroker::_perf_total_standard_compile_count = nullptr;
 169 
 170 PerfCounter* CompileBroker::_perf_sum_osr_bytes_compiled = nullptr;
 171 PerfCounter* CompileBroker::_perf_sum_standard_bytes_compiled = nullptr;
 172 PerfCounter* CompileBroker::_perf_sum_nmethod_size = nullptr;
 173 PerfCounter* CompileBroker::_perf_sum_nmethod_code_size = nullptr;
 174 
 175 PerfStringVariable* CompileBroker::_perf_last_method = nullptr;
 176 PerfStringVariable* CompileBroker::_perf_last_failed_method = nullptr;
 177 PerfStringVariable* CompileBroker::_perf_last_invalidated_method = nullptr;
 178 PerfVariable*       CompileBroker::_perf_last_compile_type = nullptr;
 179 PerfVariable*       CompileBroker::_perf_last_compile_size = nullptr;
 180 PerfVariable*       CompileBroker::_perf_last_failed_type = nullptr;
 181 PerfVariable*       CompileBroker::_perf_last_invalidated_type = nullptr;
 182 
 183 // Timers and counters for generating statistics
 184 elapsedTimer CompileBroker::_t_total_compilation;
 185 elapsedTimer CompileBroker::_t_osr_compilation;
 186 elapsedTimer CompileBroker::_t_standard_compilation;
 187 elapsedTimer CompileBroker::_t_invalidated_compilation;
 188 elapsedTimer CompileBroker::_t_bailedout_compilation;
 189 
 190 uint CompileBroker::_total_bailout_count            = 0;
 191 uint CompileBroker::_total_invalidated_count        = 0;
 192 uint CompileBroker::_total_not_entrant_count        = 0;
 193 uint CompileBroker::_total_compile_count            = 0;
 194 uint CompileBroker::_total_osr_compile_count        = 0;
 195 uint CompileBroker::_total_standard_compile_count   = 0;
 196 uint CompileBroker::_total_compiler_stopped_count   = 0;
 197 uint CompileBroker::_total_compiler_restarted_count = 0;
 198 
 199 uint CompileBroker::_sum_osr_bytes_compiled         = 0;
 200 uint CompileBroker::_sum_standard_bytes_compiled    = 0;
 201 uint CompileBroker::_sum_nmethod_size               = 0;
 202 uint CompileBroker::_sum_nmethod_code_size          = 0;
 203 
 204 jlong CompileBroker::_peak_compilation_time        = 0;
 205 
 206 CompilerStatistics CompileBroker::_stats_per_level[CompLevel_full_optimization];
 207 CompilerStatistics CompileBroker::_scc_stats;
 208 CompilerStatistics CompileBroker::_scc_stats_per_level[CompLevel_full_optimization + 1];
 209 
 210 CompileQueue* CompileBroker::_c3_compile_queue     = nullptr;
 211 CompileQueue* CompileBroker::_c2_compile_queue     = nullptr;
 212 CompileQueue* CompileBroker::_c1_compile_queue     = nullptr;
 213 CompileQueue* CompileBroker::_sc1_compile_queue    = nullptr;
 214 CompileQueue* CompileBroker::_sc2_compile_queue    = nullptr;
 215 
 216 bool compileBroker_init() {
 217   if (LogEvents) {
 218     CompilationLog::init();
 219   }
 220 
 221   // init directives stack, adding default directive
 222   DirectivesStack::init();
 223 
 224   if (DirectivesParser::has_file()) {
 225     return DirectivesParser::parse_from_flag();
 226   } else if (CompilerDirectivesPrint) {
 227     // Print default directive even when no other was added
 228     DirectivesStack::print(tty);
 229   }
 230 
 231   return true;
 232 }
 233 
 234 CompileTaskWrapper::CompileTaskWrapper(CompileTask* task) {
 235   CompilerThread* thread = CompilerThread::current();
 236   thread->set_task(task);
 237   CompileLog*     log  = thread->log();
 238   if (log != nullptr && !task->is_unloaded())  task->log_task_start(log);
 239 }
 240 
 241 CompileTaskWrapper::~CompileTaskWrapper() {
 242   CompilerThread* thread = CompilerThread::current();
 243   CompileTask* task = thread->task();
 244   CompileLog*  log  = thread->log();
 245   AbstractCompiler* comp = thread->compiler();
 246   if (log != nullptr && !task->is_unloaded())  task->log_task_done(log);
 247   thread->set_task(nullptr);
 248   thread->set_env(nullptr);
 249   if (task->is_blocking()) {
 250     bool free_task = false;
 251     {
 252       MutexLocker notifier(thread, task->lock());
 253       task->mark_complete();
 254 #if INCLUDE_JVMCI
 255       if (comp->is_jvmci()) {
 256         if (!task->has_waiter()) {
 257           // The waiting thread timed out and thus did not free the task.
 258           free_task = true;
 259         }
 260         task->set_blocking_jvmci_compile_state(nullptr);
 261       }
 262 #endif
 263       if (!free_task) {
 264         // Notify the waiting thread that the compilation has completed
 265         // so that it can free the task.
 266         task->lock()->notify_all();
 267       }
 268     }
 269     if (free_task) {
 270       // The task can only be freed once the task lock is released.
 271       CompileTask::free(task);
 272     }
 273   } else {
 274     task->mark_complete();
 275 
 276     // By convention, the compiling thread is responsible for
 277     // recycling a non-blocking CompileTask.
 278     CompileTask::free(task);
 279   }
 280 }
 281 
 282 /**
 283  * Check if a CompilerThread can be removed and update count if requested.
 284  */
 285 bool CompileBroker::can_remove(CompilerThread *ct, bool do_it) {
 286   assert(UseDynamicNumberOfCompilerThreads, "or shouldn't be here");
 287   if (!ReduceNumberOfCompilerThreads) return false;
 288 
 289   if (CompilationPolicy::have_recompilation_work()) return false;
 290 
 291   AbstractCompiler *compiler = ct->compiler();
 292   int compiler_count = compiler->num_compiler_threads();
 293   bool c1 = compiler->is_c1();
 294 
 295   // Keep at least 1 compiler thread of each type.
 296   if (compiler_count < 2) return false;
 297 
 298   // Keep thread alive for at least some time.
 299   if (ct->idle_time_millis() < (c1 ? 500 : 100)) return false;
 300 
 301 #if INCLUDE_JVMCI
 302   if (compiler->is_jvmci() && !UseJVMCINativeLibrary) {
 303     // Handles for JVMCI thread objects may get released concurrently.
 304     if (do_it) {
 305       assert(CompileThread_lock->owner() == ct, "must be holding lock");
 306     } else {
 307       // Skip check if it's the last thread and let caller check again.
 308       return true;
 309     }
 310   }
 311 #endif
 312 
 313   // We only allow the last compiler thread of each type to get removed.
 314   jobject last_compiler = c1 ? compiler1_object(compiler_count - 1)
 315                              : compiler2_object(compiler_count - 1);
 316   if (ct->threadObj() == JNIHandles::resolve_non_null(last_compiler)) {
 317     if (do_it) {
 318       assert_locked_or_safepoint(CompileThread_lock); // Update must be consistent.
 319       compiler->set_num_compiler_threads(compiler_count - 1);
 320 #if INCLUDE_JVMCI
 321       if (compiler->is_jvmci() && !UseJVMCINativeLibrary) {
 322         // Old j.l.Thread object can die when no longer referenced elsewhere.
 323         JNIHandles::destroy_global(compiler2_object(compiler_count - 1));
 324         _compiler2_objects[compiler_count - 1] = nullptr;
 325       }
 326 #endif
 327     }
 328     return true;
 329   }
 330   return false;
 331 }
 332 
 333 /**
 334  * Add a CompileTask to a CompileQueue.
 335  */
 336 void CompileQueue::add(CompileTask* task) {
 337   assert(_lock->owned_by_self(), "must own lock");
 338 
 339   task->set_next(nullptr);
 340   task->set_prev(nullptr);
 341 
 342   if (_last == nullptr) {
 343     // The compile queue is empty.
 344     assert(_first == nullptr, "queue is empty");
 345     _first = task;
 346     _last = task;
 347   } else {
 348     // Append the task to the queue.
 349     assert(_last->next() == nullptr, "not last");
 350     _last->set_next(task);
 351     task->set_prev(_last);
 352     _last = task;
 353   }
 354   ++_size;
 355   ++_total_added;
 356   if (_size > _peak_size) {
 357     _peak_size = _size;
 358   }
 359 
 360   // Mark the method as being in the compile queue.
 361   task->method()->set_queued_for_compilation();
 362 
 363   task->mark_queued(os::elapsed_counter());
 364 
 365   if (CIPrintCompileQueue) {
 366     print_tty();
 367   }
 368 
 369   if (LogCompilation && xtty != nullptr) {
 370     task->log_task_queued();
 371   }
 372 
 373   if (TrainingData::need_data() &&
 374       !CDSConfig::is_dumping_final_static_archive()) { // FIXME: !!! MetaspaceShared::preload_and_dump() temporarily enables RecordTraining !!!
 375     CompileTrainingData* tdata = CompileTrainingData::make(task);
 376     if (tdata != nullptr) {
 377       tdata->record_compilation_queued(task);
 378       task->set_training_data(tdata);
 379     }
 380   }
 381 
 382   // Notify CompilerThreads that a task is available.
 383   _lock->notify_all();
 384 }
 385 
 386 void CompileQueue::add_pending(CompileTask* task) {
 387   assert(_lock->owned_by_self() == false, "must NOT own lock");
 388   assert(UseLockFreeCompileQueues, "");
 389   task->method()->set_queued_for_compilation();
 390   _queue.push(*task);
 391   // FIXME: additional coordination needed? e.g., is it possible for compiler thread to block w/o processing pending tasks?
 392   if (is_empty()) {
 393     MutexLocker ml(_lock);
 394     _lock->notify_all();
 395   }
 396 }
 397 
 398 void CompileQueue::transfer_pending() {
 399   assert(_lock->owned_by_self(), "must own lock");
 400   while (!_queue.empty()) {
 401     CompileTask* task = _queue.pop();
 402 //    guarantee(task->method()->queued_for_compilation(), "");
 403     task->method()->set_queued_for_compilation(); // FIXME
 404     if (task->method()->pending_queue_processed()) {
 405       task->set_next(_first_stale);
 406       task->set_prev(nullptr);
 407       _first_stale = task;
 408       continue; // skip
 409     } else {
 410       // Mark the method as being in the compile queue.
 411       task->method()->set_pending_queue_processed();
 412     }
 413     if (CompileBroker::compilation_is_complete(task->method(), task->osr_bci(), task->comp_level(),
 414                                                task->requires_online_compilation(), task->compile_reason())) {
 415       task->set_next(_first_stale);
 416       task->set_prev(nullptr);
 417       _first_stale = task;
 418       continue; // skip
 419     }
 420     add(task);
 421   }
 422 }
 423 
 424 /**
 425  * Empties compilation queue by putting all compilation tasks onto
 426  * a freelist. Furthermore, the method wakes up all threads that are
 427  * waiting on a compilation task to finish. This can happen if background
 428  * compilation is disabled.
 429  */
 430 void CompileQueue::free_all() {
 431   MutexLocker mu(_lock);
 432   transfer_pending();
 433 
 434   CompileTask* next = _first;
 435 
 436   // Iterate over all tasks in the compile queue
 437   while (next != nullptr) {
 438     CompileTask* current = next;
 439     next = current->next();
 440     {
 441       // Wake up thread that blocks on the compile task.
 442       MutexLocker ct_lock(current->lock());
 443       current->lock()->notify();
 444     }
 445     // Put the task back on the freelist.
 446     CompileTask::free(current);
 447   }
 448   _first = nullptr;
 449   _last = nullptr;
 450 
 451   // Wake up all threads that block on the queue.
 452   _lock->notify_all();
 453 }
 454 
 455 /**
 456  * Get the next CompileTask from a CompileQueue
 457  */
 458 CompileTask* CompileQueue::get(CompilerThread* thread) {
 459   // save methods from RedefineClasses across safepoint
 460   // across compile queue lock below.
 461   methodHandle save_method;
 462   methodHandle save_hot_method;
 463 
 464   MonitorLocker locker(_lock);
 465   transfer_pending();
 466 
 467   CompilationPolicy::sample_load_average();
 468 
 469   // If _first is null we have no more compile jobs. There are two reasons for
 470   // having no compile jobs: First, we compiled everything we wanted. Second,
 471   // we ran out of code cache so compilation has been disabled. In the latter
 472   // case we perform code cache sweeps to free memory such that we can re-enable
 473   // compilation.
 474   while (_first == nullptr) {
 475     // Exit loop if compilation is disabled forever
 476     if (CompileBroker::is_compilation_disabled_forever()) {
 477       return nullptr;
 478     }
 479 
 480     AbstractCompiler* compiler = thread->compiler();
 481     guarantee(compiler != nullptr, "Compiler object must exist");
 482     compiler->on_empty_queue(this, thread);
 483     if (_first != nullptr) {
 484       // The call to on_empty_queue may have temporarily unlocked the MCQ lock
 485       // so check again whether any tasks were added to the queue.
 486       break;
 487     }
 488 
 489     // If there are no compilation tasks and we can compile new jobs
 490     // (i.e., there is enough free space in the code cache) there is
 491     // no need to invoke the GC.
 492     // We need a timed wait here, since compiler threads can exit if compilation
 493     // is disabled forever. We use 5 seconds wait time; the exiting of compiler threads
 494     // is not critical and we do not want idle compiler threads to wake up too often.
 495     locker.wait(5*1000);
 496 
 497     transfer_pending(); // reacquired lock
 498 
 499     if (CompilationPolicy::have_recompilation_work()) return nullptr;
 500 
 501     if (UseDynamicNumberOfCompilerThreads && _first == nullptr) {
 502       // Still nothing to compile. Give caller a chance to stop this thread.
 503       if (CompileBroker::can_remove(CompilerThread::current(), false)) return nullptr;
 504     }
 505   }
 506 
 507   if (CompileBroker::is_compilation_disabled_forever()) {
 508     return nullptr;
 509   }
 510 
 511   CompileTask* task;
 512   {
 513     NoSafepointVerifier nsv;
 514     task = CompilationPolicy::select_task(this, thread);
 515     if (task != nullptr) {
 516       task = task->select_for_compilation();
 517     }
 518   }
 519 
 520   if (task != nullptr) {
 521     // Save method pointers across unlock safepoint.  The task is removed from
 522     // the compilation queue, which is walked during RedefineClasses.
 523     Thread* thread = Thread::current();
 524     save_method = methodHandle(thread, task->method());
 525     save_hot_method = methodHandle(thread, task->hot_method());
 526 
 527     remove(task);
 528   }
 529   purge_stale_tasks(); // may temporarily release MCQ lock
 530   return task;
 531 }
 532 
 533 // Clean & deallocate stale compile tasks.
 534 // Temporarily releases MethodCompileQueue lock.
 535 void CompileQueue::purge_stale_tasks() {
 536   assert(_lock->owned_by_self(), "must own lock");
 537   if (_first_stale != nullptr) {
 538     // Stale tasks are purged when MCQ lock is released,
 539     // but _first_stale updates are protected by MCQ lock.
 540     // Once task processing starts and MCQ lock is released,
 541     // other compiler threads can reuse _first_stale.
 542     CompileTask* head = _first_stale;
 543     _first_stale = nullptr;
 544     {
 545       MutexUnlocker ul(_lock);
 546       for (CompileTask* task = head; task != nullptr; ) {
 547         CompileTask* next_task = task->next();
 548         CompileTaskWrapper ctw(task); // Frees the task
 549         task->set_failure_reason("stale task");
 550         task = next_task;
 551       }
 552     }
 553     transfer_pending(); // transfer pending after reacquiring MCQ lock
 554   }
 555 }
 556 
 557 void CompileQueue::remove(CompileTask* task) {
 558   assert(_lock->owned_by_self(), "must own lock");
 559   if (task->prev() != nullptr) {
 560     task->prev()->set_next(task->next());
 561   } else {
 562     // max is the first element
 563     assert(task == _first, "Sanity");
 564     _first = task->next();
 565   }
 566 
 567   if (task->next() != nullptr) {
 568     task->next()->set_prev(task->prev());
 569   } else {
 570     // max is the last element
 571     assert(task == _last, "Sanity");
 572     _last = task->prev();
 573   }
 574   --_size;
 575   ++_total_removed;
 576 }
 577 
 578 void CompileQueue::remove_and_mark_stale(CompileTask* task) {
 579   assert(_lock->owned_by_self(), "must own lock");
 580   remove(task);
 581 
 582   // Enqueue the task for reclamation (should be done outside MCQ lock)
 583   task->set_next(_first_stale);
 584   task->set_prev(nullptr);
 585   _first_stale = task;
 586 }
 587 
 588 // methods in the compile queue need to be marked as used on the stack
 589 // so that they don't get reclaimed by Redefine Classes
 590 void CompileQueue::mark_on_stack() {
 591   CompileTask* task = _first;
 592   while (task != nullptr) {
 593     task->mark_on_stack();
 594     task = task->next();
 595   }
 596 }
 597 
 598 
 599 CompileQueue* CompileBroker::compile_queue(int comp_level, bool is_scc) {
 600   if (is_c2_compile(comp_level)) return (is_scc ? _sc2_compile_queue : _c2_compile_queue);
 601   if (is_c1_compile(comp_level)) return (is_scc ? _sc1_compile_queue : _c1_compile_queue);
 602   return nullptr;
 603 }
 604 
 605 CompileQueue* CompileBroker::c1_compile_queue() {
 606   return _c1_compile_queue;
 607 }
 608 
 609 CompileQueue* CompileBroker::c2_compile_queue() {
 610   return _c2_compile_queue;
 611 }
 612 
 613 void CompileBroker::print_compile_queues(outputStream* st) {
 614   st->print_cr("Current compiles: ");
 615 
 616   char buf[2000];
 617   int buflen = sizeof(buf);
 618   Threads::print_threads_compiling(st, buf, buflen, /* short_form = */ true);
 619 
 620   st->cr();
 621   if (_c1_compile_queue != nullptr) {
 622     _c1_compile_queue->print(st);
 623   }
 624   if (_c2_compile_queue != nullptr) {
 625     _c2_compile_queue->print(st);
 626   }
 627   if (_c3_compile_queue != nullptr) {
 628     _c3_compile_queue->print(st);
 629   }
 630   if (_sc1_compile_queue != nullptr) {
 631     _sc1_compile_queue->print(st);
 632   }
 633   if (_sc2_compile_queue != nullptr) {
 634     _sc2_compile_queue->print(st);
 635   }
 636 }
 637 
 638 void CompileQueue::print(outputStream* st) {
 639   assert_locked_or_safepoint(_lock);
 640   st->print_cr("%s:", name());
 641   CompileTask* task = _first;
 642   if (task == nullptr) {
 643     st->print_cr("Empty");
 644   } else {
 645     while (task != nullptr) {
 646       task->print(st, nullptr, true, true);
 647       task = task->next();
 648     }
 649   }
 650   st->cr();
 651 }
 652 
 653 void CompileQueue::print_tty() {
 654   stringStream ss;
 655   // Dump the compile queue into a buffer before locking the tty
 656   print(&ss);
 657   {
 658     ttyLocker ttyl;
 659     tty->print("%s", ss.freeze());
 660   }
 661 }
 662 
 663 CompilerCounters::CompilerCounters() {
 664   _current_method[0] = '\0';
 665   _compile_type = CompileBroker::no_compile;
 666 }
 667 
 668 #if INCLUDE_JFR && COMPILER2_OR_JVMCI
 669 // It appends new compiler phase names to growable array phase_names(a new CompilerPhaseType mapping
 670 // in compiler/compilerEvent.cpp) and registers it with its serializer.
 671 //
 672 // c2 uses explicit CompilerPhaseType idToPhase mapping in opto/phasetype.hpp,
 673 // so if c2 is used, it should be always registered first.
 674 // This function is called during vm initialization.
 675 static void register_jfr_phasetype_serializer(CompilerType compiler_type) {
 676   ResourceMark rm;
 677   static bool first_registration = true;
 678   if (compiler_type == compiler_jvmci) {
 679     CompilerEvent::PhaseEvent::get_phase_id("NOT_A_PHASE_NAME", false, false, false);
 680     first_registration = false;
 681 #ifdef COMPILER2
 682   } else if (compiler_type == compiler_c2) {
 683     assert(first_registration, "invariant"); // c2 must be registered first.
 684     for (int i = 0; i < PHASE_NUM_TYPES; i++) {
 685       const char* phase_name = CompilerPhaseTypeHelper::to_description((CompilerPhaseType) i);
 686       CompilerEvent::PhaseEvent::get_phase_id(phase_name, false, false, false);
 687     }
 688     first_registration = false;
 689 #endif // COMPILER2
 690   }
 691 }
 692 #endif // INCLUDE_JFR && COMPILER2_OR_JVMCI
 693 
 694 // ------------------------------------------------------------------
 695 // CompileBroker::compilation_init
 696 //
 697 // Initialize the Compilation object
 698 void CompileBroker::compilation_init(JavaThread* THREAD) {
 699   // No need to initialize compilation system if we do not use it.
 700   if (!UseCompiler) {
 701     return;
 702   }
 703   // Set the interface to the current compiler(s).
 704   _c1_count = CompilationPolicy::c1_count();
 705   _c2_count = CompilationPolicy::c2_count();
 706   _c3_count = CompilationPolicy::c3_count();
 707   _sc_count = CompilationPolicy::sc_count();
 708 
 709 #if INCLUDE_JVMCI
 710   if (EnableJVMCI) {
 711     // This is creating a JVMCICompiler singleton.
 712     JVMCICompiler* jvmci = new JVMCICompiler();
 713 
 714     if (UseJVMCICompiler) {
 715       _compilers[1] = jvmci;
 716       if (FLAG_IS_DEFAULT(JVMCIThreads)) {
 717         if (BootstrapJVMCI) {
 718           // JVMCI will bootstrap so give it more threads
 719           _c2_count = MIN2(32, os::active_processor_count());
 720         }
 721       } else {
 722         _c2_count = JVMCIThreads;
 723       }
 724       if (FLAG_IS_DEFAULT(JVMCIHostThreads)) {
 725       } else {
 726 #ifdef COMPILER1
 727         _c1_count = JVMCIHostThreads;
 728 #endif // COMPILER1
 729       }
 730 #ifdef COMPILER2
 731       if (SCCache::is_on() && (_c3_count > 0)) {
 732         _compilers[2] = new C2Compiler();
 733       }
 734 #endif
 735     }
 736   }
 737 #endif // INCLUDE_JVMCI
 738 
 739 #ifdef COMPILER1
 740   if (_c1_count > 0) {
 741     _compilers[0] = new Compiler();
 742   }
 743 #endif // COMPILER1
 744 
 745 #ifdef COMPILER2
 746   if (true JVMCI_ONLY( && !UseJVMCICompiler)) {
 747     if (_c2_count > 0) {
 748       _compilers[1] = new C2Compiler();
 749       // Register c2 first as c2 CompilerPhaseType idToPhase mapping is explicit.
 750       // idToPhase mapping for c2 is in opto/phasetype.hpp
 751       JFR_ONLY(register_jfr_phasetype_serializer(compiler_c2);)
 752     }
 753   }
 754 #endif // COMPILER2
 755 
 756 #if INCLUDE_JVMCI
 757    // Register after c2 registration.
 758    // JVMCI CompilerPhaseType idToPhase mapping is dynamic.
 759    if (EnableJVMCI) {
 760      JFR_ONLY(register_jfr_phasetype_serializer(compiler_jvmci);)
 761    }
 762 #endif // INCLUDE_JVMCI
 763 
 764   if (CompilerOracle::should_collect_memstat()) {
 765     CompilationMemoryStatistic::initialize();
 766   }
 767 
 768   // Start the compiler thread(s)
 769   init_compiler_threads();
 770   // totalTime performance counter is always created as it is required
 771   // by the implementation of java.lang.management.CompilationMXBean.
 772   {
 773     // Ensure OOM leads to vm_exit_during_initialization.
 774     EXCEPTION_MARK;
 775     _perf_total_compilation =
 776                  PerfDataManager::create_counter(JAVA_CI, "totalTime",
 777                                                  PerfData::U_Ticks, CHECK);
 778   }
 779 
 780   if (UsePerfData) {
 781 
 782     EXCEPTION_MARK;
 783 
 784     // create the jvmstat performance counters
 785     _perf_osr_compilation =
 786                  PerfDataManager::create_counter(SUN_CI, "osrTime",
 787                                                  PerfData::U_Ticks, CHECK);
 788 
 789     _perf_standard_compilation =
 790                  PerfDataManager::create_counter(SUN_CI, "standardTime",
 791                                                  PerfData::U_Ticks, CHECK);
 792 
 793     _perf_total_bailout_count =
 794                  PerfDataManager::create_counter(SUN_CI, "totalBailouts",
 795                                                  PerfData::U_Events, CHECK);
 796 
 797     _perf_total_invalidated_count =
 798                  PerfDataManager::create_counter(SUN_CI, "totalInvalidates",
 799                                                  PerfData::U_Events, CHECK);
 800 
 801     _perf_total_compile_count =
 802                  PerfDataManager::create_counter(SUN_CI, "totalCompiles",
 803                                                  PerfData::U_Events, CHECK);
 804     _perf_total_osr_compile_count =
 805                  PerfDataManager::create_counter(SUN_CI, "osrCompiles",
 806                                                  PerfData::U_Events, CHECK);
 807 
 808     _perf_total_standard_compile_count =
 809                  PerfDataManager::create_counter(SUN_CI, "standardCompiles",
 810                                                  PerfData::U_Events, CHECK);
 811 
 812     _perf_sum_osr_bytes_compiled =
 813                  PerfDataManager::create_counter(SUN_CI, "osrBytes",
 814                                                  PerfData::U_Bytes, CHECK);
 815 
 816     _perf_sum_standard_bytes_compiled =
 817                  PerfDataManager::create_counter(SUN_CI, "standardBytes",
 818                                                  PerfData::U_Bytes, CHECK);
 819 
 820     _perf_sum_nmethod_size =
 821                  PerfDataManager::create_counter(SUN_CI, "nmethodSize",
 822                                                  PerfData::U_Bytes, CHECK);
 823 
 824     _perf_sum_nmethod_code_size =
 825                  PerfDataManager::create_counter(SUN_CI, "nmethodCodeSize",
 826                                                  PerfData::U_Bytes, CHECK);
 827 
 828     _perf_last_method =
 829                  PerfDataManager::create_string_variable(SUN_CI, "lastMethod",
 830                                        CompilerCounters::cmname_buffer_length,
 831                                        "", CHECK);
 832 
 833     _perf_last_failed_method =
 834             PerfDataManager::create_string_variable(SUN_CI, "lastFailedMethod",
 835                                        CompilerCounters::cmname_buffer_length,
 836                                        "", CHECK);
 837 
 838     _perf_last_invalidated_method =
 839         PerfDataManager::create_string_variable(SUN_CI, "lastInvalidatedMethod",
 840                                      CompilerCounters::cmname_buffer_length,
 841                                      "", CHECK);
 842 
 843     _perf_last_compile_type =
 844              PerfDataManager::create_variable(SUN_CI, "lastType",
 845                                               PerfData::U_None,
 846                                               (jlong)CompileBroker::no_compile,
 847                                               CHECK);
 848 
 849     _perf_last_compile_size =
 850              PerfDataManager::create_variable(SUN_CI, "lastSize",
 851                                               PerfData::U_Bytes,
 852                                               (jlong)CompileBroker::no_compile,
 853                                               CHECK);
 854 
 855 
 856     _perf_last_failed_type =
 857              PerfDataManager::create_variable(SUN_CI, "lastFailedType",
 858                                               PerfData::U_None,
 859                                               (jlong)CompileBroker::no_compile,
 860                                               CHECK);
 861 
 862     _perf_last_invalidated_type =
 863          PerfDataManager::create_variable(SUN_CI, "lastInvalidatedType",
 864                                           PerfData::U_None,
 865                                           (jlong)CompileBroker::no_compile,
 866                                           CHECK);
 867   }
 868 
 869   log_info(scc, init)("CompileBroker is initialized");
 870   _initialized = true;
 871 }
 872 
 873 Handle CompileBroker::create_thread_oop(const char* name, TRAPS) {
 874   Handle thread_oop = JavaThread::create_system_thread_object(name, CHECK_NH);
 875   return thread_oop;
 876 }
 877 
 878 void TrainingReplayThread::training_replay_thread_entry(JavaThread* thread, TRAPS) {
 879   CompilationPolicy::replay_training_at_init_loop(thread);
 880 }
 881 
 882 #if defined(ASSERT) && COMPILER2_OR_JVMCI
 883 // Stress testing. Dedicated threads revert optimizations based on escape analysis concurrently to
 884 // the running java application.  Configured with vm options DeoptimizeObjectsALot*.
 885 class DeoptimizeObjectsALotThread : public JavaThread {
 886 
 887   static void deopt_objs_alot_thread_entry(JavaThread* thread, TRAPS);
 888   void deoptimize_objects_alot_loop_single();
 889   void deoptimize_objects_alot_loop_all();
 890 
 891 public:
 892   DeoptimizeObjectsALotThread() : JavaThread(&deopt_objs_alot_thread_entry) { }
 893 
 894   bool is_hidden_from_external_view() const      { return true; }
 895 };
 896 
 897 // Entry for DeoptimizeObjectsALotThread. The threads are started in
 898 // CompileBroker::init_compiler_threads() iff DeoptimizeObjectsALot is enabled
 899 void DeoptimizeObjectsALotThread::deopt_objs_alot_thread_entry(JavaThread* thread, TRAPS) {
 900     DeoptimizeObjectsALotThread* dt = ((DeoptimizeObjectsALotThread*) thread);
 901     bool enter_single_loop;
 902     {
 903       MonitorLocker ml(dt, EscapeBarrier_lock, Mutex::_no_safepoint_check_flag);
 904       static int single_thread_count = 0;
 905       enter_single_loop = single_thread_count++ < DeoptimizeObjectsALotThreadCountSingle;
 906     }
 907     if (enter_single_loop) {
 908       dt->deoptimize_objects_alot_loop_single();
 909     } else {
 910       dt->deoptimize_objects_alot_loop_all();
 911     }
 912   }
 913 
 914 // Execute EscapeBarriers in an endless loop to revert optimizations based on escape analysis. Each
 915 // barrier targets a single thread which is selected round robin.
 916 void DeoptimizeObjectsALotThread::deoptimize_objects_alot_loop_single() {
 917   HandleMark hm(this);
 918   while (true) {
 919     for (JavaThreadIteratorWithHandle jtiwh; JavaThread *deoptee_thread = jtiwh.next(); ) {
 920       { // Begin new scope for escape barrier
 921         HandleMarkCleaner hmc(this);
 922         ResourceMark rm(this);
 923         EscapeBarrier eb(true, this, deoptee_thread);
 924         eb.deoptimize_objects(100);
 925       }
 926       // Now sleep after the escape barriers destructor resumed deoptee_thread.
 927       sleep(DeoptimizeObjectsALotInterval);
 928     }
 929   }
 930 }
 931 
 932 // Execute EscapeBarriers in an endless loop to revert optimizations based on escape analysis. Each
 933 // barrier targets all java threads in the vm at once.
 934 void DeoptimizeObjectsALotThread::deoptimize_objects_alot_loop_all() {
 935   HandleMark hm(this);
 936   while (true) {
 937     { // Begin new scope for escape barrier
 938       HandleMarkCleaner hmc(this);
 939       ResourceMark rm(this);
 940       EscapeBarrier eb(true, this);
 941       eb.deoptimize_objects_all_threads();
 942     }
 943     // Now sleep after the escape barriers destructor resumed the java threads.
 944     sleep(DeoptimizeObjectsALotInterval);
 945   }
 946 }
 947 #endif // defined(ASSERT) && COMPILER2_OR_JVMCI
 948 
 949 
 950 JavaThread* CompileBroker::make_thread(ThreadType type, jobject thread_handle, CompileQueue* queue, AbstractCompiler* comp, JavaThread* THREAD) {
 951   Handle thread_oop(THREAD, JNIHandles::resolve_non_null(thread_handle));
 952 
 953   if (java_lang_Thread::thread(thread_oop()) != nullptr) {
 954     assert(type == compiler_t, "should only happen with reused compiler threads");
 955     // The compiler thread hasn't actually exited yet so don't try to reuse it
 956     return nullptr;
 957   }
 958 
 959   JavaThread* new_thread = nullptr;
 960   switch (type) {
 961     case compiler_t:
 962       assert(comp != nullptr, "Compiler instance missing.");
 963       if (!InjectCompilerCreationFailure || comp->num_compiler_threads() == 0) {
 964         CompilerCounters* counters = new CompilerCounters();
 965         new_thread = new CompilerThread(queue, counters);
 966       }
 967       break;
 968 #if defined(ASSERT) && COMPILER2_OR_JVMCI
 969     case deoptimizer_t:
 970       new_thread = new DeoptimizeObjectsALotThread();
 971       break;
 972 #endif // ASSERT
 973     case training_replay_t:
 974       new_thread = new TrainingReplayThread();
 975       break;
 976     default:
 977       ShouldNotReachHere();
 978   }
 979 
 980   // At this point the new CompilerThread data-races with this startup
 981   // thread (which is the main thread and NOT the VM thread).
 982   // This means Java bytecodes being executed at startup can
 983   // queue compile jobs which will run at whatever default priority the
 984   // newly created CompilerThread runs at.
 985 
 986 
 987   // At this point it may be possible that no osthread was created for the
 988   // JavaThread due to lack of resources. We will handle that failure below.
 989   // Also check new_thread so that static analysis is happy.
 990   if (new_thread != nullptr && new_thread->osthread() != nullptr) {
 991 
 992     if (type == compiler_t) {
 993       CompilerThread::cast(new_thread)->set_compiler(comp);
 994     }
 995 
 996     // Note that we cannot call os::set_priority because it expects Java
 997     // priorities and we are *explicitly* using OS priorities so that it's
 998     // possible to set the compiler thread priority higher than any Java
 999     // thread.
1000 
1001     int native_prio = CompilerThreadPriority;
1002     if (native_prio == -1) {
1003       if (UseCriticalCompilerThreadPriority) {
1004         native_prio = os::java_to_os_priority[CriticalPriority];
1005       } else {
1006         native_prio = os::java_to_os_priority[NearMaxPriority];
1007       }
1008     }
1009     os::set_native_priority(new_thread, native_prio);
1010 
1011     // Note that this only sets the JavaThread _priority field, which by
1012     // definition is limited to Java priorities and not OS priorities.
1013     JavaThread::start_internal_daemon(THREAD, new_thread, thread_oop, NearMaxPriority);
1014 
1015   } else { // osthread initialization failure
1016     if (UseDynamicNumberOfCompilerThreads && type == compiler_t
1017         && comp->num_compiler_threads() > 0) {
1018       // The new thread is not known to Thread-SMR yet so we can just delete.
1019       delete new_thread;
1020       return nullptr;
1021     } else {
1022       vm_exit_during_initialization("java.lang.OutOfMemoryError",
1023                                     os::native_thread_creation_failed_msg());
1024     }
1025   }
1026 
1027   os::naked_yield(); // make sure that the compiler thread is started early (especially helpful on SOLARIS)
1028 
1029   return new_thread;
1030 }
1031 
1032 static bool trace_compiler_threads() {
1033   LogTarget(Debug, jit, thread) lt;
1034   return TraceCompilerThreads || lt.is_enabled();
1035 }
1036 
1037 static jobject create_compiler_thread(AbstractCompiler* compiler, int i, TRAPS) {
1038   char name_buffer[256];
1039   os::snprintf_checked(name_buffer, sizeof(name_buffer), "%s CompilerThread%d", compiler->name(), i);
1040   Handle thread_oop = JavaThread::create_system_thread_object(name_buffer, CHECK_NULL);
1041   return JNIHandles::make_global(thread_oop);
1042 }
1043 
1044 static void print_compiler_threads(stringStream& msg) {
1045   if (TraceCompilerThreads) {
1046     tty->print_cr("%7d %s", (int)tty->time_stamp().milliseconds(), msg.as_string());
1047   }
1048   LogTarget(Debug, jit, thread) lt;
1049   if (lt.is_enabled()) {
1050     LogStream ls(lt);
1051     ls.print_cr("%s", msg.as_string());
1052   }
1053 }
1054 
1055 static void print_compiler_thread(JavaThread *ct) {
1056   if (trace_compiler_threads()) {
1057     ResourceMark rm;
1058     ThreadsListHandle tlh;  // name() depends on the TLH.
1059     assert(tlh.includes(ct), "ct=" INTPTR_FORMAT " exited unexpectedly.", p2i(ct));
1060     stringStream msg;
1061     msg.print("Added initial compiler thread %s", ct->name());
1062     print_compiler_threads(msg);
1063   }
1064 }
1065 
1066 void CompileBroker::init_compiler_threads() {
1067   // Ensure any exceptions lead to vm_exit_during_initialization.
1068   EXCEPTION_MARK;
1069 #if !defined(ZERO)
1070   assert(_c2_count > 0 || _c1_count > 0, "No compilers?");
1071 #endif // !ZERO
1072   // Initialize the compilation queue
1073   if (_c2_count > 0) {
1074     const char* name = JVMCI_ONLY(UseJVMCICompiler ? "JVMCI compile queue" :) "C2 compile queue";
1075     _c2_compile_queue  = new CompileQueue(name, MethodCompileQueueC2_lock);
1076     _compiler2_objects = NEW_C_HEAP_ARRAY(jobject, _c2_count, mtCompiler);
1077     _compiler2_logs = NEW_C_HEAP_ARRAY(CompileLog*, _c2_count, mtCompiler);
1078   }
1079   if (_c1_count > 0) {
1080     _c1_compile_queue  = new CompileQueue("C1 compile queue", MethodCompileQueueC1_lock);
1081     _compiler1_objects = NEW_C_HEAP_ARRAY(jobject, _c1_count, mtCompiler);
1082     _compiler1_logs = NEW_C_HEAP_ARRAY(CompileLog*, _c1_count, mtCompiler);
1083   }
1084 
1085   if (_c3_count > 0) {
1086     const char* name = "C2 compile queue";
1087     _c3_compile_queue  = new CompileQueue(name, MethodCompileQueueC3_lock);
1088     _compiler3_objects = NEW_C_HEAP_ARRAY(jobject, _c3_count, mtCompiler);
1089     _compiler3_logs = NEW_C_HEAP_ARRAY(CompileLog*, _c3_count, mtCompiler);
1090   }
1091   if (_sc_count > 0) {
1092     if (_c1_count > 0) { // C1 is present
1093       _sc1_compile_queue  = new CompileQueue("C1 SC compile queue", MethodCompileQueueSC1_lock);
1094     }
1095     if (_c2_count > 0) { // C2 is present
1096       _sc2_compile_queue  = new CompileQueue("C2 SC compile queue", MethodCompileQueueSC2_lock);
1097     }
1098     _sc_objects = NEW_C_HEAP_ARRAY(jobject, _sc_count, mtCompiler);
1099     _sc_logs = NEW_C_HEAP_ARRAY(CompileLog*, _sc_count, mtCompiler);
1100   }
1101   char name_buffer[256];
1102 
1103   for (int i = 0; i < _c2_count; i++) {
1104     // Create a name for our thread.
1105     jobject thread_handle = create_compiler_thread(_compilers[1], i, CHECK);
1106     _compiler2_objects[i] = thread_handle;
1107     _compiler2_logs[i] = nullptr;
1108 
1109     if (!UseDynamicNumberOfCompilerThreads || i == 0) {
1110       JavaThread *ct = make_thread(compiler_t, thread_handle, _c2_compile_queue, _compilers[1], THREAD);
1111       assert(ct != nullptr, "should have been handled for initial thread");
1112       _compilers[1]->set_num_compiler_threads(i + 1);
1113       print_compiler_thread(ct);







1114     }
1115   }
1116 
1117   for (int i = 0; i < _c1_count; i++) {
1118     // Create a name for our thread.
1119     jobject thread_handle = create_compiler_thread(_compilers[0], i, CHECK);
1120     _compiler1_objects[i] = thread_handle;
1121     _compiler1_logs[i] = nullptr;
1122 
1123     if (!UseDynamicNumberOfCompilerThreads || i == 0) {
1124       JavaThread *ct = make_thread(compiler_t, thread_handle, _c1_compile_queue, _compilers[0], THREAD);
1125       assert(ct != nullptr, "should have been handled for initial thread");
1126       _compilers[0]->set_num_compiler_threads(i + 1);
1127       print_compiler_thread(ct);
1128     }
1129   }
1130 
1131   for (int i = 0; i < _c3_count; i++) {
1132     // Create a name for our thread.
1133     os::snprintf_checked(name_buffer, sizeof(name_buffer), "C2 CompilerThread%d", i);
1134     Handle thread_oop = create_thread_oop(name_buffer, CHECK);
1135     jobject thread_handle = JNIHandles::make_global(thread_oop);
1136     _compiler3_objects[i] = thread_handle;
1137     _compiler3_logs[i] = nullptr;
1138 
1139     JavaThread *ct = make_thread(compiler_t, thread_handle, _c3_compile_queue, _compilers[2], THREAD);
1140     assert(ct != nullptr, "should have been handled for initial thread");
1141     _compilers[2]->set_num_compiler_threads(i + 1);
1142     print_compiler_thread(ct);
1143   }
1144 
1145   if (_sc_count > 0) {
1146     int i = 0;
1147     if (_c1_count > 0) { // C1 is present
1148       os::snprintf_checked(name_buffer, sizeof(name_buffer), "C%d SC CompilerThread", 1);
1149       Handle thread_oop = create_thread_oop(name_buffer, CHECK);
1150       jobject thread_handle = JNIHandles::make_global(thread_oop);
1151       _sc_objects[i] = thread_handle;
1152       _sc_logs[i] = nullptr;
1153       i++;
1154 
1155       JavaThread *ct = make_thread(compiler_t, thread_handle, _sc1_compile_queue, _compilers[0], THREAD);
1156       assert(ct != nullptr, "should have been handled for initial thread");
1157       print_compiler_thread(ct);
1158     }
1159     if (_c2_count > 0) { // C2 is present
1160       os::snprintf_checked(name_buffer, sizeof(name_buffer), "C%d SC CompilerThread", 2);
1161       Handle thread_oop = create_thread_oop(name_buffer, CHECK);
1162       jobject thread_handle = JNIHandles::make_global(thread_oop);
1163       _sc_objects[i] = thread_handle;
1164       _sc_logs[i] = nullptr;
1165 
1166       JavaThread *ct = make_thread(compiler_t, thread_handle, _sc2_compile_queue, _compilers[1], THREAD);
1167       assert(ct != nullptr, "should have been handled for initial thread");
1168       print_compiler_thread(ct);
1169     }
1170   }
1171 
1172   if (UsePerfData) {
1173     PerfDataManager::create_constant(SUN_CI, "threads", PerfData::U_Bytes, _c1_count + _c2_count + _c3_count, CHECK);
1174   }
1175 
1176 #if defined(ASSERT) && COMPILER2_OR_JVMCI
1177   if (DeoptimizeObjectsALot) {
1178     // Initialize and start the object deoptimizer threads
1179     const int total_count = DeoptimizeObjectsALotThreadCountSingle + DeoptimizeObjectsALotThreadCountAll;
1180     for (int count = 0; count < total_count; count++) {
1181       Handle thread_oop = JavaThread::create_system_thread_object("Deoptimize objects a lot single mode", CHECK);
1182       jobject thread_handle = JNIHandles::make_local(THREAD, thread_oop());
1183       make_thread(deoptimizer_t, thread_handle, nullptr, nullptr, THREAD);
1184     }
1185   }
1186 #endif // defined(ASSERT) && COMPILER2_OR_JVMCI
1187 }
1188 
1189 void CompileBroker::init_training_replay() {
1190   // Ensure any exceptions lead to vm_exit_during_initialization.
1191   EXCEPTION_MARK;
1192   if (TrainingData::have_data()) {
1193     if (UseConcurrentTrainingReplay) {
1194       Handle thread_oop = create_thread_oop("Training replay thread", CHECK);
1195       jobject thread_handle = JNIHandles::make_local(THREAD, thread_oop());
1196       make_thread(training_replay_t, thread_handle, nullptr, nullptr, THREAD);
1197     }
1198     _replay_initialized = true;
1199   }
1200 }
1201 
1202 void CompileBroker::possibly_add_compiler_threads(JavaThread* THREAD) {
1203 
1204   julong free_memory = os::free_memory();
1205   // If SegmentedCodeCache is off, both values refer to the single heap (with type CodeBlobType::All).
1206   size_t available_cc_np  = CodeCache::unallocated_capacity(CodeBlobType::MethodNonProfiled),
1207          available_cc_p   = CodeCache::unallocated_capacity(CodeBlobType::MethodProfiled);
1208 
1209   // Only do attempt to start additional threads if the lock is free.
1210   if (!CompileThread_lock->try_lock()) return;
1211 
1212   if (_c2_compile_queue != nullptr) {
1213     int old_c2_count = _compilers[1]->num_compiler_threads();
1214     int new_c2_count = MIN4(_c2_count,
1215         _c2_compile_queue->size() / 2,
1216         (int)(free_memory / (200*M)),
1217         (int)(available_cc_np / (128*K)));
1218 
1219     for (int i = old_c2_count; i < new_c2_count; i++) {
1220 #if INCLUDE_JVMCI
1221       if (UseJVMCICompiler && !UseJVMCINativeLibrary && _compiler2_objects[i] == nullptr) {
1222         // Native compiler threads as used in C1/C2 can reuse the j.l.Thread objects as their
1223         // existence is completely hidden from the rest of the VM (and those compiler threads can't
1224         // call Java code to do the creation anyway).
1225         //
1226         // For pure Java JVMCI we have to create new j.l.Thread objects as they are visible and we
1227         // can see unexpected thread lifecycle transitions if we bind them to new JavaThreads.  For
1228         // native library JVMCI it's preferred to use the C1/C2 strategy as this avoids unnecessary
1229         // coupling with Java.
1230         if (!THREAD->can_call_java()) break;
1231         char name_buffer[256];
1232         os::snprintf_checked(name_buffer, sizeof(name_buffer), "%s CompilerThread%d", _compilers[1]->name(), i);
1233         Handle thread_oop;
1234         {
1235           // We have to give up the lock temporarily for the Java calls.
1236           MutexUnlocker mu(CompileThread_lock);
1237           thread_oop = JavaThread::create_system_thread_object(name_buffer, THREAD);
1238         }
1239         if (HAS_PENDING_EXCEPTION) {
1240           if (trace_compiler_threads()) {
1241             ResourceMark rm;
1242             stringStream msg;
1243             msg.print_cr("JVMCI compiler thread creation failed:");
1244             PENDING_EXCEPTION->print_on(&msg);
1245             print_compiler_threads(msg);
1246           }
1247           CLEAR_PENDING_EXCEPTION;
1248           break;
1249         }
1250         // Check if another thread has beaten us during the Java calls.
1251         if (_compilers[1]->num_compiler_threads() != i) break;
1252         jobject thread_handle = JNIHandles::make_global(thread_oop);
1253         assert(compiler2_object(i) == nullptr, "Old one must be released!");
1254         _compiler2_objects[i] = thread_handle;
1255       }
1256 #endif
1257       guarantee(compiler2_object(i) != nullptr, "Thread oop must exist");
1258       JavaThread *ct = make_thread(compiler_t, compiler2_object(i), _c2_compile_queue, _compilers[1], THREAD);
1259       if (ct == nullptr) break;
1260       _compilers[1]->set_num_compiler_threads(i + 1);
1261       if (trace_compiler_threads()) {
1262         ResourceMark rm;
1263         ThreadsListHandle tlh;  // name() depends on the TLH.
1264         assert(tlh.includes(ct), "ct=" INTPTR_FORMAT " exited unexpectedly.", p2i(ct));
1265         stringStream msg;
1266         msg.print("Added compiler thread %s (free memory: %dMB, available non-profiled code cache: %dMB)",
1267                   ct->name(), (int)(free_memory/M), (int)(available_cc_np/M));
1268         print_compiler_threads(msg);
1269       }
1270     }
1271   }
1272 
1273   if (_c1_compile_queue != nullptr) {
1274     int old_c1_count = _compilers[0]->num_compiler_threads();
1275     int new_c1_count = MIN4(_c1_count,
1276         _c1_compile_queue->size() / 4,
1277         (int)(free_memory / (100*M)),
1278         (int)(available_cc_p / (128*K)));
1279 
1280     for (int i = old_c1_count; i < new_c1_count; i++) {
1281       JavaThread *ct = make_thread(compiler_t, compiler1_object(i), _c1_compile_queue, _compilers[0], THREAD);
1282       if (ct == nullptr) break;
1283       _compilers[0]->set_num_compiler_threads(i + 1);
1284       if (trace_compiler_threads()) {
1285         ResourceMark rm;
1286         ThreadsListHandle tlh;  // name() depends on the TLH.
1287         assert(tlh.includes(ct), "ct=" INTPTR_FORMAT " exited unexpectedly.", p2i(ct));
1288         stringStream msg;
1289         msg.print("Added compiler thread %s (free memory: %dMB, available profiled code cache: %dMB)",
1290                   ct->name(), (int)(free_memory/M), (int)(available_cc_p/M));
1291         print_compiler_threads(msg);
1292       }
1293     }
1294   }
1295 
1296   CompileThread_lock->unlock();
1297 }
1298 
1299 
1300 /**
1301  * Set the methods on the stack as on_stack so that redefine classes doesn't
1302  * reclaim them. This method is executed at a safepoint.
1303  */
1304 void CompileBroker::mark_on_stack() {
1305   assert(SafepointSynchronize::is_at_safepoint(), "sanity check");
1306   // Since we are at a safepoint, we do not need a lock to access
1307   // the compile queues.
1308   if (_c3_compile_queue != nullptr) {
1309     _c3_compile_queue->mark_on_stack();
1310   }
1311   if (_c2_compile_queue != nullptr) {
1312     _c2_compile_queue->mark_on_stack();
1313   }
1314   if (_c1_compile_queue != nullptr) {
1315     _c1_compile_queue->mark_on_stack();
1316   }
1317   if (_sc1_compile_queue != nullptr) {
1318     _sc1_compile_queue->mark_on_stack();
1319   }
1320   if (_sc2_compile_queue != nullptr) {
1321     _sc2_compile_queue->mark_on_stack();
1322   }
1323 }
1324 
1325 // ------------------------------------------------------------------
1326 // CompileBroker::compile_method
1327 //
1328 // Request compilation of a method.
1329 void CompileBroker::compile_method_base(const methodHandle& method,
1330                                         int osr_bci,
1331                                         int comp_level,
1332                                         const methodHandle& hot_method,
1333                                         int hot_count,
1334                                         CompileTask::CompileReason compile_reason,
1335                                         bool requires_online_compilation,
1336                                         bool blocking,
1337                                         Thread* thread) {
1338   guarantee(!method->is_abstract(), "cannot compile abstract methods");
1339   assert(method->method_holder()->is_instance_klass(),
1340          "sanity check");
1341   assert(!method->method_holder()->is_not_initialized()   ||
1342          compile_reason == CompileTask::Reason_Preload    ||
1343          compile_reason == CompileTask::Reason_Precompile ||
1344          compile_reason == CompileTask::Reason_PrecompileForPreload, "method holder must be initialized");
1345   assert(!method->is_method_handle_intrinsic(), "do not enqueue these guys");
1346 
1347   if (CIPrintRequests) {
1348     tty->print("request: ");
1349     method->print_short_name(tty);
1350     if (osr_bci != InvocationEntryBci) {
1351       tty->print(" osr_bci: %d", osr_bci);
1352     }
1353     tty->print(" level: %d comment: %s count: %d", comp_level, CompileTask::reason_name(compile_reason), hot_count);
1354     if (!hot_method.is_null()) {
1355       tty->print(" hot: ");
1356       if (hot_method() != method()) {
1357           hot_method->print_short_name(tty);
1358       } else {
1359         tty->print("yes");
1360       }
1361     }
1362     tty->cr();
1363   }
1364 
1365   if (compile_reason != CompileTask::Reason_DirectivesChanged) {
1366     // A request has been made for compilation.  Before we do any
1367     // real work, check to see if the method has been compiled
1368     // in the meantime with a definitive result.
1369     if (compilation_is_complete(method(), osr_bci, comp_level, requires_online_compilation, compile_reason)) {
1370       return;
1371     }
1372   }
1373 
1374 #ifndef PRODUCT
1375   if (osr_bci != -1 && !FLAG_IS_DEFAULT(OSROnlyBCI)) {
1376     if ((OSROnlyBCI > 0) ? (OSROnlyBCI != osr_bci) : (-OSROnlyBCI == osr_bci)) {
1377       // Positive OSROnlyBCI means only compile that bci.  Negative means don't compile that BCI.
1378       return;
1379     }
1380   }
1381 #endif
1382 
1383   // If this method is already in the compile queue, then
1384   // we do not block the current thread.
1385   if (compilation_is_in_queue(method)) {
1386     // We may want to decay our counter a bit here to prevent
1387     // multiple denied requests for compilation.  This is an
1388     // open compilation policy issue. Note: The other possibility,
1389     // in the case that this is a blocking compile request, is to have
1390     // all subsequent blocking requesters wait for completion of
1391     // ongoing compiles. Note that in this case we'll need a protocol
1392     // for freeing the associated compile tasks. [Or we could have
1393     // a single static monitor on which all these waiters sleep.]
1394     return;
1395   }
1396 
1397   // Tiered policy requires MethodCounters to exist before adding a method to
1398   // the queue. Create if we don't have them yet.
1399   if (compile_reason != CompileTask::Reason_Preload) {
1400     method->get_method_counters(thread);
1401   }
1402 
1403   SCCEntry* scc_entry = find_scc_entry(method, osr_bci, comp_level, compile_reason, requires_online_compilation);
1404   bool is_scc = (scc_entry != nullptr);
1405 
1406   // Outputs from the following MutexLocker block:
1407   CompileTask* task = nullptr;
1408   CompileQueue* queue;
1409 #if INCLUDE_JVMCI
1410   if (is_c2_compile(comp_level) && compiler2()->is_jvmci() && compiler3() != nullptr &&
1411       ((JVMCICompiler*)compiler2())->force_comp_at_level_simple(method)) {
1412     assert(_c3_compile_queue != nullptr, "sanity");
1413     queue = _c3_compile_queue; // JVMCI compiler's methods compilation
1414   } else
1415 #endif
1416   queue = compile_queue(comp_level, is_scc);
1417 
1418   // Acquire our lock.
1419   {
1420     ConditionalMutexLocker locker(thread, queue->lock(), !UseLockFreeCompileQueues);
1421 
1422     // Make sure the method has not slipped into the queues since
1423     // last we checked; note that those checks were "fast bail-outs".
1424     // Here we need to be more careful, see 14012000 below.
1425     if (compilation_is_in_queue(method)) {
1426       return;
1427     }
1428 
1429     if (compile_reason != CompileTask::Reason_DirectivesChanged) {
1430       // We need to check again to see if the compilation has
1431       // completed.  A previous compilation may have registered
1432       // some result.
1433       if (compilation_is_complete(method(), osr_bci, comp_level, requires_online_compilation, compile_reason)) {
1434         return;
1435       }
1436     }
1437 
1438     // We now know that this compilation is not pending, complete,
1439     // or prohibited.  Assign a compile_id to this compilation
1440     // and check to see if it is in our [Start..Stop) range.
1441     int compile_id = assign_compile_id(method, osr_bci);
1442     if (compile_id == 0) {
1443       // The compilation falls outside the allowed range.
1444       return;
1445     }
1446 
1447 #if INCLUDE_JVMCI
1448     if (UseJVMCICompiler && blocking) {
1449       // Don't allow blocking compiles for requests triggered by JVMCI.
1450       if (thread->is_Compiler_thread()) {
1451         blocking = false;
1452       }
1453 
1454       // In libjvmci, JVMCI initialization should not deadlock with other threads
1455       if (!UseJVMCINativeLibrary) {
1456         // Don't allow blocking compiles if inside a class initializer or while performing class loading
1457         vframeStream vfst(JavaThread::cast(thread));
1458         for (; !vfst.at_end(); vfst.next()) {
1459           if (vfst.method()->is_static_initializer() ||
1460               (vfst.method()->method_holder()->is_subclass_of(vmClasses::ClassLoader_klass()) &&
1461                   vfst.method()->name() == vmSymbols::loadClass_name())) {
1462             blocking = false;
1463             break;
1464           }
1465         }
1466 
1467         // Don't allow blocking compilation requests to JVMCI
1468         // if JVMCI itself is not yet initialized
1469         if (!JVMCI::is_compiler_initialized() && compiler(comp_level)->is_jvmci()) {
1470           blocking = false;
1471         }
1472       }
1473 
1474       // Don't allow blocking compilation requests if we are in JVMCIRuntime::shutdown
1475       // to avoid deadlock between compiler thread(s) and threads run at shutdown
1476       // such as the DestroyJavaVM thread.
1477       if (JVMCI::in_shutdown()) {
1478         blocking = false;
1479       }
1480     }
1481 #endif // INCLUDE_JVMCI
1482 
1483     // We will enter the compilation in the queue.
1484     // 14012000: Note that this sets the queued_for_compile bits in
1485     // the target method. We can now reason that a method cannot be
1486     // queued for compilation more than once, as follows:
1487     // Before a thread queues a task for compilation, it first acquires
1488     // the compile queue lock, then checks if the method's queued bits
1489     // are set or it has already been compiled. Thus there can not be two
1490     // instances of a compilation task for the same method on the
1491     // compilation queue. Consider now the case where the compilation
1492     // thread has already removed a task for that method from the queue
1493     // and is in the midst of compiling it. In this case, the
1494     // queued_for_compile bits must be set in the method (and these
1495     // will be visible to the current thread, since the bits were set
1496     // under protection of the compile queue lock, which we hold now.
1497     // When the compilation completes, the compiler thread first sets
1498     // the compilation result and then clears the queued_for_compile
1499     // bits. Neither of these actions are protected by a barrier (or done
1500     // under the protection of a lock), so the only guarantee we have
1501     // (on machines with TSO (Total Store Order)) is that these values
1502     // will update in that order. As a result, the only combinations of
1503     // these bits that the current thread will see are, in temporal order:
1504     // <RESULT, QUEUE> :
1505     //     <0, 1> : in compile queue, but not yet compiled
1506     //     <1, 1> : compiled but queue bit not cleared
1507     //     <1, 0> : compiled and queue bit cleared
1508     // Because we first check the queue bits then check the result bits,
1509     // we are assured that we cannot introduce a duplicate task.
1510     // Note that if we did the tests in the reverse order (i.e. check
1511     // result then check queued bit), we could get the result bit before
1512     // the compilation completed, and the queue bit after the compilation
1513     // completed, and end up introducing a "duplicate" (redundant) task.
1514     // In that case, the compiler thread should first check if a method
1515     // has already been compiled before trying to compile it.
1516     // NOTE: in the event that there are multiple compiler threads and
1517     // there is de-optimization/recompilation, things will get hairy,
1518     // and in that case it's best to protect both the testing (here) of
1519     // these bits, and their updating (here and elsewhere) under a
1520     // common lock.
1521     task = create_compile_task(queue,
1522                                compile_id, method,
1523                                osr_bci, comp_level,
1524                                hot_method, hot_count, scc_entry, compile_reason,
1525                                requires_online_compilation, blocking);
1526 
1527     if (task->is_scc() && (_sc_count > 0)) {
1528       // Put it on SC queue
1529       queue = is_c1_compile(comp_level) ? _sc1_compile_queue : _sc2_compile_queue;
1530     }
1531 
1532     if (UseLockFreeCompileQueues) {
1533       assert(queue->lock()->owned_by_self() == false, "");
1534       queue->add_pending(task);
1535     } else {
1536       queue->add(task);
1537     }
1538   }
1539 
1540   if (blocking) {
1541     wait_for_completion(task);
1542   }
1543 }
1544 
1545 SCCEntry* CompileBroker::find_scc_entry(const methodHandle& method, int osr_bci, int comp_level,
1546                                         CompileTask::CompileReason compile_reason,
1547                                         bool requires_online_compilation) {
1548   SCCEntry* scc_entry = nullptr;
1549   if (_sc_count > 0 && osr_bci == InvocationEntryBci && !requires_online_compilation && SCCache::is_on_for_read()) {
1550     // Check for cached code.
1551     if (compile_reason == CompileTask::Reason_Preload) {
1552       scc_entry = method->scc_entry();
1553       assert(scc_entry != nullptr && scc_entry->for_preload(), "sanity");
1554     } else {
1555       scc_entry = SCCache::find_code_entry(method, comp_level);
1556     }
1557   }
1558   return scc_entry;
1559 }
1560 
1561 nmethod* CompileBroker::compile_method(const methodHandle& method, int osr_bci,
1562                                        int comp_level,
1563                                        const methodHandle& hot_method, int hot_count,
1564                                        bool requires_online_compilation,
1565                                        CompileTask::CompileReason compile_reason,
1566                                        TRAPS) {
1567   // Do nothing if compilebroker is not initialized or compiles are submitted on level none
1568   if (!_initialized || comp_level == CompLevel_none) {
1569     return nullptr;
1570   }
1571 
1572 #if INCLUDE_JVMCI
1573   if (EnableJVMCI && UseJVMCICompiler &&
1574       comp_level == CompLevel_full_optimization && !ClassPreloader::class_preloading_finished()) {
1575     return nullptr;
1576   }
1577 #endif
1578 
1579   AbstractCompiler *comp = CompileBroker::compiler(comp_level);
1580   assert(comp != nullptr, "Ensure we have a compiler");
1581 
1582 #if INCLUDE_JVMCI
1583   if (comp->is_jvmci() && !JVMCI::can_initialize_JVMCI()) {
1584     // JVMCI compilation is not yet initializable.
1585     return nullptr;
1586   }
1587 #endif
1588 
1589   DirectiveSet* directive = DirectivesStack::getMatchingDirective(method, comp);
1590   // CompileBroker::compile_method can trap and can have pending async exception.
1591   nmethod* nm = CompileBroker::compile_method(method, osr_bci, comp_level, hot_method, hot_count, requires_online_compilation, compile_reason, directive, THREAD);
1592   DirectivesStack::release(directive);
1593   return nm;
1594 }
1595 
1596 nmethod* CompileBroker::compile_method(const methodHandle& method, int osr_bci,
1597                                          int comp_level,
1598                                          const methodHandle& hot_method, int hot_count,
1599                                          bool requires_online_compilation,
1600                                          CompileTask::CompileReason compile_reason,
1601                                          DirectiveSet* directive,
1602                                          TRAPS) {
1603 
1604   // make sure arguments make sense
1605   assert(method->method_holder()->is_instance_klass(), "not an instance method");
1606   assert(osr_bci == InvocationEntryBci || (0 <= osr_bci && osr_bci < method->code_size()), "bci out of range");
1607   assert(!method->is_abstract() && (osr_bci == InvocationEntryBci || !method->is_native()), "cannot compile abstract/native methods");
1608   assert(!method->method_holder()->is_not_initialized()   ||
1609          compile_reason == CompileTask::Reason_Preload    ||
1610          compile_reason == CompileTask::Reason_Precompile ||
1611          compile_reason == CompileTask::Reason_PrecompileForPreload, "method holder must be initialized");
1612   // return quickly if possible
1613 
1614   if (PrecompileOnlyAndExit && !CompileTask::reason_is_precompiled(compile_reason)) {
1615     return nullptr;
1616   }
1617 
1618   // lock, make sure that the compilation
1619   // isn't prohibited in a straightforward way.
1620   AbstractCompiler* comp = CompileBroker::compiler(comp_level);
1621   if (comp == nullptr || compilation_is_prohibited(method, osr_bci, comp_level, directive->ExcludeOption)) {
1622     return nullptr;
1623   }
1624 
1625   if (osr_bci == InvocationEntryBci) {
1626     // standard compilation
1627     nmethod* method_code = method->code();
1628     if (method_code != nullptr && (compile_reason != CompileTask::Reason_DirectivesChanged)) {
1629       if (compilation_is_complete(method(), osr_bci, comp_level, requires_online_compilation, compile_reason)) {
1630         return method_code;
1631       }
1632     }
1633     if (method->is_not_compilable(comp_level)) {
1634       return nullptr;
1635     }
1636   } else {
1637     // osr compilation
1638     // We accept a higher level osr method
1639     nmethod* nm = method->lookup_osr_nmethod_for(osr_bci, comp_level, false);
1640     if (nm != nullptr) return nm;
1641     if (method->is_not_osr_compilable(comp_level)) return nullptr;
1642   }
1643 
1644   assert(!HAS_PENDING_EXCEPTION, "No exception should be present");
1645   // some prerequisites that are compiler specific
1646   if (compile_reason != CompileTask::Reason_Preload && (comp->is_c2() || comp->is_jvmci())) {
1647     method->constants()->resolve_string_constants(CHECK_AND_CLEAR_NONASYNC_NULL);
1648     // Resolve all classes seen in the signature of the method
1649     // we are compiling.
1650     Method::load_signature_classes(method, CHECK_AND_CLEAR_NONASYNC_NULL);
1651   }
1652 
1653   // If the method is native, do the lookup in the thread requesting
1654   // the compilation. Native lookups can load code, which is not
1655   // permitted during compilation.
1656   //
1657   // Note: A native method implies non-osr compilation which is
1658   //       checked with an assertion at the entry of this method.
1659   if (method->is_native() && !method->is_method_handle_intrinsic()) {
1660     address adr = NativeLookup::lookup(method, THREAD);
1661     if (HAS_PENDING_EXCEPTION) {
1662       // In case of an exception looking up the method, we just forget
1663       // about it. The interpreter will kick-in and throw the exception.
1664       method->set_not_compilable("NativeLookup::lookup failed"); // implies is_not_osr_compilable()
1665       CLEAR_PENDING_EXCEPTION;
1666       return nullptr;
1667     }
1668     assert(method->has_native_function(), "must have native code by now");
1669   }
1670 
1671   // RedefineClasses() has replaced this method; just return
1672   if (method->is_old()) {
1673     return nullptr;
1674   }
1675 
1676   // JVMTI -- post_compile_event requires jmethod_id() that may require
1677   // a lock the compiling thread can not acquire. Prefetch it here.
1678   if (JvmtiExport::should_post_compiled_method_load()) {
1679     method->jmethod_id();
1680   }
1681 
1682   // do the compilation
1683   if (method->is_native()) {
1684     if (!PreferInterpreterNativeStubs || method->is_method_handle_intrinsic()) {
1685 #if defined(X86) && !defined(ZERO)
1686       // The following native methods:
1687       //
1688       // java.lang.Float.intBitsToFloat
1689       // java.lang.Float.floatToRawIntBits
1690       // java.lang.Double.longBitsToDouble
1691       // java.lang.Double.doubleToRawLongBits
1692       //
1693       // are called through the interpreter even if interpreter native stubs
1694       // are not preferred (i.e., calling through adapter handlers is preferred).
1695       // The reason is that on x86_32 signaling NaNs (sNaNs) are not preserved
1696       // if the version of the methods from the native libraries is called.
1697       // As the interpreter and the C2-intrinsified version of the methods preserves
1698       // sNaNs, that would result in an inconsistent way of handling of sNaNs.
1699       if ((UseSSE >= 1 &&
1700           (method->intrinsic_id() == vmIntrinsics::_intBitsToFloat ||
1701            method->intrinsic_id() == vmIntrinsics::_floatToRawIntBits)) ||
1702           (UseSSE >= 2 &&
1703            (method->intrinsic_id() == vmIntrinsics::_longBitsToDouble ||
1704             method->intrinsic_id() == vmIntrinsics::_doubleToRawLongBits))) {
1705         return nullptr;
1706       }
1707 #endif // X86 && !ZERO
1708 
1709       // To properly handle the appendix argument for out-of-line calls we are using a small trampoline that
1710       // pops off the appendix argument and jumps to the target (see gen_special_dispatch in SharedRuntime).
1711       //
1712       // Since normal compiled-to-compiled calls are not able to handle such a thing we MUST generate an adapter
1713       // in this case.  If we can't generate one and use it we can not execute the out-of-line method handle calls.
1714       AdapterHandlerLibrary::create_native_wrapper(method);
1715     } else {
1716       return nullptr;
1717     }
1718   } else {
1719     // If the compiler is shut off due to code cache getting full
1720     // fail out now so blocking compiles dont hang the java thread
1721     if (!should_compile_new_jobs()) {
1722       return nullptr;
1723     }
1724     bool is_blocking = ReplayCompiles                                             ||
1725                        !directive->BackgroundCompilationOption                    ||
1726                        (compile_reason == CompileTask::Reason_Precompile)         ||
1727                        (compile_reason == CompileTask::Reason_PrecompileForPreload);
1728 	  compile_method_base(method, osr_bci, comp_level, hot_method, hot_count, compile_reason, requires_online_compilation, is_blocking, THREAD);
1729   }
1730 
1731   // return requested nmethod
1732   // We accept a higher level osr method
1733   if (osr_bci == InvocationEntryBci) {
1734     return method->code();
1735   }
1736   return method->lookup_osr_nmethod_for(osr_bci, comp_level, false);
1737 }
1738 
1739 
1740 // ------------------------------------------------------------------
1741 // CompileBroker::compilation_is_complete
1742 //
1743 // See if compilation of this method is already complete.
1744 bool CompileBroker::compilation_is_complete(Method*                    method,
1745                                             int                        osr_bci,
1746                                             int                        comp_level,
1747                                             bool                       online_only,
1748                                             CompileTask::CompileReason compile_reason) {
1749   if (compile_reason == CompileTask::Reason_Precompile ||
1750       compile_reason == CompileTask::Reason_PrecompileForPreload) {
1751     return false; // FIXME: any restrictions?
1752   }
1753   bool is_osr = (osr_bci != standard_entry_bci);
1754   if (is_osr) {
1755     if (method->is_not_osr_compilable(comp_level)) {
1756       return true;
1757     } else {
1758       nmethod* result = method->lookup_osr_nmethod_for(osr_bci, comp_level, true);
1759       return (result != nullptr);
1760     }
1761   } else {
1762     if (method->is_not_compilable(comp_level)) {
1763       return true;
1764     } else {
1765       nmethod* result = method->code();
1766       if (result == nullptr) {
1767         return false;
1768       }
1769       if (online_only && result->is_scc()) {
1770         return false;
1771       }
1772       bool same_level = (comp_level == result->comp_level());
1773       if (result->has_clinit_barriers()) {
1774         return !same_level; // Allow replace preloaded code with new code of the same level
1775       }
1776       return same_level;
1777     }
1778   }
1779 }
1780 
1781 
1782 /**
1783  * See if this compilation is already requested.
1784  *
1785  * Implementation note: there is only a single "is in queue" bit
1786  * for each method.  This means that the check below is overly
1787  * conservative in the sense that an osr compilation in the queue
1788  * will block a normal compilation from entering the queue (and vice
1789  * versa).  This can be remedied by a full queue search to disambiguate
1790  * cases.  If it is deemed profitable, this may be done.
1791  */
1792 bool CompileBroker::compilation_is_in_queue(const methodHandle& method) {
1793   return method->queued_for_compilation();
1794 }
1795 
1796 // ------------------------------------------------------------------
1797 // CompileBroker::compilation_is_prohibited
1798 //
1799 // See if this compilation is not allowed.
1800 bool CompileBroker::compilation_is_prohibited(const methodHandle& method, int osr_bci, int comp_level, bool excluded) {
1801   bool is_native = method->is_native();
1802   // Some compilers may not support the compilation of natives.
1803   AbstractCompiler *comp = compiler(comp_level);
1804   if (is_native && (!CICompileNatives || comp == nullptr)) {
1805     method->set_not_compilable_quietly("native methods not supported", comp_level);
1806     return true;
1807   }
1808 
1809   bool is_osr = (osr_bci != standard_entry_bci);
1810   // Some compilers may not support on stack replacement.
1811   if (is_osr && (!CICompileOSR || comp == nullptr)) {
1812     method->set_not_osr_compilable("OSR not supported", comp_level);
1813     return true;
1814   }
1815 
1816   // The method may be explicitly excluded by the user.
1817   double scale;
1818   if (excluded || (CompilerOracle::has_option_value(method, CompileCommand::CompileThresholdScaling, scale) && scale == 0)) {
1819     bool quietly = CompilerOracle::be_quiet();
1820     if (PrintCompilation && !quietly) {
1821       // This does not happen quietly...
1822       ResourceMark rm;
1823       tty->print("### Excluding %s:%s",
1824                  method->is_native() ? "generation of native wrapper" : "compile",
1825                  (method->is_static() ? " static" : ""));
1826       method->print_short_name(tty);
1827       tty->cr();
1828     }
1829     method->set_not_compilable("excluded by CompileCommand", comp_level, !quietly);
1830   }
1831 
1832   return false;
1833 }
1834 
1835 /**
1836  * Generate serialized IDs for compilation requests. If certain debugging flags are used
1837  * and the ID is not within the specified range, the method is not compiled and 0 is returned.
1838  * The function also allows to generate separate compilation IDs for OSR compilations.
1839  */
1840 int CompileBroker::assign_compile_id(const methodHandle& method, int osr_bci) {
1841 #ifdef ASSERT
1842   bool is_osr = (osr_bci != standard_entry_bci);
1843   int id;
1844   if (method->is_native()) {
1845     assert(!is_osr, "can't be osr");
1846     // Adapters, native wrappers and method handle intrinsics
1847     // should be generated always.
1848     return Atomic::add(CICountNative ? &_native_compilation_id : &_compilation_id, 1);
1849   } else if (CICountOSR && is_osr) {
1850     id = Atomic::add(&_osr_compilation_id, 1);
1851     if (CIStartOSR <= id && id < CIStopOSR) {
1852       return id;
1853     }
1854   } else {
1855     id = Atomic::add(&_compilation_id, 1);
1856     if (CIStart <= id && id < CIStop) {
1857       return id;
1858     }
1859   }
1860 
1861   // Method was not in the appropriate compilation range.
1862   method->set_not_compilable_quietly("Not in requested compile id range");
1863   return 0;
1864 #else
1865   // CICountOSR is a develop flag and set to 'false' by default. In a product built,
1866   // only _compilation_id is incremented.
1867   return Atomic::add(&_compilation_id, 1);
1868 #endif
1869 }
1870 
1871 // ------------------------------------------------------------------
1872 // CompileBroker::assign_compile_id_unlocked
1873 //
1874 // Public wrapper for assign_compile_id that acquires the needed locks
1875 int CompileBroker::assign_compile_id_unlocked(Thread* thread, const methodHandle& method, int osr_bci) {

1876   return assign_compile_id(method, osr_bci);
1877 }
1878 
1879 // ------------------------------------------------------------------
1880 // CompileBroker::create_compile_task
1881 //
1882 // Create a CompileTask object representing the current request for
1883 // compilation.  Add this task to the queue.
1884 CompileTask* CompileBroker::create_compile_task(CompileQueue*       queue,
1885                                                 int                 compile_id,
1886                                                 const methodHandle& method,
1887                                                 int                 osr_bci,
1888                                                 int                 comp_level,
1889                                                 const methodHandle& hot_method,
1890                                                 int                 hot_count,
1891                                                 SCCEntry*           scc_entry,
1892                                                 CompileTask::CompileReason compile_reason,
1893                                                 bool                requires_online_compilation,
1894                                                 bool                blocking) {
1895   CompileTask* new_task = CompileTask::allocate();
1896   new_task->initialize(compile_id, method, osr_bci, comp_level,
1897                        hot_method, hot_count, scc_entry, compile_reason, queue,
1898                        requires_online_compilation, blocking);

1899   return new_task;
1900 }
1901 
1902 #if INCLUDE_JVMCI
1903 // The number of milliseconds to wait before checking if
1904 // JVMCI compilation has made progress.
1905 static const long JVMCI_COMPILATION_PROGRESS_WAIT_TIMESLICE = 1000;
1906 
1907 // The number of JVMCI compilation progress checks that must fail
1908 // before unblocking a thread waiting for a blocking compilation.
1909 static const int JVMCI_COMPILATION_PROGRESS_WAIT_ATTEMPTS = 10;
1910 
1911 /**
1912  * Waits for a JVMCI compiler to complete a given task. This thread
1913  * waits until either the task completes or it sees no JVMCI compilation
1914  * progress for N consecutive milliseconds where N is
1915  * JVMCI_COMPILATION_PROGRESS_WAIT_TIMESLICE *
1916  * JVMCI_COMPILATION_PROGRESS_WAIT_ATTEMPTS.
1917  *
1918  * @return true if this thread needs to free/recycle the task
1919  */
1920 bool CompileBroker::wait_for_jvmci_completion(JVMCICompiler* jvmci, CompileTask* task, JavaThread* thread) {
1921   assert(UseJVMCICompiler, "sanity");
1922   MonitorLocker ml(thread, task->lock());
1923   int progress_wait_attempts = 0;
1924   jint thread_jvmci_compilation_ticks = 0;
1925   jint global_jvmci_compilation_ticks = jvmci->global_compilation_ticks();
1926   while (!task->is_complete() && !is_compilation_disabled_forever() &&
1927          ml.wait(JVMCI_COMPILATION_PROGRESS_WAIT_TIMESLICE)) {
1928     JVMCICompileState* jvmci_compile_state = task->blocking_jvmci_compile_state();
1929 
1930     bool progress;
1931     if (jvmci_compile_state != nullptr) {
1932       jint ticks = jvmci_compile_state->compilation_ticks();
1933       progress = (ticks - thread_jvmci_compilation_ticks) != 0;
1934       JVMCI_event_1("waiting on compilation %d [ticks=%d]", task->compile_id(), ticks);
1935       thread_jvmci_compilation_ticks = ticks;
1936     } else {
1937       // Still waiting on JVMCI compiler queue. This thread may be holding a lock
1938       // that all JVMCI compiler threads are blocked on. We use the global JVMCI
1939       // compilation ticks to determine whether JVMCI compilation
1940       // is still making progress through the JVMCI compiler queue.
1941       jint ticks = jvmci->global_compilation_ticks();
1942       progress = (ticks - global_jvmci_compilation_ticks) != 0;
1943       JVMCI_event_1("waiting on compilation %d to be queued [ticks=%d]", task->compile_id(), ticks);
1944       global_jvmci_compilation_ticks = ticks;
1945     }
1946 
1947     if (!progress) {
1948       if (++progress_wait_attempts == JVMCI_COMPILATION_PROGRESS_WAIT_ATTEMPTS) {
1949         if (PrintCompilation) {
1950           task->print(tty, "wait for blocking compilation timed out");
1951         }
1952         JVMCI_event_1("waiting on compilation %d timed out", task->compile_id());
1953         break;
1954       }
1955     } else {
1956       progress_wait_attempts = 0;
1957     }
1958   }
1959   task->clear_waiter();
1960   return task->is_complete();
1961 }
1962 #endif
1963 
1964 /**
1965  *  Wait for the compilation task to complete.
1966  */
1967 void CompileBroker::wait_for_completion(CompileTask* task) {
1968   if (CIPrintCompileQueue) {
1969     ttyLocker ttyl;
1970     tty->print_cr("BLOCKING FOR COMPILE");
1971   }
1972 
1973   assert(task->is_blocking(), "can only wait on blocking task");
1974 
1975   JavaThread* thread = JavaThread::current();
1976 
1977   methodHandle method(thread, task->method());
1978   bool free_task;
1979 #if INCLUDE_JVMCI
1980   AbstractCompiler* comp = compiler(task->comp_level());
1981   if (!UseJVMCINativeLibrary && comp->is_jvmci() && !task->should_wait_for_compilation()) {
1982     // It may return before compilation is completed.
1983     // Note that libjvmci should not pre-emptively unblock
1984     // a thread waiting for a compilation as it does not call
1985     // Java code and so is not deadlock prone like jarjvmci.
1986     free_task = wait_for_jvmci_completion((JVMCICompiler*) comp, task, thread);
1987   } else
1988 #endif
1989   {
1990     MonitorLocker ml(thread, task->lock());
1991     free_task = true;
1992     while (!task->is_complete() && !is_compilation_disabled_forever()) {
1993       ml.wait();
1994     }
1995   }
1996 
1997   if (free_task) {
1998     if (is_compilation_disabled_forever()) {
1999       CompileTask::free(task);
2000       return;
2001     }
2002 
2003     // It is harmless to check this status without the lock, because
2004     // completion is a stable property (until the task object is recycled).
2005     assert(task->is_complete(), "Compilation should have completed");
2006 
2007     // By convention, the waiter is responsible for recycling a
2008     // blocking CompileTask. Since there is only one waiter ever
2009     // waiting on a CompileTask, we know that no one else will
2010     // be using this CompileTask; we can free it.
2011     CompileTask::free(task);
2012   }
2013 }
2014 
2015 /**
2016  * Initialize compiler thread(s) + compiler object(s). The postcondition
2017  * of this function is that the compiler runtimes are initialized and that
2018  * compiler threads can start compiling.
2019  */
2020 bool CompileBroker::init_compiler_runtime() {
2021   CompilerThread* thread = CompilerThread::current();
2022   AbstractCompiler* comp = thread->compiler();
2023   // Final sanity check - the compiler object must exist
2024   guarantee(comp != nullptr, "Compiler object must exist");
2025 
2026   {
2027     // Must switch to native to allocate ci_env
2028     ThreadToNativeFromVM ttn(thread);
2029     ciEnv ci_env((CompileTask*)nullptr);
2030     // Cache Jvmti state
2031     ci_env.cache_jvmti_state();
2032     // Cache DTrace flags
2033     ci_env.cache_dtrace_flags();
2034 
2035     // Switch back to VM state to do compiler initialization
2036     ThreadInVMfromNative tv(thread);
2037 
2038     // Perform per-thread and global initializations
2039     {
2040       MutexLocker only_one (thread, CompileThread_lock);
2041       SCCache::init_table();
2042     }
2043     comp->initialize();
2044   }
2045 
2046   if (comp->is_failed()) {
2047     disable_compilation_forever();
2048     // If compiler initialization failed, no compiler thread that is specific to a
2049     // particular compiler runtime will ever start to compile methods.
2050     shutdown_compiler_runtime(comp, thread);
2051     return false;
2052   }
2053 
2054   // C1 specific check
2055   if (comp->is_c1() && (thread->get_buffer_blob() == nullptr)) {
2056     warning("Initialization of %s thread failed (no space to run compilers)", thread->name());
2057     return false;
2058   }
2059 
2060   return true;
2061 }
2062 
2063 void CompileBroker::free_buffer_blob_if_allocated(CompilerThread* thread) {
2064   BufferBlob* blob = thread->get_buffer_blob();
2065   if (blob != nullptr) {
2066     blob->purge(true /* free_code_cache_data */, true /* unregister_nmethod */);
2067     MutexLocker mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
2068     CodeCache::free(blob);
2069   }
2070 }
2071 
2072 /**
2073  * If C1 and/or C2 initialization failed, we shut down all compilation.
2074  * We do this to keep things simple. This can be changed if it ever turns
2075  * out to be a problem.
2076  */
2077 void CompileBroker::shutdown_compiler_runtime(AbstractCompiler* comp, CompilerThread* thread) {
2078   free_buffer_blob_if_allocated(thread);
2079 
2080   log_info(compilation)("shutdown_compiler_runtime: " INTPTR_FORMAT, p2i(thread));
2081 
2082   if (comp->should_perform_shutdown()) {
2083     // There are two reasons for shutting down the compiler
2084     // 1) compiler runtime initialization failed
2085     // 2) The code cache is full and the following flag is set: -XX:-UseCodeCacheFlushing
2086     warning("%s initialization failed. Shutting down all compilers", comp->name());
2087 
2088     // Only one thread per compiler runtime object enters here
2089     // Set state to shut down
2090     comp->set_shut_down();
2091 
2092     // Delete all queued compilation tasks to make compiler threads exit faster.
2093     if (_c1_compile_queue != nullptr) {
2094       _c1_compile_queue->free_all();
2095     }
2096 
2097     if (_c2_compile_queue != nullptr) {
2098       _c2_compile_queue->free_all();
2099     }
2100 
2101     if (_c3_compile_queue != nullptr) {
2102       _c3_compile_queue->free_all();
2103     }
2104 
2105     // Set flags so that we continue execution with using interpreter only.
2106     UseCompiler    = false;
2107     UseInterpreter = true;
2108 
2109     // We could delete compiler runtimes also. However, there are references to
2110     // the compiler runtime(s) (e.g.,  nmethod::is_compiled_by_c1()) which then
2111     // fail. This can be done later if necessary.
2112   }
2113 }
2114 
2115 /**
2116  * Helper function to create new or reuse old CompileLog.
2117  */
2118 CompileLog* CompileBroker::get_log(CompilerThread* ct) {
2119   if (!LogCompilation) return nullptr;
2120 
2121   AbstractCompiler *compiler = ct->compiler();
2122   bool jvmci = JVMCI_ONLY( compiler->is_jvmci() ||) false;
2123   bool c1 = compiler->is_c1();
2124   jobject* compiler_objects = c1 ? _compiler1_objects : (_c3_count == 0 ? _compiler2_objects : (jvmci ? _compiler2_objects : _compiler3_objects));
2125   assert(compiler_objects != nullptr, "must be initialized at this point");
2126   CompileLog** logs = c1 ? _compiler1_logs : (_c3_count == 0 ? _compiler2_logs : (jvmci ? _compiler2_logs : _compiler3_logs));
2127   assert(logs != nullptr, "must be initialized at this point");
2128   int count = c1 ? _c1_count : (_c3_count == 0 ? _c2_count : (jvmci ? _c2_count : _c3_count));
2129 
2130   if (ct->queue() == _sc1_compile_queue || ct->queue() == _sc2_compile_queue) {
2131     compiler_objects = _sc_objects;
2132     logs  = _sc_logs;
2133     count = _sc_count;
2134   }
2135   // Find Compiler number by its threadObj.
2136   oop compiler_obj = ct->threadObj();
2137   int compiler_number = 0;
2138   bool found = false;
2139   for (; compiler_number < count; compiler_number++) {
2140     if (JNIHandles::resolve_non_null(compiler_objects[compiler_number]) == compiler_obj) {
2141       found = true;
2142       break;
2143     }
2144   }
2145   assert(found, "Compiler must exist at this point");
2146 
2147   // Determine pointer for this thread's log.
2148   CompileLog** log_ptr = &logs[compiler_number];
2149 
2150   // Return old one if it exists.
2151   CompileLog* log = *log_ptr;
2152   if (log != nullptr) {
2153     ct->init_log(log);
2154     return log;
2155   }
2156 
2157   // Create a new one and remember it.
2158   init_compiler_thread_log();
2159   log = ct->log();
2160   *log_ptr = log;
2161   return log;
2162 }
2163 
2164 // ------------------------------------------------------------------
2165 // CompileBroker::compiler_thread_loop
2166 //
2167 // The main loop run by a CompilerThread.
2168 void CompileBroker::compiler_thread_loop() {
2169   CompilerThread* thread = CompilerThread::current();
2170   CompileQueue* queue = thread->queue();
2171   // For the thread that initializes the ciObjectFactory
2172   // this resource mark holds all the shared objects
2173   ResourceMark rm;
2174 
2175   // First thread to get here will initialize the compiler interface
2176 
2177   {
2178     ASSERT_IN_VM;
2179     MutexLocker only_one (thread, CompileThread_lock);
2180     if (!ciObjectFactory::is_initialized()) {
2181       ciObjectFactory::initialize();
2182     }
2183   }
2184 
2185   // Open a log.
2186   CompileLog* log = get_log(thread);
2187   if (log != nullptr) {
2188     log->begin_elem("start_compile_thread name='%s' thread='" UINTX_FORMAT "' process='%d'",
2189                     thread->name(),
2190                     os::current_thread_id(),
2191                     os::current_process_id());
2192     log->stamp();
2193     log->end_elem();
2194   }
2195 
2196   // If compiler thread/runtime initialization fails, exit the compiler thread
2197   if (!init_compiler_runtime()) {
2198     return;
2199   }
2200 
2201   thread->start_idle_timer();
2202 
2203   // Poll for new compilation tasks as long as the JVM runs. Compilation
2204   // should only be disabled if something went wrong while initializing the
2205   // compiler runtimes. This, in turn, should not happen. The only known case
2206   // when compiler runtime initialization fails is if there is not enough free
2207   // space in the code cache to generate the necessary stubs, etc.
2208   while (!is_compilation_disabled_forever()) {
2209     // We need this HandleMark to avoid leaking VM handles.
2210     HandleMark hm(thread);
2211 
2212     CompilationPolicy::recompilation_step(RecompilationWorkUnitSize, thread);
2213 
2214     CompileTask* task = queue->get(thread);
2215 
2216     if (task == nullptr) {
2217       if (UseDynamicNumberOfCompilerThreads) {
2218         // Access compiler_count under lock to enforce consistency.
2219         MutexLocker only_one(CompileThread_lock);
2220         if (can_remove(thread, true)) {
2221           if (trace_compiler_threads()) {
2222             ResourceMark rm;
2223             stringStream msg;
2224             msg.print("Removing compiler thread %s after " JLONG_FORMAT " ms idle time",
2225                       thread->name(), thread->idle_time_millis());
2226             print_compiler_threads(msg);
2227           }
2228 
2229           // Notify compiler that the compiler thread is about to stop
2230           thread->compiler()->stopping_compiler_thread(thread);
2231 
2232           free_buffer_blob_if_allocated(thread);
2233           return; // Stop this thread.
2234         }
2235       }
2236     } else {
2237       // Assign the task to the current thread.  Mark this compilation
2238       // thread as active for the profiler.
2239       // CompileTaskWrapper also keeps the Method* from being deallocated if redefinition
2240       // occurs after fetching the compile task off the queue.
2241       CompileTaskWrapper ctw(task);
2242       methodHandle method(thread, task->method());
2243 
2244       // Never compile a method if breakpoints are present in it
2245       if (method()->number_of_breakpoints() == 0) {
2246         // Compile the method.
2247         if ((UseCompiler || AlwaysCompileLoopMethods) && CompileBroker::should_compile_new_jobs()) {
2248           invoke_compiler_on_method(task);
2249           thread->start_idle_timer();
2250         } else {
2251           // After compilation is disabled, remove remaining methods from queue
2252           method->clear_queued_for_compilation();
2253           method->set_pending_queue_processed(false);
2254           task->set_failure_reason("compilation is disabled");
2255         }
2256       } else {
2257         task->set_failure_reason("breakpoints are present");
2258       }
2259 
2260       if (UseDynamicNumberOfCompilerThreads) {
2261         possibly_add_compiler_threads(thread);
2262         assert(!thread->has_pending_exception(), "should have been handled");
2263       }
2264     }
2265   }
2266 
2267   // Shut down compiler runtime
2268   shutdown_compiler_runtime(thread->compiler(), thread);
2269 }
2270 
2271 // ------------------------------------------------------------------
2272 // CompileBroker::init_compiler_thread_log
2273 //
2274 // Set up state required by +LogCompilation.
2275 void CompileBroker::init_compiler_thread_log() {
2276     CompilerThread* thread = CompilerThread::current();
2277     char  file_name[4*K];
2278     FILE* fp = nullptr;
2279     intx thread_id = os::current_thread_id();
2280     for (int try_temp_dir = 1; try_temp_dir >= 0; try_temp_dir--) {
2281       const char* dir = (try_temp_dir ? os::get_temp_directory() : nullptr);
2282       if (dir == nullptr) {
2283         jio_snprintf(file_name, sizeof(file_name), "hs_c" UINTX_FORMAT "_pid%u.log",
2284                      thread_id, os::current_process_id());
2285       } else {
2286         jio_snprintf(file_name, sizeof(file_name),
2287                      "%s%shs_c" UINTX_FORMAT "_pid%u.log", dir,
2288                      os::file_separator(), thread_id, os::current_process_id());
2289       }
2290 
2291       fp = os::fopen(file_name, "wt");
2292       if (fp != nullptr) {
2293         if (LogCompilation && Verbose) {
2294           tty->print_cr("Opening compilation log %s", file_name);
2295         }
2296         CompileLog* log = new(mtCompiler) CompileLog(file_name, fp, thread_id);
2297         if (log == nullptr) {
2298           fclose(fp);
2299           return;
2300         }
2301         thread->init_log(log);
2302 
2303         if (xtty != nullptr) {
2304           ttyLocker ttyl;
2305           // Record any per thread log files
2306           xtty->elem("thread_logfile thread='" INTX_FORMAT "' filename='%s'", thread_id, file_name);
2307         }
2308         return;
2309       }
2310     }
2311     warning("Cannot open log file: %s", file_name);
2312 }
2313 
2314 void CompileBroker::log_metaspace_failure() {
2315   const char* message = "some methods may not be compiled because metaspace "
2316                         "is out of memory";
2317   if (CompilationLog::log() != nullptr) {
2318     CompilationLog::log()->log_metaspace_failure(message);
2319   }
2320   if (PrintCompilation) {
2321     tty->print_cr("COMPILE PROFILING SKIPPED: %s", message);
2322   }
2323 }
2324 
2325 
2326 // ------------------------------------------------------------------
2327 // CompileBroker::set_should_block
2328 //
2329 // Set _should_block.
2330 // Call this from the VM, with Threads_lock held and a safepoint requested.
2331 void CompileBroker::set_should_block() {
2332   assert(Threads_lock->owner() == Thread::current(), "must have threads lock");
2333   assert(SafepointSynchronize::is_at_safepoint(), "must be at a safepoint already");
2334 #ifndef PRODUCT
2335   if (PrintCompilation && (Verbose || WizardMode))
2336     tty->print_cr("notifying compiler thread pool to block");
2337 #endif
2338   _should_block = true;
2339 }
2340 
2341 // ------------------------------------------------------------------
2342 // CompileBroker::maybe_block
2343 //
2344 // Call this from the compiler at convenient points, to poll for _should_block.
2345 void CompileBroker::maybe_block() {
2346   if (_should_block) {
2347 #ifndef PRODUCT
2348     if (PrintCompilation && (Verbose || WizardMode))
2349       tty->print_cr("compiler thread " INTPTR_FORMAT " poll detects block request", p2i(Thread::current()));
2350 #endif
2351     ThreadInVMfromNative tivfn(JavaThread::current());
2352   }
2353 }
2354 
2355 // wrapper for CodeCache::print_summary()
2356 static void codecache_print(bool detailed)
2357 {
2358   stringStream s;
2359   // Dump code cache  into a buffer before locking the tty,
2360   {
2361     MutexLocker mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
2362     CodeCache::print_summary(&s, detailed);
2363   }
2364   ttyLocker ttyl;
2365   tty->print("%s", s.freeze());
2366 }
2367 
2368 // wrapper for CodeCache::print_summary() using outputStream
2369 static void codecache_print(outputStream* out, bool detailed) {
2370   stringStream s;
2371 
2372   // Dump code cache into a buffer
2373   {
2374     MutexLocker mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
2375     CodeCache::print_summary(&s, detailed);
2376   }
2377 
2378   char* remaining_log = s.as_string();
2379   while (*remaining_log != '\0') {
2380     char* eol = strchr(remaining_log, '\n');
2381     if (eol == nullptr) {
2382       out->print_cr("%s", remaining_log);
2383       remaining_log = remaining_log + strlen(remaining_log);
2384     } else {
2385       *eol = '\0';
2386       out->print_cr("%s", remaining_log);
2387       remaining_log = eol + 1;
2388     }
2389   }
2390 }
2391 
2392 void CompileBroker::handle_compile_error(CompilerThread* thread, CompileTask* task, ciEnv* ci_env,
2393                                          int compilable, const char* failure_reason) {
2394   if (!AbortVMOnCompilationFailure) {
2395     return;
2396   }
2397   if (compilable == ciEnv::MethodCompilable_not_at_tier) {
2398     fatal("Not compilable at tier %d: %s", task->comp_level(), failure_reason);
2399   }
2400   if (compilable == ciEnv::MethodCompilable_never) {
2401     fatal("Never compilable: %s", failure_reason);
2402   }
2403 }
2404 
2405 static void post_compilation_event(EventCompilation& event, CompileTask* task) {
2406   assert(task != nullptr, "invariant");
2407   CompilerEvent::CompilationEvent::post(event,
2408                                         task->compile_id(),
2409                                         task->compiler()->type(),
2410                                         task->method(),
2411                                         task->comp_level(),
2412                                         task->is_success(),
2413                                         task->osr_bci() != CompileBroker::standard_entry_bci,
2414                                         task->nm_total_size(),
2415                                         task->num_inlined_bytecodes());
2416 }
2417 
2418 int DirectivesStack::_depth = 0;
2419 CompilerDirectives* DirectivesStack::_top = nullptr;
2420 CompilerDirectives* DirectivesStack::_bottom = nullptr;
2421 
2422 // Acquires Compilation_lock and waits for it to be notified
2423 // as long as WhiteBox::compilation_locked is true.
2424 static void whitebox_lock_compilation() {
2425   MonitorLocker locker(Compilation_lock, Mutex::_no_safepoint_check_flag);
2426   while (WhiteBox::compilation_locked) {
2427     locker.wait();
2428   }
2429 }
2430 
2431 // ------------------------------------------------------------------
2432 // CompileBroker::invoke_compiler_on_method
2433 //
2434 // Compile a method.
2435 //
2436 void CompileBroker::invoke_compiler_on_method(CompileTask* task) {
2437   task->print_ul();
2438   elapsedTimer time;
2439 
2440   DirectiveSet* directive = task->directive();




2441 
2442   CompilerThread* thread = CompilerThread::current();
2443   ResourceMark rm(thread);
2444 
2445   if (CompilationLog::log() != nullptr) {
2446     CompilationLog::log()->log_compile(thread, task);
2447   }
2448 
2449   // Common flags.
2450   int compile_id = task->compile_id();
2451   int osr_bci = task->osr_bci();
2452   bool is_osr = (osr_bci != standard_entry_bci);
2453   bool should_log = (thread->log() != nullptr);
2454   bool should_break = false;
2455   const int task_level = task->comp_level();
2456   AbstractCompiler* comp = task->compiler();
2457   CompileTrainingData* tdata = task->training_data();
2458   assert(tdata == nullptr || TrainingData::need_data() ||
2459          CDSConfig::is_dumping_preimage_static_archive(), ""); // FIXME: MetaspaceShared::preload_and_dump() messes with RecordTraining flag
2460   {
2461     // create the handle inside it's own block so it can't
2462     // accidentally be referenced once the thread transitions to
2463     // native.  The NoHandleMark before the transition should catch
2464     // any cases where this occurs in the future.
2465     methodHandle method(thread, task->method());
2466 
2467     assert(!method->is_native(), "no longer compile natives");
2468 
2469     // Update compile information when using perfdata.
2470     if (UsePerfData) {
2471       update_compile_perf_data(thread, method, is_osr);
2472     }
2473 
2474     DTRACE_METHOD_COMPILE_BEGIN_PROBE(method, compiler_name(task_level));
2475   }
2476 
2477   if (tdata != nullptr) {
2478     tdata->record_compilation_start(task);
2479   }
2480 
2481   should_break = directive->BreakAtCompileOption || task->check_break_at_flags();
2482   if (should_log && !directive->LogOption) {
2483     should_log = false;
2484   }
2485 
2486   // Allocate a new set of JNI handles.
2487   JNIHandleMark jhm(thread);
2488   Method* target_handle = task->method();
2489   int compilable = ciEnv::MethodCompilable;
2490   const char* failure_reason = nullptr;
2491   bool failure_reason_on_C_heap = false;
2492   const char* retry_message = nullptr;
2493 
2494 #if INCLUDE_JVMCI
2495   if (UseJVMCICompiler && comp != nullptr && comp->is_jvmci()) {
2496     JVMCICompiler* jvmci = (JVMCICompiler*) comp;
2497 
2498     TraceTime t1("compilation", &time);
2499     EventCompilation event;
2500     JVMCICompileState compile_state(task, jvmci);
2501     JVMCIRuntime *runtime = nullptr;
2502 
2503     if (JVMCI::in_shutdown()) {
2504       failure_reason = "in JVMCI shutdown";
2505       retry_message = "not retryable";
2506       compilable = ciEnv::MethodCompilable_never;
2507     } else if (compile_state.target_method_is_old()) {
2508       // Skip redefined methods
2509       failure_reason = "redefined method";
2510       retry_message = "not retryable";
2511       compilable = ciEnv::MethodCompilable_never;
2512     } else {
2513       JVMCIEnv env(thread, &compile_state, __FILE__, __LINE__);
2514       if (env.init_error() != JNI_OK) {
2515         const char* msg = env.init_error_msg();
2516         failure_reason = os::strdup(err_msg("Error attaching to libjvmci (err: %d, %s)",
2517                                     env.init_error(), msg == nullptr ? "unknown" : msg), mtJVMCI);
2518         bool reason_on_C_heap = true;
2519         // In case of JNI_ENOMEM, there's a good chance a subsequent attempt to create libjvmci or attach to it
2520         // might succeed. Other errors most likely indicate a non-recoverable error in the JVMCI runtime.
2521         bool retryable = env.init_error() == JNI_ENOMEM;
2522         compile_state.set_failure(retryable, failure_reason, reason_on_C_heap);
2523       }
2524       if (failure_reason == nullptr) {
2525         if (WhiteBoxAPI && WhiteBox::compilation_locked) {
2526           // Must switch to native to block
2527           ThreadToNativeFromVM ttn(thread);
2528           whitebox_lock_compilation();
2529         }
2530         methodHandle method(thread, target_handle);
2531         runtime = env.runtime();
2532         runtime->compile_method(&env, jvmci, method, osr_bci);
2533 
2534         failure_reason = compile_state.failure_reason();
2535         failure_reason_on_C_heap = compile_state.failure_reason_on_C_heap();
2536         if (!compile_state.retryable()) {
2537           retry_message = "not retryable";
2538           compilable = ciEnv::MethodCompilable_not_at_tier;
2539         }
2540         if (!task->is_success()) {
2541           assert(failure_reason != nullptr, "must specify failure_reason");
2542         }
2543       }
2544     }
2545     if (!task->is_success() && !JVMCI::in_shutdown()) {
2546       handle_compile_error(thread, task, nullptr, compilable, failure_reason);
2547     }
2548     if (event.should_commit()) {
2549       post_compilation_event(event, task);
2550     }
2551 
2552     if (runtime != nullptr) {
2553       runtime->post_compile(thread);
2554     }
2555   } else
2556 #endif // INCLUDE_JVMCI
2557   {
2558     NoHandleMark  nhm;
2559     ThreadToNativeFromVM ttn(thread);
2560 
2561     ciEnv ci_env(task);
2562     if (should_break) {
2563       ci_env.set_break_at_compile(true);
2564     }
2565     if (should_log) {
2566       ci_env.set_log(thread->log());
2567     }
2568     assert(thread->env() == &ci_env, "set by ci_env");
2569     // The thread-env() field is cleared in ~CompileTaskWrapper.
2570 
2571     // Cache Jvmti state
2572     bool method_is_old = ci_env.cache_jvmti_state();
2573 
2574     // Skip redefined methods
2575     if (method_is_old) {
2576       ci_env.record_method_not_compilable("redefined method", true);
2577     }
2578 
2579     // Cache DTrace flags
2580     ci_env.cache_dtrace_flags();
2581 
2582     ciMethod* target = ci_env.get_method_from_handle(target_handle);
2583 
2584     TraceTime t1("compilation", &time);
2585     EventCompilation event;
2586 
2587     bool install_code = true;
2588     if (comp == nullptr) {
2589       ci_env.record_method_not_compilable("no compiler");
2590     } else if (!ci_env.failing()) {
2591       if (WhiteBoxAPI && WhiteBox::compilation_locked) {
2592         whitebox_lock_compilation();
2593       }
2594       if (StoreCachedCode && task->is_precompiled()) {
2595         install_code = false; // not suitable in the current context
2596       }
2597       comp->compile_method(&ci_env, target, osr_bci, install_code, directive);
2598 
2599       /* Repeat compilation without installing code for profiling purposes */
2600       int repeat_compilation_count = directive->RepeatCompilationOption;
2601       while (repeat_compilation_count > 0) {
2602         ResourceMark rm(thread);
2603         task->print_ul("NO CODE INSTALLED");
2604         comp->compile_method(&ci_env, target, osr_bci, false, directive);
2605         repeat_compilation_count--;
2606       }
2607     }
2608 
2609     DirectivesStack::release(directive);
2610 
2611     if (!ci_env.failing() && !task->is_success() && install_code) {
2612       assert(ci_env.failure_reason() != nullptr, "expect failure reason");
2613       assert(false, "compiler should always document failure: %s", ci_env.failure_reason());
2614       // The compiler elected, without comment, not to register a result.
2615       // Do not attempt further compilations of this method.
2616       ci_env.record_method_not_compilable("compile failed");
2617     }
2618 
2619     // Copy this bit to the enclosing block:
2620     compilable = ci_env.compilable();
2621 
2622     if (ci_env.failing()) {
2623       // Duplicate the failure reason string, so that it outlives ciEnv
2624       failure_reason = os::strdup(ci_env.failure_reason(), mtCompiler);
2625       failure_reason_on_C_heap = true;
2626       retry_message = ci_env.retry_message();
2627       ci_env.report_failure(failure_reason);
2628     }
2629 
2630     if (ci_env.failing()) {
2631       handle_compile_error(thread, task, &ci_env, compilable, failure_reason);
2632     }
2633     if (event.should_commit()) {
2634       post_compilation_event(event, task);
2635     }
2636   }
2637 
2638   if (failure_reason != nullptr) {
2639     task->set_failure_reason(failure_reason, failure_reason_on_C_heap);
2640     if (CompilationLog::log() != nullptr) {
2641       CompilationLog::log()->log_failure(thread, task, failure_reason, retry_message);
2642     }
2643     if (PrintCompilation) {
2644       FormatBufferResource msg = retry_message != nullptr ?
2645         FormatBufferResource("COMPILE SKIPPED: %s (%s)", failure_reason, retry_message) :
2646         FormatBufferResource("COMPILE SKIPPED: %s",      failure_reason);
2647       task->print(tty, msg);
2648     }
2649   }
2650 
2651   if (tdata != nullptr) {
2652     tdata->record_compilation_end(task);
2653   }
2654 
2655   if (directive->PrintCompilationOption) {
2656     ResourceMark rm;
2657     task->print_tty();
2658   }
2659 
2660   methodHandle method(thread, task->method());
2661 
2662   DTRACE_METHOD_COMPILE_END_PROBE(method, compiler_name(task_level), task->is_success());
2663 
2664   collect_statistics(thread, time, task);
2665 
2666   if (PrintCompilation && PrintCompilation2) {
2667     tty->print("%7d ", (int) tty->time_stamp().milliseconds());  // print timestamp
2668     tty->print("%4d ", compile_id);    // print compilation number
2669     tty->print("%s ", (is_osr ? "%" : (task->is_scc() ? "A" : " ")));
2670     if (task->is_success()) {
2671       tty->print("size: %d(%d) ", task->nm_total_size(), task->nm_insts_size());
2672     }
2673     tty->print_cr("time: %d inlined: %d bytes", (int)time.milliseconds(), task->num_inlined_bytecodes());
2674   }
2675 
2676   Log(compilation, codecache) log;
2677   if (log.is_debug()) {
2678     LogStream ls(log.debug());
2679     codecache_print(&ls, /* detailed= */ false);
2680   }
2681   if (PrintCodeCacheOnCompilation) {
2682     codecache_print(/* detailed= */ false);
2683   }
2684   // Disable compilation, if required.
2685   switch (compilable) {
2686   case ciEnv::MethodCompilable_never:
2687     if (is_osr)
2688       method->set_not_osr_compilable_quietly("MethodCompilable_never");
2689     else
2690       method->set_not_compilable_quietly("MethodCompilable_never");
2691     break;
2692   case ciEnv::MethodCompilable_not_at_tier:
2693     if (is_osr)
2694       method->set_not_osr_compilable_quietly("MethodCompilable_not_at_tier", task_level);
2695     else
2696       method->set_not_compilable_quietly("MethodCompilable_not_at_tier", task_level);
2697     break;
2698   }
2699 
2700   // Note that the queued_for_compilation bits are cleared without
2701   // protection of a mutex. [They were set by the requester thread,
2702   // when adding the task to the compile queue -- at which time the
2703   // compile queue lock was held. Subsequently, we acquired the compile
2704   // queue lock to get this task off the compile queue; thus (to belabour
2705   // the point somewhat) our clearing of the bits must be occurring
2706   // only after the setting of the bits. See also 14012000 above.
2707   method->clear_queued_for_compilation();
2708   method->set_pending_queue_processed(false);
2709 }
2710 
2711 /**
2712  * The CodeCache is full. Print warning and disable compilation.
2713  * Schedule code cache cleaning so compilation can continue later.
2714  * This function needs to be called only from CodeCache::allocate(),
2715  * since we currently handle a full code cache uniformly.
2716  */
2717 void CompileBroker::handle_full_code_cache(CodeBlobType code_blob_type) {
2718   UseInterpreter = true;
2719   if (UseCompiler || AlwaysCompileLoopMethods ) {
2720     if (xtty != nullptr) {
2721       stringStream s;
2722       // Dump code cache state into a buffer before locking the tty,
2723       // because log_state() will use locks causing lock conflicts.
2724       CodeCache::log_state(&s);
2725       // Lock to prevent tearing
2726       ttyLocker ttyl;
2727       xtty->begin_elem("code_cache_full");
2728       xtty->print("%s", s.freeze());
2729       xtty->stamp();
2730       xtty->end_elem();
2731     }
2732 
2733 #ifndef PRODUCT
2734     if (ExitOnFullCodeCache) {
2735       codecache_print(/* detailed= */ true);
2736       before_exit(JavaThread::current());
2737       exit_globals(); // will delete tty
2738       vm_direct_exit(1);
2739     }
2740 #endif
2741     if (UseCodeCacheFlushing) {
2742       // Since code cache is full, immediately stop new compiles
2743       if (CompileBroker::set_should_compile_new_jobs(CompileBroker::stop_compilation)) {
2744         log_info(codecache)("Code cache is full - disabling compilation");
2745       }
2746     } else {
2747       disable_compilation_forever();
2748     }
2749 
2750     CodeCache::report_codemem_full(code_blob_type, should_print_compiler_warning());
2751   }
2752 }
2753 
2754 // ------------------------------------------------------------------
2755 // CompileBroker::update_compile_perf_data
2756 //
2757 // Record this compilation for debugging purposes.
2758 void CompileBroker::update_compile_perf_data(CompilerThread* thread, const methodHandle& method, bool is_osr) {
2759   ResourceMark rm;
2760   char* method_name = method->name()->as_C_string();
2761   char current_method[CompilerCounters::cmname_buffer_length];
2762   size_t maxLen = CompilerCounters::cmname_buffer_length;
2763 
2764   const char* class_name = method->method_holder()->name()->as_C_string();
2765 
2766   size_t s1len = strlen(class_name);
2767   size_t s2len = strlen(method_name);
2768 
2769   // check if we need to truncate the string
2770   if (s1len + s2len + 2 > maxLen) {
2771 
2772     // the strategy is to lop off the leading characters of the
2773     // class name and the trailing characters of the method name.
2774 
2775     if (s2len + 2 > maxLen) {
2776       // lop of the entire class name string, let snprintf handle
2777       // truncation of the method name.
2778       class_name += s1len; // null string
2779     }
2780     else {
2781       // lop off the extra characters from the front of the class name
2782       class_name += ((s1len + s2len + 2) - maxLen);
2783     }
2784   }
2785 
2786   jio_snprintf(current_method, maxLen, "%s %s", class_name, method_name);
2787 
2788   int last_compile_type = normal_compile;
2789   if (CICountOSR && is_osr) {
2790     last_compile_type = osr_compile;
2791   } else if (CICountNative && method->is_native()) {
2792     last_compile_type = native_compile;
2793   }
2794 
2795   CompilerCounters* counters = thread->counters();
2796   counters->set_current_method(current_method);
2797   counters->set_compile_type((jlong) last_compile_type);
2798 }
2799 
2800 // ------------------------------------------------------------------
2801 // CompileBroker::collect_statistics
2802 //
2803 // Collect statistics about the compilation.
2804 
2805 void CompileBroker::collect_statistics(CompilerThread* thread, elapsedTimer time, CompileTask* task) {
2806   bool success = task->is_success();
2807   methodHandle method (thread, task->method());
2808   int compile_id = task->compile_id();
2809   bool is_osr = (task->osr_bci() != standard_entry_bci);
2810   const int comp_level = task->comp_level();
2811   CompilerCounters* counters = thread->counters();
2812 
2813   MutexLocker locker(CompileStatistics_lock);
2814 
2815   // _perf variables are production performance counters which are
2816   // updated regardless of the setting of the CITime and CITimeEach flags
2817   //
2818 
2819   // account all time, including bailouts and failures in this counter;
2820   // C1 and C2 counters are counting both successful and unsuccessful compiles
2821   _t_total_compilation.add(&time);
2822 
2823   if (!success) {
2824     _total_bailout_count++;
2825     if (UsePerfData) {
2826       _perf_last_failed_method->set_value(counters->current_method());
2827       _perf_last_failed_type->set_value(counters->compile_type());
2828       _perf_total_bailout_count->inc();
2829     }
2830     _t_bailedout_compilation.add(&time);
2831 
2832     if (CITime || log_is_enabled(Info, init)) {
2833       CompilerStatistics* stats = nullptr;
2834       if (task->is_scc()) {
2835         int level = task->preload() ? CompLevel_full_optimization : (comp_level - 1);
2836         stats = &_scc_stats_per_level[level];
2837       } else {
2838         stats = &_stats_per_level[comp_level-1];
2839       }
2840       stats->_bailout.update(time, 0);
2841     }
2842   } else if (!task->is_success()) {
2843     if (UsePerfData) {
2844       _perf_last_invalidated_method->set_value(counters->current_method());
2845       _perf_last_invalidated_type->set_value(counters->compile_type());
2846       _perf_total_invalidated_count->inc();
2847     }
2848     _total_invalidated_count++;
2849     _t_invalidated_compilation.add(&time);
2850 
2851     if (CITime || log_is_enabled(Info, init)) {
2852       CompilerStatistics* stats = nullptr;
2853       if (task->is_scc()) {
2854         int level = task->preload() ? CompLevel_full_optimization : (comp_level - 1);
2855         stats = &_scc_stats_per_level[level];
2856       } else {
2857         stats = &_stats_per_level[comp_level-1];
2858       }
2859       stats->_invalidated.update(time, 0);
2860     }
2861   } else {
2862     // Compilation succeeded
2863 
2864     // update compilation ticks - used by the implementation of
2865     // java.lang.management.CompilationMXBean
2866     _perf_total_compilation->inc(time.ticks());
2867     _peak_compilation_time = time.milliseconds() > _peak_compilation_time ? time.milliseconds() : _peak_compilation_time;
2868 
2869     if (CITime || log_is_enabled(Info, init)) {
2870       int bytes_compiled = method->code_size() + task->num_inlined_bytecodes();
2871       if (is_osr) {
2872         _t_osr_compilation.add(&time);
2873         _sum_osr_bytes_compiled += bytes_compiled;
2874       } else {
2875         _t_standard_compilation.add(&time);
2876         _sum_standard_bytes_compiled += method->code_size() + task->num_inlined_bytecodes();
2877       }
2878 
2879       // Collect statistic per compilation level
2880       if (task->is_scc()) {
2881         _scc_stats._standard.update(time, bytes_compiled);
2882         _scc_stats._nmethods_size += task->nm_total_size();
2883         _scc_stats._nmethods_code_size += task->nm_insts_size();
2884         int level = task->preload() ? CompLevel_full_optimization : (comp_level - 1);
2885         CompilerStatistics* stats = &_scc_stats_per_level[level];
2886         stats->_standard.update(time, bytes_compiled);
2887         stats->_nmethods_size += task->nm_total_size();
2888         stats->_nmethods_code_size += task->nm_insts_size();
2889       } else if (comp_level > CompLevel_none && comp_level <= CompLevel_full_optimization) {
2890         CompilerStatistics* stats = &_stats_per_level[comp_level-1];
2891         if (is_osr) {
2892           stats->_osr.update(time, bytes_compiled);
2893         } else {
2894           stats->_standard.update(time, bytes_compiled);
2895         }
2896         stats->_nmethods_size += task->nm_total_size();
2897         stats->_nmethods_code_size += task->nm_insts_size();
2898       } else {
2899         assert(false, "CompilerStatistics object does not exist for compilation level %d", comp_level);
2900       }
2901 
2902       // Collect statistic per compiler
2903       AbstractCompiler* comp = task->compiler();
2904       if (comp && !task->is_scc()) {
2905         CompilerStatistics* stats = comp->stats();
2906         if (is_osr) {
2907           stats->_osr.update(time, bytes_compiled);
2908         } else {
2909           stats->_standard.update(time, bytes_compiled);
2910         }
2911         stats->_nmethods_size += task->nm_total_size();
2912         stats->_nmethods_code_size += task->nm_insts_size();
2913       } else if (!task->is_scc()) { // if (!comp)
2914         assert(false, "Compiler object must exist");
2915       }
2916     }
2917 
2918     if (UsePerfData) {
2919       // save the name of the last method compiled
2920       _perf_last_method->set_value(counters->current_method());
2921       _perf_last_compile_type->set_value(counters->compile_type());
2922       _perf_last_compile_size->set_value(method->code_size() +
2923                                          task->num_inlined_bytecodes());
2924       if (is_osr) {
2925         _perf_osr_compilation->inc(time.ticks());
2926         _perf_sum_osr_bytes_compiled->inc(method->code_size() + task->num_inlined_bytecodes());
2927       } else {
2928         _perf_standard_compilation->inc(time.ticks());
2929         _perf_sum_standard_bytes_compiled->inc(method->code_size() + task->num_inlined_bytecodes());
2930       }
2931     }
2932 
2933     if (CITimeEach) {
2934       double compile_time = time.seconds();
2935       double bytes_per_sec = compile_time == 0.0 ? 0.0 : (double)(method->code_size() + task->num_inlined_bytecodes()) / compile_time;
2936       tty->print_cr("%3d   seconds: %6.3f bytes/sec : %f (bytes %d + %d inlined)",
2937                     compile_id, compile_time, bytes_per_sec, method->code_size(), task->num_inlined_bytecodes());
2938     }
2939 
2940     // Collect counts of successful compilations
2941     _sum_nmethod_size      += task->nm_total_size();
2942     _sum_nmethod_code_size += task->nm_insts_size();
2943     _total_compile_count++;
2944 
2945     if (UsePerfData) {
2946       _perf_sum_nmethod_size->inc(     task->nm_total_size());
2947       _perf_sum_nmethod_code_size->inc(task->nm_insts_size());
2948       _perf_total_compile_count->inc();
2949     }
2950 
2951     if (is_osr) {
2952       if (UsePerfData) _perf_total_osr_compile_count->inc();
2953       _total_osr_compile_count++;
2954     } else {
2955       if (UsePerfData) _perf_total_standard_compile_count->inc();
2956       _total_standard_compile_count++;
2957     }
2958   }
2959   // set the current method for the thread to null
2960   if (UsePerfData) counters->set_current_method("");
2961 }
2962 
2963 const char* CompileBroker::compiler_name(int comp_level) {
2964   AbstractCompiler *comp = CompileBroker::compiler(comp_level);
2965   if (comp == nullptr) {
2966     return "no compiler";
2967   } else {
2968     return (comp->name());
2969   }
2970 }
2971 
2972 jlong CompileBroker::total_compilation_ticks() {
2973   return _perf_total_compilation != nullptr ? _perf_total_compilation->get_value() : 0;
2974 }
2975 
2976 void CompileBroker::log_not_entrant(nmethod* nm) {
2977   _total_not_entrant_count++;
2978   if (CITime || log_is_enabled(Info, init)) {
2979     CompilerStatistics* stats = nullptr;
2980     int level = nm->comp_level();
2981     if (nm->is_scc()) {
2982       if (nm->preloaded()) {
2983         assert(level == CompLevel_full_optimization, "%d", level);
2984         level = CompLevel_full_optimization + 1;
2985       }
2986       stats = &_scc_stats_per_level[level - 1];
2987     } else {
2988       stats = &_stats_per_level[level - 1];
2989     }
2990     stats->_made_not_entrant._count++;
2991   }
2992 }
2993 
2994 void CompileBroker::print_times(const char* name, CompilerStatistics* stats) {
2995   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}",
2996                 name, stats->bytes_per_second(),
2997                 stats->_standard._time.seconds(), stats->_standard._bytes, stats->_standard._count,
2998                 stats->_osr._time.seconds(), stats->_osr._bytes, stats->_osr._count,
2999                 stats->_nmethods_size, stats->_nmethods_code_size);
3000 }
3001 
3002 static void print_helper(outputStream* st, const char* name, CompilerStatistics::Data data, bool print_time = true) {
3003   if (data._count > 0) {
3004     st->print("; %s: %4u methods", name, data._count);
3005     if (print_time) {
3006       st->print(" (in %.3fs)", data._time.seconds());
3007     }
3008   }
3009 }
3010 
3011 static void print_tier_helper(outputStream* st, const char* prefix, int tier, CompilerStatistics* stats) {
3012   st->print("    %s%d: %5u methods", prefix, tier, stats->_standard._count);
3013   if (stats->_standard._count > 0) {
3014     st->print(" (in %.3fs)", stats->_standard._time.seconds());
3015   }
3016   print_helper(st, "osr",     stats->_osr);
3017   print_helper(st, "bailout", stats->_bailout);
3018   print_helper(st, "invalid", stats->_invalidated);
3019   print_helper(st, "not_entrant", stats->_made_not_entrant, false);
3020   st->cr();
3021 }
3022 
3023 static void print_queue_info(outputStream* st, CompileQueue* queue) {
3024   if (queue != nullptr) {
3025     MutexLocker ml(queue->lock());
3026 
3027     uint  total_cnt = 0;
3028     uint active_cnt = 0;
3029     for (JavaThread* jt : *ThreadsSMRSupport::get_java_thread_list()) {
3030       guarantee(jt != nullptr, "");
3031       if (jt->is_Compiler_thread()) {
3032         CompilerThread* ct = (CompilerThread*)jt;
3033 
3034         guarantee(ct != nullptr, "");
3035         if (ct->queue() == queue) {
3036           ++total_cnt;
3037           CompileTask* task = ct->task();
3038           if (task != nullptr) {
3039             ++active_cnt;
3040           }
3041         }
3042       }
3043     }
3044 
3045     st->print("  %s (%d active / %d total threads): %u tasks",
3046               queue->name(), active_cnt, total_cnt, queue->size());
3047     if (queue->size() > 0) {
3048       uint counts[] = {0, 0, 0, 0, 0}; // T1 ... T5
3049       for (CompileTask* task = queue->first(); task != nullptr; task = task->next()) {
3050         int tier = task->comp_level();
3051         if (task->is_scc() && task->preload()) {
3052           assert(tier == CompLevel_full_optimization, "%d", tier);
3053           tier = CompLevel_full_optimization + 1;
3054         }
3055         counts[tier-1]++;
3056       }
3057       st->print(":");
3058       for (int tier = CompLevel_simple; tier <= CompilationPolicy::highest_compile_level() + 1; tier++) {
3059         uint cnt = counts[tier-1];
3060         if (cnt > 0) {
3061           st->print(" T%d: %u tasks;", tier, cnt);
3062         }
3063       }
3064     }
3065     st->cr();
3066 
3067 //    for (JavaThread* jt : *ThreadsSMRSupport::get_java_thread_list()) {
3068 //      guarantee(jt != nullptr, "");
3069 //      if (jt->is_Compiler_thread()) {
3070 //        CompilerThread* ct = (CompilerThread*)jt;
3071 //
3072 //        guarantee(ct != nullptr, "");
3073 //        if (ct->queue() == queue) {
3074 //          ResourceMark rm;
3075 //          CompileTask* task = ct->task();
3076 //          st->print("    %s: ", ct->name_raw());
3077 //          if (task != nullptr) {
3078 //            task->print(st, nullptr, true /*short_form*/, false /*cr*/);
3079 //          }
3080 //          st->cr();
3081 //        }
3082 //      }
3083 //    }
3084   }
3085 }
3086 void CompileBroker::print_statistics_on(outputStream* st) {
3087   st->print_cr("  Total: %u methods; %u bailouts, %u invalidated, %u non_entrant",
3088                _total_compile_count, _total_bailout_count, _total_invalidated_count, _total_not_entrant_count);
3089   for (int tier = CompLevel_simple; tier <= CompilationPolicy::highest_compile_level(); tier++) {
3090     print_tier_helper(st, "Tier", tier, &_stats_per_level[tier-1]);
3091   }
3092   st->cr();
3093 
3094   if (LoadCachedCode || StoreCachedCode) {
3095     for (int tier = CompLevel_simple; tier <= CompilationPolicy::highest_compile_level() + 1; tier++) {
3096       if (tier != CompLevel_full_profile) {
3097         print_tier_helper(st, "SC T", tier, &_scc_stats_per_level[tier - 1]);
3098       }
3099     }
3100     st->cr();
3101   }
3102 
3103   print_queue_info(st, _c1_compile_queue);
3104   print_queue_info(st, _c2_compile_queue);
3105   print_queue_info(st, _c3_compile_queue);
3106   print_queue_info(st, _sc1_compile_queue);
3107   print_queue_info(st, _sc2_compile_queue);
3108 }
3109 
3110 void CompileBroker::print_times(bool per_compiler, bool aggregate) {
3111   if (per_compiler) {
3112     if (aggregate) {
3113       tty->cr();
3114       tty->print_cr("[%dms] Individual compiler times (for compiled methods only)", (int)tty->time_stamp().milliseconds());
3115       tty->print_cr("------------------------------------------------");
3116       tty->cr();
3117     }
3118     for (unsigned int i = 0; i < sizeof(_compilers) / sizeof(AbstractCompiler*); i++) {
3119       AbstractCompiler* comp = _compilers[i];
3120       if (comp != nullptr) {
3121         print_times(comp->name(), comp->stats());
3122       }
3123     }
3124     if (_scc_stats._standard._count > 0) {
3125       print_times("SC", &_scc_stats);
3126     }
3127     if (aggregate) {
3128       tty->cr();
3129       tty->print_cr("Individual compilation Tier times (for compiled methods only)");
3130       tty->print_cr("------------------------------------------------");
3131       tty->cr();
3132     }
3133     char tier_name[256];
3134     for (int tier = CompLevel_simple; tier <= CompilationPolicy::highest_compile_level(); tier++) {
3135       CompilerStatistics* stats = &_stats_per_level[tier-1];
3136       os::snprintf_checked(tier_name, sizeof(tier_name), "Tier%d", tier);
3137       print_times(tier_name, stats);
3138     }
3139     for (int tier = CompLevel_simple; tier <= CompilationPolicy::highest_compile_level() + 1; tier++) {
3140       CompilerStatistics* stats = &_scc_stats_per_level[tier-1];
3141       if (stats->_standard._bytes > 0) {
3142         os::snprintf_checked(tier_name, sizeof(tier_name), "SC T%d", tier);
3143         print_times(tier_name, stats);
3144       }
3145     }
3146   }
3147 
3148   if (!aggregate) {
3149     return;
3150   }
3151 
3152   elapsedTimer standard_compilation = CompileBroker::_t_standard_compilation;
3153   elapsedTimer osr_compilation = CompileBroker::_t_osr_compilation;
3154   elapsedTimer total_compilation = CompileBroker::_t_total_compilation;
3155 
3156   uint standard_bytes_compiled = CompileBroker::_sum_standard_bytes_compiled;
3157   uint osr_bytes_compiled = CompileBroker::_sum_osr_bytes_compiled;
3158 
3159   uint standard_compile_count = CompileBroker::_total_standard_compile_count;
3160   uint osr_compile_count = CompileBroker::_total_osr_compile_count;
3161   uint total_compile_count = CompileBroker::_total_compile_count;
3162   uint total_bailout_count = CompileBroker::_total_bailout_count;
3163   uint total_invalidated_count = CompileBroker::_total_invalidated_count;
3164 
3165   uint nmethods_code_size = CompileBroker::_sum_nmethod_code_size;
3166   uint nmethods_size = CompileBroker::_sum_nmethod_size;
3167 
3168   tty->cr();
3169   tty->print_cr("Accumulated compiler times");
3170   tty->print_cr("----------------------------------------------------------");
3171                //0000000000111111111122222222223333333333444444444455555555556666666666
3172                //0123456789012345678901234567890123456789012345678901234567890123456789
3173   tty->print_cr("  Total compilation time   : %7.3f s", total_compilation.seconds());
3174   tty->print_cr("    Standard compilation   : %7.3f s, Average : %2.3f s",
3175                 standard_compilation.seconds(),
3176                 standard_compile_count == 0 ? 0.0 : standard_compilation.seconds() / standard_compile_count);
3177   tty->print_cr("    Bailed out compilation : %7.3f s, Average : %2.3f s",
3178                 CompileBroker::_t_bailedout_compilation.seconds(),
3179                 total_bailout_count == 0 ? 0.0 : CompileBroker::_t_bailedout_compilation.seconds() / total_bailout_count);
3180   tty->print_cr("    On stack replacement   : %7.3f s, Average : %2.3f s",
3181                 osr_compilation.seconds(),
3182                 osr_compile_count == 0 ? 0.0 : osr_compilation.seconds() / osr_compile_count);
3183   tty->print_cr("    Invalidated            : %7.3f s, Average : %2.3f s",
3184                 CompileBroker::_t_invalidated_compilation.seconds(),
3185                 total_invalidated_count == 0 ? 0.0 : CompileBroker::_t_invalidated_compilation.seconds() / total_invalidated_count);
3186 
3187   if (StoreCachedCode || LoadCachedCode) { // Check flags because SC cache could be closed already
3188     tty->cr();
3189     SCCache::print_timers_on(tty);
3190   }
3191   AbstractCompiler *comp = compiler(CompLevel_simple);
3192   if (comp != nullptr) {
3193     tty->cr();
3194     comp->print_timers();
3195   }
3196   comp = compiler(CompLevel_full_optimization);
3197   if (comp != nullptr) {
3198     tty->cr();
3199     comp->print_timers();
3200   }
3201   comp = _compilers[2];
3202   if (comp != nullptr) {
3203     tty->cr();
3204     comp->print_timers();
3205   }
3206 #if INCLUDE_JVMCI
3207   if (EnableJVMCI) {
3208     JVMCICompiler *jvmci_comp = JVMCICompiler::instance(false, JavaThread::current_or_null());
3209     if (jvmci_comp != nullptr && jvmci_comp != comp) {
3210       tty->cr();
3211       jvmci_comp->print_timers();
3212     }
3213   }
3214 #endif
3215 
3216   tty->cr();
3217   tty->print_cr("  Total compiled methods    : %8u methods", total_compile_count);
3218   tty->print_cr("    Standard compilation    : %8u methods", standard_compile_count);
3219   tty->print_cr("    On stack replacement    : %8u methods", osr_compile_count);
3220   uint tcb = osr_bytes_compiled + standard_bytes_compiled;
3221   tty->print_cr("  Total compiled bytecodes  : %8u bytes", tcb);
3222   tty->print_cr("    Standard compilation    : %8u bytes", standard_bytes_compiled);
3223   tty->print_cr("    On stack replacement    : %8u bytes", osr_bytes_compiled);
3224   double tcs = total_compilation.seconds();
3225   uint bps = tcs == 0.0 ? 0 : (uint)(tcb / tcs);
3226   tty->print_cr("  Average compilation speed : %8u bytes/s", bps);
3227   tty->cr();
3228   tty->print_cr("  nmethod code size         : %8u bytes", nmethods_code_size);
3229   tty->print_cr("  nmethod total size        : %8u bytes", nmethods_size);
3230 }
3231 
3232 // Print general/accumulated JIT information.
3233 void CompileBroker::print_info(outputStream *out) {
3234   if (out == nullptr) out = tty;
3235   out->cr();
3236   out->print_cr("======================");
3237   out->print_cr("   General JIT info   ");
3238   out->print_cr("======================");
3239   out->cr();
3240   out->print_cr("            JIT is : %7s",     should_compile_new_jobs() ? "on" : "off");
3241   out->print_cr("  Compiler threads : %7d",     (int)CICompilerCount);
3242   out->cr();
3243   out->print_cr("CodeCache overview");
3244   out->print_cr("--------------------------------------------------------");
3245   out->cr();
3246   out->print_cr("         Reserved size : " SIZE_FORMAT_W(7) " KB", CodeCache::max_capacity() / K);
3247   out->print_cr("        Committed size : " SIZE_FORMAT_W(7) " KB", CodeCache::capacity() / K);
3248   out->print_cr("  Unallocated capacity : " SIZE_FORMAT_W(7) " KB", CodeCache::unallocated_capacity() / K);
3249   out->cr();
3250 }
3251 
3252 // Note: tty_lock must not be held upon entry to this function.
3253 //       Print functions called from herein do "micro-locking" on tty_lock.
3254 //       That's a tradeoff which keeps together important blocks of output.
3255 //       At the same time, continuous tty_lock hold time is kept in check,
3256 //       preventing concurrently printing threads from stalling a long time.
3257 void CompileBroker::print_heapinfo(outputStream* out, const char* function, size_t granularity) {
3258   TimeStamp ts_total;
3259   TimeStamp ts_global;
3260   TimeStamp ts;
3261 
3262   bool allFun = !strcmp(function, "all");
3263   bool aggregate = !strcmp(function, "aggregate") || !strcmp(function, "analyze") || allFun;
3264   bool usedSpace = !strcmp(function, "UsedSpace") || allFun;
3265   bool freeSpace = !strcmp(function, "FreeSpace") || allFun;
3266   bool methodCount = !strcmp(function, "MethodCount") || allFun;
3267   bool methodSpace = !strcmp(function, "MethodSpace") || allFun;
3268   bool methodAge = !strcmp(function, "MethodAge") || allFun;
3269   bool methodNames = !strcmp(function, "MethodNames") || allFun;
3270   bool discard = !strcmp(function, "discard") || allFun;
3271 
3272   if (out == nullptr) {
3273     out = tty;
3274   }
3275 
3276   if (!(aggregate || usedSpace || freeSpace || methodCount || methodSpace || methodAge || methodNames || discard)) {
3277     out->print_cr("\n__ CodeHeapStateAnalytics: Function %s is not supported", function);
3278     out->cr();
3279     return;
3280   }
3281 
3282   ts_total.update(); // record starting point
3283 
3284   if (aggregate) {
3285     print_info(out);
3286   }
3287 
3288   // We hold the CodeHeapStateAnalytics_lock all the time, from here until we leave this function.
3289   // That prevents other threads from destroying (making inconsistent) our view on the CodeHeap.
3290   // When we request individual parts of the analysis via the jcmd interface, it is possible
3291   // that in between another thread (another jcmd user or the vm running into CodeCache OOM)
3292   // updated the aggregated data. We will then see a modified, but again consistent, view
3293   // on the CodeHeap. That's a tolerable tradeoff we have to accept because we can't hold
3294   // a lock across user interaction.
3295 
3296   // We should definitely acquire this lock before acquiring Compile_lock and CodeCache_lock.
3297   // CodeHeapStateAnalytics_lock may be held by a concurrent thread for a long time,
3298   // leading to an unnecessarily long hold time of the other locks we acquired before.
3299   ts.update(); // record starting point
3300   MutexLocker mu0(CodeHeapStateAnalytics_lock, Mutex::_safepoint_check_flag);
3301   out->print_cr("\n__ CodeHeapStateAnalytics lock wait took %10.3f seconds _________\n", ts.seconds());
3302 
3303   // Holding the CodeCache_lock protects from concurrent alterations of the CodeCache.
3304   // Unfortunately, such protection is not sufficient:
3305   // When a new nmethod is created via ciEnv::register_method(), the
3306   // Compile_lock is taken first. After some initializations,
3307   // nmethod::new_nmethod() takes over, grabbing the CodeCache_lock
3308   // immediately (after finalizing the oop references). To lock out concurrent
3309   // modifiers, we have to grab both locks as well in the described sequence.
3310   //
3311   // If we serve an "allFun" call, it is beneficial to hold CodeCache_lock and Compile_lock
3312   // for the entire duration of aggregation and printing. That makes sure we see
3313   // a consistent picture and do not run into issues caused by concurrent alterations.
3314   bool should_take_Compile_lock   = !SafepointSynchronize::is_at_safepoint() &&
3315                                     !Compile_lock->owned_by_self();
3316   bool should_take_CodeCache_lock = !SafepointSynchronize::is_at_safepoint() &&
3317                                     !CodeCache_lock->owned_by_self();
3318   bool take_global_lock_1   =  allFun && should_take_Compile_lock;
3319   bool take_global_lock_2   =  allFun && should_take_CodeCache_lock;
3320   bool take_function_lock_1 = !allFun && should_take_Compile_lock;
3321   bool take_function_lock_2 = !allFun && should_take_CodeCache_lock;
3322   bool take_global_locks    = take_global_lock_1 || take_global_lock_2;
3323   bool take_function_locks  = take_function_lock_1 || take_function_lock_2;
3324 
3325   ts_global.update(); // record starting point
3326 
3327   ConditionalMutexLocker mu1(Compile_lock, take_global_lock_1, Mutex::_safepoint_check_flag);
3328   ConditionalMutexLocker mu2(CodeCache_lock, take_global_lock_2, Mutex::_no_safepoint_check_flag);
3329   if (take_global_locks) {
3330     out->print_cr("\n__ Compile & CodeCache (global) lock wait took %10.3f seconds _________\n", ts_global.seconds());
3331     ts_global.update(); // record starting point
3332   }
3333 
3334   if (aggregate) {
3335     ts.update(); // record starting point
3336     ConditionalMutexLocker mu11(Compile_lock, take_function_lock_1,  Mutex::_safepoint_check_flag);
3337     ConditionalMutexLocker mu22(CodeCache_lock, take_function_lock_2, Mutex::_no_safepoint_check_flag);
3338     if (take_function_locks) {
3339       out->print_cr("\n__ Compile & CodeCache (function) lock wait took %10.3f seconds _________\n", ts.seconds());
3340     }
3341 
3342     ts.update(); // record starting point
3343     CodeCache::aggregate(out, granularity);
3344     if (take_function_locks) {
3345       out->print_cr("\n__ Compile & CodeCache (function) lock hold took %10.3f seconds _________\n", ts.seconds());
3346     }
3347   }
3348 
3349   if (usedSpace) CodeCache::print_usedSpace(out);
3350   if (freeSpace) CodeCache::print_freeSpace(out);
3351   if (methodCount) CodeCache::print_count(out);
3352   if (methodSpace) CodeCache::print_space(out);
3353   if (methodAge) CodeCache::print_age(out);
3354   if (methodNames) {
3355     if (allFun) {
3356       // print_names() can only be used safely if the locks have been continuously held
3357       // since aggregation begin. That is true only for function "all".
3358       CodeCache::print_names(out);
3359     } else {
3360       out->print_cr("\nCodeHeapStateAnalytics: Function 'MethodNames' is only available as part of function 'all'");
3361     }
3362   }
3363   if (discard) CodeCache::discard(out);
3364 
3365   if (take_global_locks) {
3366     out->print_cr("\n__ Compile & CodeCache (global) lock hold took %10.3f seconds _________\n", ts_global.seconds());
3367   }
3368   out->print_cr("\n__ CodeHeapStateAnalytics total duration %10.3f seconds _________\n", ts_total.seconds());
3369 }
--- EOF ---