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