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