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