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