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