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