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