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