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