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