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