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