1 /*
2 * Copyright (c) 1999, 2026, 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 "cds/cdsConfig.hpp"
26 #include "classfile/javaClasses.inline.hpp"
27 #include "classfile/symbolTable.hpp"
28 #include "classfile/vmClasses.hpp"
29 #include "classfile/vmSymbols.hpp"
30 #include "code/codeCache.hpp"
31 #include "code/codeHeapState.hpp"
32 #include "code/dependencyContext.hpp"
33 #include "compiler/compilationLog.hpp"
34 #include "compiler/compilationMemoryStatistic.hpp"
35 #include "compiler/compilationPolicy.hpp"
36 #include "compiler/compileBroker.hpp"
37 #include "compiler/compileLog.hpp"
38 #include "compiler/compilerEvent.hpp"
39 #include "compiler/compilerOracle.hpp"
40 #include "compiler/directivesParser.hpp"
41 #include "gc/shared/memAllocator.hpp"
42 #include "interpreter/linkResolver.hpp"
43 #include "jfr/jfrEvents.hpp"
44 #include "jvm.h"
45 #include "logging/log.hpp"
46 #include "logging/logStream.hpp"
47 #include "memory/allocation.inline.hpp"
48 #include "memory/resourceArea.hpp"
49 #include "memory/universe.hpp"
50 #include "oops/method.inline.hpp"
51 #include "oops/methodData.hpp"
52 #include "oops/oop.inline.hpp"
53 #include "prims/jvmtiExport.hpp"
54 #include "prims/nativeLookup.hpp"
55 #include "prims/whitebox.hpp"
56 #include "runtime/atomicAccess.hpp"
57 #include "runtime/escapeBarrier.hpp"
58 #include "runtime/globals_extension.hpp"
59 #include "runtime/handles.inline.hpp"
60 #include "runtime/init.hpp"
61 #include "runtime/interfaceSupport.inline.hpp"
62 #include "runtime/java.hpp"
63 #include "runtime/javaCalls.hpp"
64 #include "runtime/jniHandles.inline.hpp"
65 #include "runtime/os.hpp"
66 #include "runtime/perfData.hpp"
67 #include "runtime/safepointVerifiers.hpp"
68 #include "runtime/sharedRuntime.hpp"
69 #include "runtime/threads.hpp"
70 #include "runtime/threadSMR.hpp"
71 #include "runtime/timerTrace.hpp"
72 #include "runtime/vframe.inline.hpp"
73 #include "utilities/debug.hpp"
74 #include "utilities/dtrace.hpp"
75 #include "utilities/events.hpp"
76 #include "utilities/formatBuffer.hpp"
77 #include "utilities/macros.hpp"
78 #ifdef COMPILER1
79 #include "c1/c1_Compiler.hpp"
80 #endif
81 #ifdef COMPILER2
82 #include "opto/c2compiler.hpp"
83 #endif
84 #if INCLUDE_JVMCI
85 #include "jvmci/jvmciEnv.hpp"
86 #include "jvmci/jvmciRuntime.hpp"
87 #endif
88
89 #ifdef DTRACE_ENABLED
90
91 // Only bother with this argument setup if dtrace is available
92
93 #define DTRACE_METHOD_COMPILE_BEGIN_PROBE(method, comp_name) \
94 { \
95 Symbol* klass_name = (method)->klass_name(); \
96 Symbol* name = (method)->name(); \
97 Symbol* signature = (method)->signature(); \
98 HOTSPOT_METHOD_COMPILE_BEGIN( \
99 (char *) comp_name, strlen(comp_name), \
100 (char *) klass_name->bytes(), klass_name->utf8_length(), \
101 (char *) name->bytes(), name->utf8_length(), \
102 (char *) signature->bytes(), signature->utf8_length()); \
103 }
104
105 #define DTRACE_METHOD_COMPILE_END_PROBE(method, comp_name, success) \
106 { \
107 Symbol* klass_name = (method)->klass_name(); \
108 Symbol* name = (method)->name(); \
109 Symbol* signature = (method)->signature(); \
110 HOTSPOT_METHOD_COMPILE_END( \
111 (char *) comp_name, strlen(comp_name), \
112 (char *) klass_name->bytes(), klass_name->utf8_length(), \
113 (char *) name->bytes(), name->utf8_length(), \
114 (char *) signature->bytes(), signature->utf8_length(), (success)); \
115 }
116
117 #else // ndef DTRACE_ENABLED
118
119 #define DTRACE_METHOD_COMPILE_BEGIN_PROBE(method, comp_name)
120 #define DTRACE_METHOD_COMPILE_END_PROBE(method, comp_name, success)
121
122 #endif // ndef DTRACE_ENABLED
123
124 bool CompileBroker::_initialized = false;
125 volatile bool CompileBroker::_should_block = false;
126 volatile int CompileBroker::_print_compilation_warning = 0;
127 volatile jint CompileBroker::_should_compile_new_jobs = run_compilation;
128
129 // The installed compiler(s)
130 AbstractCompiler* CompileBroker::_compilers[2];
131
132 // The maximum numbers of compiler threads to be determined during startup.
133 int CompileBroker::_c1_count = 0;
134 int CompileBroker::_c2_count = 0;
135
136 // An array of compiler names as Java String objects
137 jobject* CompileBroker::_compiler1_objects = nullptr;
138 jobject* CompileBroker::_compiler2_objects = nullptr;
139
140 CompileLog** CompileBroker::_compiler1_logs = nullptr;
141 CompileLog** CompileBroker::_compiler2_logs = nullptr;
142
143 // These counters are used to assign an unique ID to each compilation.
144 volatile jint CompileBroker::_compilation_id = 0;
145 volatile jint CompileBroker::_osr_compilation_id = 0;
146 volatile jint CompileBroker::_native_compilation_id = 0;
147
148 // Performance counters
149 PerfCounter* CompileBroker::_perf_total_compilation = nullptr;
150 PerfCounter* CompileBroker::_perf_osr_compilation = nullptr;
151 PerfCounter* CompileBroker::_perf_standard_compilation = nullptr;
152
153 PerfCounter* CompileBroker::_perf_total_bailout_count = nullptr;
154 PerfCounter* CompileBroker::_perf_total_invalidated_count = nullptr;
155 PerfCounter* CompileBroker::_perf_total_compile_count = nullptr;
156 PerfCounter* CompileBroker::_perf_total_osr_compile_count = nullptr;
157 PerfCounter* CompileBroker::_perf_total_standard_compile_count = nullptr;
158
159 PerfCounter* CompileBroker::_perf_sum_osr_bytes_compiled = nullptr;
160 PerfCounter* CompileBroker::_perf_sum_standard_bytes_compiled = nullptr;
161 PerfCounter* CompileBroker::_perf_sum_nmethod_size = nullptr;
162 PerfCounter* CompileBroker::_perf_sum_nmethod_code_size = nullptr;
163
164 PerfStringVariable* CompileBroker::_perf_last_method = nullptr;
165 PerfStringVariable* CompileBroker::_perf_last_failed_method = nullptr;
166 PerfStringVariable* CompileBroker::_perf_last_invalidated_method = nullptr;
167 PerfVariable* CompileBroker::_perf_last_compile_type = nullptr;
168 PerfVariable* CompileBroker::_perf_last_compile_size = nullptr;
169 PerfVariable* CompileBroker::_perf_last_failed_type = nullptr;
170 PerfVariable* CompileBroker::_perf_last_invalidated_type = nullptr;
171
172 // Timers and counters for generating statistics
173 elapsedTimer CompileBroker::_t_total_compilation;
174 elapsedTimer CompileBroker::_t_osr_compilation;
175 elapsedTimer CompileBroker::_t_standard_compilation;
176 elapsedTimer CompileBroker::_t_invalidated_compilation;
177 elapsedTimer CompileBroker::_t_bailedout_compilation;
178
179 uint CompileBroker::_total_bailout_count = 0;
180 uint CompileBroker::_total_invalidated_count = 0;
181 uint CompileBroker::_total_compile_count = 0;
182 uint CompileBroker::_total_osr_compile_count = 0;
183 uint CompileBroker::_total_standard_compile_count = 0;
184 uint CompileBroker::_total_compiler_stopped_count = 0;
185 uint CompileBroker::_total_compiler_restarted_count = 0;
186
187 uint CompileBroker::_sum_osr_bytes_compiled = 0;
188 uint CompileBroker::_sum_standard_bytes_compiled = 0;
189 uint CompileBroker::_sum_nmethod_size = 0;
190 uint CompileBroker::_sum_nmethod_code_size = 0;
191 uint CompileBroker::_largest_nmethod_code_size = 0;
192
193 jlong CompileBroker::_peak_compilation_time = 0;
194
195 CompilerStatistics CompileBroker::_stats_per_level[CompLevel_full_optimization];
196
197 CompileQueue* CompileBroker::_c2_compile_queue = nullptr;
198 CompileQueue* CompileBroker::_c1_compile_queue = nullptr;
199
200 bool compileBroker_init() {
201 if (LogEvents) {
202 CompilationLog::init();
203 }
204
205 // init directives stack, adding default directive
206 DirectivesStack::init();
207
208 if (DirectivesParser::has_file()) {
209 return DirectivesParser::parse_from_flag();
210 } else if (CompilerDirectivesPrint) {
211 // Print default directive even when no other was added
212 DirectivesStack::print(tty);
213 }
214
215 return true;
216 }
217
218 CompileTaskWrapper::CompileTaskWrapper(CompileTask* task) {
219 CompilerThread* thread = CompilerThread::current();
220 thread->set_task(task);
221 CompileLog* log = thread->log();
222 thread->timeout()->arm();
223 if (log != nullptr && !task->is_unloaded()) task->log_task_start(log);
224 }
225
226 CompileTaskWrapper::~CompileTaskWrapper() {
227 CompilerThread* thread = CompilerThread::current();
228
229 // First, disarm the timeout. This still relies on the underlying task.
230 thread->timeout()->disarm();
231
232 CompileTask* task = thread->task();
233 CompileLog* log = thread->log();
234 if (log != nullptr && !task->is_unloaded()) task->log_task_done(log);
235 thread->set_task(nullptr);
236 thread->set_env(nullptr);
237 if (task->is_blocking()) {
238 bool free_task = false;
239 {
240 MutexLocker notifier(thread, CompileTaskWait_lock);
241 task->mark_complete();
242 #if INCLUDE_JVMCI
243 if (CompileBroker::compiler(task->comp_level())->is_jvmci()) {
244 if (!task->has_waiter()) {
245 // The waiting thread timed out and thus did not delete the task.
246 free_task = true;
247 }
248 task->set_blocking_jvmci_compile_state(nullptr);
249 }
250 #endif
251 if (!free_task) {
252 // Notify the waiting thread that the compilation has completed
253 // so that it can free the task.
254 CompileTaskWait_lock->notify_all();
255 }
256 }
257 if (free_task) {
258 // The task can only be deleted once the task lock is released.
259 delete task;
260 }
261 } else {
262 task->mark_complete();
263
264 // By convention, the compiling thread is responsible for deleting
265 // a non-blocking CompileTask.
266 delete task;
267 }
268 }
269
270 /**
271 * Check if a CompilerThread can be removed and update count if requested.
272 */
273 bool CompileBroker::can_remove(CompilerThread *ct, bool do_it) {
274 assert(UseDynamicNumberOfCompilerThreads, "or shouldn't be here");
275 if (!ReduceNumberOfCompilerThreads) return false;
276
277 AbstractCompiler *compiler = ct->compiler();
278 int compiler_count = compiler->num_compiler_threads();
279 bool c1 = compiler->is_c1();
280
281 // Keep at least 1 compiler thread of each type.
282 if (compiler_count < 2) return false;
283
284 // Keep thread alive for at least some time.
285 if (ct->idle_time_millis() < (c1 ? 500 : 100)) return false;
286
287 #if INCLUDE_JVMCI
288 if (compiler->is_jvmci() && !UseJVMCINativeLibrary) {
289 // Handles for JVMCI thread objects may get released concurrently.
290 if (do_it) {
291 assert(CompileThread_lock->owner() == ct, "must be holding lock");
292 } else {
293 // Skip check if it's the last thread and let caller check again.
294 return true;
295 }
296 }
297 #endif
298
299 // We only allow the last compiler thread of each type to get removed.
300 jobject last_compiler = c1 ? compiler1_object(compiler_count - 1)
301 : compiler2_object(compiler_count - 1);
302 if (ct->threadObj() == JNIHandles::resolve_non_null(last_compiler)) {
303 if (do_it) {
304 assert_locked_or_safepoint(CompileThread_lock); // Update must be consistent.
305 compiler->set_num_compiler_threads(compiler_count - 1);
306 #if INCLUDE_JVMCI
307 if (compiler->is_jvmci() && !UseJVMCINativeLibrary) {
308 // Old j.l.Thread object can die when no longer referenced elsewhere.
309 JNIHandles::destroy_global(compiler2_object(compiler_count - 1));
310 _compiler2_objects[compiler_count - 1] = nullptr;
311 }
312 #endif
313 }
314 return true;
315 }
316 return false;
317 }
318
319 /**
320 * Add a CompileTask to a CompileQueue.
321 */
322 void CompileQueue::add(CompileTask* task) {
323 assert(MethodCompileQueue_lock->owned_by_self(), "must own lock");
324
325 task->set_next(nullptr);
326 task->set_prev(nullptr);
327
328 if (_last == nullptr) {
329 // The compile queue is empty.
330 assert(_first == nullptr, "queue is empty");
331 _first = task;
332 _last = task;
333 } else {
334 // Append the task to the queue.
335 assert(_last->next() == nullptr, "not last");
336 _last->set_next(task);
337 task->set_prev(_last);
338 _last = task;
339 }
340 ++_size;
341 ++_total_added;
342 if (_size > _peak_size) {
343 _peak_size = _size;
344 }
345
346 // Mark the method as being in the compile queue.
347 task->method()->set_queued_for_compilation();
348
349 if (CIPrintCompileQueue) {
350 print_tty();
351 }
352
353 if (LogCompilation && xtty != nullptr) {
354 task->log_task_queued();
355 }
356
357 if (TrainingData::need_data() && !CDSConfig::is_dumping_final_static_archive()) {
358 CompileTrainingData* ctd = CompileTrainingData::make(task);
359 if (ctd != nullptr) {
360 task->set_training_data(ctd);
361 }
362 }
363
364 // Notify CompilerThreads that a task is available.
365 MethodCompileQueue_lock->notify_all();
366 }
367
368 /**
369 * Empties compilation queue by deleting all compilation tasks.
370 * Furthermore, the method wakes up all threads that are waiting
371 * on a compilation task to finish. This can happen if background
372 * compilation is disabled.
373 */
374 void CompileQueue::delete_all() {
375 MutexLocker mu(MethodCompileQueue_lock);
376 CompileTask* current = _first;
377
378 // Iterate over all tasks in the compile queue
379 while (current != nullptr) {
380 CompileTask* next = current->next();
381 if (!current->is_blocking()) {
382 // Non-blocking task. No one is waiting for it, delete it now.
383 delete current;
384 } else {
385 // Blocking task. By convention, it is the waiters responsibility
386 // to delete the task. We cannot delete it here, because we do not
387 // coordinate with waiters. We will notify the waiters later.
388 }
389 current = next;
390 }
391 _first = nullptr;
392 _last = nullptr;
393
394 // Wake up all blocking task waiters to deal with remaining blocking
395 // tasks. This is not a performance sensitive path, so we do this
396 // unconditionally to simplify coding/testing.
397 {
398 MonitorLocker ml(Thread::current(), CompileTaskWait_lock);
399 ml.notify_all();
400 }
401
402 // Wake up all threads that block on the queue.
403 MethodCompileQueue_lock->notify_all();
404 }
405
406 /**
407 * Get the next CompileTask from a CompileQueue
408 */
409 CompileTask* CompileQueue::get(CompilerThread* thread) {
410 // save methods from RedefineClasses across safepoint
411 // across MethodCompileQueue_lock below.
412 methodHandle save_method;
413
414 MonitorLocker locker(MethodCompileQueue_lock);
415 // If _first is null we have no more compile jobs. There are two reasons for
416 // having no compile jobs: First, we compiled everything we wanted. Second,
417 // we ran out of code cache so compilation has been disabled. In the latter
418 // case we perform code cache sweeps to free memory such that we can re-enable
419 // compilation.
420 while (_first == nullptr) {
421 // Exit loop if compilation is disabled forever
422 if (CompileBroker::is_compilation_disabled_forever()) {
423 return nullptr;
424 }
425
426 AbstractCompiler* compiler = thread->compiler();
427 guarantee(compiler != nullptr, "Compiler object must exist");
428 compiler->on_empty_queue(this, thread);
429 if (_first != nullptr) {
430 // The call to on_empty_queue may have temporarily unlocked the MCQ lock
431 // so check again whether any tasks were added to the queue.
432 break;
433 }
434
435 // If there are no compilation tasks and we can compile new jobs
436 // (i.e., there is enough free space in the code cache) there is
437 // no need to invoke the GC.
438 // We need a timed wait here, since compiler threads can exit if compilation
439 // is disabled forever. We use 5 seconds wait time; the exiting of compiler threads
440 // is not critical and we do not want idle compiler threads to wake up too often.
441 locker.wait(5*1000);
442
443 if (UseDynamicNumberOfCompilerThreads && _first == nullptr) {
444 // Still nothing to compile. Give caller a chance to stop this thread.
445 if (CompileBroker::can_remove(CompilerThread::current(), false)) return nullptr;
446 }
447 }
448
449 if (CompileBroker::is_compilation_disabled_forever()) {
450 return nullptr;
451 }
452
453 CompileTask* task;
454 {
455 NoSafepointVerifier nsv;
456 task = CompilationPolicy::select_task(this, thread);
457 if (task != nullptr) {
458 task = task->select_for_compilation();
459 }
460 }
461
462 if (task != nullptr) {
463 // Save method pointers across unlock safepoint. The task is removed from
464 // the compilation queue, which is walked during RedefineClasses.
465 Thread* thread = Thread::current();
466 save_method = methodHandle(thread, task->method());
467
468 remove(task);
469 }
470 purge_stale_tasks(); // may temporarily release MCQ lock
471 return task;
472 }
473
474 // Clean & deallocate stale compile tasks.
475 // Temporarily releases MethodCompileQueue lock.
476 void CompileQueue::purge_stale_tasks() {
477 assert(MethodCompileQueue_lock->owned_by_self(), "must own lock");
478 if (_first_stale != nullptr) {
479 // Stale tasks are purged when MCQ lock is released,
480 // but _first_stale updates are protected by MCQ lock.
481 // Once task processing starts and MCQ lock is released,
482 // other compiler threads can reuse _first_stale.
483 CompileTask* head = _first_stale;
484 _first_stale = nullptr;
485 {
486 MutexUnlocker ul(MethodCompileQueue_lock);
487 for (CompileTask* task = head; task != nullptr; ) {
488 CompileTask* next_task = task->next();
489 task->set_next(nullptr);
490 CompileTaskWrapper ctw(task); // Frees the task
491 task->set_failure_reason("stale task");
492 task = next_task;
493 }
494 }
495 }
496 }
497
498 void CompileQueue::remove(CompileTask* task) {
499 assert(MethodCompileQueue_lock->owned_by_self(), "must own lock");
500 if (task->prev() != nullptr) {
501 task->prev()->set_next(task->next());
502 } else {
503 // max is the first element
504 assert(task == _first, "Sanity");
505 _first = task->next();
506 }
507
508 if (task->next() != nullptr) {
509 task->next()->set_prev(task->prev());
510 } else {
511 // max is the last element
512 assert(task == _last, "Sanity");
513 _last = task->prev();
514 }
515 task->set_next(nullptr);
516 task->set_prev(nullptr);
517 --_size;
518 ++_total_removed;
519 }
520
521 void CompileQueue::remove_and_mark_stale(CompileTask* task) {
522 assert(MethodCompileQueue_lock->owned_by_self(), "must own lock");
523 remove(task);
524
525 // Enqueue the task for reclamation (should be done outside MCQ lock)
526 task->set_next(_first_stale);
527 task->set_prev(nullptr);
528 _first_stale = task;
529 }
530
531 // methods in the compile queue need to be marked as used on the stack
532 // so that they don't get reclaimed by Redefine Classes
533 void CompileQueue::mark_on_stack() {
534 CompileTask* task = _first;
535 while (task != nullptr) {
536 task->mark_on_stack();
537 task = task->next();
538 }
539 }
540
541
542 CompileQueue* CompileBroker::compile_queue(int comp_level) {
543 if (is_c2_compile(comp_level)) return _c2_compile_queue;
544 if (is_c1_compile(comp_level)) return _c1_compile_queue;
545 return nullptr;
546 }
547
548 CompileQueue* CompileBroker::c1_compile_queue() {
549 return _c1_compile_queue;
550 }
551
552 CompileQueue* CompileBroker::c2_compile_queue() {
553 return _c2_compile_queue;
554 }
555
556 void CompileBroker::print_compile_queues(outputStream* st) {
557 st->print_cr("Current compiles: ");
558
559 char buf[2000];
560 int buflen = sizeof(buf);
561 Threads::print_threads_compiling(st, buf, buflen, /* short_form = */ true);
562
563 st->cr();
564 if (_c1_compile_queue != nullptr) {
565 _c1_compile_queue->print(st);
566 }
567 if (_c2_compile_queue != nullptr) {
568 _c2_compile_queue->print(st);
569 }
570 }
571
572 void CompileQueue::print(outputStream* st) {
573 assert_locked_or_safepoint(MethodCompileQueue_lock);
574 st->print_cr("%s:", name());
575 CompileTask* task = _first;
576 if (task == nullptr) {
577 st->print_cr("Empty");
578 } else {
579 while (task != nullptr) {
580 task->print(st, nullptr, true, true);
581 task = task->next();
582 }
583 }
584 st->cr();
585 }
586
587 void CompileQueue::print_tty() {
588 stringStream ss;
589 // Dump the compile queue into a buffer before locking the tty
590 print(&ss);
591 {
592 ttyLocker ttyl;
593 tty->print("%s", ss.freeze());
594 }
595 }
596
597 CompilerCounters::CompilerCounters() {
598 _current_method[0] = '\0';
599 _compile_type = CompileBroker::no_compile;
600 }
601
602 #if INCLUDE_JFR && COMPILER2_OR_JVMCI
603 // It appends new compiler phase names to growable array phase_names(a new CompilerPhaseType mapping
604 // in compiler/compilerEvent.cpp) and registers it with its serializer.
605 //
606 // c2 uses explicit CompilerPhaseType idToPhase mapping in opto/phasetype.hpp,
607 // so if c2 is used, it should be always registered first.
608 // This function is called during vm initialization.
609 static void register_jfr_phasetype_serializer(CompilerType compiler_type) {
610 ResourceMark rm;
611 static bool first_registration = true;
612 if (compiler_type == compiler_jvmci) {
613 CompilerEvent::PhaseEvent::get_phase_id("NOT_A_PHASE_NAME", false, false, false);
614 first_registration = false;
615 #ifdef COMPILER2
616 } else if (compiler_type == compiler_c2) {
617 assert(first_registration, "invariant"); // c2 must be registered first.
618 for (int i = 0; i < PHASE_NUM_TYPES; i++) {
619 const char* phase_name = CompilerPhaseTypeHelper::to_description((CompilerPhaseType) i);
620 CompilerEvent::PhaseEvent::get_phase_id(phase_name, false, false, false);
621 }
622 first_registration = false;
623 #endif // COMPILER2
624 }
625 }
626 #endif // INCLUDE_JFR && COMPILER2_OR_JVMCI
627
628 // ------------------------------------------------------------------
629 // CompileBroker::compilation_init
630 //
631 // Initialize the Compilation object
632 void CompileBroker::compilation_init(JavaThread* THREAD) {
633 // No need to initialize compilation system if we do not use it.
634 if (!UseCompiler) {
635 return;
636 }
637 // Set the interface to the current compiler(s).
638 _c1_count = CompilationPolicy::c1_count();
639 _c2_count = CompilationPolicy::c2_count();
640
641 #if INCLUDE_JVMCI
642 if (EnableJVMCI) {
643 // This is creating a JVMCICompiler singleton.
644 JVMCICompiler* jvmci = new JVMCICompiler();
645
646 if (UseJVMCICompiler) {
647 _compilers[1] = jvmci;
648 if (FLAG_IS_DEFAULT(JVMCIThreads)) {
649 if (BootstrapJVMCI) {
650 // JVMCI will bootstrap so give it more threads
651 _c2_count = MIN2(32, os::active_processor_count());
652 }
653 } else {
654 _c2_count = JVMCIThreads;
655 }
656 if (FLAG_IS_DEFAULT(JVMCIHostThreads)) {
657 } else {
658 #ifdef COMPILER1
659 _c1_count = JVMCIHostThreads;
660 #endif // COMPILER1
661 }
662 }
663 }
664 #endif // INCLUDE_JVMCI
665
666 #ifdef COMPILER1
667 if (_c1_count > 0) {
668 _compilers[0] = new Compiler();
669 }
670 #endif // COMPILER1
671
672 #ifdef COMPILER2
673 if (true JVMCI_ONLY( && !UseJVMCICompiler)) {
674 if (_c2_count > 0) {
675 _compilers[1] = new C2Compiler();
676 // Register c2 first as c2 CompilerPhaseType idToPhase mapping is explicit.
677 // idToPhase mapping for c2 is in opto/phasetype.hpp
678 JFR_ONLY(register_jfr_phasetype_serializer(compiler_c2);)
679 }
680 }
681 #endif // COMPILER2
682
683 #if INCLUDE_JVMCI
684 // Register after c2 registration.
685 // JVMCI CompilerPhaseType idToPhase mapping is dynamic.
686 if (EnableJVMCI) {
687 JFR_ONLY(register_jfr_phasetype_serializer(compiler_jvmci);)
688 }
689 #endif // INCLUDE_JVMCI
690
691 if (CompilerOracle::should_collect_memstat()) {
692 CompilationMemoryStatistic::initialize();
693 }
694
695 // Start the compiler thread(s)
696 init_compiler_threads();
697 // totalTime performance counter is always created as it is required
698 // by the implementation of java.lang.management.CompilationMXBean.
699 {
700 // Ensure OOM leads to vm_exit_during_initialization.
701 EXCEPTION_MARK;
702 _perf_total_compilation =
703 PerfDataManager::create_counter(JAVA_CI, "totalTime",
704 PerfData::U_Ticks, CHECK);
705 }
706
707 if (UsePerfData) {
708
709 EXCEPTION_MARK;
710
711 // create the jvmstat performance counters
712 _perf_osr_compilation =
713 PerfDataManager::create_counter(SUN_CI, "osrTime",
714 PerfData::U_Ticks, CHECK);
715
716 _perf_standard_compilation =
717 PerfDataManager::create_counter(SUN_CI, "standardTime",
718 PerfData::U_Ticks, CHECK);
719
720 _perf_total_bailout_count =
721 PerfDataManager::create_counter(SUN_CI, "totalBailouts",
722 PerfData::U_Events, CHECK);
723
724 _perf_total_invalidated_count =
725 PerfDataManager::create_counter(SUN_CI, "totalInvalidates",
726 PerfData::U_Events, CHECK);
727
728 _perf_total_compile_count =
729 PerfDataManager::create_counter(SUN_CI, "totalCompiles",
730 PerfData::U_Events, CHECK);
731 _perf_total_osr_compile_count =
732 PerfDataManager::create_counter(SUN_CI, "osrCompiles",
733 PerfData::U_Events, CHECK);
734
735 _perf_total_standard_compile_count =
736 PerfDataManager::create_counter(SUN_CI, "standardCompiles",
737 PerfData::U_Events, CHECK);
738
739 _perf_sum_osr_bytes_compiled =
740 PerfDataManager::create_counter(SUN_CI, "osrBytes",
741 PerfData::U_Bytes, CHECK);
742
743 _perf_sum_standard_bytes_compiled =
744 PerfDataManager::create_counter(SUN_CI, "standardBytes",
745 PerfData::U_Bytes, CHECK);
746
747 _perf_sum_nmethod_size =
748 PerfDataManager::create_counter(SUN_CI, "nmethodSize",
749 PerfData::U_Bytes, CHECK);
750
751 _perf_sum_nmethod_code_size =
752 PerfDataManager::create_counter(SUN_CI, "nmethodCodeSize",
753 PerfData::U_Bytes, CHECK);
754
755 _perf_last_method =
756 PerfDataManager::create_string_variable(SUN_CI, "lastMethod",
757 CompilerCounters::cmname_buffer_length,
758 "", CHECK);
759
760 _perf_last_failed_method =
761 PerfDataManager::create_string_variable(SUN_CI, "lastFailedMethod",
762 CompilerCounters::cmname_buffer_length,
763 "", CHECK);
764
765 _perf_last_invalidated_method =
766 PerfDataManager::create_string_variable(SUN_CI, "lastInvalidatedMethod",
767 CompilerCounters::cmname_buffer_length,
768 "", CHECK);
769
770 _perf_last_compile_type =
771 PerfDataManager::create_variable(SUN_CI, "lastType",
772 PerfData::U_None,
773 (jlong)CompileBroker::no_compile,
774 CHECK);
775
776 _perf_last_compile_size =
777 PerfDataManager::create_variable(SUN_CI, "lastSize",
778 PerfData::U_Bytes,
779 (jlong)CompileBroker::no_compile,
780 CHECK);
781
782
783 _perf_last_failed_type =
784 PerfDataManager::create_variable(SUN_CI, "lastFailedType",
785 PerfData::U_None,
786 (jlong)CompileBroker::no_compile,
787 CHECK);
788
789 _perf_last_invalidated_type =
790 PerfDataManager::create_variable(SUN_CI, "lastInvalidatedType",
791 PerfData::U_None,
792 (jlong)CompileBroker::no_compile,
793 CHECK);
794 }
795
796 _initialized = true;
797 }
798
799 void TrainingReplayThread::training_replay_thread_entry(JavaThread* thread, TRAPS) {
800 CompilationPolicy::replay_training_at_init_loop(thread);
801 }
802
803 #if defined(ASSERT) && COMPILER2_OR_JVMCI
804 // Entry for DeoptimizeObjectsALotThread. The threads are started in
805 // CompileBroker::init_compiler_threads() iff DeoptimizeObjectsALot is enabled
806 void DeoptimizeObjectsALotThread::deopt_objs_alot_thread_entry(JavaThread* thread, TRAPS) {
807 DeoptimizeObjectsALotThread* dt = ((DeoptimizeObjectsALotThread*) thread);
808 bool enter_single_loop;
809 {
810 MonitorLocker ml(dt, EscapeBarrier_lock, Mutex::_no_safepoint_check_flag);
811 static int single_thread_count = 0;
812 enter_single_loop = single_thread_count++ < DeoptimizeObjectsALotThreadCountSingle;
813 }
814 if (enter_single_loop) {
815 dt->deoptimize_objects_alot_loop_single();
816 } else {
817 dt->deoptimize_objects_alot_loop_all();
818 }
819 }
820
821 // Execute EscapeBarriers in an endless loop to revert optimizations based on escape analysis. Each
822 // barrier targets a single thread which is selected round robin.
823 void DeoptimizeObjectsALotThread::deoptimize_objects_alot_loop_single() {
824 HandleMark hm(this);
825 while (true) {
826 for (JavaThreadIteratorWithHandle jtiwh; JavaThread *deoptee_thread = jtiwh.next(); ) {
827 { // Begin new scope for escape barrier
828 HandleMarkCleaner hmc(this);
829 ResourceMark rm(this);
830 EscapeBarrier eb(true, this, deoptee_thread);
831 eb.deoptimize_objects(100);
832 }
833 // Now sleep after the escape barriers destructor resumed deoptee_thread.
834 sleep(DeoptimizeObjectsALotInterval);
835 }
836 }
837 }
838
839 // Execute EscapeBarriers in an endless loop to revert optimizations based on escape analysis. Each
840 // barrier targets all java threads in the vm at once.
841 void DeoptimizeObjectsALotThread::deoptimize_objects_alot_loop_all() {
842 HandleMark hm(this);
843 while (true) {
844 { // Begin new scope for escape barrier
845 HandleMarkCleaner hmc(this);
846 ResourceMark rm(this);
847 EscapeBarrier eb(true, this);
848 eb.deoptimize_objects_all_threads();
849 }
850 // Now sleep after the escape barriers destructor resumed the java threads.
851 sleep(DeoptimizeObjectsALotInterval);
852 }
853 }
854 #endif // defined(ASSERT) && COMPILER2_OR_JVMCI
855
856
857 JavaThread* CompileBroker::make_thread(ThreadType type, jobject thread_handle, CompileQueue* queue, AbstractCompiler* comp, JavaThread* THREAD) {
858 Handle thread_oop(THREAD, JNIHandles::resolve_non_null(thread_handle));
859
860 if (java_lang_Thread::thread(thread_oop()) != nullptr) {
861 assert(type == compiler_t, "should only happen with reused compiler threads");
862 // The compiler thread hasn't actually exited yet so don't try to reuse it
863 return nullptr;
864 }
865
866 JavaThread* new_thread = nullptr;
867 switch (type) {
868 case compiler_t:
869 assert(comp != nullptr, "Compiler instance missing.");
870 if (!InjectCompilerCreationFailure || comp->num_compiler_threads() == 0) {
871 CompilerCounters* counters = new CompilerCounters();
872 new_thread = new CompilerThread(queue, counters);
873 }
874 break;
875 #if defined(ASSERT) && COMPILER2_OR_JVMCI
876 case deoptimizer_t:
877 new_thread = new DeoptimizeObjectsALotThread();
878 break;
879 #endif // ASSERT
880 case training_replay_t:
881 new_thread = new TrainingReplayThread();
882 break;
883 default:
884 ShouldNotReachHere();
885 }
886
887 // At this point the new CompilerThread data-races with this startup
888 // thread (which is the main thread and NOT the VM thread).
889 // This means Java bytecodes being executed at startup can
890 // queue compile jobs which will run at whatever default priority the
891 // newly created CompilerThread runs at.
892
893
894 // At this point it may be possible that no osthread was created for the
895 // JavaThread due to lack of resources. We will handle that failure below.
896 // Also check new_thread so that static analysis is happy.
897 if (new_thread != nullptr && new_thread->osthread() != nullptr) {
898
899 if (type == compiler_t) {
900 CompilerThread::cast(new_thread)->set_compiler(comp);
901 }
902
903 // Note that we cannot call os::set_priority because it expects Java
904 // priorities and we are *explicitly* using OS priorities so that it's
905 // possible to set the compiler thread priority higher than any Java
906 // thread.
907
908 int native_prio = CompilerThreadPriority;
909 if (native_prio == -1) {
910 if (UseCriticalCompilerThreadPriority) {
911 native_prio = os::java_to_os_priority[CriticalPriority];
912 } else {
913 native_prio = os::java_to_os_priority[NearMaxPriority];
914 }
915 }
916 os::set_native_priority(new_thread, native_prio);
917
918 // Note that this only sets the JavaThread _priority field, which by
919 // definition is limited to Java priorities and not OS priorities.
920 JavaThread::start_internal_daemon(THREAD, new_thread, thread_oop, NearMaxPriority);
921
922 } else { // osthread initialization failure
923 if (UseDynamicNumberOfCompilerThreads && type == compiler_t
924 && comp->num_compiler_threads() > 0) {
925 // The new thread is not known to Thread-SMR yet so we can just delete.
926 delete new_thread;
927 return nullptr;
928 } else {
929 vm_exit_during_initialization("java.lang.OutOfMemoryError",
930 os::native_thread_creation_failed_msg());
931 }
932 }
933
934 os::naked_yield(); // make sure that the compiler thread is started early (especially helpful on SOLARIS)
935
936 return new_thread;
937 }
938
939 static bool trace_compiler_threads() {
940 LogTarget(Debug, jit, thread) lt;
941 return TraceCompilerThreads || lt.is_enabled();
942 }
943
944 static jobject create_compiler_thread(AbstractCompiler* compiler, int i, TRAPS) {
945 char name_buffer[256];
946 os::snprintf_checked(name_buffer, sizeof(name_buffer), "%s CompilerThread%d", compiler->name(), i);
947 Handle thread_oop = JavaThread::create_system_thread_object(name_buffer, CHECK_NULL);
948 return JNIHandles::make_global(thread_oop);
949 }
950
951 static void print_compiler_threads(stringStream& msg) {
952 if (TraceCompilerThreads) {
953 tty->print_cr("%7d %s", (int)tty->time_stamp().milliseconds(), msg.as_string());
954 }
955 LogTarget(Debug, jit, thread) lt;
956 if (lt.is_enabled()) {
957 LogStream ls(lt);
958 ls.print_cr("%s", msg.as_string());
959 }
960 }
961
962 void CompileBroker::init_compiler_threads() {
963 // Ensure any exceptions lead to vm_exit_during_initialization.
964 EXCEPTION_MARK;
965 #if !defined(ZERO)
966 assert(_c2_count > 0 || _c1_count > 0, "No compilers?");
967 #endif // !ZERO
968 // Initialize the compilation queue
969 if (_c2_count > 0) {
970 const char* name = JVMCI_ONLY(UseJVMCICompiler ? "JVMCI compile queue" :) "C2 compile queue";
971 _c2_compile_queue = new CompileQueue(name);
972 _compiler2_objects = NEW_C_HEAP_ARRAY(jobject, _c2_count, mtCompiler);
973 _compiler2_logs = NEW_C_HEAP_ARRAY(CompileLog*, _c2_count, mtCompiler);
974 }
975 if (_c1_count > 0) {
976 _c1_compile_queue = new CompileQueue("C1 compile queue");
977 _compiler1_objects = NEW_C_HEAP_ARRAY(jobject, _c1_count, mtCompiler);
978 _compiler1_logs = NEW_C_HEAP_ARRAY(CompileLog*, _c1_count, mtCompiler);
979 }
980
981 for (int i = 0; i < _c2_count; i++) {
982 // Create a name for our thread.
983 jobject thread_handle = create_compiler_thread(_compilers[1], i, CHECK);
984 _compiler2_objects[i] = thread_handle;
985 _compiler2_logs[i] = nullptr;
986
987 if (!UseDynamicNumberOfCompilerThreads || i == 0) {
988 JavaThread *ct = make_thread(compiler_t, thread_handle, _c2_compile_queue, _compilers[1], THREAD);
989 assert(ct != nullptr, "should have been handled for initial thread");
990 _compilers[1]->set_num_compiler_threads(i + 1);
991 if (trace_compiler_threads()) {
992 ResourceMark rm;
993 ThreadsListHandle tlh; // name() depends on the TLH.
994 assert(tlh.includes(ct), "ct=" INTPTR_FORMAT " exited unexpectedly.", p2i(ct));
995 stringStream msg;
996 msg.print("Added initial compiler thread %s", ct->name());
997 print_compiler_threads(msg);
998 }
999 }
1000 }
1001
1002 for (int i = 0; i < _c1_count; i++) {
1003 // Create a name for our thread.
1004 jobject thread_handle = create_compiler_thread(_compilers[0], i, CHECK);
1005 _compiler1_objects[i] = thread_handle;
1006 _compiler1_logs[i] = nullptr;
1007
1008 if (!UseDynamicNumberOfCompilerThreads || i == 0) {
1009 JavaThread *ct = make_thread(compiler_t, thread_handle, _c1_compile_queue, _compilers[0], THREAD);
1010 assert(ct != nullptr, "should have been handled for initial thread");
1011 _compilers[0]->set_num_compiler_threads(i + 1);
1012 if (trace_compiler_threads()) {
1013 ResourceMark rm;
1014 ThreadsListHandle tlh; // name() depends on the TLH.
1015 assert(tlh.includes(ct), "ct=" INTPTR_FORMAT " exited unexpectedly.", p2i(ct));
1016 stringStream msg;
1017 msg.print("Added initial compiler thread %s", ct->name());
1018 print_compiler_threads(msg);
1019 }
1020 }
1021 }
1022
1023 if (UsePerfData) {
1024 PerfDataManager::create_constant(SUN_CI, "threads", PerfData::U_Bytes, _c1_count + _c2_count, CHECK);
1025 }
1026
1027 #if defined(ASSERT) && COMPILER2_OR_JVMCI
1028 if (DeoptimizeObjectsALot) {
1029 // Initialize and start the object deoptimizer threads
1030 const int total_count = DeoptimizeObjectsALotThreadCountSingle + DeoptimizeObjectsALotThreadCountAll;
1031 for (int count = 0; count < total_count; count++) {
1032 Handle thread_oop = JavaThread::create_system_thread_object("Deoptimize objects a lot single mode", CHECK);
1033 jobject thread_handle = JNIHandles::make_local(THREAD, thread_oop());
1034 make_thread(deoptimizer_t, thread_handle, nullptr, nullptr, THREAD);
1035 }
1036 }
1037 #endif // defined(ASSERT) && COMPILER2_OR_JVMCI
1038 }
1039
1040 void CompileBroker::init_training_replay() {
1041 // Ensure any exceptions lead to vm_exit_during_initialization.
1042 EXCEPTION_MARK;
1043 if (TrainingData::have_data()) {
1044 Handle thread_oop = JavaThread::create_system_thread_object("Training replay thread", CHECK);
1045 jobject thread_handle = JNIHandles::make_local(THREAD, thread_oop());
1046 make_thread(training_replay_t, thread_handle, nullptr, nullptr, THREAD);
1047 }
1048 }
1049
1050 void CompileBroker::possibly_add_compiler_threads(JavaThread* THREAD) {
1051
1052 int old_c2_count = 0, new_c2_count = 0, old_c1_count = 0, new_c1_count = 0;
1053 const int c2_tasks_per_thread = 2, c1_tasks_per_thread = 4;
1054
1055 // Quick check if we already have enough compiler threads without taking the lock.
1056 // Numbers may change concurrently, so we read them again after we have the lock.
1057 if (_c2_compile_queue != nullptr) {
1058 old_c2_count = get_c2_thread_count();
1059 new_c2_count = MIN2(_c2_count, _c2_compile_queue->size() / c2_tasks_per_thread);
1060 }
1061 if (_c1_compile_queue != nullptr) {
1062 old_c1_count = get_c1_thread_count();
1063 new_c1_count = MIN2(_c1_count, _c1_compile_queue->size() / c1_tasks_per_thread);
1064 }
1065 if (new_c2_count <= old_c2_count && new_c1_count <= old_c1_count) return;
1066
1067 // Now, we do the more expensive operations.
1068 physical_memory_size_type free_memory = 0;
1069 // Return value ignored - defaulting to 0 on failure.
1070 (void)os::free_memory(free_memory);
1071 // If SegmentedCodeCache is off, both values refer to the single heap (with type CodeBlobType::All).
1072 size_t available_cc_np = CodeCache::unallocated_capacity(CodeBlobType::MethodNonProfiled),
1073 available_cc_p = CodeCache::unallocated_capacity(CodeBlobType::MethodProfiled);
1074
1075 // Only attempt to start additional threads if the lock is free.
1076 if (!CompileThread_lock->try_lock()) return;
1077
1078 if (_c2_compile_queue != nullptr) {
1079 old_c2_count = get_c2_thread_count();
1080 new_c2_count = MIN4(_c2_count,
1081 _c2_compile_queue->size() / c2_tasks_per_thread,
1082 (int)(free_memory / (200*M)),
1083 (int)(available_cc_np / (128*K)));
1084
1085 for (int i = old_c2_count; i < new_c2_count; i++) {
1086 #if INCLUDE_JVMCI
1087 if (UseJVMCICompiler && !UseJVMCINativeLibrary && _compiler2_objects[i] == nullptr) {
1088 // Native compiler threads as used in C1/C2 can reuse the j.l.Thread objects as their
1089 // existence is completely hidden from the rest of the VM (and those compiler threads can't
1090 // call Java code to do the creation anyway).
1091 //
1092 // For pure Java JVMCI we have to create new j.l.Thread objects as they are visible and we
1093 // can see unexpected thread lifecycle transitions if we bind them to new JavaThreads. For
1094 // native library JVMCI it's preferred to use the C1/C2 strategy as this avoids unnecessary
1095 // coupling with Java.
1096 if (!THREAD->can_call_java()) break;
1097 char name_buffer[256];
1098 os::snprintf_checked(name_buffer, sizeof(name_buffer), "%s CompilerThread%d", _compilers[1]->name(), i);
1099 Handle thread_oop;
1100 {
1101 // We have to give up the lock temporarily for the Java calls.
1102 MutexUnlocker mu(CompileThread_lock);
1103 thread_oop = JavaThread::create_system_thread_object(name_buffer, THREAD);
1104 }
1105 if (HAS_PENDING_EXCEPTION) {
1106 if (trace_compiler_threads()) {
1107 ResourceMark rm;
1108 stringStream msg;
1109 msg.print_cr("JVMCI compiler thread creation failed:");
1110 PENDING_EXCEPTION->print_on(&msg);
1111 print_compiler_threads(msg);
1112 }
1113 CLEAR_PENDING_EXCEPTION;
1114 break;
1115 }
1116 // Check if another thread has beaten us during the Java calls.
1117 if (get_c2_thread_count() != i) break;
1118 jobject thread_handle = JNIHandles::make_global(thread_oop);
1119 assert(compiler2_object(i) == nullptr, "Old one must be released!");
1120 _compiler2_objects[i] = thread_handle;
1121 }
1122 #endif
1123 guarantee(compiler2_object(i) != nullptr, "Thread oop must exist");
1124 JavaThread *ct = make_thread(compiler_t, compiler2_object(i), _c2_compile_queue, _compilers[1], THREAD);
1125 if (ct == nullptr) break;
1126 _compilers[1]->set_num_compiler_threads(i + 1);
1127 if (trace_compiler_threads()) {
1128 ResourceMark rm;
1129 ThreadsListHandle tlh; // name() depends on the TLH.
1130 assert(tlh.includes(ct), "ct=" INTPTR_FORMAT " exited unexpectedly.", p2i(ct));
1131 stringStream msg;
1132 msg.print("Added compiler thread %s (free memory: %dMB, available non-profiled code cache: %dMB)",
1133 ct->name(), (int)(free_memory/M), (int)(available_cc_np/M));
1134 print_compiler_threads(msg);
1135 }
1136 }
1137 }
1138
1139 if (_c1_compile_queue != nullptr) {
1140 old_c1_count = get_c1_thread_count();
1141 new_c1_count = MIN4(_c1_count,
1142 _c1_compile_queue->size() / c1_tasks_per_thread,
1143 (int)(free_memory / (100*M)),
1144 (int)(available_cc_p / (128*K)));
1145
1146 for (int i = old_c1_count; i < new_c1_count; i++) {
1147 JavaThread *ct = make_thread(compiler_t, compiler1_object(i), _c1_compile_queue, _compilers[0], THREAD);
1148 if (ct == nullptr) break;
1149 _compilers[0]->set_num_compiler_threads(i + 1);
1150 if (trace_compiler_threads()) {
1151 ResourceMark rm;
1152 ThreadsListHandle tlh; // name() depends on the TLH.
1153 assert(tlh.includes(ct), "ct=" INTPTR_FORMAT " exited unexpectedly.", p2i(ct));
1154 stringStream msg;
1155 msg.print("Added compiler thread %s (free memory: %dMB, available profiled code cache: %dMB)",
1156 ct->name(), (int)(free_memory/M), (int)(available_cc_p/M));
1157 print_compiler_threads(msg);
1158 }
1159 }
1160 }
1161
1162 CompileThread_lock->unlock();
1163 }
1164
1165
1166 /**
1167 * Set the methods on the stack as on_stack so that redefine classes doesn't
1168 * reclaim them. This method is executed at a safepoint.
1169 */
1170 void CompileBroker::mark_on_stack() {
1171 assert(SafepointSynchronize::is_at_safepoint(), "sanity check");
1172 // Since we are at a safepoint, we do not need a lock to access
1173 // the compile queues.
1174 if (_c2_compile_queue != nullptr) {
1175 _c2_compile_queue->mark_on_stack();
1176 }
1177 if (_c1_compile_queue != nullptr) {
1178 _c1_compile_queue->mark_on_stack();
1179 }
1180 }
1181
1182 // ------------------------------------------------------------------
1183 // CompileBroker::compile_method
1184 //
1185 // Request compilation of a method.
1186 void CompileBroker::compile_method_base(const methodHandle& method,
1187 int osr_bci,
1188 int comp_level,
1189 int hot_count,
1190 CompileTask::CompileReason compile_reason,
1191 bool blocking,
1192 Thread* thread) {
1193 guarantee(!method->is_abstract(), "cannot compile abstract methods");
1194 assert(method->method_holder()->is_instance_klass(),
1195 "sanity check");
1196 assert(!method->method_holder()->is_not_initialized(),
1197 "method holder must be initialized");
1198 assert(!method->is_method_handle_intrinsic(), "do not enqueue these guys");
1199
1200 if (CIPrintRequests) {
1201 tty->print("request: ");
1202 method->print_short_name(tty);
1203 if (osr_bci != InvocationEntryBci) {
1204 tty->print(" osr_bci: %d", osr_bci);
1205 }
1206 tty->print(" level: %d comment: %s count: %d", comp_level, CompileTask::reason_name(compile_reason), hot_count);
1207 if (hot_count > 0) {
1208 tty->print(" hot: yes");
1209 }
1210 tty->cr();
1211 }
1212
1213 // A request has been made for compilation. Before we do any
1214 // real work, check to see if the method has been compiled
1215 // in the meantime with a definitive result.
1216 if (compilation_is_complete(method, osr_bci, comp_level)) {
1217 return;
1218 }
1219
1220 #ifndef PRODUCT
1221 if (osr_bci != -1 && !FLAG_IS_DEFAULT(OSROnlyBCI)) {
1222 if ((OSROnlyBCI > 0) ? (OSROnlyBCI != osr_bci) : (-OSROnlyBCI == osr_bci)) {
1223 // Positive OSROnlyBCI means only compile that bci. Negative means don't compile that BCI.
1224 return;
1225 }
1226 }
1227 #endif
1228
1229 // If this method is already in the compile queue, then
1230 // we do not block the current thread.
1231 if (compilation_is_in_queue(method)) {
1232 // We may want to decay our counter a bit here to prevent
1233 // multiple denied requests for compilation. This is an
1234 // open compilation policy issue. Note: The other possibility,
1235 // in the case that this is a blocking compile request, is to have
1236 // all subsequent blocking requesters wait for completion of
1237 // ongoing compiles. Note that in this case we'll need a protocol
1238 // for freeing the associated compile tasks. [Or we could have
1239 // a single static monitor on which all these waiters sleep.]
1240 return;
1241 }
1242
1243 // Tiered policy requires MethodCounters to exist before adding a method to
1244 // the queue. Create if we don't have them yet.
1245 method->get_method_counters(thread);
1246
1247 // Outputs from the following MutexLocker block:
1248 CompileTask* task = nullptr;
1249 CompileQueue* queue = compile_queue(comp_level);
1250
1251 // Acquire our lock.
1252 {
1253 MutexLocker locker(thread, MethodCompileQueue_lock);
1254
1255 // Make sure the method has not slipped into the queues since
1256 // last we checked; note that those checks were "fast bail-outs".
1257 // Here we need to be more careful, see 14012000 below.
1258 if (compilation_is_in_queue(method)) {
1259 return;
1260 }
1261
1262 // We need to check again to see if the compilation has
1263 // completed. A previous compilation may have registered
1264 // some result.
1265 if (compilation_is_complete(method, osr_bci, comp_level)) {
1266 return;
1267 }
1268
1269 // We now know that this compilation is not pending, complete,
1270 // or prohibited. Assign a compile_id to this compilation
1271 // and check to see if it is in our [Start..Stop) range.
1272 int compile_id = assign_compile_id(method, osr_bci);
1273 if (compile_id == 0) {
1274 // The compilation falls outside the allowed range.
1275 return;
1276 }
1277
1278 #if INCLUDE_JVMCI
1279 if (UseJVMCICompiler && blocking) {
1280 // Don't allow blocking compiles for requests triggered by JVMCI.
1281 if (thread->is_Compiler_thread()) {
1282 blocking = false;
1283 }
1284
1285 // In libjvmci, JVMCI initialization should not deadlock with other threads
1286 if (!UseJVMCINativeLibrary) {
1287 // Don't allow blocking compiles if inside a class initializer or while performing class loading
1288 vframeStream vfst(JavaThread::cast(thread));
1289 for (; !vfst.at_end(); vfst.next()) {
1290 if (vfst.method()->is_static_initializer() ||
1291 (vfst.method()->method_holder()->is_subclass_of(vmClasses::ClassLoader_klass()) &&
1292 vfst.method()->name() == vmSymbols::loadClass_name())) {
1293 blocking = false;
1294 break;
1295 }
1296 }
1297
1298 // Don't allow blocking compilation requests to JVMCI
1299 // if JVMCI itself is not yet initialized
1300 if (!JVMCI::is_compiler_initialized() && compiler(comp_level)->is_jvmci()) {
1301 blocking = false;
1302 }
1303 }
1304
1305 // Don't allow blocking compilation requests if we are in JVMCIRuntime::shutdown
1306 // to avoid deadlock between compiler thread(s) and threads run at shutdown
1307 // such as the DestroyJavaVM thread.
1308 if (JVMCI::in_shutdown()) {
1309 blocking = false;
1310 }
1311 }
1312 #endif // INCLUDE_JVMCI
1313
1314 // We will enter the compilation in the queue.
1315 // 14012000: Note that this sets the queued_for_compile bits in
1316 // the target method. We can now reason that a method cannot be
1317 // queued for compilation more than once, as follows:
1318 // Before a thread queues a task for compilation, it first acquires
1319 // the compile queue lock, then checks if the method's queued bits
1320 // are set or it has already been compiled. Thus there can not be two
1321 // instances of a compilation task for the same method on the
1322 // compilation queue. Consider now the case where the compilation
1323 // thread has already removed a task for that method from the queue
1324 // and is in the midst of compiling it. In this case, the
1325 // queued_for_compile bits must be set in the method (and these
1326 // will be visible to the current thread, since the bits were set
1327 // under protection of the compile queue lock, which we hold now.
1328 // When the compilation completes, the compiler thread first sets
1329 // the compilation result and then clears the queued_for_compile
1330 // bits. Neither of these actions are protected by a barrier (or done
1331 // under the protection of a lock), so the only guarantee we have
1332 // (on machines with TSO (Total Store Order)) is that these values
1333 // will update in that order. As a result, the only combinations of
1334 // these bits that the current thread will see are, in temporal order:
1335 // <RESULT, QUEUE> :
1336 // <0, 1> : in compile queue, but not yet compiled
1337 // <1, 1> : compiled but queue bit not cleared
1338 // <1, 0> : compiled and queue bit cleared
1339 // Because we first check the queue bits then check the result bits,
1340 // we are assured that we cannot introduce a duplicate task.
1341 // Note that if we did the tests in the reverse order (i.e. check
1342 // result then check queued bit), we could get the result bit before
1343 // the compilation completed, and the queue bit after the compilation
1344 // completed, and end up introducing a "duplicate" (redundant) task.
1345 // In that case, the compiler thread should first check if a method
1346 // has already been compiled before trying to compile it.
1347 // NOTE: in the event that there are multiple compiler threads and
1348 // there is de-optimization/recompilation, things will get hairy,
1349 // and in that case it's best to protect both the testing (here) of
1350 // these bits, and their updating (here and elsewhere) under a
1351 // common lock.
1352 task = create_compile_task(queue,
1353 compile_id, method,
1354 osr_bci, comp_level,
1355 hot_count, compile_reason,
1356 blocking);
1357 }
1358
1359 if (blocking) {
1360 wait_for_completion(task);
1361 }
1362 }
1363
1364 nmethod* CompileBroker::compile_method(const methodHandle& method, int osr_bci,
1365 int comp_level,
1366 int hot_count,
1367 CompileTask::CompileReason compile_reason,
1368 TRAPS) {
1369 // Do nothing if compilebroker is not initialized or compiles are submitted on level none
1370 if (!_initialized || comp_level == CompLevel_none) {
1371 return nullptr;
1372 }
1373
1374 AbstractCompiler *comp = CompileBroker::compiler(comp_level);
1375 assert(comp != nullptr, "Ensure we have a compiler");
1376
1377 #if INCLUDE_JVMCI
1378 if (comp->is_jvmci() && !JVMCI::can_initialize_JVMCI()) {
1379 // JVMCI compilation is not yet initializable.
1380 return nullptr;
1381 }
1382 #endif
1383
1384 DirectiveSet* directive = DirectivesStack::getMatchingDirective(method, comp);
1385 // CompileBroker::compile_method can trap and can have pending async exception.
1386 nmethod* nm = CompileBroker::compile_method(method, osr_bci, comp_level, hot_count, compile_reason, directive, THREAD);
1387 DirectivesStack::release(directive);
1388 return nm;
1389 }
1390
1391 nmethod* CompileBroker::compile_method(const methodHandle& method, int osr_bci,
1392 int comp_level,
1393 int hot_count,
1394 CompileTask::CompileReason compile_reason,
1395 DirectiveSet* directive,
1396 TRAPS) {
1397
1398 // make sure arguments make sense
1399 assert(method->method_holder()->is_instance_klass(), "not an instance method");
1400 assert(osr_bci == InvocationEntryBci || (0 <= osr_bci && osr_bci < method->code_size()), "bci out of range");
1401 assert(!method->is_abstract() && (osr_bci == InvocationEntryBci || !method->is_native()), "cannot compile abstract/native methods");
1402 assert(!method->method_holder()->is_not_initialized(), "method holder must be initialized");
1403 // return quickly if possible
1404
1405 // lock, make sure that the compilation
1406 // isn't prohibited in a straightforward way.
1407 AbstractCompiler* comp = CompileBroker::compiler(comp_level);
1408 if (comp == nullptr || compilation_is_prohibited(method, osr_bci, comp_level, directive->ExcludeOption)) {
1409 return nullptr;
1410 }
1411
1412 if (osr_bci == InvocationEntryBci) {
1413 // standard compilation
1414 nmethod* method_code = method->code();
1415 if (method_code != nullptr) {
1416 if (compilation_is_complete(method, osr_bci, comp_level)) {
1417 return method_code;
1418 }
1419 }
1420 if (method->is_not_compilable(comp_level)) {
1421 return nullptr;
1422 }
1423 } else {
1424 // osr compilation
1425 // We accept a higher level osr method
1426 nmethod* nm = method->lookup_osr_nmethod_for(osr_bci, comp_level, false);
1427 if (nm != nullptr) return nm;
1428 if (method->is_not_osr_compilable(comp_level)) return nullptr;
1429 }
1430
1431 assert(!HAS_PENDING_EXCEPTION, "No exception should be present");
1432 // some prerequisites that are compiler specific
1433 if (comp->is_c2() || comp->is_jvmci()) {
1434 InternalOOMEMark iom(THREAD);
1435 method->constants()->resolve_string_constants(CHECK_AND_CLEAR_NONASYNC_NULL);
1436 // Resolve all classes seen in the signature of the method
1437 // we are compiling.
1438 Method::load_signature_classes(method, CHECK_AND_CLEAR_NONASYNC_NULL);
1439 }
1440
1441 // If the method is native, do the lookup in the thread requesting
1442 // the compilation. Native lookups can load code, which is not
1443 // permitted during compilation.
1444 //
1445 // Note: A native method implies non-osr compilation which is
1446 // checked with an assertion at the entry of this method.
1447 if (method->is_native() && !method->is_method_handle_intrinsic()) {
1448 address adr = NativeLookup::lookup(method, THREAD);
1449 if (HAS_PENDING_EXCEPTION) {
1450 // In case of an exception looking up the method, we just forget
1451 // about it. The interpreter will kick-in and throw the exception.
1452 method->set_not_compilable("NativeLookup::lookup failed"); // implies is_not_osr_compilable()
1453 CLEAR_PENDING_EXCEPTION;
1454 return nullptr;
1455 }
1456 assert(method->has_native_function(), "must have native code by now");
1457 }
1458
1459 // RedefineClasses() has replaced this method; just return
1460 if (method->is_old()) {
1461 return nullptr;
1462 }
1463
1464 // JVMTI -- post_compile_event requires jmethod_id() that may require
1465 // a lock the compiling thread can not acquire. Prefetch it here.
1466 if (JvmtiExport::should_post_compiled_method_load()) {
1467 method->jmethod_id();
1468 }
1469
1470 // do the compilation
1471 if (method->is_native()) {
1472 if (!PreferInterpreterNativeStubs || method->is_method_handle_intrinsic()) {
1473 // To properly handle the appendix argument for out-of-line calls we are using a small trampoline that
1474 // pops off the appendix argument and jumps to the target (see gen_special_dispatch in SharedRuntime).
1475 //
1476 // Since normal compiled-to-compiled calls are not able to handle such a thing we MUST generate an adapter
1477 // in this case. If we can't generate one and use it we can not execute the out-of-line method handle calls.
1478 AdapterHandlerLibrary::create_native_wrapper(method);
1479 } else {
1480 return nullptr;
1481 }
1482 } else {
1483 // If the compiler is shut off due to code cache getting full
1484 // fail out now so blocking compiles dont hang the java thread
1485 if (!should_compile_new_jobs()) {
1486 return nullptr;
1487 }
1488 bool is_blocking = !directive->BackgroundCompilationOption || ReplayCompiles;
1489 compile_method_base(method, osr_bci, comp_level, hot_count, compile_reason, is_blocking, THREAD);
1490 }
1491
1492 // return requested nmethod
1493 // We accept a higher level osr method
1494 if (osr_bci == InvocationEntryBci) {
1495 return method->code();
1496 }
1497 return method->lookup_osr_nmethod_for(osr_bci, comp_level, false);
1498 }
1499
1500
1501 // ------------------------------------------------------------------
1502 // CompileBroker::compilation_is_complete
1503 //
1504 // See if compilation of this method is already complete.
1505 bool CompileBroker::compilation_is_complete(const methodHandle& method,
1506 int osr_bci,
1507 int comp_level) {
1508 bool is_osr = (osr_bci != standard_entry_bci);
1509 if (is_osr) {
1510 if (method->is_not_osr_compilable(comp_level)) {
1511 return true;
1512 } else {
1513 nmethod* result = method->lookup_osr_nmethod_for(osr_bci, comp_level, true);
1514 return (result != nullptr);
1515 }
1516 } else {
1517 if (method->is_not_compilable(comp_level)) {
1518 return true;
1519 } else {
1520 nmethod* result = method->code();
1521 if (result == nullptr) return false;
1522 return comp_level == result->comp_level();
1523 }
1524 }
1525 }
1526
1527
1528 /**
1529 * See if this compilation is already requested.
1530 *
1531 * Implementation note: there is only a single "is in queue" bit
1532 * for each method. This means that the check below is overly
1533 * conservative in the sense that an osr compilation in the queue
1534 * will block a normal compilation from entering the queue (and vice
1535 * versa). This can be remedied by a full queue search to disambiguate
1536 * cases. If it is deemed profitable, this may be done.
1537 */
1538 bool CompileBroker::compilation_is_in_queue(const methodHandle& method) {
1539 return method->queued_for_compilation();
1540 }
1541
1542 // ------------------------------------------------------------------
1543 // CompileBroker::compilation_is_prohibited
1544 //
1545 // See if this compilation is not allowed.
1546 bool CompileBroker::compilation_is_prohibited(const methodHandle& method, int osr_bci, int comp_level, bool excluded) {
1547 bool is_native = method->is_native();
1548 // Some compilers may not support the compilation of natives.
1549 AbstractCompiler *comp = compiler(comp_level);
1550 if (is_native && (!CICompileNatives || comp == nullptr)) {
1551 method->set_not_compilable_quietly("native methods not supported", comp_level);
1552 return true;
1553 }
1554
1555 bool is_osr = (osr_bci != standard_entry_bci);
1556 // Some compilers may not support on stack replacement.
1557 if (is_osr && (!CICompileOSR || comp == nullptr)) {
1558 method->set_not_osr_compilable("OSR not supported", comp_level);
1559 return true;
1560 }
1561
1562 // The method may be explicitly excluded by the user.
1563 double scale;
1564 if (excluded || (CompilerOracle::has_option_value(method, CompileCommandEnum::CompileThresholdScaling, scale) && scale == 0)) {
1565 bool quietly = CompilerOracle::be_quiet();
1566 if (PrintCompilation && !quietly) {
1567 // This does not happen quietly...
1568 ResourceMark rm;
1569 tty->print("### Excluding %s:%s",
1570 method->is_native() ? "generation of native wrapper" : "compile",
1571 (method->is_static() ? " static" : ""));
1572 method->print_short_name(tty);
1573 tty->cr();
1574 }
1575 method->set_not_compilable("excluded by CompileCommand", comp_level, !quietly);
1576 }
1577
1578 return false;
1579 }
1580
1581 /**
1582 * Generate serialized IDs for compilation requests. If certain debugging flags are used
1583 * and the ID is not within the specified range, the method is not compiled and 0 is returned.
1584 * The function also allows to generate separate compilation IDs for OSR compilations.
1585 */
1586 int CompileBroker::assign_compile_id(const methodHandle& method, int osr_bci) {
1587 #ifdef ASSERT
1588 bool is_osr = (osr_bci != standard_entry_bci);
1589 int id;
1590 if (method->is_native()) {
1591 assert(!is_osr, "can't be osr");
1592 // Adapters, native wrappers and method handle intrinsics
1593 // should be generated always.
1594 return AtomicAccess::add(CICountNative ? &_native_compilation_id : &_compilation_id, 1);
1595 } else if (CICountOSR && is_osr) {
1596 id = AtomicAccess::add(&_osr_compilation_id, 1);
1597 if (CIStartOSR <= id && id < CIStopOSR) {
1598 return id;
1599 }
1600 } else {
1601 id = AtomicAccess::add(&_compilation_id, 1);
1602 if (CIStart <= id && id < CIStop) {
1603 return id;
1604 }
1605 }
1606
1607 // Method was not in the appropriate compilation range.
1608 method->set_not_compilable_quietly("Not in requested compile id range");
1609 return 0;
1610 #else
1611 // CICountOSR is a develop flag and set to 'false' by default. In a product built,
1612 // only _compilation_id is incremented.
1613 return AtomicAccess::add(&_compilation_id, 1);
1614 #endif
1615 }
1616
1617 // ------------------------------------------------------------------
1618 // CompileBroker::assign_compile_id_unlocked
1619 //
1620 // Public wrapper for assign_compile_id that acquires the needed locks
1621 int CompileBroker::assign_compile_id_unlocked(Thread* thread, const methodHandle& method, int osr_bci) {
1622 MutexLocker locker(thread, MethodCompileQueue_lock);
1623 return assign_compile_id(method, osr_bci);
1624 }
1625
1626 // ------------------------------------------------------------------
1627 // CompileBroker::create_compile_task
1628 //
1629 // Create a CompileTask object representing the current request for
1630 // compilation. Add this task to the queue.
1631 CompileTask* CompileBroker::create_compile_task(CompileQueue* queue,
1632 int compile_id,
1633 const methodHandle& method,
1634 int osr_bci,
1635 int comp_level,
1636 int hot_count,
1637 CompileTask::CompileReason compile_reason,
1638 bool blocking) {
1639 CompileTask* new_task = new CompileTask(compile_id, method, osr_bci, comp_level,
1640 hot_count, compile_reason, blocking);
1641 queue->add(new_task);
1642 return new_task;
1643 }
1644
1645 #if INCLUDE_JVMCI
1646 // The number of milliseconds to wait before checking if
1647 // JVMCI compilation has made progress.
1648 static const long JVMCI_COMPILATION_PROGRESS_WAIT_TIMESLICE = 1000;
1649
1650 // The number of JVMCI compilation progress checks that must fail
1651 // before unblocking a thread waiting for a blocking compilation.
1652 static const int JVMCI_COMPILATION_PROGRESS_WAIT_ATTEMPTS = 10;
1653
1654 /**
1655 * Waits for a JVMCI compiler to complete a given task. This thread
1656 * waits until either the task completes or it sees no JVMCI compilation
1657 * progress for N consecutive milliseconds where N is
1658 * JVMCI_COMPILATION_PROGRESS_WAIT_TIMESLICE *
1659 * JVMCI_COMPILATION_PROGRESS_WAIT_ATTEMPTS.
1660 *
1661 * @return true if this thread needs to delete the task
1662 */
1663 bool CompileBroker::wait_for_jvmci_completion(JVMCICompiler* jvmci, CompileTask* task, JavaThread* thread) {
1664 assert(UseJVMCICompiler, "sanity");
1665 MonitorLocker ml(thread, CompileTaskWait_lock);
1666 int progress_wait_attempts = 0;
1667 jint thread_jvmci_compilation_ticks = 0;
1668 jint global_jvmci_compilation_ticks = jvmci->global_compilation_ticks();
1669 while (!task->is_complete() && !is_compilation_disabled_forever() &&
1670 ml.wait(JVMCI_COMPILATION_PROGRESS_WAIT_TIMESLICE)) {
1671 JVMCICompileState* jvmci_compile_state = task->blocking_jvmci_compile_state();
1672
1673 bool progress;
1674 if (jvmci_compile_state != nullptr) {
1675 jint ticks = jvmci_compile_state->compilation_ticks();
1676 progress = (ticks - thread_jvmci_compilation_ticks) != 0;
1677 JVMCI_event_1("waiting on compilation %d [ticks=%d]", task->compile_id(), ticks);
1678 thread_jvmci_compilation_ticks = ticks;
1679 } else {
1680 // Still waiting on JVMCI compiler queue. This thread may be holding a lock
1681 // that all JVMCI compiler threads are blocked on. We use the global JVMCI
1682 // compilation ticks to determine whether JVMCI compilation
1683 // is still making progress through the JVMCI compiler queue.
1684 jint ticks = jvmci->global_compilation_ticks();
1685 progress = (ticks - global_jvmci_compilation_ticks) != 0;
1686 JVMCI_event_1("waiting on compilation %d to be queued [ticks=%d]", task->compile_id(), ticks);
1687 global_jvmci_compilation_ticks = ticks;
1688 }
1689
1690 if (!progress) {
1691 if (++progress_wait_attempts == JVMCI_COMPILATION_PROGRESS_WAIT_ATTEMPTS) {
1692 if (PrintCompilation) {
1693 task->print(tty, "wait for blocking compilation timed out");
1694 }
1695 JVMCI_event_1("waiting on compilation %d timed out", task->compile_id());
1696 break;
1697 }
1698 } else {
1699 progress_wait_attempts = 0;
1700 }
1701 }
1702 task->clear_waiter();
1703 return task->is_complete();
1704 }
1705 #endif
1706
1707 /**
1708 * Wait for the compilation task to complete.
1709 */
1710 void CompileBroker::wait_for_completion(CompileTask* task) {
1711 if (CIPrintCompileQueue) {
1712 ttyLocker ttyl;
1713 tty->print_cr("BLOCKING FOR COMPILE");
1714 }
1715
1716 assert(task->is_blocking(), "can only wait on blocking task");
1717
1718 JavaThread* thread = JavaThread::current();
1719
1720 methodHandle method(thread, task->method());
1721 bool free_task;
1722 #if INCLUDE_JVMCI
1723 AbstractCompiler* comp = compiler(task->comp_level());
1724 if (!UseJVMCINativeLibrary && comp->is_jvmci() && !task->should_wait_for_compilation()) {
1725 // It may return before compilation is completed.
1726 // Note that libjvmci should not pre-emptively unblock
1727 // a thread waiting for a compilation as it does not call
1728 // Java code and so is not deadlock prone like jarjvmci.
1729 free_task = wait_for_jvmci_completion((JVMCICompiler*) comp, task, thread);
1730 } else
1731 #endif
1732 {
1733 free_task = true;
1734 // Wait until the task is complete or compilation is shut down.
1735 MonitorLocker ml(thread, CompileTaskWait_lock);
1736 while (!task->is_complete() && !is_compilation_disabled_forever()) {
1737 ml.wait();
1738 }
1739 }
1740
1741 // It is harmless to check this status without the lock, because
1742 // completion is a stable property.
1743 if (!task->is_complete()) {
1744 // Task is not complete, likely because we are exiting for compilation
1745 // shutdown. The task can still be reached through the queue, or executed
1746 // by some compiler thread. There is no coordination with either MCQ lock
1747 // holders or compilers, therefore we cannot delete the task.
1748 //
1749 // This will leave task allocated, which leaks it. At this (degraded) point,
1750 // it is less risky to abandon the task, rather than attempting a more
1751 // complicated deletion protocol.
1752 free_task = false;
1753 }
1754
1755 if (free_task) {
1756 assert(task->is_complete(), "Compilation should have completed");
1757 assert(task->next() == nullptr && task->prev() == nullptr,
1758 "Completed task should not be in the queue");
1759
1760 // By convention, the waiter is responsible for deleting a
1761 // blocking CompileTask. Since there is only one waiter ever
1762 // waiting on a CompileTask, we know that no one else will
1763 // be using this CompileTask; we can delete it.
1764 delete task;
1765 }
1766 }
1767
1768 void CompileBroker::wait_for_no_active_tasks() {
1769 CompileTask::wait_for_no_active_tasks();
1770 }
1771
1772 /**
1773 * Initialize compiler thread(s) + compiler object(s). The postcondition
1774 * of this function is that the compiler runtimes are initialized and that
1775 * compiler threads can start compiling.
1776 */
1777 bool CompileBroker::init_compiler_runtime() {
1778 CompilerThread* thread = CompilerThread::current();
1779 AbstractCompiler* comp = thread->compiler();
1780 // Final sanity check - the compiler object must exist
1781 guarantee(comp != nullptr, "Compiler object must exist");
1782
1783 {
1784 // Must switch to native to allocate ci_env
1785 ThreadToNativeFromVM ttn(thread);
1786 ciEnv ci_env((CompileTask*)nullptr);
1787 // Cache Jvmti state
1788 ci_env.cache_jvmti_state();
1789 // Cache DTrace flags
1790 ci_env.cache_dtrace_flags();
1791
1792 // Switch back to VM state to do compiler initialization
1793 ThreadInVMfromNative tv(thread);
1794
1795 // Perform per-thread and global initializations
1796 comp->initialize();
1797 }
1798
1799 if (comp->is_failed()) {
1800 disable_compilation_forever();
1801 // If compiler initialization failed, no compiler thread that is specific to a
1802 // particular compiler runtime will ever start to compile methods.
1803 shutdown_compiler_runtime(comp, thread);
1804 return false;
1805 }
1806
1807 // C1 specific check
1808 if (comp->is_c1() && (thread->get_buffer_blob() == nullptr)) {
1809 warning("Initialization of %s thread failed (no space to run compilers)", thread->name());
1810 return false;
1811 }
1812
1813 return true;
1814 }
1815
1816 void CompileBroker::free_buffer_blob_if_allocated(CompilerThread* thread) {
1817 BufferBlob* blob = thread->get_buffer_blob();
1818 if (blob != nullptr) {
1819 blob->purge();
1820 MutexLocker mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
1821 CodeCache::free(blob);
1822 }
1823 }
1824
1825 /**
1826 * If C1 and/or C2 initialization failed, we shut down all compilation.
1827 * We do this to keep things simple. This can be changed if it ever turns
1828 * out to be a problem.
1829 */
1830 void CompileBroker::shutdown_compiler_runtime(AbstractCompiler* comp, CompilerThread* thread) {
1831 free_buffer_blob_if_allocated(thread);
1832
1833 if (comp->should_perform_shutdown()) {
1834 // There are two reasons for shutting down the compiler
1835 // 1) compiler runtime initialization failed
1836 // 2) The code cache is full and the following flag is set: -XX:-UseCodeCacheFlushing
1837 warning("%s initialization failed. Shutting down all compilers", comp->name());
1838
1839 // Only one thread per compiler runtime object enters here
1840 // Set state to shut down
1841 comp->set_shut_down();
1842
1843 // Delete all queued compilation tasks to make compiler threads exit faster.
1844 if (_c1_compile_queue != nullptr) {
1845 _c1_compile_queue->delete_all();
1846 }
1847
1848 if (_c2_compile_queue != nullptr) {
1849 _c2_compile_queue->delete_all();
1850 }
1851
1852 // Set flags so that we continue execution with using interpreter only.
1853 UseCompiler = false;
1854 UseInterpreter = true;
1855
1856 // We could delete compiler runtimes also. However, there are references to
1857 // the compiler runtime(s) (e.g., nmethod::is_compiled_by_c1()) which then
1858 // fail. This can be done later if necessary.
1859 }
1860 }
1861
1862 /**
1863 * Helper function to create new or reuse old CompileLog.
1864 */
1865 CompileLog* CompileBroker::get_log(CompilerThread* ct) {
1866 if (!LogCompilation) return nullptr;
1867
1868 AbstractCompiler *compiler = ct->compiler();
1869 bool c1 = compiler->is_c1();
1870 jobject* compiler_objects = c1 ? _compiler1_objects : _compiler2_objects;
1871 assert(compiler_objects != nullptr, "must be initialized at this point");
1872 CompileLog** logs = c1 ? _compiler1_logs : _compiler2_logs;
1873 assert(logs != nullptr, "must be initialized at this point");
1874 int count = c1 ? _c1_count : _c2_count;
1875
1876 // Find Compiler number by its threadObj.
1877 oop compiler_obj = ct->threadObj();
1878 int compiler_number = 0;
1879 bool found = false;
1880 for (; compiler_number < count; compiler_number++) {
1881 if (JNIHandles::resolve_non_null(compiler_objects[compiler_number]) == compiler_obj) {
1882 found = true;
1883 break;
1884 }
1885 }
1886 assert(found, "Compiler must exist at this point");
1887
1888 // Determine pointer for this thread's log.
1889 CompileLog** log_ptr = &logs[compiler_number];
1890
1891 // Return old one if it exists.
1892 CompileLog* log = *log_ptr;
1893 if (log != nullptr) {
1894 ct->init_log(log);
1895 return log;
1896 }
1897
1898 // Create a new one and remember it.
1899 init_compiler_thread_log();
1900 log = ct->log();
1901 *log_ptr = log;
1902 return log;
1903 }
1904
1905 // ------------------------------------------------------------------
1906 // CompileBroker::compiler_thread_loop
1907 //
1908 // The main loop run by a CompilerThread.
1909 void CompileBroker::compiler_thread_loop() {
1910 CompilerThread* thread = CompilerThread::current();
1911 CompileQueue* queue = thread->queue();
1912 // For the thread that initializes the ciObjectFactory
1913 // this resource mark holds all the shared objects
1914 ResourceMark rm;
1915
1916 // First thread to get here will initialize the compiler interface
1917
1918 {
1919 ASSERT_IN_VM;
1920 MutexLocker only_one (thread, CompileThread_lock);
1921 if (!ciObjectFactory::is_initialized()) {
1922 ciObjectFactory::initialize();
1923 }
1924 }
1925
1926 // Open a log.
1927 CompileLog* log = get_log(thread);
1928 if (log != nullptr) {
1929 log->begin_elem("start_compile_thread name='%s' thread='%zu' process='%d'",
1930 thread->name(),
1931 os::current_thread_id(),
1932 os::current_process_id());
1933 log->stamp();
1934 log->end_elem();
1935 }
1936
1937 if (!thread->init_compilation_timeout()) {
1938 return;
1939 }
1940
1941 // If compiler thread/runtime initialization fails, exit the compiler thread
1942 if (!init_compiler_runtime()) {
1943 return;
1944 }
1945
1946 thread->start_idle_timer();
1947
1948 // Poll for new compilation tasks as long as the JVM runs. Compilation
1949 // should only be disabled if something went wrong while initializing the
1950 // compiler runtimes. This, in turn, should not happen. The only known case
1951 // when compiler runtime initialization fails is if there is not enough free
1952 // space in the code cache to generate the necessary stubs, etc.
1953 while (!is_compilation_disabled_forever()) {
1954 // We need this HandleMark to avoid leaking VM handles.
1955 HandleMark hm(thread);
1956
1957 CompileTask* task = queue->get(thread);
1958 if (task == nullptr) {
1959 if (UseDynamicNumberOfCompilerThreads) {
1960 // Access compiler_count under lock to enforce consistency.
1961 MutexLocker only_one(CompileThread_lock);
1962 if (can_remove(thread, true)) {
1963 if (trace_compiler_threads()) {
1964 ResourceMark rm;
1965 stringStream msg;
1966 msg.print("Removing compiler thread %s after " JLONG_FORMAT " ms idle time",
1967 thread->name(), thread->idle_time_millis());
1968 print_compiler_threads(msg);
1969 }
1970
1971 // Notify compiler that the compiler thread is about to stop
1972 thread->compiler()->stopping_compiler_thread(thread);
1973
1974 free_buffer_blob_if_allocated(thread);
1975 return; // Stop this thread.
1976 }
1977 }
1978 } else {
1979 // Assign the task to the current thread. Mark this compilation
1980 // thread as active for the profiler.
1981 // CompileTaskWrapper also keeps the Method* from being deallocated if redefinition
1982 // occurs after fetching the compile task off the queue.
1983 CompileTaskWrapper ctw(task);
1984 methodHandle method(thread, task->method());
1985
1986 // Never compile a method if breakpoints are present in it
1987 if (method()->number_of_breakpoints() == 0) {
1988 // Compile the method.
1989 if ((UseCompiler || AlwaysCompileLoopMethods) && CompileBroker::should_compile_new_jobs()) {
1990 invoke_compiler_on_method(task);
1991 thread->start_idle_timer();
1992 } else {
1993 // After compilation is disabled, remove remaining methods from queue
1994 method->clear_queued_for_compilation();
1995 task->set_failure_reason("compilation is disabled");
1996 }
1997 } else {
1998 task->set_failure_reason("breakpoints are present");
1999 }
2000
2001 if (UseDynamicNumberOfCompilerThreads) {
2002 possibly_add_compiler_threads(thread);
2003 assert(!thread->has_pending_exception(), "should have been handled");
2004 }
2005 }
2006 }
2007
2008 // Shut down compiler runtime
2009 shutdown_compiler_runtime(thread->compiler(), thread);
2010 }
2011
2012 // ------------------------------------------------------------------
2013 // CompileBroker::init_compiler_thread_log
2014 //
2015 // Set up state required by +LogCompilation.
2016 void CompileBroker::init_compiler_thread_log() {
2017 CompilerThread* thread = CompilerThread::current();
2018 char file_name[4*K];
2019 FILE* fp = nullptr;
2020 intx thread_id = os::current_thread_id();
2021 for (int try_temp_dir = 1; try_temp_dir >= 0; try_temp_dir--) {
2022 const char* dir = (try_temp_dir ? os::get_temp_directory() : nullptr);
2023 if (dir == nullptr) {
2024 jio_snprintf(file_name, sizeof(file_name), "hs_c%zu_pid%u.log",
2025 thread_id, os::current_process_id());
2026 } else {
2027 jio_snprintf(file_name, sizeof(file_name),
2028 "%s%shs_c%zu_pid%u.log", dir,
2029 os::file_separator(), thread_id, os::current_process_id());
2030 }
2031
2032 fp = os::fopen(file_name, "wt");
2033 if (fp != nullptr) {
2034 if (LogCompilation && Verbose) {
2035 tty->print_cr("Opening compilation log %s", file_name);
2036 }
2037 CompileLog* log = new(mtCompiler) CompileLog(file_name, fp, thread_id);
2038 if (log == nullptr) {
2039 fclose(fp);
2040 return;
2041 }
2042 thread->init_log(log);
2043
2044 if (xtty != nullptr) {
2045 ttyLocker ttyl;
2046 // Record any per thread log files
2047 xtty->elem("thread_logfile thread='%zd' filename='%s'", thread_id, file_name);
2048 }
2049 return;
2050 }
2051 }
2052 warning("Cannot open log file: %s", file_name);
2053 }
2054
2055 void CompileBroker::log_metaspace_failure() {
2056 const char* message = "some methods may not be compiled because metaspace "
2057 "is out of memory";
2058 if (CompilationLog::log() != nullptr) {
2059 CompilationLog::log()->log_metaspace_failure(message);
2060 }
2061 if (PrintCompilation) {
2062 tty->print_cr("COMPILE PROFILING SKIPPED: %s", message);
2063 }
2064 }
2065
2066
2067 // ------------------------------------------------------------------
2068 // CompileBroker::set_should_block
2069 //
2070 // Set _should_block.
2071 // Call this from the VM, with Threads_lock held and a safepoint requested.
2072 void CompileBroker::set_should_block() {
2073 assert(Threads_lock->owner() == Thread::current(), "must have threads lock");
2074 assert(SafepointSynchronize::is_at_safepoint(), "must be at a safepoint already");
2075 #ifndef PRODUCT
2076 if (PrintCompilation && (Verbose || WizardMode))
2077 tty->print_cr("notifying compiler thread pool to block");
2078 #endif
2079 _should_block = true;
2080 }
2081
2082 // ------------------------------------------------------------------
2083 // CompileBroker::maybe_block
2084 //
2085 // Call this from the compiler at convenient points, to poll for _should_block.
2086 void CompileBroker::maybe_block() {
2087 if (_should_block) {
2088 #ifndef PRODUCT
2089 if (PrintCompilation && (Verbose || WizardMode))
2090 tty->print_cr("compiler thread " INTPTR_FORMAT " poll detects block request", p2i(Thread::current()));
2091 #endif
2092 // If we are executing a task during the request to block, report the task
2093 // before disappearing.
2094 CompilerThread* thread = CompilerThread::current();
2095 if (thread != nullptr) {
2096 CompileTask* task = thread->task();
2097 if (task != nullptr) {
2098 if (PrintCompilation) {
2099 task->print(tty, "blocked");
2100 }
2101 task->print_ul("blocked");
2102 }
2103 }
2104 // Go to VM state and block for final VM shutdown safepoint.
2105 ThreadInVMfromNative tivfn(JavaThread::current());
2106 assert(false, "Should never unblock from TIVNM entry");
2107 }
2108 }
2109
2110 // wrapper for CodeCache::print_summary()
2111 static void codecache_print(bool detailed)
2112 {
2113 stringStream s;
2114 // Dump code cache into a buffer before locking the tty,
2115 {
2116 MutexLocker mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
2117 CodeCache::print_summary(&s, detailed);
2118 }
2119 ttyLocker ttyl;
2120 tty->print("%s", s.freeze());
2121 }
2122
2123 // wrapper for CodeCache::print_summary() using outputStream
2124 static void codecache_print(outputStream* out, bool detailed) {
2125 stringStream s;
2126
2127 // Dump code cache into a buffer
2128 {
2129 MutexLocker mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
2130 CodeCache::print_summary(&s, detailed);
2131 }
2132
2133 char* remaining_log = s.as_string();
2134 while (*remaining_log != '\0') {
2135 char* eol = strchr(remaining_log, '\n');
2136 if (eol == nullptr) {
2137 out->print_cr("%s", remaining_log);
2138 remaining_log = remaining_log + strlen(remaining_log);
2139 } else {
2140 *eol = '\0';
2141 out->print_cr("%s", remaining_log);
2142 remaining_log = eol + 1;
2143 }
2144 }
2145 }
2146
2147 void CompileBroker::handle_compile_error(CompilerThread* thread, CompileTask* task, ciEnv* ci_env,
2148 int compilable, const char* failure_reason) {
2149 if (!AbortVMOnCompilationFailure) {
2150 return;
2151 }
2152 if (compilable == ciEnv::MethodCompilable_not_at_tier) {
2153 fatal("Not compilable at tier %d: %s", task->comp_level(), failure_reason);
2154 }
2155 if (compilable == ciEnv::MethodCompilable_never) {
2156 fatal("Never compilable: %s", failure_reason);
2157 }
2158 }
2159
2160 static void post_compilation_event(EventCompilation& event, CompileTask* task) {
2161 assert(task != nullptr, "invariant");
2162 CompilerEvent::CompilationEvent::post(event,
2163 task->compile_id(),
2164 task->compiler()->type(),
2165 task->method(),
2166 task->comp_level(),
2167 task->is_success(),
2168 task->osr_bci() != CompileBroker::standard_entry_bci,
2169 task->nm_total_size(),
2170 task->num_inlined_bytecodes(),
2171 task->arena_bytes());
2172 }
2173
2174 int DirectivesStack::_depth = 0;
2175 CompilerDirectives* DirectivesStack::_top = nullptr;
2176 CompilerDirectives* DirectivesStack::_bottom = nullptr;
2177
2178 // Acquires Compilation_lock and waits for it to be notified
2179 // as long as WhiteBox::compilation_locked is true.
2180 static void whitebox_lock_compilation() {
2181 MonitorLocker locker(Compilation_lock, Mutex::_no_safepoint_check_flag);
2182 while (WhiteBox::compilation_locked) {
2183 locker.wait();
2184 }
2185 }
2186
2187 // ------------------------------------------------------------------
2188 // CompileBroker::invoke_compiler_on_method
2189 //
2190 // Compile a method.
2191 //
2192 void CompileBroker::invoke_compiler_on_method(CompileTask* task) {
2193 task->print_ul();
2194 elapsedTimer time;
2195
2196 DirectiveSet* directive = task->directive();
2197 if (directive->PrintCompilationOption) {
2198 ResourceMark rm;
2199 task->print_tty();
2200 }
2201
2202 CompilerThread* thread = CompilerThread::current();
2203 ResourceMark rm(thread);
2204
2205 if (CompilationLog::log() != nullptr) {
2206 CompilationLog::log()->log_compile(thread, task);
2207 }
2208
2209 // Common flags.
2210 int compile_id = task->compile_id();
2211 int osr_bci = task->osr_bci();
2212 bool is_osr = (osr_bci != standard_entry_bci);
2213 bool should_log = (thread->log() != nullptr);
2214 bool should_break = false;
2215 const int task_level = task->comp_level();
2216 AbstractCompiler* comp = task->compiler();
2217 {
2218 // create the handle inside it's own block so it can't
2219 // accidentally be referenced once the thread transitions to
2220 // native. The NoHandleMark before the transition should catch
2221 // any cases where this occurs in the future.
2222 methodHandle method(thread, task->method());
2223
2224 assert(!method->is_native(), "no longer compile natives");
2225
2226 // Update compile information when using perfdata.
2227 if (UsePerfData) {
2228 update_compile_perf_data(thread, method, is_osr);
2229 }
2230
2231 DTRACE_METHOD_COMPILE_BEGIN_PROBE(method, compiler_name(task_level));
2232 }
2233
2234 should_break = directive->BreakAtCompileOption || task->check_break_at_flags();
2235 if (should_log && !directive->LogOption) {
2236 should_log = false;
2237 }
2238
2239 // Allocate a new set of JNI handles.
2240 JNIHandleMark jhm(thread);
2241 Method* target_handle = task->method();
2242 int compilable = ciEnv::MethodCompilable;
2243 const char* failure_reason = nullptr;
2244 bool failure_reason_on_C_heap = false;
2245 const char* retry_message = nullptr;
2246
2247 #if INCLUDE_JVMCI
2248 if (UseJVMCICompiler && comp != nullptr && comp->is_jvmci()) {
2249 JVMCICompiler* jvmci = (JVMCICompiler*) comp;
2250
2251 TraceTime t1("compilation", &time);
2252 EventCompilation event;
2253 JVMCICompileState compile_state(task, jvmci);
2254 JVMCIRuntime *runtime = nullptr;
2255
2256 if (JVMCI::in_shutdown()) {
2257 failure_reason = "in JVMCI shutdown";
2258 retry_message = "not retryable";
2259 compilable = ciEnv::MethodCompilable_never;
2260 } else if (compile_state.target_method_is_old()) {
2261 // Skip redefined methods
2262 failure_reason = "redefined method";
2263 retry_message = "not retryable";
2264 compilable = ciEnv::MethodCompilable_never;
2265 } else {
2266 JVMCIEnv env(thread, &compile_state, __FILE__, __LINE__);
2267 if (env.init_error() != JNI_OK) {
2268 const char* msg = env.init_error_msg();
2269 failure_reason = os::strdup(err_msg("Error attaching to libjvmci (err: %d, %s)",
2270 env.init_error(), msg == nullptr ? "unknown" : msg), mtJVMCI);
2271 bool reason_on_C_heap = true;
2272 // In case of JNI_ENOMEM, there's a good chance a subsequent attempt to create libjvmci or attach to it
2273 // might succeed. Other errors most likely indicate a non-recoverable error in the JVMCI runtime.
2274 bool retryable = env.init_error() == JNI_ENOMEM;
2275 compile_state.set_failure(retryable, failure_reason, reason_on_C_heap);
2276 }
2277 if (failure_reason == nullptr) {
2278 if (WhiteBoxAPI && WhiteBox::compilation_locked) {
2279 // Must switch to native to block
2280 ThreadToNativeFromVM ttn(thread);
2281 whitebox_lock_compilation();
2282 }
2283 methodHandle method(thread, target_handle);
2284 runtime = env.runtime();
2285 runtime->compile_method(&env, jvmci, method, osr_bci);
2286
2287 failure_reason = compile_state.failure_reason();
2288 failure_reason_on_C_heap = compile_state.failure_reason_on_C_heap();
2289 if (!compile_state.retryable()) {
2290 retry_message = "not retryable";
2291 compilable = ciEnv::MethodCompilable_not_at_tier;
2292 }
2293 if (!task->is_success()) {
2294 assert(failure_reason != nullptr, "must specify failure_reason");
2295 }
2296 }
2297 }
2298 if (!task->is_success() && !JVMCI::in_shutdown()) {
2299 handle_compile_error(thread, task, nullptr, compilable, failure_reason);
2300 }
2301 if (event.should_commit()) {
2302 post_compilation_event(event, task);
2303 }
2304
2305 if (runtime != nullptr) {
2306 runtime->post_compile(thread);
2307 }
2308 } else
2309 #endif // INCLUDE_JVMCI
2310 {
2311 NoHandleMark nhm;
2312 ThreadToNativeFromVM ttn(thread);
2313
2314 ciEnv ci_env(task);
2315 if (should_break) {
2316 ci_env.set_break_at_compile(true);
2317 }
2318 if (should_log) {
2319 ci_env.set_log(thread->log());
2320 }
2321 assert(thread->env() == &ci_env, "set by ci_env");
2322 // The thread-env() field is cleared in ~CompileTaskWrapper.
2323
2324 // Cache Jvmti state
2325 bool method_is_old = ci_env.cache_jvmti_state();
2326
2327 // Skip redefined methods
2328 if (method_is_old) {
2329 ci_env.record_method_not_compilable("redefined method", true);
2330 }
2331
2332 // Cache DTrace flags
2333 ci_env.cache_dtrace_flags();
2334
2335 ciMethod* target = ci_env.get_method_from_handle(target_handle);
2336
2337 TraceTime t1("compilation", &time);
2338 EventCompilation event;
2339
2340 if (comp == nullptr) {
2341 ci_env.record_method_not_compilable("no compiler");
2342 } else if (!ci_env.failing()) {
2343 if (WhiteBoxAPI && WhiteBox::compilation_locked) {
2344 whitebox_lock_compilation();
2345 }
2346 comp->compile_method(&ci_env, target, osr_bci, true, directive);
2347
2348 /* Repeat compilation without installing code for profiling purposes */
2349 int repeat_compilation_count = directive->RepeatCompilationOption;
2350 if (repeat_compilation_count > 0) {
2351 CHeapStringHolder failure_reason;
2352 failure_reason.set(ci_env._failure_reason.get());
2353 while (repeat_compilation_count > 0) {
2354 ResourceMark rm(thread);
2355 task->print_ul("NO CODE INSTALLED");
2356 thread->timeout()->reset();
2357 ci_env._failure_reason.clear();
2358 comp->compile_method(&ci_env, target, osr_bci, false, directive);
2359 repeat_compilation_count--;
2360 }
2361 ci_env._failure_reason.set(failure_reason.get());
2362 }
2363 }
2364
2365
2366 if (!ci_env.failing() && !task->is_success()) {
2367 assert(ci_env.failure_reason() != nullptr, "expect failure reason");
2368 assert(false, "compiler should always document failure: %s", ci_env.failure_reason());
2369 // The compiler elected, without comment, not to register a result.
2370 // Do not attempt further compilations of this method.
2371 ci_env.record_method_not_compilable("compile failed");
2372 }
2373
2374 // Copy this bit to the enclosing block:
2375 compilable = ci_env.compilable();
2376
2377 if (ci_env.failing()) {
2378 // Duplicate the failure reason string, so that it outlives ciEnv
2379 failure_reason = os::strdup(ci_env.failure_reason(), mtCompiler);
2380 failure_reason_on_C_heap = true;
2381 retry_message = ci_env.retry_message();
2382 ci_env.report_failure(failure_reason);
2383 }
2384
2385 if (ci_env.failing()) {
2386 handle_compile_error(thread, task, &ci_env, compilable, failure_reason);
2387 }
2388 if (event.should_commit()) {
2389 post_compilation_event(event, task);
2390 }
2391 }
2392
2393 if (failure_reason != nullptr) {
2394 task->set_failure_reason(failure_reason, failure_reason_on_C_heap);
2395 if (CompilationLog::log() != nullptr) {
2396 CompilationLog::log()->log_failure(thread, task, failure_reason, retry_message);
2397 }
2398 if (PrintCompilation || directive->PrintCompilationOption) {
2399 FormatBufferResource msg = retry_message != nullptr ?
2400 FormatBufferResource("COMPILE SKIPPED: %s (%s)", failure_reason, retry_message) :
2401 FormatBufferResource("COMPILE SKIPPED: %s", failure_reason);
2402 task->print(tty, msg);
2403 }
2404 }
2405
2406 DirectivesStack::release(directive);
2407
2408 methodHandle method(thread, task->method());
2409
2410 DTRACE_METHOD_COMPILE_END_PROBE(method, compiler_name(task_level), task->is_success());
2411
2412 collect_statistics(thread, time, task);
2413
2414 if (PrintCompilation && PrintCompilation2) {
2415 tty->print("%7d ", (int) tty->time_stamp().milliseconds()); // print timestamp
2416 tty->print("%4d ", compile_id); // print compilation number
2417 tty->print("%s ", (is_osr ? "%" : " "));
2418 if (task->is_success()) {
2419 tty->print("size: %d(%d) ", task->nm_total_size(), task->nm_insts_size());
2420 }
2421 tty->print_cr("time: %d inlined: %d bytes", (int)time.milliseconds(), task->num_inlined_bytecodes());
2422 }
2423
2424 Log(compilation, codecache) log;
2425 if (log.is_debug()) {
2426 LogStream ls(log.debug());
2427 codecache_print(&ls, /* detailed= */ false);
2428 }
2429 if (PrintCodeCacheOnCompilation) {
2430 codecache_print(/* detailed= */ false);
2431 }
2432 // Disable compilation, if required.
2433 switch (compilable) {
2434 case ciEnv::MethodCompilable_never:
2435 if (is_osr)
2436 method->set_not_osr_compilable_quietly("MethodCompilable_never");
2437 else
2438 method->set_not_compilable_quietly("MethodCompilable_never");
2439 break;
2440 case ciEnv::MethodCompilable_not_at_tier:
2441 if (is_osr)
2442 method->set_not_osr_compilable_quietly("MethodCompilable_not_at_tier", task_level);
2443 else
2444 method->set_not_compilable_quietly("MethodCompilable_not_at_tier", task_level);
2445 break;
2446 }
2447
2448 // Note that the queued_for_compilation bits are cleared without
2449 // protection of a mutex. [They were set by the requester thread,
2450 // when adding the task to the compile queue -- at which time the
2451 // compile queue lock was held. Subsequently, we acquired the compile
2452 // queue lock to get this task off the compile queue; thus (to belabour
2453 // the point somewhat) our clearing of the bits must be occurring
2454 // only after the setting of the bits. See also 14012000 above.
2455 method->clear_queued_for_compilation();
2456 }
2457
2458 /**
2459 * The CodeCache is full. Print warning and disable compilation.
2460 * Schedule code cache cleaning so compilation can continue later.
2461 * This function needs to be called only from CodeCache::allocate(),
2462 * since we currently handle a full code cache uniformly.
2463 */
2464 void CompileBroker::handle_full_code_cache(CodeBlobType code_blob_type) {
2465 UseInterpreter = true;
2466 if (UseCompiler || AlwaysCompileLoopMethods ) {
2467 if (xtty != nullptr) {
2468 stringStream s;
2469 // Dump code cache state into a buffer before locking the tty,
2470 // because log_state() will use locks causing lock conflicts.
2471 CodeCache::log_state(&s);
2472 // Lock to prevent tearing
2473 ttyLocker ttyl;
2474 xtty->begin_elem("code_cache_full");
2475 xtty->print("%s", s.freeze());
2476 xtty->stamp();
2477 xtty->end_elem();
2478 }
2479
2480 #ifndef PRODUCT
2481 if (ExitOnFullCodeCache) {
2482 codecache_print(/* detailed= */ true);
2483 before_exit(JavaThread::current());
2484 exit_globals(); // will delete tty
2485 vm_direct_exit(1);
2486 }
2487 #endif
2488 if (UseCodeCacheFlushing) {
2489 // Since code cache is full, immediately stop new compiles
2490 if (CompileBroker::set_should_compile_new_jobs(CompileBroker::stop_compilation)) {
2491 log_info(codecache)("Code cache is full - disabling compilation");
2492 }
2493 } else {
2494 disable_compilation_forever();
2495 }
2496
2497 CodeCache::report_codemem_full(code_blob_type, should_print_compiler_warning());
2498 }
2499 }
2500
2501 // ------------------------------------------------------------------
2502 // CompileBroker::update_compile_perf_data
2503 //
2504 // Record this compilation for debugging purposes.
2505 void CompileBroker::update_compile_perf_data(CompilerThread* thread, const methodHandle& method, bool is_osr) {
2506 ResourceMark rm;
2507 char* method_name = method->name()->as_C_string();
2508 char current_method[CompilerCounters::cmname_buffer_length];
2509 size_t maxLen = CompilerCounters::cmname_buffer_length;
2510
2511 const char* class_name = method->method_holder()->name()->as_C_string();
2512
2513 size_t s1len = strlen(class_name);
2514 size_t s2len = strlen(method_name);
2515
2516 // check if we need to truncate the string
2517 if (s1len + s2len + 2 > maxLen) {
2518
2519 // the strategy is to lop off the leading characters of the
2520 // class name and the trailing characters of the method name.
2521
2522 if (s2len + 2 > maxLen) {
2523 // lop of the entire class name string, let snprintf handle
2524 // truncation of the method name.
2525 class_name += s1len; // null string
2526 }
2527 else {
2528 // lop off the extra characters from the front of the class name
2529 class_name += ((s1len + s2len + 2) - maxLen);
2530 }
2531 }
2532
2533 jio_snprintf(current_method, maxLen, "%s %s", class_name, method_name);
2534
2535 int last_compile_type = normal_compile;
2536 if (CICountOSR && is_osr) {
2537 last_compile_type = osr_compile;
2538 } else if (CICountNative && method->is_native()) {
2539 last_compile_type = native_compile;
2540 }
2541
2542 CompilerCounters* counters = thread->counters();
2543 counters->set_current_method(current_method);
2544 counters->set_compile_type((jlong) last_compile_type);
2545 }
2546
2547 // ------------------------------------------------------------------
2548 // CompileBroker::collect_statistics
2549 //
2550 // Collect statistics about the compilation.
2551
2552 void CompileBroker::collect_statistics(CompilerThread* thread, elapsedTimer time, CompileTask* task) {
2553 bool success = task->is_success();
2554 methodHandle method (thread, task->method());
2555 int compile_id = task->compile_id();
2556 bool is_osr = (task->osr_bci() != standard_entry_bci);
2557 const int comp_level = task->comp_level();
2558 CompilerCounters* counters = thread->counters();
2559
2560 MutexLocker locker(CompileStatistics_lock);
2561
2562 // _perf variables are production performance counters which are
2563 // updated regardless of the setting of the CITime and CITimeEach flags
2564 //
2565
2566 // account all time, including bailouts and failures in this counter;
2567 // C1 and C2 counters are counting both successful and unsuccessful compiles
2568 _t_total_compilation.add(time);
2569
2570 // Update compilation times. Used by the implementation of JFR CompilerStatistics
2571 // and java.lang.management.CompilationMXBean.
2572 _perf_total_compilation->inc(time.ticks());
2573 _peak_compilation_time = MAX2(time.milliseconds(), _peak_compilation_time);
2574
2575 if (!success) {
2576 _total_bailout_count++;
2577 if (UsePerfData) {
2578 _perf_last_failed_method->set_value(counters->current_method());
2579 _perf_last_failed_type->set_value(counters->compile_type());
2580 _perf_total_bailout_count->inc();
2581 }
2582 _t_bailedout_compilation.add(time);
2583 } else if (!task->is_success()) {
2584 if (UsePerfData) {
2585 _perf_last_invalidated_method->set_value(counters->current_method());
2586 _perf_last_invalidated_type->set_value(counters->compile_type());
2587 _perf_total_invalidated_count->inc();
2588 }
2589 _total_invalidated_count++;
2590 _t_invalidated_compilation.add(time);
2591 } else {
2592 // Compilation succeeded
2593 if (CITime) {
2594 int bytes_compiled = method->code_size() + task->num_inlined_bytecodes();
2595 if (is_osr) {
2596 _t_osr_compilation.add(time);
2597 _sum_osr_bytes_compiled += bytes_compiled;
2598 } else {
2599 _t_standard_compilation.add(time);
2600 _sum_standard_bytes_compiled += method->code_size() + task->num_inlined_bytecodes();
2601 }
2602
2603 // Collect statistic per compilation level
2604 if (comp_level > CompLevel_none && comp_level <= CompLevel_full_optimization) {
2605 CompilerStatistics* stats = &_stats_per_level[comp_level-1];
2606 if (is_osr) {
2607 stats->_osr.update(time, bytes_compiled);
2608 } else {
2609 stats->_standard.update(time, bytes_compiled);
2610 }
2611 stats->_nmethods_size += task->nm_total_size();
2612 stats->_nmethods_code_size += task->nm_insts_size();
2613 } else {
2614 assert(false, "CompilerStatistics object does not exist for compilation level %d", comp_level);
2615 }
2616
2617 // Collect statistic per compiler
2618 AbstractCompiler* comp = compiler(comp_level);
2619 if (comp) {
2620 CompilerStatistics* stats = comp->stats();
2621 if (is_osr) {
2622 stats->_osr.update(time, bytes_compiled);
2623 } else {
2624 stats->_standard.update(time, bytes_compiled);
2625 }
2626 stats->_nmethods_size += task->nm_total_size();
2627 stats->_nmethods_code_size += task->nm_insts_size();
2628 } else { // if (!comp)
2629 assert(false, "Compiler object must exist");
2630 }
2631 }
2632
2633 if (UsePerfData) {
2634 // save the name of the last method compiled
2635 _perf_last_method->set_value(counters->current_method());
2636 _perf_last_compile_type->set_value(counters->compile_type());
2637 _perf_last_compile_size->set_value(method->code_size() +
2638 task->num_inlined_bytecodes());
2639 if (is_osr) {
2640 _perf_osr_compilation->inc(time.ticks());
2641 _perf_sum_osr_bytes_compiled->inc(method->code_size() + task->num_inlined_bytecodes());
2642 } else {
2643 _perf_standard_compilation->inc(time.ticks());
2644 _perf_sum_standard_bytes_compiled->inc(method->code_size() + task->num_inlined_bytecodes());
2645 }
2646 }
2647
2648 if (CITimeEach) {
2649 double compile_time = time.seconds();
2650 double bytes_per_sec = compile_time == 0.0 ? 0.0 : (double)(method->code_size() + task->num_inlined_bytecodes()) / compile_time;
2651 tty->print_cr("%3d seconds: %6.3f bytes/sec : %f (bytes %d + %d inlined)",
2652 compile_id, compile_time, bytes_per_sec, method->code_size(), task->num_inlined_bytecodes());
2653 }
2654
2655 // Collect counts of successful compilations
2656 _sum_nmethod_size += task->nm_total_size();
2657 _sum_nmethod_code_size += task->nm_insts_size();
2658 _largest_nmethod_code_size = MAX2(_largest_nmethod_code_size, (uint) task->nm_insts_size());
2659 _total_compile_count++;
2660
2661 if (UsePerfData) {
2662 _perf_sum_nmethod_size->inc( task->nm_total_size());
2663 _perf_sum_nmethod_code_size->inc(task->nm_insts_size());
2664 _perf_total_compile_count->inc();
2665 }
2666
2667 if (is_osr) {
2668 if (UsePerfData) _perf_total_osr_compile_count->inc();
2669 _total_osr_compile_count++;
2670 } else {
2671 if (UsePerfData) _perf_total_standard_compile_count->inc();
2672 _total_standard_compile_count++;
2673 }
2674 }
2675 // set the current method for the thread to null
2676 if (UsePerfData) counters->set_current_method("");
2677 }
2678
2679 const char* CompileBroker::compiler_name(int comp_level) {
2680 AbstractCompiler *comp = CompileBroker::compiler(comp_level);
2681 if (comp == nullptr) {
2682 return "no compiler";
2683 } else {
2684 return (comp->name());
2685 }
2686 }
2687
2688 jlong CompileBroker::total_compilation_ticks() {
2689 return _perf_total_compilation != nullptr ? _perf_total_compilation->get_value() : 0;
2690 }
2691
2692 void CompileBroker::print_times(const char* name, CompilerStatistics* stats) {
2693 tty->print_cr(" %s {speed: %6.3f bytes/s; standard: %6.3f s, %u bytes, %u methods; osr: %6.3f s, %u bytes, %u methods; nmethods_size: %u bytes; nmethods_code_size: %u bytes}",
2694 name, stats->bytes_per_second(),
2695 stats->_standard._time.seconds(), stats->_standard._bytes, stats->_standard._count,
2696 stats->_osr._time.seconds(), stats->_osr._bytes, stats->_osr._count,
2697 stats->_nmethods_size, stats->_nmethods_code_size);
2698 }
2699
2700 void CompileBroker::print_times(bool per_compiler, bool aggregate) {
2701 if (per_compiler) {
2702 if (aggregate) {
2703 tty->cr();
2704 tty->print_cr("Individual compiler times (for compiled methods only)");
2705 tty->print_cr("------------------------------------------------");
2706 tty->cr();
2707 }
2708 for (unsigned int i = 0; i < sizeof(_compilers) / sizeof(AbstractCompiler*); i++) {
2709 AbstractCompiler* comp = _compilers[i];
2710 if (comp != nullptr) {
2711 print_times(comp->name(), comp->stats());
2712 }
2713 }
2714 if (aggregate) {
2715 tty->cr();
2716 tty->print_cr("Individual compilation Tier times (for compiled methods only)");
2717 tty->print_cr("------------------------------------------------");
2718 tty->cr();
2719 }
2720 char tier_name[256];
2721 for (int tier = CompLevel_simple; tier <= CompilationPolicy::highest_compile_level(); tier++) {
2722 CompilerStatistics* stats = &_stats_per_level[tier-1];
2723 os::snprintf_checked(tier_name, sizeof(tier_name), "Tier%d", tier);
2724 print_times(tier_name, stats);
2725 }
2726 }
2727
2728 if (!aggregate) {
2729 return;
2730 }
2731
2732 elapsedTimer standard_compilation = CompileBroker::_t_standard_compilation;
2733 elapsedTimer osr_compilation = CompileBroker::_t_osr_compilation;
2734 elapsedTimer total_compilation = CompileBroker::_t_total_compilation;
2735
2736 uint standard_bytes_compiled = CompileBroker::_sum_standard_bytes_compiled;
2737 uint osr_bytes_compiled = CompileBroker::_sum_osr_bytes_compiled;
2738
2739 uint standard_compile_count = CompileBroker::_total_standard_compile_count;
2740 uint osr_compile_count = CompileBroker::_total_osr_compile_count;
2741 uint total_compile_count = CompileBroker::_total_compile_count;
2742 uint total_bailout_count = CompileBroker::_total_bailout_count;
2743 uint total_invalidated_count = CompileBroker::_total_invalidated_count;
2744
2745 uint nmethods_code_size = CompileBroker::_sum_nmethod_code_size;
2746 uint largest_nmethod_code_size = CompileBroker::_largest_nmethod_code_size;
2747 uint nmethods_size = CompileBroker::_sum_nmethod_size;
2748
2749 tty->cr();
2750 tty->print_cr("Accumulated compiler times");
2751 tty->print_cr("----------------------------------------------------------");
2752 //0000000000111111111122222222223333333333444444444455555555556666666666
2753 //0123456789012345678901234567890123456789012345678901234567890123456789
2754 tty->print_cr(" Total compilation time : %7.3f s", total_compilation.seconds());
2755 tty->print_cr(" Standard compilation : %7.3f s, Average : %2.3f s",
2756 standard_compilation.seconds(),
2757 standard_compile_count == 0 ? 0.0 : standard_compilation.seconds() / standard_compile_count);
2758 tty->print_cr(" Bailed out compilation : %7.3f s, Average : %2.3f s",
2759 CompileBroker::_t_bailedout_compilation.seconds(),
2760 total_bailout_count == 0 ? 0.0 : CompileBroker::_t_bailedout_compilation.seconds() / total_bailout_count);
2761 tty->print_cr(" On stack replacement : %7.3f s, Average : %2.3f s",
2762 osr_compilation.seconds(),
2763 osr_compile_count == 0 ? 0.0 : osr_compilation.seconds() / osr_compile_count);
2764 tty->print_cr(" Invalidated : %7.3f s, Average : %2.3f s",
2765 CompileBroker::_t_invalidated_compilation.seconds(),
2766 total_invalidated_count == 0 ? 0.0 : CompileBroker::_t_invalidated_compilation.seconds() / total_invalidated_count);
2767
2768 AbstractCompiler *comp = compiler(CompLevel_simple);
2769 if (comp != nullptr) {
2770 tty->cr();
2771 comp->print_timers();
2772 }
2773 comp = compiler(CompLevel_full_optimization);
2774 if (comp != nullptr) {
2775 tty->cr();
2776 comp->print_timers();
2777 }
2778 #if INCLUDE_JVMCI
2779 if (EnableJVMCI) {
2780 JVMCICompiler *jvmci_comp = JVMCICompiler::instance(false, JavaThread::current_or_null());
2781 if (jvmci_comp != nullptr && jvmci_comp != comp) {
2782 tty->cr();
2783 jvmci_comp->print_timers();
2784 }
2785 }
2786 #endif
2787
2788 tty->cr();
2789 tty->print_cr(" Total compiled methods : %8u methods", total_compile_count);
2790 tty->print_cr(" Standard compilation : %8u methods", standard_compile_count);
2791 tty->print_cr(" On stack replacement : %8u methods", osr_compile_count);
2792 uint tcb = osr_bytes_compiled + standard_bytes_compiled;
2793 tty->print_cr(" Total compiled bytecodes : %8u bytes", tcb);
2794 tty->print_cr(" Standard compilation : %8u bytes", standard_bytes_compiled);
2795 tty->print_cr(" On stack replacement : %8u bytes", osr_bytes_compiled);
2796 double tcs = total_compilation.seconds();
2797 uint bps = tcs == 0.0 ? 0 : (uint)(tcb / tcs);
2798 tty->print_cr(" Average compilation speed : %8u bytes/s", bps);
2799 tty->cr();
2800 tty->print_cr(" largest nmethod code size : %8u bytes", largest_nmethod_code_size);
2801 tty->print_cr(" nmethod code size : %8u bytes", nmethods_code_size);
2802 tty->print_cr(" nmethod total size : %8u bytes", nmethods_size);
2803 }
2804
2805 // Print general/accumulated JIT information.
2806 void CompileBroker::print_info(outputStream *out) {
2807 if (out == nullptr) out = tty;
2808 out->cr();
2809 out->print_cr("======================");
2810 out->print_cr(" General JIT info ");
2811 out->print_cr("======================");
2812 out->cr();
2813 out->print_cr(" JIT is : %7s", should_compile_new_jobs() ? "on" : "off");
2814 out->print_cr(" Compiler threads : %7d", (int)CICompilerCount);
2815 out->cr();
2816 out->print_cr("CodeCache overview");
2817 out->print_cr("--------------------------------------------------------");
2818 out->cr();
2819 out->print_cr(" Reserved size : %7zu KB", CodeCache::max_capacity() / K);
2820 out->print_cr(" Committed size : %7zu KB", CodeCache::capacity() / K);
2821 out->print_cr(" Unallocated capacity : %7zu KB", CodeCache::unallocated_capacity() / K);
2822 out->cr();
2823 }
2824
2825 // Note: tty_lock must not be held upon entry to this function.
2826 // Print functions called from herein do "micro-locking" on tty_lock.
2827 // That's a tradeoff which keeps together important blocks of output.
2828 // At the same time, continuous tty_lock hold time is kept in check,
2829 // preventing concurrently printing threads from stalling a long time.
2830 void CompileBroker::print_heapinfo(outputStream* out, const char* function, size_t granularity) {
2831 TimeStamp ts_total;
2832 TimeStamp ts_global;
2833 TimeStamp ts;
2834
2835 bool allFun = !strcmp(function, "all");
2836 bool aggregate = !strcmp(function, "aggregate") || !strcmp(function, "analyze") || allFun;
2837 bool usedSpace = !strcmp(function, "UsedSpace") || allFun;
2838 bool freeSpace = !strcmp(function, "FreeSpace") || allFun;
2839 bool methodCount = !strcmp(function, "MethodCount") || allFun;
2840 bool methodSpace = !strcmp(function, "MethodSpace") || allFun;
2841 bool methodAge = !strcmp(function, "MethodAge") || allFun;
2842 bool methodNames = !strcmp(function, "MethodNames") || allFun;
2843 bool discard = !strcmp(function, "discard") || allFun;
2844
2845 if (out == nullptr) {
2846 out = tty;
2847 }
2848
2849 if (!(aggregate || usedSpace || freeSpace || methodCount || methodSpace || methodAge || methodNames || discard)) {
2850 out->print_cr("\n__ CodeHeapStateAnalytics: Function %s is not supported", function);
2851 out->cr();
2852 return;
2853 }
2854
2855 ts_total.update(); // record starting point
2856
2857 if (aggregate) {
2858 print_info(out);
2859 }
2860
2861 // We hold the CodeHeapStateAnalytics_lock all the time, from here until we leave this function.
2862 // That prevents other threads from destroying (making inconsistent) our view on the CodeHeap.
2863 // When we request individual parts of the analysis via the jcmd interface, it is possible
2864 // that in between another thread (another jcmd user or the vm running into CodeCache OOM)
2865 // updated the aggregated data. We will then see a modified, but again consistent, view
2866 // on the CodeHeap. That's a tolerable tradeoff we have to accept because we can't hold
2867 // a lock across user interaction.
2868
2869 // We should definitely acquire this lock before acquiring Compile_lock and CodeCache_lock.
2870 // CodeHeapStateAnalytics_lock may be held by a concurrent thread for a long time,
2871 // leading to an unnecessarily long hold time of the other locks we acquired before.
2872 ts.update(); // record starting point
2873 MutexLocker mu0(CodeHeapStateAnalytics_lock, Mutex::_safepoint_check_flag);
2874 out->print_cr("\n__ CodeHeapStateAnalytics lock wait took %10.3f seconds _________\n", ts.seconds());
2875
2876 // Holding the CodeCache_lock protects from concurrent alterations of the CodeCache.
2877 // Unfortunately, such protection is not sufficient:
2878 // When a new nmethod is created via ciEnv::register_method(), the
2879 // Compile_lock is taken first. After some initializations,
2880 // nmethod::new_nmethod() takes over, grabbing the CodeCache_lock
2881 // immediately (after finalizing the oop references). To lock out concurrent
2882 // modifiers, we have to grab both locks as well in the described sequence.
2883 //
2884 // If we serve an "allFun" call, it is beneficial to hold CodeCache_lock and Compile_lock
2885 // for the entire duration of aggregation and printing. That makes sure we see
2886 // a consistent picture and do not run into issues caused by concurrent alterations.
2887 bool should_take_Compile_lock = !SafepointSynchronize::is_at_safepoint() &&
2888 !Compile_lock->owned_by_self();
2889 bool should_take_CodeCache_lock = !SafepointSynchronize::is_at_safepoint() &&
2890 !CodeCache_lock->owned_by_self();
2891 bool take_global_lock_1 = allFun && should_take_Compile_lock;
2892 bool take_global_lock_2 = allFun && should_take_CodeCache_lock;
2893 bool take_function_lock_1 = !allFun && should_take_Compile_lock;
2894 bool take_function_lock_2 = !allFun && should_take_CodeCache_lock;
2895 bool take_global_locks = take_global_lock_1 || take_global_lock_2;
2896 bool take_function_locks = take_function_lock_1 || take_function_lock_2;
2897
2898 ts_global.update(); // record starting point
2899
2900 ConditionalMutexLocker mu1(Compile_lock, take_global_lock_1, Mutex::_safepoint_check_flag);
2901 ConditionalMutexLocker mu2(CodeCache_lock, take_global_lock_2, Mutex::_no_safepoint_check_flag);
2902 if (take_global_locks) {
2903 out->print_cr("\n__ Compile & CodeCache (global) lock wait took %10.3f seconds _________\n", ts_global.seconds());
2904 ts_global.update(); // record starting point
2905 }
2906
2907 if (aggregate) {
2908 ts.update(); // record starting point
2909 ConditionalMutexLocker mu11(Compile_lock, take_function_lock_1, Mutex::_safepoint_check_flag);
2910 ConditionalMutexLocker mu22(CodeCache_lock, take_function_lock_2, Mutex::_no_safepoint_check_flag);
2911 if (take_function_locks) {
2912 out->print_cr("\n__ Compile & CodeCache (function) lock wait took %10.3f seconds _________\n", ts.seconds());
2913 }
2914
2915 ts.update(); // record starting point
2916 CodeCache::aggregate(out, granularity);
2917 if (take_function_locks) {
2918 out->print_cr("\n__ Compile & CodeCache (function) lock hold took %10.3f seconds _________\n", ts.seconds());
2919 }
2920 }
2921
2922 if (usedSpace) CodeCache::print_usedSpace(out);
2923 if (freeSpace) CodeCache::print_freeSpace(out);
2924 if (methodCount) CodeCache::print_count(out);
2925 if (methodSpace) CodeCache::print_space(out);
2926 if (methodAge) CodeCache::print_age(out);
2927 if (methodNames) {
2928 if (allFun) {
2929 // print_names() can only be used safely if the locks have been continuously held
2930 // since aggregation begin. That is true only for function "all".
2931 CodeCache::print_names(out);
2932 } else {
2933 out->print_cr("\nCodeHeapStateAnalytics: Function 'MethodNames' is only available as part of function 'all'");
2934 }
2935 }
2936 if (discard) CodeCache::discard(out);
2937
2938 if (take_global_locks) {
2939 out->print_cr("\n__ Compile & CodeCache (global) lock hold took %10.3f seconds _________\n", ts_global.seconds());
2940 }
2941 out->print_cr("\n__ CodeHeapStateAnalytics total duration %10.3f seconds _________\n", ts_total.seconds());
2942 }