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