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