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