Wed, 31 Mar 2010 16:51:18 -0700
6938627: Make temporary directory use property java.io.tmpdir when specified
Summary: Get java.io.tmpdir property in os::get_temp_directory() and call this instead of harcoding "/tmp". Don't assume trailing file_separator either.
Reviewed-by: dholmes, kamg
1 /*
2 * Copyright 1999-2010 Sun Microsystems, Inc. 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
20 * CA 95054 USA or visit www.sun.com if you need additional information or
21 * have any questions.
22 *
23 */
25 #include "incls/_precompiled.incl"
26 #include "incls/_compileBroker.cpp.incl"
28 #ifdef DTRACE_ENABLED
30 // Only bother with this argument setup if dtrace is available
32 HS_DTRACE_PROBE_DECL8(hotspot, method__compile__begin,
33 char*, intptr_t, char*, intptr_t, char*, intptr_t, char*, intptr_t);
34 HS_DTRACE_PROBE_DECL9(hotspot, method__compile__end,
35 char*, intptr_t, char*, intptr_t, char*, intptr_t, char*, intptr_t, bool);
37 #define DTRACE_METHOD_COMPILE_BEGIN_PROBE(compiler, method) \
38 { \
39 char* comp_name = (char*)(compiler)->name(); \
40 symbolOop klass_name = (method)->klass_name(); \
41 symbolOop name = (method)->name(); \
42 symbolOop signature = (method)->signature(); \
43 HS_DTRACE_PROBE8(hotspot, method__compile__begin, \
44 comp_name, strlen(comp_name), \
45 klass_name->bytes(), klass_name->utf8_length(), \
46 name->bytes(), name->utf8_length(), \
47 signature->bytes(), signature->utf8_length()); \
48 }
50 #define DTRACE_METHOD_COMPILE_END_PROBE(compiler, method, success) \
51 { \
52 char* comp_name = (char*)(compiler)->name(); \
53 symbolOop klass_name = (method)->klass_name(); \
54 symbolOop name = (method)->name(); \
55 symbolOop signature = (method)->signature(); \
56 HS_DTRACE_PROBE9(hotspot, method__compile__end, \
57 comp_name, strlen(comp_name), \
58 klass_name->bytes(), klass_name->utf8_length(), \
59 name->bytes(), name->utf8_length(), \
60 signature->bytes(), signature->utf8_length(), (success)); \
61 }
63 #else // ndef DTRACE_ENABLED
65 #define DTRACE_METHOD_COMPILE_BEGIN_PROBE(compiler, method)
66 #define DTRACE_METHOD_COMPILE_END_PROBE(compiler, method, success)
68 #endif // ndef DTRACE_ENABLED
70 bool CompileBroker::_initialized = false;
71 volatile bool CompileBroker::_should_block = false;
72 volatile jint CompileBroker::_should_compile_new_jobs = run_compilation;
74 // The installed compiler(s)
75 AbstractCompiler* CompileBroker::_compilers[2];
77 // These counters are used for assigning id's to each compilation
78 uint CompileBroker::_compilation_id = 0;
79 uint CompileBroker::_osr_compilation_id = 0;
81 // Debugging information
82 int CompileBroker::_last_compile_type = no_compile;
83 int CompileBroker::_last_compile_level = CompLevel_none;
84 char CompileBroker::_last_method_compiled[CompileBroker::name_buffer_length];
86 // Performance counters
87 PerfCounter* CompileBroker::_perf_total_compilation = NULL;
88 PerfCounter* CompileBroker::_perf_osr_compilation = NULL;
89 PerfCounter* CompileBroker::_perf_standard_compilation = NULL;
91 PerfCounter* CompileBroker::_perf_total_bailout_count = NULL;
92 PerfCounter* CompileBroker::_perf_total_invalidated_count = NULL;
93 PerfCounter* CompileBroker::_perf_total_compile_count = NULL;
94 PerfCounter* CompileBroker::_perf_total_osr_compile_count = NULL;
95 PerfCounter* CompileBroker::_perf_total_standard_compile_count = NULL;
97 PerfCounter* CompileBroker::_perf_sum_osr_bytes_compiled = NULL;
98 PerfCounter* CompileBroker::_perf_sum_standard_bytes_compiled = NULL;
99 PerfCounter* CompileBroker::_perf_sum_nmethod_size = NULL;
100 PerfCounter* CompileBroker::_perf_sum_nmethod_code_size = NULL;
102 PerfStringVariable* CompileBroker::_perf_last_method = NULL;
103 PerfStringVariable* CompileBroker::_perf_last_failed_method = NULL;
104 PerfStringVariable* CompileBroker::_perf_last_invalidated_method = NULL;
105 PerfVariable* CompileBroker::_perf_last_compile_type = NULL;
106 PerfVariable* CompileBroker::_perf_last_compile_size = NULL;
107 PerfVariable* CompileBroker::_perf_last_failed_type = NULL;
108 PerfVariable* CompileBroker::_perf_last_invalidated_type = NULL;
110 // Timers and counters for generating statistics
111 elapsedTimer CompileBroker::_t_total_compilation;
112 elapsedTimer CompileBroker::_t_osr_compilation;
113 elapsedTimer CompileBroker::_t_standard_compilation;
115 int CompileBroker::_total_bailout_count = 0;
116 int CompileBroker::_total_invalidated_count = 0;
117 int CompileBroker::_total_compile_count = 0;
118 int CompileBroker::_total_osr_compile_count = 0;
119 int CompileBroker::_total_standard_compile_count = 0;
121 int CompileBroker::_sum_osr_bytes_compiled = 0;
122 int CompileBroker::_sum_standard_bytes_compiled = 0;
123 int CompileBroker::_sum_nmethod_size = 0;
124 int CompileBroker::_sum_nmethod_code_size = 0;
126 CompileQueue* CompileBroker::_method_queue = NULL;
127 CompileTask* CompileBroker::_task_free_list = NULL;
129 GrowableArray<CompilerThread*>* CompileBroker::_method_threads = NULL;
131 // CompileTaskWrapper
132 //
133 // Assign this task to the current thread. Deallocate the task
134 // when the compilation is complete.
135 class CompileTaskWrapper : StackObj {
136 public:
137 CompileTaskWrapper(CompileTask* task);
138 ~CompileTaskWrapper();
139 };
141 CompileTaskWrapper::CompileTaskWrapper(CompileTask* task) {
142 CompilerThread* thread = CompilerThread::current();
143 thread->set_task(task);
144 CompileLog* log = thread->log();
145 if (log != NULL) task->log_task_start(log);
146 }
148 CompileTaskWrapper::~CompileTaskWrapper() {
149 CompilerThread* thread = CompilerThread::current();
150 CompileTask* task = thread->task();
151 CompileLog* log = thread->log();
152 if (log != NULL) task->log_task_done(log);
153 thread->set_task(NULL);
154 task->set_code_handle(NULL);
155 DEBUG_ONLY(thread->set_env((ciEnv*)badAddress));
156 if (task->is_blocking()) {
157 MutexLocker notifier(task->lock(), thread);
158 task->mark_complete();
159 // Notify the waiting thread that the compilation has completed.
160 task->lock()->notify_all();
161 } else {
162 task->mark_complete();
164 // By convention, the compiling thread is responsible for
165 // recycling a non-blocking CompileTask.
166 CompileBroker::free_task(task);
167 }
168 }
171 // ------------------------------------------------------------------
172 // CompileTask::initialize
173 void CompileTask::initialize(int compile_id,
174 methodHandle method,
175 int osr_bci,
176 int comp_level,
177 methodHandle hot_method,
178 int hot_count,
179 const char* comment,
180 bool is_blocking) {
181 assert(!_lock->is_locked(), "bad locking");
183 _compile_id = compile_id;
184 _method = JNIHandles::make_global(method);
185 _osr_bci = osr_bci;
186 _is_blocking = is_blocking;
187 _comp_level = comp_level;
188 _num_inlined_bytecodes = 0;
190 _is_complete = false;
191 _is_success = false;
192 _code_handle = NULL;
194 _hot_method = NULL;
195 _hot_count = hot_count;
196 _time_queued = 0; // tidy
197 _comment = comment;
199 if (LogCompilation) {
200 _time_queued = os::elapsed_counter();
201 if (hot_method.not_null()) {
202 if (hot_method == method) {
203 _hot_method = _method;
204 } else {
205 _hot_method = JNIHandles::make_global(hot_method);
206 }
207 }
208 }
210 _next = NULL;
211 }
213 // ------------------------------------------------------------------
214 // CompileTask::code/set_code
215 nmethod* CompileTask::code() const {
216 if (_code_handle == NULL) return NULL;
217 return _code_handle->code();
218 }
219 void CompileTask::set_code(nmethod* nm) {
220 if (_code_handle == NULL && nm == NULL) return;
221 guarantee(_code_handle != NULL, "");
222 _code_handle->set_code(nm);
223 if (nm == NULL) _code_handle = NULL; // drop the handle also
224 }
226 // ------------------------------------------------------------------
227 // CompileTask::free
228 void CompileTask::free() {
229 set_code(NULL);
230 assert(!_lock->is_locked(), "Should not be locked when freed");
231 if (_hot_method != NULL && _hot_method != _method) {
232 JNIHandles::destroy_global(_hot_method);
233 }
234 JNIHandles::destroy_global(_method);
235 }
238 // ------------------------------------------------------------------
239 // CompileTask::print
240 void CompileTask::print() {
241 tty->print("<CompileTask compile_id=%d ", _compile_id);
242 tty->print("method=");
243 ((methodOop)JNIHandles::resolve(_method))->print_name(tty);
244 tty->print_cr(" osr_bci=%d is_blocking=%s is_complete=%s is_success=%s>",
245 _osr_bci, bool_to_str(_is_blocking),
246 bool_to_str(_is_complete), bool_to_str(_is_success));
247 }
249 // ------------------------------------------------------------------
250 // CompileTask::print_line_on_error
251 //
252 // This function is called by fatal error handler when the thread
253 // causing troubles is a compiler thread.
254 //
255 // Do not grab any lock, do not allocate memory.
256 //
257 // Otherwise it's the same as CompileTask::print_line()
258 //
259 void CompileTask::print_line_on_error(outputStream* st, char* buf, int buflen) {
260 methodOop method = (methodOop)JNIHandles::resolve(_method);
262 // print compiler name
263 st->print("%s:", CompileBroker::compiler(comp_level())->name());
265 // print compilation number
266 st->print("%3d", compile_id());
268 // print method attributes
269 const bool is_osr = osr_bci() != CompileBroker::standard_entry_bci;
270 { const char blocking_char = is_blocking() ? 'b' : ' ';
271 const char compile_type = is_osr ? '%' : ' ';
272 const char sync_char = method->is_synchronized() ? 's' : ' ';
273 const char exception_char = method->has_exception_handler() ? '!' : ' ';
274 const char tier_char =
275 is_highest_tier_compile(comp_level()) ? ' ' : ('0' + comp_level());
276 st->print("%c%c%c%c%c ", compile_type, sync_char, exception_char, blocking_char, tier_char);
277 }
279 // Use buf to get method name and signature
280 if (method != NULL) st->print("%s", method->name_and_sig_as_C_string(buf, buflen));
282 // print osr_bci if any
283 if (is_osr) st->print(" @ %d", osr_bci());
285 // print method size
286 st->print_cr(" (%d bytes)", method->code_size());
287 }
289 // ------------------------------------------------------------------
290 // CompileTask::print_line
291 void CompileTask::print_line() {
292 Thread *thread = Thread::current();
293 methodHandle method(thread,
294 (methodOop)JNIHandles::resolve(method_handle()));
295 ResourceMark rm(thread);
297 ttyLocker ttyl; // keep the following output all in one block
299 // print compiler name if requested
300 if (CIPrintCompilerName) tty->print("%s:", CompileBroker::compiler(comp_level())->name());
302 // print compilation number
303 tty->print("%3d", compile_id());
305 // print method attributes
306 const bool is_osr = osr_bci() != CompileBroker::standard_entry_bci;
307 { const char blocking_char = is_blocking() ? 'b' : ' ';
308 const char compile_type = is_osr ? '%' : ' ';
309 const char sync_char = method->is_synchronized() ? 's' : ' ';
310 const char exception_char = method->has_exception_handler() ? '!' : ' ';
311 const char tier_char =
312 is_highest_tier_compile(comp_level()) ? ' ' : ('0' + comp_level());
313 tty->print("%c%c%c%c%c ", compile_type, sync_char, exception_char, blocking_char, tier_char);
314 }
316 // print method name
317 method->print_short_name(tty);
319 // print osr_bci if any
320 if (is_osr) tty->print(" @ %d", osr_bci());
322 // print method size
323 tty->print_cr(" (%d bytes)", method->code_size());
324 }
327 // ------------------------------------------------------------------
328 // CompileTask::log_task
329 void CompileTask::log_task(xmlStream* log) {
330 Thread* thread = Thread::current();
331 methodHandle method(thread,
332 (methodOop)JNIHandles::resolve(method_handle()));
333 ResourceMark rm(thread);
335 // <task id='9' method='M' osr_bci='X' level='1' blocking='1' stamp='1.234'>
336 if (_compile_id != 0) log->print(" compile_id='%d'", _compile_id);
337 if (_osr_bci != CompileBroker::standard_entry_bci) {
338 log->print(" compile_kind='osr'"); // same as nmethod::compile_kind
339 } // else compile_kind='c2c'
340 if (!method.is_null()) log->method(method);
341 if (_osr_bci != CompileBroker::standard_entry_bci) {
342 log->print(" osr_bci='%d'", _osr_bci);
343 }
344 if (_comp_level != CompLevel_highest_tier) {
345 log->print(" level='%d'", _comp_level);
346 }
347 if (_is_blocking) {
348 log->print(" blocking='1'");
349 }
350 log->stamp();
351 }
354 // ------------------------------------------------------------------
355 // CompileTask::log_task_queued
356 void CompileTask::log_task_queued() {
357 Thread* thread = Thread::current();
358 ttyLocker ttyl;
359 ResourceMark rm(thread);
361 xtty->begin_elem("task_queued");
362 log_task(xtty);
363 if (_comment != NULL) {
364 xtty->print(" comment='%s'", _comment);
365 }
366 if (_hot_method != NULL) {
367 methodHandle hot(thread,
368 (methodOop)JNIHandles::resolve(_hot_method));
369 methodHandle method(thread,
370 (methodOop)JNIHandles::resolve(_method));
371 if (hot() != method()) {
372 xtty->method(hot);
373 }
374 }
375 if (_hot_count != 0) {
376 xtty->print(" hot_count='%d'", _hot_count);
377 }
378 xtty->end_elem();
379 }
382 // ------------------------------------------------------------------
383 // CompileTask::log_task_start
384 void CompileTask::log_task_start(CompileLog* log) {
385 log->begin_head("task");
386 log_task(log);
387 log->end_head();
388 }
391 // ------------------------------------------------------------------
392 // CompileTask::log_task_done
393 void CompileTask::log_task_done(CompileLog* log) {
394 Thread* thread = Thread::current();
395 methodHandle method(thread,
396 (methodOop)JNIHandles::resolve(method_handle()));
397 ResourceMark rm(thread);
399 // <task_done ... stamp='1.234'> </task>
400 nmethod* nm = code();
401 log->begin_elem("task_done success='%d' nmsize='%d' count='%d'",
402 _is_success, nm == NULL ? 0 : nm->instructions_size(),
403 method->invocation_count());
404 int bec = method->backedge_count();
405 if (bec != 0) log->print(" backedge_count='%d'", bec);
406 // Note: "_is_complete" is about to be set, but is not.
407 if (_num_inlined_bytecodes != 0) {
408 log->print(" inlined_bytes='%d'", _num_inlined_bytecodes);
409 }
410 log->stamp();
411 log->end_elem();
412 log->tail("task");
413 log->clear_identities(); // next task will have different CI
414 if (log->unflushed_count() > 2000) {
415 log->flush();
416 }
417 log->mark_file_end();
418 }
422 // ------------------------------------------------------------------
423 // CompileQueue::add
424 //
425 // Add a CompileTask to a CompileQueue
426 void CompileQueue::add(CompileTask* task) {
427 assert(lock()->owned_by_self(), "must own lock");
429 task->set_next(NULL);
431 if (_last == NULL) {
432 // The compile queue is empty.
433 assert(_first == NULL, "queue is empty");
434 _first = task;
435 _last = task;
436 } else {
437 // Append the task to the queue.
438 assert(_last->next() == NULL, "not last");
439 _last->set_next(task);
440 _last = task;
441 }
443 // Mark the method as being in the compile queue.
444 ((methodOop)JNIHandles::resolve(task->method_handle()))->set_queued_for_compilation();
446 if (CIPrintCompileQueue) {
447 print();
448 }
450 if (LogCompilation && xtty != NULL) {
451 task->log_task_queued();
452 }
454 // Notify CompilerThreads that a task is available.
455 lock()->notify();
456 }
459 // ------------------------------------------------------------------
460 // CompileQueue::get
461 //
462 // Get the next CompileTask from a CompileQueue
463 CompileTask* CompileQueue::get() {
464 MutexLocker locker(lock());
466 // Wait for an available CompileTask.
467 while (_first == NULL) {
468 // There is no work to be done right now. Wait.
469 lock()->wait();
470 }
472 CompileTask* task = _first;
474 // Update queue first and last
475 _first =_first->next();
476 if (_first == NULL) {
477 _last = NULL;
478 }
480 return task;
482 }
485 // ------------------------------------------------------------------
486 // CompileQueue::print
487 void CompileQueue::print() {
488 tty->print_cr("Contents of %s", name());
489 tty->print_cr("----------------------");
490 CompileTask* task = _first;
491 while (task != NULL) {
492 task->print_line();
493 task = task->next();
494 }
495 tty->print_cr("----------------------");
496 }
498 CompilerCounters::CompilerCounters(const char* thread_name, int instance, TRAPS) {
500 _current_method[0] = '\0';
501 _compile_type = CompileBroker::no_compile;
503 if (UsePerfData) {
504 ResourceMark rm;
506 // create the thread instance name space string - don't create an
507 // instance subspace if instance is -1 - keeps the adapterThread
508 // counters from having a ".0" namespace.
509 const char* thread_i = (instance == -1) ? thread_name :
510 PerfDataManager::name_space(thread_name, instance);
513 char* name = PerfDataManager::counter_name(thread_i, "method");
514 _perf_current_method =
515 PerfDataManager::create_string_variable(SUN_CI, name,
516 cmname_buffer_length,
517 _current_method, CHECK);
519 name = PerfDataManager::counter_name(thread_i, "type");
520 _perf_compile_type = PerfDataManager::create_variable(SUN_CI, name,
521 PerfData::U_None,
522 (jlong)_compile_type,
523 CHECK);
525 name = PerfDataManager::counter_name(thread_i, "time");
526 _perf_time = PerfDataManager::create_counter(SUN_CI, name,
527 PerfData::U_Ticks, CHECK);
529 name = PerfDataManager::counter_name(thread_i, "compiles");
530 _perf_compiles = PerfDataManager::create_counter(SUN_CI, name,
531 PerfData::U_Events, CHECK);
532 }
533 }
536 // ------------------------------------------------------------------
537 // CompileBroker::compilation_init
538 //
539 // Initialize the Compilation object
540 void CompileBroker::compilation_init() {
541 _last_method_compiled[0] = '\0';
543 // Set the interface to the current compiler(s).
544 #ifdef COMPILER1
545 _compilers[0] = new Compiler();
546 #ifndef COMPILER2
547 _compilers[1] = _compilers[0];
548 #endif
549 #endif // COMPILER1
551 #ifdef COMPILER2
552 _compilers[1] = new C2Compiler();
553 #ifndef COMPILER1
554 _compilers[0] = _compilers[1];
555 #endif
556 #endif // COMPILER2
558 // Initialize the CompileTask free list
559 _task_free_list = NULL;
561 // Start the CompilerThreads
562 init_compiler_threads(compiler_count());
565 // totalTime performance counter is always created as it is required
566 // by the implementation of java.lang.management.CompilationMBean.
567 {
568 EXCEPTION_MARK;
569 _perf_total_compilation =
570 PerfDataManager::create_counter(JAVA_CI, "totalTime",
571 PerfData::U_Ticks, CHECK);
572 }
575 if (UsePerfData) {
577 EXCEPTION_MARK;
579 // create the jvmstat performance counters
580 _perf_osr_compilation =
581 PerfDataManager::create_counter(SUN_CI, "osrTime",
582 PerfData::U_Ticks, CHECK);
584 _perf_standard_compilation =
585 PerfDataManager::create_counter(SUN_CI, "standardTime",
586 PerfData::U_Ticks, CHECK);
588 _perf_total_bailout_count =
589 PerfDataManager::create_counter(SUN_CI, "totalBailouts",
590 PerfData::U_Events, CHECK);
592 _perf_total_invalidated_count =
593 PerfDataManager::create_counter(SUN_CI, "totalInvalidates",
594 PerfData::U_Events, CHECK);
596 _perf_total_compile_count =
597 PerfDataManager::create_counter(SUN_CI, "totalCompiles",
598 PerfData::U_Events, CHECK);
599 _perf_total_osr_compile_count =
600 PerfDataManager::create_counter(SUN_CI, "osrCompiles",
601 PerfData::U_Events, CHECK);
603 _perf_total_standard_compile_count =
604 PerfDataManager::create_counter(SUN_CI, "standardCompiles",
605 PerfData::U_Events, CHECK);
607 _perf_sum_osr_bytes_compiled =
608 PerfDataManager::create_counter(SUN_CI, "osrBytes",
609 PerfData::U_Bytes, CHECK);
611 _perf_sum_standard_bytes_compiled =
612 PerfDataManager::create_counter(SUN_CI, "standardBytes",
613 PerfData::U_Bytes, CHECK);
615 _perf_sum_nmethod_size =
616 PerfDataManager::create_counter(SUN_CI, "nmethodSize",
617 PerfData::U_Bytes, CHECK);
619 _perf_sum_nmethod_code_size =
620 PerfDataManager::create_counter(SUN_CI, "nmethodCodeSize",
621 PerfData::U_Bytes, CHECK);
623 _perf_last_method =
624 PerfDataManager::create_string_variable(SUN_CI, "lastMethod",
625 CompilerCounters::cmname_buffer_length,
626 "", CHECK);
628 _perf_last_failed_method =
629 PerfDataManager::create_string_variable(SUN_CI, "lastFailedMethod",
630 CompilerCounters::cmname_buffer_length,
631 "", CHECK);
633 _perf_last_invalidated_method =
634 PerfDataManager::create_string_variable(SUN_CI, "lastInvalidatedMethod",
635 CompilerCounters::cmname_buffer_length,
636 "", CHECK);
638 _perf_last_compile_type =
639 PerfDataManager::create_variable(SUN_CI, "lastType",
640 PerfData::U_None,
641 (jlong)CompileBroker::no_compile,
642 CHECK);
644 _perf_last_compile_size =
645 PerfDataManager::create_variable(SUN_CI, "lastSize",
646 PerfData::U_Bytes,
647 (jlong)CompileBroker::no_compile,
648 CHECK);
651 _perf_last_failed_type =
652 PerfDataManager::create_variable(SUN_CI, "lastFailedType",
653 PerfData::U_None,
654 (jlong)CompileBroker::no_compile,
655 CHECK);
657 _perf_last_invalidated_type =
658 PerfDataManager::create_variable(SUN_CI, "lastInvalidatedType",
659 PerfData::U_None,
660 (jlong)CompileBroker::no_compile,
661 CHECK);
662 }
664 _initialized = true;
665 }
669 // ------------------------------------------------------------------
670 // CompileBroker::make_compiler_thread
671 CompilerThread* CompileBroker::make_compiler_thread(const char* name, CompileQueue* queue, CompilerCounters* counters, TRAPS) {
672 CompilerThread* compiler_thread = NULL;
674 klassOop k =
675 SystemDictionary::resolve_or_fail(vmSymbolHandles::java_lang_Thread(),
676 true, CHECK_0);
677 instanceKlassHandle klass (THREAD, k);
678 instanceHandle thread_oop = klass->allocate_instance_handle(CHECK_0);
679 Handle string = java_lang_String::create_from_str(name, CHECK_0);
681 // Initialize thread_oop to put it into the system threadGroup
682 Handle thread_group (THREAD, Universe::system_thread_group());
683 JavaValue result(T_VOID);
684 JavaCalls::call_special(&result, thread_oop,
685 klass,
686 vmSymbolHandles::object_initializer_name(),
687 vmSymbolHandles::threadgroup_string_void_signature(),
688 thread_group,
689 string,
690 CHECK_0);
692 {
693 MutexLocker mu(Threads_lock, THREAD);
694 compiler_thread = new CompilerThread(queue, counters);
695 // At this point the new CompilerThread data-races with this startup
696 // thread (which I believe is the primoridal thread and NOT the VM
697 // thread). This means Java bytecodes being executed at startup can
698 // queue compile jobs which will run at whatever default priority the
699 // newly created CompilerThread runs at.
702 // At this point it may be possible that no osthread was created for the
703 // JavaThread due to lack of memory. We would have to throw an exception
704 // in that case. However, since this must work and we do not allow
705 // exceptions anyway, check and abort if this fails.
707 if (compiler_thread == NULL || compiler_thread->osthread() == NULL){
708 vm_exit_during_initialization("java.lang.OutOfMemoryError",
709 "unable to create new native thread");
710 }
712 java_lang_Thread::set_thread(thread_oop(), compiler_thread);
714 // Note that this only sets the JavaThread _priority field, which by
715 // definition is limited to Java priorities and not OS priorities.
716 // The os-priority is set in the CompilerThread startup code itself
717 java_lang_Thread::set_priority(thread_oop(), NearMaxPriority);
718 // CLEANUP PRIORITIES: This -if- statement hids a bug whereby the compiler
719 // threads never have their OS priority set. The assumption here is to
720 // enable the Performance group to do flag tuning, figure out a suitable
721 // CompilerThreadPriority, and then remove this 'if' statement (and
722 // comment) and unconditionally set the priority.
724 // Compiler Threads should be at the highest Priority
725 if ( CompilerThreadPriority != -1 )
726 os::set_native_priority( compiler_thread, CompilerThreadPriority );
727 else
728 os::set_native_priority( compiler_thread, os::java_to_os_priority[NearMaxPriority]);
730 // Note that I cannot call os::set_priority because it expects Java
731 // priorities and I am *explicitly* using OS priorities so that it's
732 // possible to set the compiler thread priority higher than any Java
733 // thread.
735 java_lang_Thread::set_daemon(thread_oop());
737 compiler_thread->set_threadObj(thread_oop());
738 Threads::add(compiler_thread);
739 Thread::start(compiler_thread);
740 }
741 // Let go of Threads_lock before yielding
742 os::yield(); // make sure that the compiler thread is started early (especially helpful on SOLARIS)
744 return compiler_thread;
745 }
748 // ------------------------------------------------------------------
749 // CompileBroker::init_compiler_threads
750 //
751 // Initialize the compilation queue
752 void CompileBroker::init_compiler_threads(int compiler_count) {
753 EXCEPTION_MARK;
755 _method_queue = new CompileQueue("MethodQueue", MethodCompileQueue_lock);
756 _method_threads =
757 new (ResourceObj::C_HEAP) GrowableArray<CompilerThread*>(compiler_count, true);
759 char name_buffer[256];
760 int i;
761 for (i = 0; i < compiler_count; i++) {
762 // Create a name for our thread.
763 sprintf(name_buffer, "CompilerThread%d", i);
764 CompilerCounters* counters = new CompilerCounters("compilerThread", i, CHECK);
766 CompilerThread* new_thread = make_compiler_thread(name_buffer, _method_queue, counters, CHECK);
767 _method_threads->append(new_thread);
768 }
769 if (UsePerfData) {
770 PerfDataManager::create_constant(SUN_CI, "threads", PerfData::U_Bytes,
771 compiler_count, CHECK);
772 }
773 }
775 // ------------------------------------------------------------------
776 // CompileBroker::is_idle
777 bool CompileBroker::is_idle() {
778 if (!_method_queue->is_empty()) {
779 return false;
780 } else {
781 int num_threads = _method_threads->length();
782 for (int i=0; i<num_threads; i++) {
783 if (_method_threads->at(i)->task() != NULL) {
784 return false;
785 }
786 }
788 // No pending or active compilations.
789 return true;
790 }
791 }
794 // ------------------------------------------------------------------
795 // CompileBroker::compile_method
796 //
797 // Request compilation of a method.
798 void CompileBroker::compile_method_base(methodHandle method,
799 int osr_bci,
800 int comp_level,
801 methodHandle hot_method,
802 int hot_count,
803 const char* comment,
804 TRAPS) {
805 // do nothing if compiler thread(s) is not available
806 if (!_initialized ) {
807 return;
808 }
810 guarantee(!method->is_abstract(), "cannot compile abstract methods");
811 assert(method->method_holder()->klass_part()->oop_is_instance(),
812 "sanity check");
813 assert(!instanceKlass::cast(method->method_holder())->is_not_initialized(),
814 "method holder must be initialized");
816 if (CIPrintRequests) {
817 tty->print("request: ");
818 method->print_short_name(tty);
819 if (osr_bci != InvocationEntryBci) {
820 tty->print(" osr_bci: %d", osr_bci);
821 }
822 tty->print(" comment: %s count: %d", comment, hot_count);
823 if (!hot_method.is_null()) {
824 tty->print(" hot: ");
825 if (hot_method() != method()) {
826 hot_method->print_short_name(tty);
827 } else {
828 tty->print("yes");
829 }
830 }
831 tty->cr();
832 }
834 // A request has been made for compilation. Before we do any
835 // real work, check to see if the method has been compiled
836 // in the meantime with a definitive result.
837 if (compilation_is_complete(method, osr_bci, comp_level)) {
838 return;
839 }
841 // If this method is already in the compile queue, then
842 // we do not block the current thread.
843 if (compilation_is_in_queue(method, osr_bci)) {
844 // We may want to decay our counter a bit here to prevent
845 // multiple denied requests for compilation. This is an
846 // open compilation policy issue. Note: The other possibility,
847 // in the case that this is a blocking compile request, is to have
848 // all subsequent blocking requesters wait for completion of
849 // ongoing compiles. Note that in this case we'll need a protocol
850 // for freeing the associated compile tasks. [Or we could have
851 // a single static monitor on which all these waiters sleep.]
852 return;
853 }
855 // Outputs from the following MutexLocker block:
856 CompileTask* task = NULL;
857 bool blocking = false;
859 // Acquire our lock.
860 {
861 MutexLocker locker(_method_queue->lock(), THREAD);
863 // Make sure the method has not slipped into the queues since
864 // last we checked; note that those checks were "fast bail-outs".
865 // Here we need to be more careful, see 14012000 below.
866 if (compilation_is_in_queue(method, osr_bci)) {
867 return;
868 }
870 // We need to check again to see if the compilation has
871 // completed. A previous compilation may have registered
872 // some result.
873 if (compilation_is_complete(method, osr_bci, comp_level)) {
874 return;
875 }
877 // We now know that this compilation is not pending, complete,
878 // or prohibited. Assign a compile_id to this compilation
879 // and check to see if it is in our [Start..Stop) range.
880 uint compile_id = assign_compile_id(method, osr_bci);
881 if (compile_id == 0) {
882 // The compilation falls outside the allowed range.
883 return;
884 }
886 // Should this thread wait for completion of the compile?
887 blocking = is_compile_blocking(method, osr_bci);
889 // We will enter the compilation in the queue.
890 // 14012000: Note that this sets the queued_for_compile bits in
891 // the target method. We can now reason that a method cannot be
892 // queued for compilation more than once, as follows:
893 // Before a thread queues a task for compilation, it first acquires
894 // the compile queue lock, then checks if the method's queued bits
895 // are set or it has already been compiled. Thus there can not be two
896 // instances of a compilation task for the same method on the
897 // compilation queue. Consider now the case where the compilation
898 // thread has already removed a task for that method from the queue
899 // and is in the midst of compiling it. In this case, the
900 // queued_for_compile bits must be set in the method (and these
901 // will be visible to the current thread, since the bits were set
902 // under protection of the compile queue lock, which we hold now.
903 // When the compilation completes, the compiler thread first sets
904 // the compilation result and then clears the queued_for_compile
905 // bits. Neither of these actions are protected by a barrier (or done
906 // under the protection of a lock), so the only guarantee we have
907 // (on machines with TSO (Total Store Order)) is that these values
908 // will update in that order. As a result, the only combinations of
909 // these bits that the current thread will see are, in temporal order:
910 // <RESULT, QUEUE> :
911 // <0, 1> : in compile queue, but not yet compiled
912 // <1, 1> : compiled but queue bit not cleared
913 // <1, 0> : compiled and queue bit cleared
914 // Because we first check the queue bits then check the result bits,
915 // we are assured that we cannot introduce a duplicate task.
916 // Note that if we did the tests in the reverse order (i.e. check
917 // result then check queued bit), we could get the result bit before
918 // the compilation completed, and the queue bit after the compilation
919 // completed, and end up introducing a "duplicate" (redundant) task.
920 // In that case, the compiler thread should first check if a method
921 // has already been compiled before trying to compile it.
922 // NOTE: in the event that there are multiple compiler threads and
923 // there is de-optimization/recompilation, things will get hairy,
924 // and in that case it's best to protect both the testing (here) of
925 // these bits, and their updating (here and elsewhere) under a
926 // common lock.
927 task = create_compile_task(_method_queue,
928 compile_id, method,
929 osr_bci, comp_level,
930 hot_method, hot_count, comment,
931 blocking);
932 }
934 if (blocking) {
935 wait_for_completion(task);
936 }
937 }
940 nmethod* CompileBroker::compile_method(methodHandle method, int osr_bci,
941 methodHandle hot_method, int hot_count,
942 const char* comment, TRAPS) {
943 // make sure arguments make sense
944 assert(method->method_holder()->klass_part()->oop_is_instance(), "not an instance method");
945 assert(osr_bci == InvocationEntryBci || (0 <= osr_bci && osr_bci < method->code_size()), "bci out of range");
946 assert(!method->is_abstract() && (osr_bci == InvocationEntryBci || !method->is_native()), "cannot compile abstract/native methods");
947 assert(!instanceKlass::cast(method->method_holder())->is_not_initialized(), "method holder must be initialized");
949 int comp_level = CompilationPolicy::policy()->compilation_level(method, osr_bci);
951 #ifdef TIERED
952 if (TieredCompilation && StressTieredRuntime) {
953 static int flipper = 0;
954 if (is_even(flipper++)) {
955 comp_level = CompLevel_fast_compile;
956 } else {
957 comp_level = CompLevel_full_optimization;
958 }
959 }
960 #ifdef SPARC
961 // QQQ FIX ME
962 // C2 only returns long results in G1 and c1 doesn't understand so disallow c2
963 // compiles of long results
964 if (TieredCompilation && method()->result_type() == T_LONG) {
965 comp_level = CompLevel_fast_compile;
966 }
967 #endif // SPARC
968 #endif // TIERED
970 // return quickly if possible
972 // lock, make sure that the compilation
973 // isn't prohibited in a straightforward way.
975 if (compiler(comp_level) == NULL || compilation_is_prohibited(method, osr_bci, comp_level)) {
976 return NULL;
977 }
979 if (osr_bci == InvocationEntryBci) {
980 // standard compilation
981 nmethod* method_code = method->code();
982 if (method_code != NULL
983 #ifdef TIERED
984 && ( method_code->is_compiled_by_c2() || comp_level == CompLevel_fast_compile )
985 #endif // TIERED
986 ) {
987 return method_code;
988 }
989 if (method->is_not_compilable(comp_level)) return NULL;
991 if (UseCodeCacheFlushing) {
992 nmethod* saved = CodeCache::find_and_remove_saved_code(method());
993 if (saved != NULL) {
994 method->set_code(method, saved);
995 return saved;
996 }
997 }
999 } else {
1000 // osr compilation
1001 #ifndef TIERED
1002 // seems like an assert of dubious value
1003 assert(comp_level == CompLevel_full_optimization,
1004 "all OSR compiles are assumed to be at a single compilation lavel");
1005 #endif // TIERED
1006 nmethod* nm = method->lookup_osr_nmethod_for(osr_bci);
1007 if (nm != NULL) return nm;
1008 if (method->is_not_osr_compilable()) return NULL;
1009 }
1011 assert(!HAS_PENDING_EXCEPTION, "No exception should be present");
1012 // some prerequisites that are compiler specific
1013 if (compiler(comp_level)->is_c2()) {
1014 method->constants()->resolve_string_constants(CHECK_0);
1015 // Resolve all classes seen in the signature of the method
1016 // we are compiling.
1017 methodOopDesc::load_signature_classes(method, CHECK_0);
1018 }
1020 // If the method is native, do the lookup in the thread requesting
1021 // the compilation. Native lookups can load code, which is not
1022 // permitted during compilation.
1023 //
1024 // Note: A native method implies non-osr compilation which is
1025 // checked with an assertion at the entry of this method.
1026 if (method->is_native()) {
1027 bool in_base_library;
1028 address adr = NativeLookup::lookup(method, in_base_library, THREAD);
1029 if (HAS_PENDING_EXCEPTION) {
1030 // In case of an exception looking up the method, we just forget
1031 // about it. The interpreter will kick-in and throw the exception.
1032 method->set_not_compilable(); // implies is_not_osr_compilable()
1033 CLEAR_PENDING_EXCEPTION;
1034 return NULL;
1035 }
1036 assert(method->has_native_function(), "must have native code by now");
1037 }
1039 // RedefineClasses() has replaced this method; just return
1040 if (method->is_old()) {
1041 return NULL;
1042 }
1044 // JVMTI -- post_compile_event requires jmethod_id() that may require
1045 // a lock the compiling thread can not acquire. Prefetch it here.
1046 if (JvmtiExport::should_post_compiled_method_load()) {
1047 method->jmethod_id();
1048 }
1050 // If the compiler is shut off due to code cache flushing or otherwise,
1051 // fail out now so blocking compiles dont hang the java thread
1052 if (!should_compile_new_jobs() || (UseCodeCacheFlushing && CodeCache::needs_flushing())) {
1053 method->invocation_counter()->decay();
1054 method->backedge_counter()->decay();
1055 return NULL;
1056 }
1058 // do the compilation
1059 if (method->is_native()) {
1060 if (!PreferInterpreterNativeStubs) {
1061 (void) AdapterHandlerLibrary::create_native_wrapper(method);
1062 } else {
1063 return NULL;
1064 }
1065 } else {
1066 compile_method_base(method, osr_bci, comp_level, hot_method, hot_count, comment, CHECK_0);
1067 }
1069 // return requested nmethod
1070 return osr_bci == InvocationEntryBci ? method->code() : method->lookup_osr_nmethod_for(osr_bci);
1071 }
1074 // ------------------------------------------------------------------
1075 // CompileBroker::compilation_is_complete
1076 //
1077 // See if compilation of this method is already complete.
1078 bool CompileBroker::compilation_is_complete(methodHandle method,
1079 int osr_bci,
1080 int comp_level) {
1081 bool is_osr = (osr_bci != standard_entry_bci);
1082 if (is_osr) {
1083 if (method->is_not_osr_compilable()) {
1084 return true;
1085 } else {
1086 nmethod* result = method->lookup_osr_nmethod_for(osr_bci);
1087 return (result != NULL);
1088 }
1089 } else {
1090 if (method->is_not_compilable(comp_level)) {
1091 return true;
1092 } else {
1093 nmethod* result = method->code();
1094 if (result == NULL) return false;
1095 #ifdef TIERED
1096 if (comp_level == CompLevel_fast_compile) {
1097 // At worst the code is from c1
1098 return true;
1099 }
1100 // comp level must be full opt
1101 return result->is_compiled_by_c2();
1102 #endif // TIERED
1103 return true;
1104 }
1105 }
1106 }
1109 // ------------------------------------------------------------------
1110 // CompileBroker::compilation_is_in_queue
1111 //
1112 // See if this compilation is already requested.
1113 //
1114 // Implementation note: there is only a single "is in queue" bit
1115 // for each method. This means that the check below is overly
1116 // conservative in the sense that an osr compilation in the queue
1117 // will block a normal compilation from entering the queue (and vice
1118 // versa). This can be remedied by a full queue search to disambiguate
1119 // cases. If it is deemed profitible, this may be done.
1120 bool CompileBroker::compilation_is_in_queue(methodHandle method,
1121 int osr_bci) {
1122 return method->queued_for_compilation();
1123 }
1126 // ------------------------------------------------------------------
1127 // CompileBroker::compilation_is_prohibited
1128 //
1129 // See if this compilation is not allowed.
1130 bool CompileBroker::compilation_is_prohibited(methodHandle method, int osr_bci, int comp_level) {
1131 bool is_native = method->is_native();
1132 // Some compilers may not support the compilation of natives.
1133 // QQQ this needs some work ought to only record not compilable at
1134 // the specified level
1135 if (is_native &&
1136 (!CICompileNatives || !compiler(comp_level)->supports_native())) {
1137 method->set_not_compilable_quietly();
1138 return true;
1139 }
1141 bool is_osr = (osr_bci != standard_entry_bci);
1142 // Some compilers may not support on stack replacement.
1143 if (is_osr &&
1144 (!CICompileOSR || !compiler(comp_level)->supports_osr())) {
1145 method->set_not_osr_compilable();
1146 return true;
1147 }
1149 // The method may be explicitly excluded by the user.
1150 bool quietly;
1151 if (CompilerOracle::should_exclude(method, quietly)) {
1152 if (!quietly) {
1153 // This does not happen quietly...
1154 ResourceMark rm;
1155 tty->print("### Excluding %s:%s",
1156 method->is_native() ? "generation of native wrapper" : "compile",
1157 (method->is_static() ? " static" : ""));
1158 method->print_short_name(tty);
1159 tty->cr();
1160 }
1161 method->set_not_compilable_quietly();
1162 }
1164 return false;
1165 }
1168 // ------------------------------------------------------------------
1169 // CompileBroker::assign_compile_id
1170 //
1171 // Assign a serialized id number to this compilation request. If the
1172 // number falls out of the allowed range, return a 0. OSR
1173 // compilations may be numbered separately from regular compilations
1174 // if certain debugging flags are used.
1175 uint CompileBroker::assign_compile_id(methodHandle method, int osr_bci) {
1176 assert(_method_queue->lock()->owner() == JavaThread::current(),
1177 "must hold the compilation queue lock");
1178 bool is_osr = (osr_bci != standard_entry_bci);
1179 assert(!method->is_native(), "no longer compile natives");
1180 uint id;
1181 if (CICountOSR && is_osr) {
1182 id = ++_osr_compilation_id;
1183 if ((uint)CIStartOSR <= id && id < (uint)CIStopOSR) {
1184 return id;
1185 }
1186 } else {
1187 id = ++_compilation_id;
1188 if ((uint)CIStart <= id && id < (uint)CIStop) {
1189 return id;
1190 }
1191 }
1193 // Method was not in the appropriate compilation range.
1194 method->set_not_compilable_quietly();
1195 return 0;
1196 }
1199 // ------------------------------------------------------------------
1200 // CompileBroker::is_compile_blocking
1201 //
1202 // Should the current thread be blocked until this compilation request
1203 // has been fulfilled?
1204 bool CompileBroker::is_compile_blocking(methodHandle method, int osr_bci) {
1205 return !BackgroundCompilation;
1206 }
1209 // ------------------------------------------------------------------
1210 // CompileBroker::preload_classes
1211 void CompileBroker::preload_classes(methodHandle method, TRAPS) {
1212 // Move this code over from c1_Compiler.cpp
1213 ShouldNotReachHere();
1214 }
1217 // ------------------------------------------------------------------
1218 // CompileBroker::create_compile_task
1219 //
1220 // Create a CompileTask object representing the current request for
1221 // compilation. Add this task to the queue.
1222 CompileTask* CompileBroker::create_compile_task(CompileQueue* queue,
1223 int compile_id,
1224 methodHandle method,
1225 int osr_bci,
1226 int comp_level,
1227 methodHandle hot_method,
1228 int hot_count,
1229 const char* comment,
1230 bool blocking) {
1231 CompileTask* new_task = allocate_task();
1232 new_task->initialize(compile_id, method, osr_bci, comp_level,
1233 hot_method, hot_count, comment,
1234 blocking);
1235 queue->add(new_task);
1236 return new_task;
1237 }
1240 // ------------------------------------------------------------------
1241 // CompileBroker::allocate_task
1242 //
1243 // Allocate a CompileTask, from the free list if possible.
1244 CompileTask* CompileBroker::allocate_task() {
1245 MutexLocker locker(CompileTaskAlloc_lock);
1246 CompileTask* task = NULL;
1247 if (_task_free_list != NULL) {
1248 task = _task_free_list;
1249 _task_free_list = task->next();
1250 task->set_next(NULL);
1251 } else {
1252 task = new CompileTask();
1253 task->set_next(NULL);
1254 }
1255 return task;
1256 }
1259 // ------------------------------------------------------------------
1260 // CompileBroker::free_task
1261 //
1262 // Add a task to the free list.
1263 void CompileBroker::free_task(CompileTask* task) {
1264 MutexLocker locker(CompileTaskAlloc_lock);
1265 task->free();
1266 task->set_next(_task_free_list);
1267 _task_free_list = task;
1268 }
1271 // ------------------------------------------------------------------
1272 // CompileBroker::wait_for_completion
1273 //
1274 // Wait for the given method CompileTask to complete.
1275 void CompileBroker::wait_for_completion(CompileTask* task) {
1276 if (CIPrintCompileQueue) {
1277 tty->print_cr("BLOCKING FOR COMPILE");
1278 }
1280 assert(task->is_blocking(), "can only wait on blocking task");
1282 JavaThread *thread = JavaThread::current();
1283 thread->set_blocked_on_compilation(true);
1285 methodHandle method(thread,
1286 (methodOop)JNIHandles::resolve(task->method_handle()));
1287 {
1288 MutexLocker waiter(task->lock(), thread);
1290 while (!task->is_complete())
1291 task->lock()->wait();
1292 }
1293 // It is harmless to check this status without the lock, because
1294 // completion is a stable property (until the task object is recycled).
1295 assert(task->is_complete(), "Compilation should have completed");
1296 assert(task->code_handle() == NULL, "must be reset");
1298 thread->set_blocked_on_compilation(false);
1300 // By convention, the waiter is responsible for recycling a
1301 // blocking CompileTask. Since there is only one waiter ever
1302 // waiting on a CompileTask, we know that no one else will
1303 // be using this CompileTask; we can free it.
1304 free_task(task);
1305 }
1307 // ------------------------------------------------------------------
1308 // CompileBroker::compiler_thread_loop
1309 //
1310 // The main loop run by a CompilerThread.
1311 void CompileBroker::compiler_thread_loop() {
1312 CompilerThread* thread = CompilerThread::current();
1313 CompileQueue* queue = thread->queue();
1315 // For the thread that initializes the ciObjectFactory
1316 // this resource mark holds all the shared objects
1317 ResourceMark rm;
1319 // First thread to get here will initialize the compiler interface
1321 if (!ciObjectFactory::is_initialized()) {
1322 ASSERT_IN_VM;
1323 MutexLocker only_one (CompileThread_lock, thread);
1324 if (!ciObjectFactory::is_initialized()) {
1325 ciObjectFactory::initialize();
1326 }
1327 }
1329 // Open a log.
1330 if (LogCompilation) {
1331 init_compiler_thread_log();
1332 }
1333 CompileLog* log = thread->log();
1334 if (log != NULL) {
1335 log->begin_elem("start_compile_thread thread='" UINTX_FORMAT "' process='%d'",
1336 os::current_thread_id(),
1337 os::current_process_id());
1338 log->stamp();
1339 log->end_elem();
1340 }
1342 while (true) {
1343 {
1344 // We need this HandleMark to avoid leaking VM handles.
1345 HandleMark hm(thread);
1347 if (CodeCache::unallocated_capacity() < CodeCacheMinimumFreeSpace) {
1348 // the code cache is really full
1349 handle_full_code_cache();
1350 } else if (UseCodeCacheFlushing && CodeCache::needs_flushing()) {
1351 // Attempt to start cleaning the code cache while there is still a little headroom
1352 NMethodSweeper::handle_full_code_cache(false);
1353 }
1355 CompileTask* task = queue->get();
1357 // Give compiler threads an extra quanta. They tend to be bursty and
1358 // this helps the compiler to finish up the job.
1359 if( CompilerThreadHintNoPreempt )
1360 os::hint_no_preempt();
1362 // trace per thread time and compile statistics
1363 CompilerCounters* counters = ((CompilerThread*)thread)->counters();
1364 PerfTraceTimedEvent(counters->time_counter(), counters->compile_counter());
1366 // Assign the task to the current thread. Mark this compilation
1367 // thread as active for the profiler.
1368 CompileTaskWrapper ctw(task);
1369 nmethodLocker result_handle; // (handle for the nmethod produced by this task)
1370 task->set_code_handle(&result_handle);
1371 methodHandle method(thread,
1372 (methodOop)JNIHandles::resolve(task->method_handle()));
1374 // Never compile a method if breakpoints are present in it
1375 if (method()->number_of_breakpoints() == 0) {
1376 // Compile the method.
1377 if ((UseCompiler || AlwaysCompileLoopMethods) && CompileBroker::should_compile_new_jobs()) {
1378 #ifdef COMPILER1
1379 // Allow repeating compilations for the purpose of benchmarking
1380 // compile speed. This is not useful for customers.
1381 if (CompilationRepeat != 0) {
1382 int compile_count = CompilationRepeat;
1383 while (compile_count > 0) {
1384 invoke_compiler_on_method(task);
1385 nmethod* nm = method->code();
1386 if (nm != NULL) {
1387 nm->make_zombie();
1388 method->clear_code();
1389 }
1390 compile_count--;
1391 }
1392 }
1393 #endif /* COMPILER1 */
1394 invoke_compiler_on_method(task);
1395 } else {
1396 // After compilation is disabled, remove remaining methods from queue
1397 method->clear_queued_for_compilation();
1398 }
1399 }
1400 }
1401 }
1402 }
1405 // ------------------------------------------------------------------
1406 // CompileBroker::init_compiler_thread_log
1407 //
1408 // Set up state required by +LogCompilation.
1409 void CompileBroker::init_compiler_thread_log() {
1410 CompilerThread* thread = CompilerThread::current();
1411 char fileBuf[4*K];
1412 FILE* fp = NULL;
1413 char* file = NULL;
1414 intx thread_id = os::current_thread_id();
1415 for (int try_temp_dir = 1; try_temp_dir >= 0; try_temp_dir--) {
1416 const char* dir = (try_temp_dir ? os::get_temp_directory() : NULL);
1417 if (dir == NULL) {
1418 jio_snprintf(fileBuf, sizeof(fileBuf), "hs_c" UINTX_FORMAT "_pid%u.log",
1419 thread_id, os::current_process_id());
1420 } else {
1421 jio_snprintf(fileBuf, sizeof(fileBuf),
1422 "%s%shs_c" UINTX_FORMAT "_pid%u.log", dir,
1423 os::file_separator(), thread_id, os::current_process_id());
1424 }
1425 fp = fopen(fileBuf, "at");
1426 if (fp != NULL) {
1427 file = NEW_C_HEAP_ARRAY(char, strlen(fileBuf)+1);
1428 strcpy(file, fileBuf);
1429 break;
1430 }
1431 }
1432 if (fp == NULL) {
1433 warning("Cannot open log file: %s", fileBuf);
1434 } else {
1435 if (LogCompilation && Verbose)
1436 tty->print_cr("Opening compilation log %s", file);
1437 CompileLog* log = new(ResourceObj::C_HEAP) CompileLog(file, fp, thread_id);
1438 thread->init_log(log);
1440 if (xtty != NULL) {
1441 ttyLocker ttyl;
1443 // Record any per thread log files
1444 xtty->elem("thread_logfile thread='%d' filename='%s'", thread_id, file);
1445 }
1446 }
1447 }
1449 // ------------------------------------------------------------------
1450 // CompileBroker::set_should_block
1451 //
1452 // Set _should_block.
1453 // Call this from the VM, with Threads_lock held and a safepoint requested.
1454 void CompileBroker::set_should_block() {
1455 assert(Threads_lock->owner() == Thread::current(), "must have threads lock");
1456 assert(SafepointSynchronize::is_at_safepoint(), "must be at a safepoint already");
1457 #ifndef PRODUCT
1458 if (PrintCompilation && (Verbose || WizardMode))
1459 tty->print_cr("notifying compiler thread pool to block");
1460 #endif
1461 _should_block = true;
1462 }
1464 // ------------------------------------------------------------------
1465 // CompileBroker::maybe_block
1466 //
1467 // Call this from the compiler at convenient points, to poll for _should_block.
1468 void CompileBroker::maybe_block() {
1469 if (_should_block) {
1470 #ifndef PRODUCT
1471 if (PrintCompilation && (Verbose || WizardMode))
1472 tty->print_cr("compiler thread " INTPTR_FORMAT " poll detects block request", Thread::current());
1473 #endif
1474 ThreadInVMfromNative tivfn(JavaThread::current());
1475 }
1476 }
1479 // ------------------------------------------------------------------
1480 // CompileBroker::invoke_compiler_on_method
1481 //
1482 // Compile a method.
1483 //
1484 void CompileBroker::invoke_compiler_on_method(CompileTask* task) {
1485 if (PrintCompilation) {
1486 ResourceMark rm;
1487 task->print_line();
1488 }
1489 elapsedTimer time;
1491 CompilerThread* thread = CompilerThread::current();
1492 ResourceMark rm(thread);
1494 // Common flags.
1495 uint compile_id = task->compile_id();
1496 int osr_bci = task->osr_bci();
1497 bool is_osr = (osr_bci != standard_entry_bci);
1498 bool should_log = (thread->log() != NULL);
1499 bool should_break = false;
1500 {
1501 // create the handle inside it's own block so it can't
1502 // accidentally be referenced once the thread transitions to
1503 // native. The NoHandleMark before the transition should catch
1504 // any cases where this occurs in the future.
1505 methodHandle method(thread,
1506 (methodOop)JNIHandles::resolve(task->method_handle()));
1507 should_break = check_break_at(method, compile_id, is_osr);
1508 if (should_log && !CompilerOracle::should_log(method)) {
1509 should_log = false;
1510 }
1511 assert(!method->is_native(), "no longer compile natives");
1513 // Save information about this method in case of failure.
1514 set_last_compile(thread, method, is_osr, task->comp_level());
1516 DTRACE_METHOD_COMPILE_BEGIN_PROBE(compiler(task->comp_level()), method);
1517 }
1519 // Allocate a new set of JNI handles.
1520 push_jni_handle_block();
1521 jobject target_handle = JNIHandles::make_local(thread, JNIHandles::resolve(task->method_handle()));
1522 int compilable = ciEnv::MethodCompilable;
1523 {
1524 int system_dictionary_modification_counter;
1525 {
1526 MutexLocker locker(Compile_lock, thread);
1527 system_dictionary_modification_counter = SystemDictionary::number_of_modifications();
1528 }
1530 NoHandleMark nhm;
1531 ThreadToNativeFromVM ttn(thread);
1533 ciEnv ci_env(task, system_dictionary_modification_counter);
1534 if (should_break) {
1535 ci_env.set_break_at_compile(true);
1536 }
1537 if (should_log) {
1538 ci_env.set_log(thread->log());
1539 }
1540 assert(thread->env() == &ci_env, "set by ci_env");
1541 // The thread-env() field is cleared in ~CompileTaskWrapper.
1543 // Cache Jvmti state
1544 ci_env.cache_jvmti_state();
1546 // Cache DTrace flags
1547 ci_env.cache_dtrace_flags();
1549 ciMethod* target = ci_env.get_method_from_handle(target_handle);
1551 TraceTime t1("compilation", &time);
1553 compiler(task->comp_level())->compile_method(&ci_env, target, osr_bci);
1555 if (!ci_env.failing() && task->code() == NULL) {
1556 //assert(false, "compiler should always document failure");
1557 // The compiler elected, without comment, not to register a result.
1558 // Do not attempt further compilations of this method.
1559 ci_env.record_method_not_compilable("compile failed");
1560 }
1562 if (ci_env.failing()) {
1563 // Copy this bit to the enclosing block:
1564 compilable = ci_env.compilable();
1565 if (PrintCompilation) {
1566 const char* reason = ci_env.failure_reason();
1567 if (compilable == ciEnv::MethodCompilable_not_at_tier) {
1568 if (is_highest_tier_compile(ci_env.comp_level())) {
1569 // Already at highest tier, promote to not compilable.
1570 compilable = ciEnv::MethodCompilable_never;
1571 } else {
1572 tty->print_cr("%3d COMPILE SKIPPED: %s (retry at different tier)", compile_id, reason);
1573 }
1574 }
1576 if (compilable == ciEnv::MethodCompilable_never) {
1577 tty->print_cr("%3d COMPILE SKIPPED: %s (not retryable)", compile_id, reason);
1578 } else if (compilable == ciEnv::MethodCompilable) {
1579 tty->print_cr("%3d COMPILE SKIPPED: %s", compile_id, reason);
1580 }
1581 }
1582 } else {
1583 task->mark_success();
1584 task->set_num_inlined_bytecodes(ci_env.num_inlined_bytecodes());
1585 }
1586 }
1587 pop_jni_handle_block();
1589 methodHandle method(thread,
1590 (methodOop)JNIHandles::resolve(task->method_handle()));
1592 DTRACE_METHOD_COMPILE_END_PROBE(compiler(task->comp_level()), method, task->is_success());
1594 collect_statistics(thread, time, task);
1596 if (compilable == ciEnv::MethodCompilable_never) {
1597 if (is_osr) {
1598 method->set_not_osr_compilable();
1599 } else {
1600 method->set_not_compilable_quietly();
1601 }
1602 } else if (compilable == ciEnv::MethodCompilable_not_at_tier) {
1603 method->set_not_compilable_quietly(task->comp_level());
1604 }
1606 // Note that the queued_for_compilation bits are cleared without
1607 // protection of a mutex. [They were set by the requester thread,
1608 // when adding the task to the complie queue -- at which time the
1609 // compile queue lock was held. Subsequently, we acquired the compile
1610 // queue lock to get this task off the compile queue; thus (to belabour
1611 // the point somewhat) our clearing of the bits must be occurring
1612 // only after the setting of the bits. See also 14012000 above.
1613 method->clear_queued_for_compilation();
1615 #ifdef ASSERT
1616 if (CollectedHeap::fired_fake_oom()) {
1617 // The current compile received a fake OOM during compilation so
1618 // go ahead and exit the VM since the test apparently succeeded
1619 tty->print_cr("*** Shutting down VM after successful fake OOM");
1620 vm_exit(0);
1621 }
1622 #endif
1623 }
1626 // ------------------------------------------------------------------
1627 // CompileBroker::handle_full_code_cache
1628 //
1629 // The CodeCache is full. Print out warning and disable compilation or
1630 // try code cache cleaning so compilation can continue later.
1631 void CompileBroker::handle_full_code_cache() {
1632 UseInterpreter = true;
1633 if (UseCompiler || AlwaysCompileLoopMethods ) {
1634 CompilerThread* thread = CompilerThread::current();
1635 CompileLog* log = thread->log();
1636 if (log != NULL) {
1637 log->begin_elem("code_cache_full");
1638 log->stamp();
1639 log->end_elem();
1640 }
1641 #ifndef PRODUCT
1642 warning("CodeCache is full. Compiler has been disabled");
1643 if (CompileTheWorld || ExitOnFullCodeCache) {
1644 before_exit(JavaThread::current());
1645 exit_globals(); // will delete tty
1646 vm_direct_exit(CompileTheWorld ? 0 : 1);
1647 }
1648 #endif
1649 if (UseCodeCacheFlushing) {
1650 NMethodSweeper::handle_full_code_cache(true);
1651 } else {
1652 UseCompiler = false;
1653 AlwaysCompileLoopMethods = false;
1654 }
1655 }
1656 }
1658 // ------------------------------------------------------------------
1659 // CompileBroker::set_last_compile
1660 //
1661 // Record this compilation for debugging purposes.
1662 void CompileBroker::set_last_compile(CompilerThread* thread, methodHandle method, bool is_osr, int comp_level) {
1663 ResourceMark rm;
1664 char* method_name = method->name()->as_C_string();
1665 strncpy(_last_method_compiled, method_name, CompileBroker::name_buffer_length);
1666 char current_method[CompilerCounters::cmname_buffer_length];
1667 size_t maxLen = CompilerCounters::cmname_buffer_length;
1669 if (UsePerfData) {
1670 const char* class_name = method->method_holder()->klass_part()->name()->as_C_string();
1672 size_t s1len = strlen(class_name);
1673 size_t s2len = strlen(method_name);
1675 // check if we need to truncate the string
1676 if (s1len + s2len + 2 > maxLen) {
1678 // the strategy is to lop off the leading characters of the
1679 // class name and the trailing characters of the method name.
1681 if (s2len + 2 > maxLen) {
1682 // lop of the entire class name string, let snprintf handle
1683 // truncation of the method name.
1684 class_name += s1len; // null string
1685 }
1686 else {
1687 // lop off the extra characters from the front of the class name
1688 class_name += ((s1len + s2len + 2) - maxLen);
1689 }
1690 }
1692 jio_snprintf(current_method, maxLen, "%s %s", class_name, method_name);
1693 }
1695 if (CICountOSR && is_osr) {
1696 _last_compile_type = osr_compile;
1697 } else {
1698 _last_compile_type = normal_compile;
1699 }
1700 _last_compile_level = comp_level;
1702 if (UsePerfData) {
1703 CompilerCounters* counters = thread->counters();
1704 counters->set_current_method(current_method);
1705 counters->set_compile_type((jlong)_last_compile_type);
1706 }
1707 }
1710 // ------------------------------------------------------------------
1711 // CompileBroker::push_jni_handle_block
1712 //
1713 // Push on a new block of JNI handles.
1714 void CompileBroker::push_jni_handle_block() {
1715 JavaThread* thread = JavaThread::current();
1717 // Allocate a new block for JNI handles.
1718 // Inlined code from jni_PushLocalFrame()
1719 JNIHandleBlock* java_handles = thread->active_handles();
1720 JNIHandleBlock* compile_handles = JNIHandleBlock::allocate_block(thread);
1721 assert(compile_handles != NULL && java_handles != NULL, "should not be NULL");
1722 compile_handles->set_pop_frame_link(java_handles); // make sure java handles get gc'd.
1723 thread->set_active_handles(compile_handles);
1724 }
1727 // ------------------------------------------------------------------
1728 // CompileBroker::pop_jni_handle_block
1729 //
1730 // Pop off the current block of JNI handles.
1731 void CompileBroker::pop_jni_handle_block() {
1732 JavaThread* thread = JavaThread::current();
1734 // Release our JNI handle block
1735 JNIHandleBlock* compile_handles = thread->active_handles();
1736 JNIHandleBlock* java_handles = compile_handles->pop_frame_link();
1737 thread->set_active_handles(java_handles);
1738 compile_handles->set_pop_frame_link(NULL);
1739 JNIHandleBlock::release_block(compile_handles, thread); // may block
1740 }
1743 // ------------------------------------------------------------------
1744 // CompileBroker::check_break_at
1745 //
1746 // Should the compilation break at the current compilation.
1747 bool CompileBroker::check_break_at(methodHandle method, int compile_id, bool is_osr) {
1748 if (CICountOSR && is_osr && (compile_id == CIBreakAtOSR)) {
1749 return true;
1750 } else if( CompilerOracle::should_break_at(method) ) { // break when compiling
1751 return true;
1752 } else {
1753 return (compile_id == CIBreakAt);
1754 }
1755 }
1757 // ------------------------------------------------------------------
1758 // CompileBroker::collect_statistics
1759 //
1760 // Collect statistics about the compilation.
1762 void CompileBroker::collect_statistics(CompilerThread* thread, elapsedTimer time, CompileTask* task) {
1763 bool success = task->is_success();
1764 methodHandle method (thread, (methodOop)JNIHandles::resolve(task->method_handle()));
1765 uint compile_id = task->compile_id();
1766 bool is_osr = (task->osr_bci() != standard_entry_bci);
1767 nmethod* code = task->code();
1768 CompilerCounters* counters = thread->counters();
1770 assert(code == NULL || code->is_locked_by_vm(), "will survive the MutexLocker");
1771 MutexLocker locker(CompileStatistics_lock);
1773 // _perf variables are production performance counters which are
1774 // updated regardless of the setting of the CITime and CITimeEach flags
1775 //
1776 if (!success) {
1777 _total_bailout_count++;
1778 if (UsePerfData) {
1779 _perf_last_failed_method->set_value(counters->current_method());
1780 _perf_last_failed_type->set_value(counters->compile_type());
1781 _perf_total_bailout_count->inc();
1782 }
1783 } else if (code == NULL) {
1784 if (UsePerfData) {
1785 _perf_last_invalidated_method->set_value(counters->current_method());
1786 _perf_last_invalidated_type->set_value(counters->compile_type());
1787 _perf_total_invalidated_count->inc();
1788 }
1789 _total_invalidated_count++;
1790 } else {
1791 // Compilation succeeded
1793 // update compilation ticks - used by the implementation of
1794 // java.lang.management.CompilationMBean
1795 _perf_total_compilation->inc(time.ticks());
1797 if (CITime) {
1798 _t_total_compilation.add(time);
1799 if (is_osr) {
1800 _t_osr_compilation.add(time);
1801 _sum_osr_bytes_compiled += method->code_size() + task->num_inlined_bytecodes();
1802 } else {
1803 _t_standard_compilation.add(time);
1804 _sum_standard_bytes_compiled += method->code_size() + task->num_inlined_bytecodes();
1805 }
1806 }
1808 if (UsePerfData) {
1809 // save the name of the last method compiled
1810 _perf_last_method->set_value(counters->current_method());
1811 _perf_last_compile_type->set_value(counters->compile_type());
1812 _perf_last_compile_size->set_value(method->code_size() +
1813 task->num_inlined_bytecodes());
1814 if (is_osr) {
1815 _perf_osr_compilation->inc(time.ticks());
1816 _perf_sum_osr_bytes_compiled->inc(method->code_size() + task->num_inlined_bytecodes());
1817 } else {
1818 _perf_standard_compilation->inc(time.ticks());
1819 _perf_sum_standard_bytes_compiled->inc(method->code_size() + task->num_inlined_bytecodes());
1820 }
1821 }
1823 if (CITimeEach) {
1824 float bytes_per_sec = 1.0 * (method->code_size() + task->num_inlined_bytecodes()) / time.seconds();
1825 tty->print_cr("%3d seconds: %f bytes/sec : %f (bytes %d + %d inlined)",
1826 compile_id, time.seconds(), bytes_per_sec, method->code_size(), task->num_inlined_bytecodes());
1827 }
1829 // Collect counts of successful compilations
1830 _sum_nmethod_size += code->total_size();
1831 _sum_nmethod_code_size += code->code_size();
1832 _total_compile_count++;
1834 if (UsePerfData) {
1835 _perf_sum_nmethod_size->inc(code->total_size());
1836 _perf_sum_nmethod_code_size->inc(code->code_size());
1837 _perf_total_compile_count->inc();
1838 }
1840 if (is_osr) {
1841 if (UsePerfData) _perf_total_osr_compile_count->inc();
1842 _total_osr_compile_count++;
1843 } else {
1844 if (UsePerfData) _perf_total_standard_compile_count->inc();
1845 _total_standard_compile_count++;
1846 }
1847 }
1848 // set the current method for the thread to null
1849 if (UsePerfData) counters->set_current_method("");
1850 }
1854 void CompileBroker::print_times() {
1855 tty->cr();
1856 tty->print_cr("Accumulated compiler times (for compiled methods only)");
1857 tty->print_cr("------------------------------------------------");
1858 //0000000000111111111122222222223333333333444444444455555555556666666666
1859 //0123456789012345678901234567890123456789012345678901234567890123456789
1860 tty->print_cr(" Total compilation time : %6.3f s", CompileBroker::_t_total_compilation.seconds());
1861 tty->print_cr(" Standard compilation : %6.3f s, Average : %2.3f",
1862 CompileBroker::_t_standard_compilation.seconds(),
1863 CompileBroker::_t_standard_compilation.seconds() / CompileBroker::_total_standard_compile_count);
1864 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);
1866 if (compiler(CompLevel_fast_compile)) {
1867 compiler(CompLevel_fast_compile)->print_timers();
1868 if (compiler(CompLevel_fast_compile) != compiler(CompLevel_highest_tier))
1869 compiler(CompLevel_highest_tier)->print_timers();
1870 }
1872 tty->cr();
1873 int tcb = CompileBroker::_sum_osr_bytes_compiled + CompileBroker::_sum_standard_bytes_compiled;
1874 tty->print_cr(" Total compiled bytecodes : %6d bytes", tcb);
1875 tty->print_cr(" Standard compilation : %6d bytes", CompileBroker::_sum_standard_bytes_compiled);
1876 tty->print_cr(" On stack replacement : %6d bytes", CompileBroker::_sum_osr_bytes_compiled);
1877 int bps = (int)(tcb / CompileBroker::_t_total_compilation.seconds());
1878 tty->print_cr(" Average compilation speed: %6d bytes/s", bps);
1879 tty->cr();
1880 tty->print_cr(" nmethod code size : %6d bytes", CompileBroker::_sum_nmethod_code_size);
1881 tty->print_cr(" nmethod total size : %6d bytes", CompileBroker::_sum_nmethod_size);
1882 }
1885 // Debugging output for failure
1886 void CompileBroker::print_last_compile() {
1887 if ( _last_compile_level != CompLevel_none &&
1888 compiler(_last_compile_level) != NULL &&
1889 _last_method_compiled != NULL &&
1890 _last_compile_type != no_compile) {
1891 if (_last_compile_type == osr_compile) {
1892 tty->print_cr("Last parse: [osr]%d+++(%d) %s",
1893 _osr_compilation_id, _last_compile_level, _last_method_compiled);
1894 } else {
1895 tty->print_cr("Last parse: %d+++(%d) %s",
1896 _compilation_id, _last_compile_level, _last_method_compiled);
1897 }
1898 }
1899 }
1902 void CompileBroker::print_compiler_threads_on(outputStream* st) {
1903 #ifndef PRODUCT
1904 st->print_cr("Compiler thread printing unimplemented.");
1905 st->cr();
1906 #endif
1907 }