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