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