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