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