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/atomic.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(); \
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 CompileTask* task = thread->task();
228 CompileLog* log = thread->log();
229 if (log != nullptr && !task->is_unloaded()) task->log_task_done(log);
230 thread->set_task(nullptr);
231 thread->set_env(nullptr);
232 thread->timeout()->disarm();
233 if (task->is_blocking()) {
234 bool free_task = false;
235 {
236 MutexLocker notifier(thread, CompileTaskWait_lock);
237 task->mark_complete();
238 #if INCLUDE_JVMCI
239 if (CompileBroker::compiler(task->comp_level())->is_jvmci()) {
240 if (!task->has_waiter()) {
241 // The waiting thread timed out and thus did not delete the task.
242 free_task = true;
243 }
244 task->set_blocking_jvmci_compile_state(nullptr);
245 }
246 #endif
247 if (!free_task) {
248 // Notify the waiting thread that the compilation has completed
249 // so that it can free the task.
250 CompileTaskWait_lock->notify_all();
251 }
252 }
253 if (free_task) {
254 // The task can only be deleted once the task lock is released.
255 delete task;
256 }
257 } else {
258 task->mark_complete();
259
260 // By convention, the compiling thread is responsible for deleting
261 // a non-blocking CompileTask.
262 delete task;
263 }
264 }
265
266 /**
267 * Check if a CompilerThread can be removed and update count if requested.
268 */
269 bool CompileBroker::can_remove(CompilerThread *ct, bool do_it) {
270 assert(UseDynamicNumberOfCompilerThreads, "or shouldn't be here");
271 if (!ReduceNumberOfCompilerThreads) return false;
272
273 AbstractCompiler *compiler = ct->compiler();
274 int compiler_count = compiler->num_compiler_threads();
275 bool c1 = compiler->is_c1();
276
277 // Keep at least 1 compiler thread of each type.
278 if (compiler_count < 2) return false;
279
280 // Keep thread alive for at least some time.
281 if (ct->idle_time_millis() < (c1 ? 500 : 100)) return false;
282
283 #if INCLUDE_JVMCI
284 if (compiler->is_jvmci() && !UseJVMCINativeLibrary) {
285 // Handles for JVMCI thread objects may get released concurrently.
286 if (do_it) {
287 assert(CompileThread_lock->owner() == ct, "must be holding lock");
288 } else {
289 // Skip check if it's the last thread and let caller check again.
290 return true;
291 }
292 }
299 if (do_it) {
300 assert_locked_or_safepoint(CompileThread_lock); // Update must be consistent.
301 compiler->set_num_compiler_threads(compiler_count - 1);
302 #if INCLUDE_JVMCI
303 if (compiler->is_jvmci() && !UseJVMCINativeLibrary) {
304 // Old j.l.Thread object can die when no longer referenced elsewhere.
305 JNIHandles::destroy_global(compiler2_object(compiler_count - 1));
306 _compiler2_objects[compiler_count - 1] = nullptr;
307 }
308 #endif
309 }
310 return true;
311 }
312 return false;
313 }
314
315 /**
316 * Add a CompileTask to a CompileQueue.
317 */
318 void CompileQueue::add(CompileTask* task) {
319 assert(MethodCompileQueue_lock->owned_by_self(), "must own lock");
320
321 task->set_next(nullptr);
322 task->set_prev(nullptr);
323
324 if (_last == nullptr) {
325 // The compile queue is empty.
326 assert(_first == nullptr, "queue is empty");
327 _first = task;
328 _last = task;
329 } else {
330 // Append the task to the queue.
331 assert(_last->next() == nullptr, "not last");
332 _last->set_next(task);
333 task->set_prev(_last);
334 _last = task;
335 }
336 ++_size;
337 ++_total_added;
338 if (_size > _peak_size) {
339 _peak_size = _size;
340 }
341
342 // Mark the method as being in the compile queue.
343 task->method()->set_queued_for_compilation();
344
345 if (CIPrintCompileQueue) {
346 print_tty();
347 }
348
349 if (LogCompilation && xtty != nullptr) {
350 task->log_task_queued();
351 }
352
353 if (TrainingData::need_data() && !CDSConfig::is_dumping_final_static_archive()) {
354 CompileTrainingData* ctd = CompileTrainingData::make(task);
355 if (ctd != nullptr) {
356 task->set_training_data(ctd);
357 }
358 }
359
360 // Notify CompilerThreads that a task is available.
361 MethodCompileQueue_lock->notify_all();
362 }
363
364 /**
365 * Empties compilation queue by deleting all compilation tasks.
366 * Furthermore, the method wakes up all threads that are waiting
367 * on a compilation task to finish. This can happen if background
368 * compilation is disabled.
369 */
370 void CompileQueue::delete_all() {
371 MutexLocker mu(MethodCompileQueue_lock);
372 CompileTask* current = _first;
373
374 // Iterate over all tasks in the compile queue
375 while (current != nullptr) {
376 CompileTask* next = current->next();
377 if (!current->is_blocking()) {
378 // Non-blocking task. No one is waiting for it, delete it now.
379 delete current;
380 } else {
381 // Blocking task. By convention, it is the waiters responsibility
382 // to delete the task. We cannot delete it here, because we do not
383 // coordinate with waiters. We will notify the waiters later.
384 }
385 current = next;
386 }
387 _first = nullptr;
388 _last = nullptr;
389
390 // Wake up all blocking task waiters to deal with remaining blocking
391 // tasks. This is not a performance sensitive path, so we do this
392 // unconditionally to simplify coding/testing.
393 {
394 MonitorLocker ml(Thread::current(), CompileTaskWait_lock);
395 ml.notify_all();
396 }
397
398 // Wake up all threads that block on the queue.
399 MethodCompileQueue_lock->notify_all();
400 }
401
402 /**
403 * Get the next CompileTask from a CompileQueue
404 */
405 CompileTask* CompileQueue::get(CompilerThread* thread) {
406 // save methods from RedefineClasses across safepoint
407 // across MethodCompileQueue_lock below.
408 methodHandle save_method;
409
410 MonitorLocker locker(MethodCompileQueue_lock);
411 // If _first is null we have no more compile jobs. There are two reasons for
412 // having no compile jobs: First, we compiled everything we wanted. Second,
413 // we ran out of code cache so compilation has been disabled. In the latter
414 // case we perform code cache sweeps to free memory such that we can re-enable
415 // compilation.
416 while (_first == nullptr) {
417 // Exit loop if compilation is disabled forever
418 if (CompileBroker::is_compilation_disabled_forever()) {
419 return nullptr;
420 }
421
422 AbstractCompiler* compiler = thread->compiler();
423 guarantee(compiler != nullptr, "Compiler object must exist");
424 compiler->on_empty_queue(this, thread);
425 if (_first != nullptr) {
426 // The call to on_empty_queue may have temporarily unlocked the MCQ lock
427 // so check again whether any tasks were added to the queue.
428 break;
429 }
430
431 // If there are no compilation tasks and we can compile new jobs
432 // (i.e., there is enough free space in the code cache) there is
433 // no need to invoke the GC.
434 // We need a timed wait here, since compiler threads can exit if compilation
435 // is disabled forever. We use 5 seconds wait time; the exiting of compiler threads
436 // is not critical and we do not want idle compiler threads to wake up too often.
437 locker.wait(5*1000);
438
439 if (UseDynamicNumberOfCompilerThreads && _first == nullptr) {
440 // Still nothing to compile. Give caller a chance to stop this thread.
441 if (CompileBroker::can_remove(CompilerThread::current(), false)) return nullptr;
442 }
443 }
444
445 if (CompileBroker::is_compilation_disabled_forever()) {
446 return nullptr;
447 }
448
449 CompileTask* task;
450 {
451 NoSafepointVerifier nsv;
452 task = CompilationPolicy::select_task(this, thread);
453 if (task != nullptr) {
454 task = task->select_for_compilation();
455 }
456 }
457
458 if (task != nullptr) {
459 // Save method pointers across unlock safepoint. The task is removed from
460 // the compilation queue, which is walked during RedefineClasses.
461 Thread* thread = Thread::current();
462 save_method = methodHandle(thread, task->method());
463
464 remove(task);
465 }
466 purge_stale_tasks(); // may temporarily release MCQ lock
467 return task;
468 }
469
470 // Clean & deallocate stale compile tasks.
471 // Temporarily releases MethodCompileQueue lock.
472 void CompileQueue::purge_stale_tasks() {
473 assert(MethodCompileQueue_lock->owned_by_self(), "must own lock");
474 if (_first_stale != nullptr) {
475 // Stale tasks are purged when MCQ lock is released,
476 // but _first_stale updates are protected by MCQ lock.
477 // Once task processing starts and MCQ lock is released,
478 // other compiler threads can reuse _first_stale.
479 CompileTask* head = _first_stale;
480 _first_stale = nullptr;
481 {
482 MutexUnlocker ul(MethodCompileQueue_lock);
483 for (CompileTask* task = head; task != nullptr; ) {
484 CompileTask* next_task = task->next();
485 task->set_next(nullptr);
486 CompileTaskWrapper ctw(task); // Frees the task
487 task->set_failure_reason("stale task");
488 task = next_task;
489 }
490 }
491 }
492 }
493
494 void CompileQueue::remove(CompileTask* task) {
495 assert(MethodCompileQueue_lock->owned_by_self(), "must own lock");
496 if (task->prev() != nullptr) {
497 task->prev()->set_next(task->next());
498 } else {
499 // max is the first element
500 assert(task == _first, "Sanity");
501 _first = task->next();
502 }
503
504 if (task->next() != nullptr) {
505 task->next()->set_prev(task->prev());
506 } else {
507 // max is the last element
508 assert(task == _last, "Sanity");
509 _last = task->prev();
510 }
511 task->set_next(nullptr);
512 task->set_prev(nullptr);
513 --_size;
514 ++_total_removed;
515 }
516
517 void CompileQueue::remove_and_mark_stale(CompileTask* task) {
518 assert(MethodCompileQueue_lock->owned_by_self(), "must own lock");
519 remove(task);
520
521 // Enqueue the task for reclamation (should be done outside MCQ lock)
522 task->set_next(_first_stale);
523 task->set_prev(nullptr);
524 _first_stale = task;
525 }
526
527 // methods in the compile queue need to be marked as used on the stack
528 // so that they don't get reclaimed by Redefine Classes
529 void CompileQueue::mark_on_stack() {
530 CompileTask* task = _first;
531 while (task != nullptr) {
532 task->mark_on_stack();
533 task = task->next();
534 }
535 }
536
537
538 CompileQueue* CompileBroker::compile_queue(int comp_level) {
539 if (is_c2_compile(comp_level)) return _c2_compile_queue;
540 if (is_c1_compile(comp_level)) return _c1_compile_queue;
541 return nullptr;
542 }
543
544 CompileQueue* CompileBroker::c1_compile_queue() {
545 return _c1_compile_queue;
546 }
547
548 CompileQueue* CompileBroker::c2_compile_queue() {
549 return _c2_compile_queue;
550 }
551
552 void CompileBroker::print_compile_queues(outputStream* st) {
553 st->print_cr("Current compiles: ");
554
555 char buf[2000];
556 int buflen = sizeof(buf);
557 Threads::print_threads_compiling(st, buf, buflen, /* short_form = */ true);
558
559 st->cr();
560 if (_c1_compile_queue != nullptr) {
561 _c1_compile_queue->print(st);
562 }
563 if (_c2_compile_queue != nullptr) {
564 _c2_compile_queue->print(st);
565 }
566 }
567
568 void CompileQueue::print(outputStream* st) {
569 assert_locked_or_safepoint(MethodCompileQueue_lock);
570 st->print_cr("%s:", name());
571 CompileTask* task = _first;
572 if (task == nullptr) {
573 st->print_cr("Empty");
574 } else {
575 while (task != nullptr) {
576 task->print(st, nullptr, true, true);
577 task = task->next();
578 }
579 }
580 st->cr();
581 }
582
583 void CompileQueue::print_tty() {
584 stringStream ss;
585 // Dump the compile queue into a buffer before locking the tty
586 print(&ss);
587 {
588 ttyLocker ttyl;
589 tty->print("%s", ss.freeze());
616 CompilerEvent::PhaseEvent::get_phase_id(phase_name, false, false, false);
617 }
618 first_registration = false;
619 #endif // COMPILER2
620 }
621 }
622 #endif // INCLUDE_JFR && COMPILER2_OR_JVMCI
623
624 // ------------------------------------------------------------------
625 // CompileBroker::compilation_init
626 //
627 // Initialize the Compilation object
628 void CompileBroker::compilation_init(JavaThread* THREAD) {
629 // No need to initialize compilation system if we do not use it.
630 if (!UseCompiler) {
631 return;
632 }
633 // Set the interface to the current compiler(s).
634 _c1_count = CompilationPolicy::c1_count();
635 _c2_count = CompilationPolicy::c2_count();
636
637 #if INCLUDE_JVMCI
638 if (EnableJVMCI) {
639 // This is creating a JVMCICompiler singleton.
640 JVMCICompiler* jvmci = new JVMCICompiler();
641
642 if (UseJVMCICompiler) {
643 _compilers[1] = jvmci;
644 if (FLAG_IS_DEFAULT(JVMCIThreads)) {
645 if (BootstrapJVMCI) {
646 // JVMCI will bootstrap so give it more threads
647 _c2_count = MIN2(32, os::active_processor_count());
648 }
649 } else {
650 _c2_count = JVMCIThreads;
651 }
652 if (FLAG_IS_DEFAULT(JVMCIHostThreads)) {
653 } else {
654 #ifdef COMPILER1
655 _c1_count = JVMCIHostThreads;
772 _perf_last_compile_size =
773 PerfDataManager::create_variable(SUN_CI, "lastSize",
774 PerfData::U_Bytes,
775 (jlong)CompileBroker::no_compile,
776 CHECK);
777
778
779 _perf_last_failed_type =
780 PerfDataManager::create_variable(SUN_CI, "lastFailedType",
781 PerfData::U_None,
782 (jlong)CompileBroker::no_compile,
783 CHECK);
784
785 _perf_last_invalidated_type =
786 PerfDataManager::create_variable(SUN_CI, "lastInvalidatedType",
787 PerfData::U_None,
788 (jlong)CompileBroker::no_compile,
789 CHECK);
790 }
791
792 _initialized = true;
793 }
794
795 void TrainingReplayThread::training_replay_thread_entry(JavaThread* thread, TRAPS) {
796 CompilationPolicy::replay_training_at_init_loop(thread);
797 }
798
799 #if defined(ASSERT) && COMPILER2_OR_JVMCI
800 // Entry for DeoptimizeObjectsALotThread. The threads are started in
801 // CompileBroker::init_compiler_threads() iff DeoptimizeObjectsALot is enabled
802 void DeoptimizeObjectsALotThread::deopt_objs_alot_thread_entry(JavaThread* thread, TRAPS) {
803 DeoptimizeObjectsALotThread* dt = ((DeoptimizeObjectsALotThread*) thread);
804 bool enter_single_loop;
805 {
806 MonitorLocker ml(dt, EscapeBarrier_lock, Mutex::_no_safepoint_check_flag);
807 static int single_thread_count = 0;
808 enter_single_loop = single_thread_count++ < DeoptimizeObjectsALotThreadCountSingle;
809 }
810 if (enter_single_loop) {
811 dt->deoptimize_objects_alot_loop_single();
812 } else {
813 dt->deoptimize_objects_alot_loop_all();
814 }
938 }
939
940 static jobject create_compiler_thread(AbstractCompiler* compiler, int i, TRAPS) {
941 char name_buffer[256];
942 os::snprintf_checked(name_buffer, sizeof(name_buffer), "%s CompilerThread%d", compiler->name(), i);
943 Handle thread_oop = JavaThread::create_system_thread_object(name_buffer, CHECK_NULL);
944 return JNIHandles::make_global(thread_oop);
945 }
946
947 static void print_compiler_threads(stringStream& msg) {
948 if (TraceCompilerThreads) {
949 tty->print_cr("%7d %s", (int)tty->time_stamp().milliseconds(), msg.as_string());
950 }
951 LogTarget(Debug, jit, thread) lt;
952 if (lt.is_enabled()) {
953 LogStream ls(lt);
954 ls.print_cr("%s", msg.as_string());
955 }
956 }
957
958 void CompileBroker::init_compiler_threads() {
959 // Ensure any exceptions lead to vm_exit_during_initialization.
960 EXCEPTION_MARK;
961 #if !defined(ZERO)
962 assert(_c2_count > 0 || _c1_count > 0, "No compilers?");
963 #endif // !ZERO
964 // Initialize the compilation queue
965 if (_c2_count > 0) {
966 const char* name = JVMCI_ONLY(UseJVMCICompiler ? "JVMCI compile queue" :) "C2 compile queue";
967 _c2_compile_queue = new CompileQueue(name);
968 _compiler2_objects = NEW_C_HEAP_ARRAY(jobject, _c2_count, mtCompiler);
969 _compiler2_logs = NEW_C_HEAP_ARRAY(CompileLog*, _c2_count, mtCompiler);
970 }
971 if (_c1_count > 0) {
972 _c1_compile_queue = new CompileQueue("C1 compile queue");
973 _compiler1_objects = NEW_C_HEAP_ARRAY(jobject, _c1_count, mtCompiler);
974 _compiler1_logs = NEW_C_HEAP_ARRAY(CompileLog*, _c1_count, mtCompiler);
975 }
976
977 for (int i = 0; i < _c2_count; i++) {
978 // Create a name for our thread.
979 jobject thread_handle = create_compiler_thread(_compilers[1], i, CHECK);
980 _compiler2_objects[i] = thread_handle;
981 _compiler2_logs[i] = nullptr;
982
983 if (!UseDynamicNumberOfCompilerThreads || i == 0) {
984 JavaThread *ct = make_thread(compiler_t, thread_handle, _c2_compile_queue, _compilers[1], THREAD);
985 assert(ct != nullptr, "should have been handled for initial thread");
986 _compilers[1]->set_num_compiler_threads(i + 1);
987 if (trace_compiler_threads()) {
988 ResourceMark rm;
989 ThreadsListHandle tlh; // name() depends on the TLH.
990 assert(tlh.includes(ct), "ct=" INTPTR_FORMAT " exited unexpectedly.", p2i(ct));
991 stringStream msg;
992 msg.print("Added initial compiler thread %s", ct->name());
993 print_compiler_threads(msg);
994 }
995 }
996 }
997
998 for (int i = 0; i < _c1_count; i++) {
999 // Create a name for our thread.
1000 jobject thread_handle = create_compiler_thread(_compilers[0], i, CHECK);
1001 _compiler1_objects[i] = thread_handle;
1002 _compiler1_logs[i] = nullptr;
1003
1004 if (!UseDynamicNumberOfCompilerThreads || i == 0) {
1005 JavaThread *ct = make_thread(compiler_t, thread_handle, _c1_compile_queue, _compilers[0], THREAD);
1006 assert(ct != nullptr, "should have been handled for initial thread");
1007 _compilers[0]->set_num_compiler_threads(i + 1);
1008 if (trace_compiler_threads()) {
1009 ResourceMark rm;
1010 ThreadsListHandle tlh; // name() depends on the TLH.
1011 assert(tlh.includes(ct), "ct=" INTPTR_FORMAT " exited unexpectedly.", p2i(ct));
1012 stringStream msg;
1013 msg.print("Added initial compiler thread %s", ct->name());
1014 print_compiler_threads(msg);
1015 }
1016 }
1017 }
1018
1019 if (UsePerfData) {
1020 PerfDataManager::create_constant(SUN_CI, "threads", PerfData::U_Bytes, _c1_count + _c2_count, CHECK);
1021 }
1022
1023 #if defined(ASSERT) && COMPILER2_OR_JVMCI
1024 if (DeoptimizeObjectsALot) {
1025 // Initialize and start the object deoptimizer threads
1026 const int total_count = DeoptimizeObjectsALotThreadCountSingle + DeoptimizeObjectsALotThreadCountAll;
1027 for (int count = 0; count < total_count; count++) {
1028 Handle thread_oop = JavaThread::create_system_thread_object("Deoptimize objects a lot single mode", CHECK);
1029 jobject thread_handle = JNIHandles::make_local(THREAD, thread_oop());
1030 make_thread(deoptimizer_t, thread_handle, nullptr, nullptr, THREAD);
1031 }
1032 }
1033 #endif // defined(ASSERT) && COMPILER2_OR_JVMCI
1034 }
1035
1036 void CompileBroker::init_training_replay() {
1037 // Ensure any exceptions lead to vm_exit_during_initialization.
1038 EXCEPTION_MARK;
1039 if (TrainingData::have_data()) {
1040 Handle thread_oop = JavaThread::create_system_thread_object("Training replay thread", CHECK);
1041 jobject thread_handle = JNIHandles::make_local(THREAD, thread_oop());
1042 make_thread(training_replay_t, thread_handle, nullptr, nullptr, THREAD);
1043 }
1044 }
1045
1046 void CompileBroker::possibly_add_compiler_threads(JavaThread* THREAD) {
1047
1048 int old_c2_count = 0, new_c2_count = 0, old_c1_count = 0, new_c1_count = 0;
1049 const int c2_tasks_per_thread = 2, c1_tasks_per_thread = 4;
1050
1051 // Quick check if we already have enough compiler threads without taking the lock.
1052 // Numbers may change concurrently, so we read them again after we have the lock.
1053 if (_c2_compile_queue != nullptr) {
1054 old_c2_count = get_c2_thread_count();
1055 new_c2_count = MIN2(_c2_count, _c2_compile_queue->size() / c2_tasks_per_thread);
1056 }
1057 if (_c1_compile_queue != nullptr) {
1058 old_c1_count = get_c1_thread_count();
1059 new_c1_count = MIN2(_c1_count, _c1_compile_queue->size() / c1_tasks_per_thread);
1060 }
1156 }
1157
1158 CompileThread_lock->unlock();
1159 }
1160
1161
1162 /**
1163 * Set the methods on the stack as on_stack so that redefine classes doesn't
1164 * reclaim them. This method is executed at a safepoint.
1165 */
1166 void CompileBroker::mark_on_stack() {
1167 assert(SafepointSynchronize::is_at_safepoint(), "sanity check");
1168 // Since we are at a safepoint, we do not need a lock to access
1169 // the compile queues.
1170 if (_c2_compile_queue != nullptr) {
1171 _c2_compile_queue->mark_on_stack();
1172 }
1173 if (_c1_compile_queue != nullptr) {
1174 _c1_compile_queue->mark_on_stack();
1175 }
1176 }
1177
1178 // ------------------------------------------------------------------
1179 // CompileBroker::compile_method
1180 //
1181 // Request compilation of a method.
1182 void CompileBroker::compile_method_base(const methodHandle& method,
1183 int osr_bci,
1184 int comp_level,
1185 int hot_count,
1186 CompileTask::CompileReason compile_reason,
1187 bool blocking,
1188 Thread* thread) {
1189 guarantee(!method->is_abstract(), "cannot compile abstract methods");
1190 assert(method->method_holder()->is_instance_klass(),
1191 "sanity check");
1192 assert(!method->method_holder()->is_not_initialized(),
1193 "method holder must be initialized");
1194 assert(!method->is_method_handle_intrinsic(), "do not enqueue these guys");
1195
1196 if (CIPrintRequests) {
1197 tty->print("request: ");
1198 method->print_short_name(tty);
1199 if (osr_bci != InvocationEntryBci) {
1200 tty->print(" osr_bci: %d", osr_bci);
1201 }
1202 tty->print(" level: %d comment: %s count: %d", comp_level, CompileTask::reason_name(compile_reason), hot_count);
1203 if (hot_count > 0) {
1204 tty->print(" hot: yes");
1205 }
1206 tty->cr();
1207 }
1208
1209 // A request has been made for compilation. Before we do any
1210 // real work, check to see if the method has been compiled
1211 // in the meantime with a definitive result.
1212 if (compilation_is_complete(method, osr_bci, comp_level)) {
1213 return;
1214 }
1215
1216 #ifndef PRODUCT
1217 if (osr_bci != -1 && !FLAG_IS_DEFAULT(OSROnlyBCI)) {
1218 if ((OSROnlyBCI > 0) ? (OSROnlyBCI != osr_bci) : (-OSROnlyBCI == osr_bci)) {
1219 // Positive OSROnlyBCI means only compile that bci. Negative means don't compile that BCI.
1220 return;
1221 }
1222 }
1223 #endif
1224
1225 // If this method is already in the compile queue, then
1226 // we do not block the current thread.
1227 if (compilation_is_in_queue(method)) {
1228 // We may want to decay our counter a bit here to prevent
1229 // multiple denied requests for compilation. This is an
1230 // open compilation policy issue. Note: The other possibility,
1231 // in the case that this is a blocking compile request, is to have
1232 // all subsequent blocking requesters wait for completion of
1233 // ongoing compiles. Note that in this case we'll need a protocol
1234 // for freeing the associated compile tasks. [Or we could have
1235 // a single static monitor on which all these waiters sleep.]
1236 return;
1237 }
1238
1239 // Tiered policy requires MethodCounters to exist before adding a method to
1240 // the queue. Create if we don't have them yet.
1241 method->get_method_counters(thread);
1242
1243 // Outputs from the following MutexLocker block:
1244 CompileTask* task = nullptr;
1245 CompileQueue* queue = compile_queue(comp_level);
1246
1247 // Acquire our lock.
1248 {
1249 MutexLocker locker(thread, MethodCompileQueue_lock);
1250
1251 // Make sure the method has not slipped into the queues since
1252 // last we checked; note that those checks were "fast bail-outs".
1253 // Here we need to be more careful, see 14012000 below.
1254 if (compilation_is_in_queue(method)) {
1255 return;
1256 }
1257
1258 // We need to check again to see if the compilation has
1259 // completed. A previous compilation may have registered
1260 // some result.
1261 if (compilation_is_complete(method, osr_bci, comp_level)) {
1262 return;
1263 }
1264
1265 // We now know that this compilation is not pending, complete,
1266 // or prohibited. Assign a compile_id to this compilation
1267 // and check to see if it is in our [Start..Stop) range.
1268 int compile_id = assign_compile_id(method, osr_bci);
1269 if (compile_id == 0) {
1270 // The compilation falls outside the allowed range.
1271 return;
1272 }
1273
1274 #if INCLUDE_JVMCI
1275 if (UseJVMCICompiler && blocking) {
1276 // Don't allow blocking compiles for requests triggered by JVMCI.
1277 if (thread->is_Compiler_thread()) {
1278 blocking = false;
1279 }
1280
1281 // In libjvmci, JVMCI initialization should not deadlock with other threads
1331 // <RESULT, QUEUE> :
1332 // <0, 1> : in compile queue, but not yet compiled
1333 // <1, 1> : compiled but queue bit not cleared
1334 // <1, 0> : compiled and queue bit cleared
1335 // Because we first check the queue bits then check the result bits,
1336 // we are assured that we cannot introduce a duplicate task.
1337 // Note that if we did the tests in the reverse order (i.e. check
1338 // result then check queued bit), we could get the result bit before
1339 // the compilation completed, and the queue bit after the compilation
1340 // completed, and end up introducing a "duplicate" (redundant) task.
1341 // In that case, the compiler thread should first check if a method
1342 // has already been compiled before trying to compile it.
1343 // NOTE: in the event that there are multiple compiler threads and
1344 // there is de-optimization/recompilation, things will get hairy,
1345 // and in that case it's best to protect both the testing (here) of
1346 // these bits, and their updating (here and elsewhere) under a
1347 // common lock.
1348 task = create_compile_task(queue,
1349 compile_id, method,
1350 osr_bci, comp_level,
1351 hot_count, compile_reason,
1352 blocking);
1353 }
1354
1355 if (blocking) {
1356 wait_for_completion(task);
1357 }
1358 }
1359
1360 nmethod* CompileBroker::compile_method(const methodHandle& method, int osr_bci,
1361 int comp_level,
1362 int hot_count,
1363 CompileTask::CompileReason compile_reason,
1364 TRAPS) {
1365 // Do nothing if compilebroker is not initialized or compiles are submitted on level none
1366 if (!_initialized || comp_level == CompLevel_none) {
1367 return nullptr;
1368 }
1369
1370 AbstractCompiler *comp = CompileBroker::compiler(comp_level);
1371 assert(comp != nullptr, "Ensure we have a compiler");
1372
1373 #if INCLUDE_JVMCI
1374 if (comp->is_jvmci() && !JVMCI::can_initialize_JVMCI()) {
1375 // JVMCI compilation is not yet initializable.
1376 return nullptr;
1377 }
1378 #endif
1379
1380 DirectiveSet* directive = DirectivesStack::getMatchingDirective(method, comp);
1381 // CompileBroker::compile_method can trap and can have pending async exception.
1382 nmethod* nm = CompileBroker::compile_method(method, osr_bci, comp_level, hot_count, compile_reason, directive, THREAD);
1383 DirectivesStack::release(directive);
1384 return nm;
1385 }
1386
1387 nmethod* CompileBroker::compile_method(const methodHandle& method, int osr_bci,
1388 int comp_level,
1389 int hot_count,
1390 CompileTask::CompileReason compile_reason,
1391 DirectiveSet* directive,
1392 TRAPS) {
1393
1394 // make sure arguments make sense
1395 assert(method->method_holder()->is_instance_klass(), "not an instance method");
1396 assert(osr_bci == InvocationEntryBci || (0 <= osr_bci && osr_bci < method->code_size()), "bci out of range");
1397 assert(!method->is_abstract() && (osr_bci == InvocationEntryBci || !method->is_native()), "cannot compile abstract/native methods");
1398 assert(!method->method_holder()->is_not_initialized(), "method holder must be initialized");
1399 // return quickly if possible
1400
1401 // lock, make sure that the compilation
1402 // isn't prohibited in a straightforward way.
1403 AbstractCompiler* comp = CompileBroker::compiler(comp_level);
1404 if (comp == nullptr || compilation_is_prohibited(method, osr_bci, comp_level, directive->ExcludeOption)) {
1405 return nullptr;
1406 }
1407
1408 if (osr_bci == InvocationEntryBci) {
1409 // standard compilation
1410 nmethod* method_code = method->code();
1411 if (method_code != nullptr) {
1412 if (compilation_is_complete(method, osr_bci, comp_level)) {
1413 return method_code;
1414 }
1415 }
1416 if (method->is_not_compilable(comp_level)) {
1417 return nullptr;
1418 }
1419 } else {
1420 // osr compilation
1421 // We accept a higher level osr method
1422 nmethod* nm = method->lookup_osr_nmethod_for(osr_bci, comp_level, false);
1423 if (nm != nullptr) return nm;
1424 if (method->is_not_osr_compilable(comp_level)) return nullptr;
1425 }
1426
1427 assert(!HAS_PENDING_EXCEPTION, "No exception should be present");
1428 // some prerequisites that are compiler specific
1429 if (comp->is_c2() || comp->is_jvmci()) {
1430 InternalOOMEMark iom(THREAD);
1431 method->constants()->resolve_string_constants(CHECK_AND_CLEAR_NONASYNC_NULL);
1432 // Resolve all classes seen in the signature of the method
1433 // we are compiling.
1434 Method::load_signature_classes(method, CHECK_AND_CLEAR_NONASYNC_NULL);
1435 }
1436
1437 // If the method is native, do the lookup in the thread requesting
1438 // the compilation. Native lookups can load code, which is not
1439 // permitted during compilation.
1440 //
1441 // Note: A native method implies non-osr compilation which is
1442 // checked with an assertion at the entry of this method.
1443 if (method->is_native() && !method->is_method_handle_intrinsic()) {
1444 address adr = NativeLookup::lookup(method, THREAD);
1445 if (HAS_PENDING_EXCEPTION) {
1446 // In case of an exception looking up the method, we just forget
1447 // about it. The interpreter will kick-in and throw the exception.
1448 method->set_not_compilable("NativeLookup::lookup failed"); // implies is_not_osr_compilable()
1449 CLEAR_PENDING_EXCEPTION;
1464 }
1465
1466 // do the compilation
1467 if (method->is_native()) {
1468 if (!PreferInterpreterNativeStubs || method->is_method_handle_intrinsic()) {
1469 // To properly handle the appendix argument for out-of-line calls we are using a small trampoline that
1470 // pops off the appendix argument and jumps to the target (see gen_special_dispatch in SharedRuntime).
1471 //
1472 // Since normal compiled-to-compiled calls are not able to handle such a thing we MUST generate an adapter
1473 // in this case. If we can't generate one and use it we can not execute the out-of-line method handle calls.
1474 AdapterHandlerLibrary::create_native_wrapper(method);
1475 } else {
1476 return nullptr;
1477 }
1478 } else {
1479 // If the compiler is shut off due to code cache getting full
1480 // fail out now so blocking compiles dont hang the java thread
1481 if (!should_compile_new_jobs()) {
1482 return nullptr;
1483 }
1484 bool is_blocking = !directive->BackgroundCompilationOption || ReplayCompiles;
1485 compile_method_base(method, osr_bci, comp_level, hot_count, compile_reason, is_blocking, THREAD);
1486 }
1487
1488 // return requested nmethod
1489 // We accept a higher level osr method
1490 if (osr_bci == InvocationEntryBci) {
1491 return method->code();
1492 }
1493 return method->lookup_osr_nmethod_for(osr_bci, comp_level, false);
1494 }
1495
1496
1497 // ------------------------------------------------------------------
1498 // CompileBroker::compilation_is_complete
1499 //
1500 // See if compilation of this method is already complete.
1501 bool CompileBroker::compilation_is_complete(const methodHandle& method,
1502 int osr_bci,
1503 int comp_level) {
1504 bool is_osr = (osr_bci != standard_entry_bci);
1505 if (is_osr) {
1506 if (method->is_not_osr_compilable(comp_level)) {
1507 return true;
1508 } else {
1509 nmethod* result = method->lookup_osr_nmethod_for(osr_bci, comp_level, true);
1510 return (result != nullptr);
1511 }
1512 } else {
1513 if (method->is_not_compilable(comp_level)) {
1514 return true;
1515 } else {
1516 nmethod* result = method->code();
1517 if (result == nullptr) return false;
1518 return comp_level == result->comp_level();
1519 }
1520 }
1521 }
1522
1523
1524 /**
1525 * See if this compilation is already requested.
1526 *
1527 * Implementation note: there is only a single "is in queue" bit
1528 * for each method. This means that the check below is overly
1529 * conservative in the sense that an osr compilation in the queue
1530 * will block a normal compilation from entering the queue (and vice
1531 * versa). This can be remedied by a full queue search to disambiguate
1532 * cases. If it is deemed profitable, this may be done.
1533 */
1534 bool CompileBroker::compilation_is_in_queue(const methodHandle& method) {
1535 return method->queued_for_compilation();
1536 }
1537
1538 // ------------------------------------------------------------------
1598 if (CIStart <= id && id < CIStop) {
1599 return id;
1600 }
1601 }
1602
1603 // Method was not in the appropriate compilation range.
1604 method->set_not_compilable_quietly("Not in requested compile id range");
1605 return 0;
1606 #else
1607 // CICountOSR is a develop flag and set to 'false' by default. In a product built,
1608 // only _compilation_id is incremented.
1609 return Atomic::add(&_compilation_id, 1);
1610 #endif
1611 }
1612
1613 // ------------------------------------------------------------------
1614 // CompileBroker::assign_compile_id_unlocked
1615 //
1616 // Public wrapper for assign_compile_id that acquires the needed locks
1617 int CompileBroker::assign_compile_id_unlocked(Thread* thread, const methodHandle& method, int osr_bci) {
1618 MutexLocker locker(thread, MethodCompileQueue_lock);
1619 return assign_compile_id(method, osr_bci);
1620 }
1621
1622 // ------------------------------------------------------------------
1623 // CompileBroker::create_compile_task
1624 //
1625 // Create a CompileTask object representing the current request for
1626 // compilation. Add this task to the queue.
1627 CompileTask* CompileBroker::create_compile_task(CompileQueue* queue,
1628 int compile_id,
1629 const methodHandle& method,
1630 int osr_bci,
1631 int comp_level,
1632 int hot_count,
1633 CompileTask::CompileReason compile_reason,
1634 bool blocking) {
1635 CompileTask* new_task = new CompileTask(compile_id, method, osr_bci, comp_level,
1636 hot_count, compile_reason, blocking);
1637 queue->add(new_task);
1638 return new_task;
1639 }
1640
1641 #if INCLUDE_JVMCI
1642 // The number of milliseconds to wait before checking if
1643 // JVMCI compilation has made progress.
1644 static const long JVMCI_COMPILATION_PROGRESS_WAIT_TIMESLICE = 1000;
1645
1646 // The number of JVMCI compilation progress checks that must fail
1647 // before unblocking a thread waiting for a blocking compilation.
1648 static const int JVMCI_COMPILATION_PROGRESS_WAIT_ATTEMPTS = 10;
1649
1650 /**
1651 * Waits for a JVMCI compiler to complete a given task. This thread
1652 * waits until either the task completes or it sees no JVMCI compilation
1653 * progress for N consecutive milliseconds where N is
1654 * JVMCI_COMPILATION_PROGRESS_WAIT_TIMESLICE *
1655 * JVMCI_COMPILATION_PROGRESS_WAIT_ATTEMPTS.
1656 *
1657 * @return true if this thread needs to delete the task
1771 * compiler threads can start compiling.
1772 */
1773 bool CompileBroker::init_compiler_runtime() {
1774 CompilerThread* thread = CompilerThread::current();
1775 AbstractCompiler* comp = thread->compiler();
1776 // Final sanity check - the compiler object must exist
1777 guarantee(comp != nullptr, "Compiler object must exist");
1778
1779 {
1780 // Must switch to native to allocate ci_env
1781 ThreadToNativeFromVM ttn(thread);
1782 ciEnv ci_env((CompileTask*)nullptr);
1783 // Cache Jvmti state
1784 ci_env.cache_jvmti_state();
1785 // Cache DTrace flags
1786 ci_env.cache_dtrace_flags();
1787
1788 // Switch back to VM state to do compiler initialization
1789 ThreadInVMfromNative tv(thread);
1790
1791 // Perform per-thread and global initializations
1792 comp->initialize();
1793 }
1794
1795 if (comp->is_failed()) {
1796 disable_compilation_forever();
1797 // If compiler initialization failed, no compiler thread that is specific to a
1798 // particular compiler runtime will ever start to compile methods.
1799 shutdown_compiler_runtime(comp, thread);
1800 return false;
1801 }
1802
1803 // C1 specific check
1804 if (comp->is_c1() && (thread->get_buffer_blob() == nullptr)) {
1805 warning("Initialization of %s thread failed (no space to run compilers)", thread->name());
1806 return false;
1807 }
1808
1809 return true;
1810 }
1811
1812 void CompileBroker::free_buffer_blob_if_allocated(CompilerThread* thread) {
1813 BufferBlob* blob = thread->get_buffer_blob();
1814 if (blob != nullptr) {
1815 blob->purge();
1816 MutexLocker mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
1817 CodeCache::free(blob);
1818 }
1819 }
1820
1821 /**
1822 * If C1 and/or C2 initialization failed, we shut down all compilation.
1823 * We do this to keep things simple. This can be changed if it ever turns
1824 * out to be a problem.
1825 */
1826 void CompileBroker::shutdown_compiler_runtime(AbstractCompiler* comp, CompilerThread* thread) {
1827 free_buffer_blob_if_allocated(thread);
1828
1829 if (comp->should_perform_shutdown()) {
1830 // There are two reasons for shutting down the compiler
1831 // 1) compiler runtime initialization failed
1832 // 2) The code cache is full and the following flag is set: -XX:-UseCodeCacheFlushing
1833 warning("%s initialization failed. Shutting down all compilers", comp->name());
1834
1835 // Only one thread per compiler runtime object enters here
1836 // Set state to shut down
1837 comp->set_shut_down();
1838
1839 // Delete all queued compilation tasks to make compiler threads exit faster.
1840 if (_c1_compile_queue != nullptr) {
1841 _c1_compile_queue->delete_all();
1842 }
1843
1844 if (_c2_compile_queue != nullptr) {
1845 _c2_compile_queue->delete_all();
1846 }
1847
1848 // Set flags so that we continue execution with using interpreter only.
1852 // We could delete compiler runtimes also. However, there are references to
1853 // the compiler runtime(s) (e.g., nmethod::is_compiled_by_c1()) which then
1854 // fail. This can be done later if necessary.
1855 }
1856 }
1857
1858 /**
1859 * Helper function to create new or reuse old CompileLog.
1860 */
1861 CompileLog* CompileBroker::get_log(CompilerThread* ct) {
1862 if (!LogCompilation) return nullptr;
1863
1864 AbstractCompiler *compiler = ct->compiler();
1865 bool c1 = compiler->is_c1();
1866 jobject* compiler_objects = c1 ? _compiler1_objects : _compiler2_objects;
1867 assert(compiler_objects != nullptr, "must be initialized at this point");
1868 CompileLog** logs = c1 ? _compiler1_logs : _compiler2_logs;
1869 assert(logs != nullptr, "must be initialized at this point");
1870 int count = c1 ? _c1_count : _c2_count;
1871
1872 // Find Compiler number by its threadObj.
1873 oop compiler_obj = ct->threadObj();
1874 int compiler_number = 0;
1875 bool found = false;
1876 for (; compiler_number < count; compiler_number++) {
1877 if (JNIHandles::resolve_non_null(compiler_objects[compiler_number]) == compiler_obj) {
1878 found = true;
1879 break;
1880 }
1881 }
1882 assert(found, "Compiler must exist at this point");
1883
1884 // Determine pointer for this thread's log.
1885 CompileLog** log_ptr = &logs[compiler_number];
1886
1887 // Return old one if it exists.
1888 CompileLog* log = *log_ptr;
1889 if (log != nullptr) {
1890 ct->init_log(log);
1891 return log;
1933 if (!thread->init_compilation_timeout()) {
1934 return;
1935 }
1936
1937 // If compiler thread/runtime initialization fails, exit the compiler thread
1938 if (!init_compiler_runtime()) {
1939 return;
1940 }
1941
1942 thread->start_idle_timer();
1943
1944 // Poll for new compilation tasks as long as the JVM runs. Compilation
1945 // should only be disabled if something went wrong while initializing the
1946 // compiler runtimes. This, in turn, should not happen. The only known case
1947 // when compiler runtime initialization fails is if there is not enough free
1948 // space in the code cache to generate the necessary stubs, etc.
1949 while (!is_compilation_disabled_forever()) {
1950 // We need this HandleMark to avoid leaking VM handles.
1951 HandleMark hm(thread);
1952
1953 CompileTask* task = queue->get(thread);
1954 if (task == nullptr) {
1955 if (UseDynamicNumberOfCompilerThreads) {
1956 // Access compiler_count under lock to enforce consistency.
1957 MutexLocker only_one(CompileThread_lock);
1958 if (can_remove(thread, true)) {
1959 if (trace_compiler_threads()) {
1960 ResourceMark rm;
1961 stringStream msg;
1962 msg.print("Removing compiler thread %s after " JLONG_FORMAT " ms idle time",
1963 thread->name(), thread->idle_time_millis());
1964 print_compiler_threads(msg);
1965 }
1966
1967 // Notify compiler that the compiler thread is about to stop
1968 thread->compiler()->stopping_compiler_thread(thread);
1969
1970 free_buffer_blob_if_allocated(thread);
1971 return; // Stop this thread.
1972 }
1973 }
1974 } else {
1975 // Assign the task to the current thread. Mark this compilation
1976 // thread as active for the profiler.
1977 // CompileTaskWrapper also keeps the Method* from being deallocated if redefinition
1978 // occurs after fetching the compile task off the queue.
1979 CompileTaskWrapper ctw(task);
1980 methodHandle method(thread, task->method());
1981
1982 // Never compile a method if breakpoints are present in it
1983 if (method()->number_of_breakpoints() == 0) {
1984 // Compile the method.
1985 if ((UseCompiler || AlwaysCompileLoopMethods) && CompileBroker::should_compile_new_jobs()) {
1986 invoke_compiler_on_method(task);
1987 thread->start_idle_timer();
1988 } else {
1989 // After compilation is disabled, remove remaining methods from queue
1990 method->clear_queued_for_compilation();
1991 task->set_failure_reason("compilation is disabled");
1992 }
1993 } else {
1994 task->set_failure_reason("breakpoints are present");
1995 }
1996
1997 if (UseDynamicNumberOfCompilerThreads) {
1998 possibly_add_compiler_threads(thread);
1999 assert(!thread->has_pending_exception(), "should have been handled");
2000 }
2001 }
2002 }
2003
2004 // Shut down compiler runtime
2005 shutdown_compiler_runtime(thread->compiler(), thread);
2006 }
2007
2008 // ------------------------------------------------------------------
2009 // CompileBroker::init_compiler_thread_log
2010 //
2011 // Set up state required by +LogCompilation.
2012 void CompileBroker::init_compiler_thread_log() {
2013 CompilerThread* thread = CompilerThread::current();
2014 char file_name[4*K];
2015 FILE* fp = nullptr;
2016 intx thread_id = os::current_thread_id();
2017 for (int try_temp_dir = 1; try_temp_dir >= 0; try_temp_dir--) {
2173
2174 // Acquires Compilation_lock and waits for it to be notified
2175 // as long as WhiteBox::compilation_locked is true.
2176 static void whitebox_lock_compilation() {
2177 MonitorLocker locker(Compilation_lock, Mutex::_no_safepoint_check_flag);
2178 while (WhiteBox::compilation_locked) {
2179 locker.wait();
2180 }
2181 }
2182
2183 // ------------------------------------------------------------------
2184 // CompileBroker::invoke_compiler_on_method
2185 //
2186 // Compile a method.
2187 //
2188 void CompileBroker::invoke_compiler_on_method(CompileTask* task) {
2189 task->print_ul();
2190 elapsedTimer time;
2191
2192 DirectiveSet* directive = task->directive();
2193 if (directive->PrintCompilationOption) {
2194 ResourceMark rm;
2195 task->print_tty();
2196 }
2197
2198 CompilerThread* thread = CompilerThread::current();
2199 ResourceMark rm(thread);
2200
2201 if (CompilationLog::log() != nullptr) {
2202 CompilationLog::log()->log_compile(thread, task);
2203 }
2204
2205 // Common flags.
2206 int compile_id = task->compile_id();
2207 int osr_bci = task->osr_bci();
2208 bool is_osr = (osr_bci != standard_entry_bci);
2209 bool should_log = (thread->log() != nullptr);
2210 bool should_break = false;
2211 const int task_level = task->comp_level();
2212 AbstractCompiler* comp = task->compiler();
2213 {
2214 // create the handle inside it's own block so it can't
2215 // accidentally be referenced once the thread transitions to
2216 // native. The NoHandleMark before the transition should catch
2217 // any cases where this occurs in the future.
2218 methodHandle method(thread, task->method());
2219
2220 assert(!method->is_native(), "no longer compile natives");
2221
2222 // Update compile information when using perfdata.
2223 if (UsePerfData) {
2224 update_compile_perf_data(thread, method, is_osr);
2225 }
2226
2227 DTRACE_METHOD_COMPILE_BEGIN_PROBE(method, compiler_name(task_level));
2228 }
2229
2230 should_break = directive->BreakAtCompileOption || task->check_break_at_flags();
2335
2336 if (comp == nullptr) {
2337 ci_env.record_method_not_compilable("no compiler");
2338 } else if (!ci_env.failing()) {
2339 if (WhiteBoxAPI && WhiteBox::compilation_locked) {
2340 whitebox_lock_compilation();
2341 }
2342 comp->compile_method(&ci_env, target, osr_bci, true, directive);
2343
2344 /* Repeat compilation without installing code for profiling purposes */
2345 int repeat_compilation_count = directive->RepeatCompilationOption;
2346 while (repeat_compilation_count > 0) {
2347 ResourceMark rm(thread);
2348 task->print_ul("NO CODE INSTALLED");
2349 comp->compile_method(&ci_env, target, osr_bci, false, directive);
2350 repeat_compilation_count--;
2351 }
2352 }
2353
2354
2355 if (!ci_env.failing() && !task->is_success()) {
2356 assert(ci_env.failure_reason() != nullptr, "expect failure reason");
2357 assert(false, "compiler should always document failure: %s", ci_env.failure_reason());
2358 // The compiler elected, without comment, not to register a result.
2359 // Do not attempt further compilations of this method.
2360 ci_env.record_method_not_compilable("compile failed");
2361 }
2362
2363 // Copy this bit to the enclosing block:
2364 compilable = ci_env.compilable();
2365
2366 if (ci_env.failing()) {
2367 // Duplicate the failure reason string, so that it outlives ciEnv
2368 failure_reason = os::strdup(ci_env.failure_reason(), mtCompiler);
2369 failure_reason_on_C_heap = true;
2370 retry_message = ci_env.retry_message();
2371 ci_env.report_failure(failure_reason);
2372 }
2373
2374 if (ci_env.failing()) {
2375 handle_compile_error(thread, task, &ci_env, compilable, failure_reason);
2376 }
2377 if (event.should_commit()) {
2378 post_compilation_event(event, task);
2379 }
2380 }
2381
2382 if (failure_reason != nullptr) {
2383 task->set_failure_reason(failure_reason, failure_reason_on_C_heap);
2384 if (CompilationLog::log() != nullptr) {
2385 CompilationLog::log()->log_failure(thread, task, failure_reason, retry_message);
2386 }
2387 if (PrintCompilation || directive->PrintCompilationOption) {
2388 FormatBufferResource msg = retry_message != nullptr ?
2389 FormatBufferResource("COMPILE SKIPPED: %s (%s)", failure_reason, retry_message) :
2390 FormatBufferResource("COMPILE SKIPPED: %s", failure_reason);
2391 task->print(tty, msg);
2392 }
2393 }
2394
2395 DirectivesStack::release(directive);
2396
2397 methodHandle method(thread, task->method());
2398
2399 DTRACE_METHOD_COMPILE_END_PROBE(method, compiler_name(task_level), task->is_success());
2400
2401 collect_statistics(thread, time, task);
2402
2403 if (PrintCompilation && PrintCompilation2) {
2404 tty->print("%7d ", (int) tty->time_stamp().milliseconds()); // print timestamp
2405 tty->print("%4d ", compile_id); // print compilation number
2406 tty->print("%s ", (is_osr ? "%" : " "));
2407 if (task->is_success()) {
2408 tty->print("size: %d(%d) ", task->nm_total_size(), task->nm_insts_size());
2409 }
2410 tty->print_cr("time: %d inlined: %d bytes", (int)time.milliseconds(), task->num_inlined_bytecodes());
2411 }
2412
2413 Log(compilation, codecache) log;
2414 if (log.is_debug()) {
2415 LogStream ls(log.debug());
2416 codecache_print(&ls, /* detailed= */ false);
2417 }
2418 if (PrintCodeCacheOnCompilation) {
2419 codecache_print(/* detailed= */ false);
2420 }
2421 // Disable compilation, if required.
2422 switch (compilable) {
2423 case ciEnv::MethodCompilable_never:
2424 if (is_osr)
2425 method->set_not_osr_compilable_quietly("MethodCompilable_never");
2426 else
2427 method->set_not_compilable_quietly("MethodCompilable_never");
2428 break;
2429 case ciEnv::MethodCompilable_not_at_tier:
2430 if (is_osr)
2431 method->set_not_osr_compilable_quietly("MethodCompilable_not_at_tier", task_level);
2432 else
2433 method->set_not_compilable_quietly("MethodCompilable_not_at_tier", task_level);
2434 break;
2435 }
2436
2437 // Note that the queued_for_compilation bits are cleared without
2438 // protection of a mutex. [They were set by the requester thread,
2439 // when adding the task to the compile queue -- at which time the
2440 // compile queue lock was held. Subsequently, we acquired the compile
2441 // queue lock to get this task off the compile queue; thus (to belabour
2442 // the point somewhat) our clearing of the bits must be occurring
2443 // only after the setting of the bits. See also 14012000 above.
2444 method->clear_queued_for_compilation();
2445 }
2446
2447 /**
2448 * The CodeCache is full. Print warning and disable compilation.
2449 * Schedule code cache cleaning so compilation can continue later.
2450 * This function needs to be called only from CodeCache::allocate(),
2451 * since we currently handle a full code cache uniformly.
2452 */
2453 void CompileBroker::handle_full_code_cache(CodeBlobType code_blob_type) {
2454 UseInterpreter = true;
2455 if (UseCompiler || AlwaysCompileLoopMethods ) {
2456 if (xtty != nullptr) {
2457 stringStream s;
2458 // Dump code cache state into a buffer before locking the tty,
2459 // because log_state() will use locks causing lock conflicts.
2460 CodeCache::log_state(&s);
2461 // Lock to prevent tearing
2462 ttyLocker ttyl;
2463 xtty->begin_elem("code_cache_full");
2464 xtty->print("%s", s.freeze());
2537 // CompileBroker::collect_statistics
2538 //
2539 // Collect statistics about the compilation.
2540
2541 void CompileBroker::collect_statistics(CompilerThread* thread, elapsedTimer time, CompileTask* task) {
2542 bool success = task->is_success();
2543 methodHandle method (thread, task->method());
2544 int compile_id = task->compile_id();
2545 bool is_osr = (task->osr_bci() != standard_entry_bci);
2546 const int comp_level = task->comp_level();
2547 CompilerCounters* counters = thread->counters();
2548
2549 MutexLocker locker(CompileStatistics_lock);
2550
2551 // _perf variables are production performance counters which are
2552 // updated regardless of the setting of the CITime and CITimeEach flags
2553 //
2554
2555 // account all time, including bailouts and failures in this counter;
2556 // C1 and C2 counters are counting both successful and unsuccessful compiles
2557 _t_total_compilation.add(time);
2558
2559 // Update compilation times. Used by the implementation of JFR CompilerStatistics
2560 // and java.lang.management.CompilationMXBean.
2561 _perf_total_compilation->inc(time.ticks());
2562 _peak_compilation_time = MAX2(time.milliseconds(), _peak_compilation_time);
2563
2564 if (!success) {
2565 _total_bailout_count++;
2566 if (UsePerfData) {
2567 _perf_last_failed_method->set_value(counters->current_method());
2568 _perf_last_failed_type->set_value(counters->compile_type());
2569 _perf_total_bailout_count->inc();
2570 }
2571 _t_bailedout_compilation.add(time);
2572 } else if (!task->is_success()) {
2573 if (UsePerfData) {
2574 _perf_last_invalidated_method->set_value(counters->current_method());
2575 _perf_last_invalidated_type->set_value(counters->compile_type());
2576 _perf_total_invalidated_count->inc();
2577 }
2578 _total_invalidated_count++;
2579 _t_invalidated_compilation.add(time);
2580 } else {
2581 // Compilation succeeded
2582 if (CITime) {
2583 int bytes_compiled = method->code_size() + task->num_inlined_bytecodes();
2584 if (is_osr) {
2585 _t_osr_compilation.add(time);
2586 _sum_osr_bytes_compiled += bytes_compiled;
2587 } else {
2588 _t_standard_compilation.add(time);
2589 _sum_standard_bytes_compiled += method->code_size() + task->num_inlined_bytecodes();
2590 }
2591
2592 // Collect statistic per compilation level
2593 if (comp_level > CompLevel_none && comp_level <= CompLevel_full_optimization) {
2594 CompilerStatistics* stats = &_stats_per_level[comp_level-1];
2595 if (is_osr) {
2596 stats->_osr.update(time, bytes_compiled);
2597 } else {
2598 stats->_standard.update(time, bytes_compiled);
2599 }
2600 stats->_nmethods_size += task->nm_total_size();
2601 stats->_nmethods_code_size += task->nm_insts_size();
2602 } else {
2603 assert(false, "CompilerStatistics object does not exist for compilation level %d", comp_level);
2604 }
2605
2606 // Collect statistic per compiler
2607 AbstractCompiler* comp = compiler(comp_level);
2608 if (comp) {
2609 CompilerStatistics* stats = comp->stats();
2610 if (is_osr) {
2611 stats->_osr.update(time, bytes_compiled);
2612 } else {
2613 stats->_standard.update(time, bytes_compiled);
2614 }
2615 stats->_nmethods_size += task->nm_total_size();
2616 stats->_nmethods_code_size += task->nm_insts_size();
2617 } else { // if (!comp)
2618 assert(false, "Compiler object must exist");
2619 }
2620 }
2621
2622 if (UsePerfData) {
2623 // save the name of the last method compiled
2624 _perf_last_method->set_value(counters->current_method());
2625 _perf_last_compile_type->set_value(counters->compile_type());
2626 _perf_last_compile_size->set_value(method->code_size() +
2627 task->num_inlined_bytecodes());
2628 if (is_osr) {
2629 _perf_osr_compilation->inc(time.ticks());
2630 _perf_sum_osr_bytes_compiled->inc(method->code_size() + task->num_inlined_bytecodes());
2631 } else {
2632 _perf_standard_compilation->inc(time.ticks());
2633 _perf_sum_standard_bytes_compiled->inc(method->code_size() + task->num_inlined_bytecodes());
2634 }
2635 }
2636
2637 if (CITimeEach) {
2660 _total_standard_compile_count++;
2661 }
2662 }
2663 // set the current method for the thread to null
2664 if (UsePerfData) counters->set_current_method("");
2665 }
2666
2667 const char* CompileBroker::compiler_name(int comp_level) {
2668 AbstractCompiler *comp = CompileBroker::compiler(comp_level);
2669 if (comp == nullptr) {
2670 return "no compiler";
2671 } else {
2672 return (comp->name());
2673 }
2674 }
2675
2676 jlong CompileBroker::total_compilation_ticks() {
2677 return _perf_total_compilation != nullptr ? _perf_total_compilation->get_value() : 0;
2678 }
2679
2680 void CompileBroker::print_times(const char* name, CompilerStatistics* stats) {
2681 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}",
2682 name, stats->bytes_per_second(),
2683 stats->_standard._time.seconds(), stats->_standard._bytes, stats->_standard._count,
2684 stats->_osr._time.seconds(), stats->_osr._bytes, stats->_osr._count,
2685 stats->_nmethods_size, stats->_nmethods_code_size);
2686 }
2687
2688 void CompileBroker::print_times(bool per_compiler, bool aggregate) {
2689 if (per_compiler) {
2690 if (aggregate) {
2691 tty->cr();
2692 tty->print_cr("Individual compiler times (for compiled methods only)");
2693 tty->print_cr("------------------------------------------------");
2694 tty->cr();
2695 }
2696 for (unsigned int i = 0; i < sizeof(_compilers) / sizeof(AbstractCompiler*); i++) {
2697 AbstractCompiler* comp = _compilers[i];
2698 if (comp != nullptr) {
2699 print_times(comp->name(), comp->stats());
2700 }
2701 }
2702 if (aggregate) {
2703 tty->cr();
2704 tty->print_cr("Individual compilation Tier times (for compiled methods only)");
2705 tty->print_cr("------------------------------------------------");
2706 tty->cr();
2707 }
2708 char tier_name[256];
2709 for (int tier = CompLevel_simple; tier <= CompilationPolicy::highest_compile_level(); tier++) {
2710 CompilerStatistics* stats = &_stats_per_level[tier-1];
2711 os::snprintf_checked(tier_name, sizeof(tier_name), "Tier%d", tier);
2712 print_times(tier_name, stats);
2713 }
2714 }
2715
2716 if (!aggregate) {
2717 return;
2718 }
2719
2720 elapsedTimer standard_compilation = CompileBroker::_t_standard_compilation;
2721 elapsedTimer osr_compilation = CompileBroker::_t_osr_compilation;
2722 elapsedTimer total_compilation = CompileBroker::_t_total_compilation;
2723
2724 uint standard_bytes_compiled = CompileBroker::_sum_standard_bytes_compiled;
2725 uint osr_bytes_compiled = CompileBroker::_sum_osr_bytes_compiled;
2726
2727 uint standard_compile_count = CompileBroker::_total_standard_compile_count;
2728 uint osr_compile_count = CompileBroker::_total_osr_compile_count;
2729 uint total_compile_count = CompileBroker::_total_compile_count;
2730 uint total_bailout_count = CompileBroker::_total_bailout_count;
2731 uint total_invalidated_count = CompileBroker::_total_invalidated_count;
2732
2733 uint nmethods_code_size = CompileBroker::_sum_nmethod_code_size;
2735
2736 tty->cr();
2737 tty->print_cr("Accumulated compiler times");
2738 tty->print_cr("----------------------------------------------------------");
2739 //0000000000111111111122222222223333333333444444444455555555556666666666
2740 //0123456789012345678901234567890123456789012345678901234567890123456789
2741 tty->print_cr(" Total compilation time : %7.3f s", total_compilation.seconds());
2742 tty->print_cr(" Standard compilation : %7.3f s, Average : %2.3f s",
2743 standard_compilation.seconds(),
2744 standard_compile_count == 0 ? 0.0 : standard_compilation.seconds() / standard_compile_count);
2745 tty->print_cr(" Bailed out compilation : %7.3f s, Average : %2.3f s",
2746 CompileBroker::_t_bailedout_compilation.seconds(),
2747 total_bailout_count == 0 ? 0.0 : CompileBroker::_t_bailedout_compilation.seconds() / total_bailout_count);
2748 tty->print_cr(" On stack replacement : %7.3f s, Average : %2.3f s",
2749 osr_compilation.seconds(),
2750 osr_compile_count == 0 ? 0.0 : osr_compilation.seconds() / osr_compile_count);
2751 tty->print_cr(" Invalidated : %7.3f s, Average : %2.3f s",
2752 CompileBroker::_t_invalidated_compilation.seconds(),
2753 total_invalidated_count == 0 ? 0.0 : CompileBroker::_t_invalidated_compilation.seconds() / total_invalidated_count);
2754
2755 AbstractCompiler *comp = compiler(CompLevel_simple);
2756 if (comp != nullptr) {
2757 tty->cr();
2758 comp->print_timers();
2759 }
2760 comp = compiler(CompLevel_full_optimization);
2761 if (comp != nullptr) {
2762 tty->cr();
2763 comp->print_timers();
2764 }
2765 #if INCLUDE_JVMCI
2766 if (EnableJVMCI) {
2767 JVMCICompiler *jvmci_comp = JVMCICompiler::instance(false, JavaThread::current_or_null());
2768 if (jvmci_comp != nullptr && jvmci_comp != comp) {
2769 tty->cr();
2770 jvmci_comp->print_timers();
2771 }
2772 }
2773 #endif
2774
|
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/aotLinkedClassBulkLoader.hpp"
26 #include "cds/cdsConfig.hpp"
27 #include "classfile/javaClasses.inline.hpp"
28 #include "classfile/symbolTable.hpp"
29 #include "classfile/vmClasses.hpp"
30 #include "classfile/vmSymbols.hpp"
31 #include "code/aotCodeCache.hpp"
32 #include "code/codeCache.hpp"
33 #include "code/codeHeapState.hpp"
34 #include "code/dependencyContext.hpp"
35 #include "compiler/compilationLog.hpp"
36 #include "compiler/compilationMemoryStatistic.hpp"
37 #include "compiler/compilationPolicy.hpp"
38 #include "compiler/compileBroker.hpp"
39 #include "compiler/compileLog.hpp"
40 #include "compiler/compilerDefinitions.inline.hpp"
41 #include "compiler/compilerEvent.hpp"
42 #include "compiler/compilerOracle.hpp"
43 #include "compiler/directivesParser.hpp"
44 #include "compiler/recompilationPolicy.hpp"
45 #include "gc/shared/memAllocator.hpp"
46 #include "interpreter/linkResolver.hpp"
47 #include "jfr/jfrEvents.hpp"
48 #include "jvm.h"
49 #include "logging/log.hpp"
50 #include "logging/logStream.hpp"
51 #include "memory/allocation.inline.hpp"
52 #include "memory/resourceArea.hpp"
53 #include "memory/universe.hpp"
54 #include "oops/method.inline.hpp"
55 #include "oops/methodData.hpp"
56 #include "oops/oop.inline.hpp"
57 #include "prims/jvmtiExport.hpp"
58 #include "prims/nativeLookup.hpp"
59 #include "prims/whitebox.hpp"
60 #include "runtime/atomic.hpp"
61 #include "runtime/escapeBarrier.hpp"
62 #include "runtime/globals_extension.hpp"
63 #include "runtime/handles.inline.hpp"
64 #include "runtime/init.hpp"
65 #include "runtime/interfaceSupport.inline.hpp"
66 #include "runtime/java.hpp"
67 #include "runtime/javaCalls.hpp"
68 #include "runtime/jniHandles.inline.hpp"
69 #include "runtime/os.hpp"
70 #include "runtime/perfData.hpp"
71 #include "runtime/safepointVerifiers.hpp"
72 #include "runtime/sharedRuntime.hpp"
73 #include "runtime/threads.hpp"
74 #include "runtime/threadSMR.inline.hpp"
75 #include "runtime/timerTrace.hpp"
76 #include "runtime/vframe.inline.hpp"
77 #include "services/management.hpp"
78 #include "utilities/debug.hpp"
79 #include "utilities/dtrace.hpp"
80 #include "utilities/events.hpp"
81 #include "utilities/formatBuffer.hpp"
82 #include "utilities/macros.hpp"
83 #include "utilities/nonblockingQueue.inline.hpp"
84 #ifdef COMPILER1
85 #include "c1/c1_Compiler.hpp"
86 #endif
87 #ifdef COMPILER2
88 #include "opto/c2compiler.hpp"
89 #endif
90 #if INCLUDE_JVMCI
91 #include "jvmci/jvmciEnv.hpp"
92 #include "jvmci/jvmciRuntime.hpp"
93 #endif
94
95 #ifdef DTRACE_ENABLED
96
97 // Only bother with this argument setup if dtrace is available
98
99 #define DTRACE_METHOD_COMPILE_BEGIN_PROBE(method, comp_name) \
100 { \
101 Symbol* klass_name = (method)->klass_name(); \
102 Symbol* name = (method)->name(); \
103 Symbol* signature = (method)->signature(); \
121 }
122
123 #else // ndef DTRACE_ENABLED
124
125 #define DTRACE_METHOD_COMPILE_BEGIN_PROBE(method, comp_name)
126 #define DTRACE_METHOD_COMPILE_END_PROBE(method, comp_name, success)
127
128 #endif // ndef DTRACE_ENABLED
129
130 bool CompileBroker::_initialized = false;
131 volatile bool CompileBroker::_should_block = false;
132 volatile int CompileBroker::_print_compilation_warning = 0;
133 volatile jint CompileBroker::_should_compile_new_jobs = run_compilation;
134
135 // The installed compiler(s)
136 AbstractCompiler* CompileBroker::_compilers[2];
137
138 // The maximum numbers of compiler threads to be determined during startup.
139 int CompileBroker::_c1_count = 0;
140 int CompileBroker::_c2_count = 0;
141 int CompileBroker::_ac_count = 0;
142
143 // An array of compiler names as Java String objects
144 jobject* CompileBroker::_compiler1_objects = nullptr;
145 jobject* CompileBroker::_compiler2_objects = nullptr;
146 jobject* CompileBroker::_ac_objects = nullptr;
147
148 CompileLog** CompileBroker::_compiler1_logs = nullptr;
149 CompileLog** CompileBroker::_compiler2_logs = nullptr;
150 CompileLog** CompileBroker::_ac_logs = nullptr;
151
152 // These counters are used to assign an unique ID to each compilation.
153 volatile jint CompileBroker::_compilation_id = 0;
154 volatile jint CompileBroker::_osr_compilation_id = 0;
155 volatile jint CompileBroker::_native_compilation_id = 0;
156
157 // Performance counters
158 PerfCounter* CompileBroker::_perf_total_compilation = nullptr;
159 PerfCounter* CompileBroker::_perf_osr_compilation = nullptr;
160 PerfCounter* CompileBroker::_perf_standard_compilation = nullptr;
161
162 PerfCounter* CompileBroker::_perf_total_bailout_count = nullptr;
163 PerfCounter* CompileBroker::_perf_total_invalidated_count = nullptr;
164 PerfCounter* CompileBroker::_perf_total_compile_count = nullptr;
165 PerfCounter* CompileBroker::_perf_total_osr_compile_count = nullptr;
166 PerfCounter* CompileBroker::_perf_total_standard_compile_count = nullptr;
167
168 PerfCounter* CompileBroker::_perf_sum_osr_bytes_compiled = nullptr;
169 PerfCounter* CompileBroker::_perf_sum_standard_bytes_compiled = nullptr;
170 PerfCounter* CompileBroker::_perf_sum_nmethod_size = nullptr;
171 PerfCounter* CompileBroker::_perf_sum_nmethod_code_size = nullptr;
172
173 PerfStringVariable* CompileBroker::_perf_last_method = nullptr;
174 PerfStringVariable* CompileBroker::_perf_last_failed_method = nullptr;
175 PerfStringVariable* CompileBroker::_perf_last_invalidated_method = nullptr;
176 PerfVariable* CompileBroker::_perf_last_compile_type = nullptr;
177 PerfVariable* CompileBroker::_perf_last_compile_size = nullptr;
178 PerfVariable* CompileBroker::_perf_last_failed_type = nullptr;
179 PerfVariable* CompileBroker::_perf_last_invalidated_type = nullptr;
180
181 // Timers and counters for generating statistics
182 elapsedTimer CompileBroker::_t_total_compilation;
183 elapsedTimer CompileBroker::_t_osr_compilation;
184 elapsedTimer CompileBroker::_t_standard_compilation;
185 elapsedTimer CompileBroker::_t_invalidated_compilation;
186 elapsedTimer CompileBroker::_t_bailedout_compilation;
187
188 uint CompileBroker::_total_bailout_count = 0;
189 uint CompileBroker::_total_invalidated_count = 0;
190 uint CompileBroker::_total_not_entrant_count = 0;
191 uint CompileBroker::_total_compile_count = 0;
192 uint CompileBroker::_total_osr_compile_count = 0;
193 uint CompileBroker::_total_standard_compile_count = 0;
194 uint CompileBroker::_total_compiler_stopped_count = 0;
195 uint CompileBroker::_total_compiler_restarted_count = 0;
196
197 uint CompileBroker::_sum_osr_bytes_compiled = 0;
198 uint CompileBroker::_sum_standard_bytes_compiled = 0;
199 uint CompileBroker::_sum_nmethod_size = 0;
200 uint CompileBroker::_sum_nmethod_code_size = 0;
201
202 jlong CompileBroker::_peak_compilation_time = 0;
203
204 CompilerStatistics CompileBroker::_stats_per_level[CompLevel_full_optimization];
205 CompilerStatistics CompileBroker::_aot_stats;
206 CompilerStatistics CompileBroker::_aot_stats_per_level[CompLevel_full_optimization + 1];
207
208 CompileQueue* CompileBroker::_c2_compile_queue = nullptr;
209 CompileQueue* CompileBroker::_c1_compile_queue = nullptr;
210 CompileQueue* CompileBroker::_ac1_compile_queue = nullptr;
211 CompileQueue* CompileBroker::_ac2_compile_queue = nullptr;
212
213 bool compileBroker_init() {
214 if (LogEvents) {
215 CompilationLog::init();
216 }
217
218 // init directives stack, adding default directive
219 DirectivesStack::init();
220
221 if (DirectivesParser::has_file()) {
222 return DirectivesParser::parse_from_flag();
223 } else if (CompilerDirectivesPrint) {
224 // Print default directive even when no other was added
225 DirectivesStack::print(tty);
226 }
227
228 return true;
229 }
230
231 CompileTaskWrapper::CompileTaskWrapper(CompileTask* task) {
232 CompilerThread* thread = CompilerThread::current();
233 thread->set_task(task);
234 CompileLog* log = thread->log();
235 thread->timeout()->arm();
236 if (log != nullptr && !task->is_unloaded()) task->log_task_start(log);
237 }
238
239 CompileTaskWrapper::~CompileTaskWrapper() {
240 CompilerThread* thread = CompilerThread::current();
241 CompileTask* task = thread->task();
242 CompileLog* log = thread->log();
243 AbstractCompiler* comp = thread->compiler();
244 if (log != nullptr && !task->is_unloaded()) task->log_task_done(log);
245 thread->set_task(nullptr);
246 thread->set_env(nullptr);
247 thread->timeout()->disarm();
248 if (task->is_blocking()) {
249 bool free_task = false;
250 {
251 MutexLocker notifier(thread, CompileTaskWait_lock);
252 task->mark_complete();
253 #if INCLUDE_JVMCI
254 if (comp->is_jvmci()) {
255 if (!task->has_waiter()) {
256 // The waiting thread timed out and thus did not delete the task.
257 free_task = true;
258 }
259 task->set_blocking_jvmci_compile_state(nullptr);
260 }
261 #endif
262 if (!free_task) {
263 // Notify the waiting thread that the compilation has completed
264 // so that it can free the task.
265 CompileTaskWait_lock->notify_all();
266 }
267 }
268 if (free_task) {
269 // The task can only be deleted once the task lock is released.
270 delete task;
271 }
272 } else {
273 task->mark_complete();
274
275 // By convention, the compiling thread is responsible for deleting
276 // a non-blocking CompileTask.
277 delete task;
278 }
279 }
280
281 /**
282 * Check if a CompilerThread can be removed and update count if requested.
283 */
284 bool CompileBroker::can_remove(CompilerThread *ct, bool do_it) {
285 assert(UseDynamicNumberOfCompilerThreads, "or shouldn't be here");
286 if (!ReduceNumberOfCompilerThreads) return false;
287
288 if (RecompilationPolicy::have_recompilation_work()) return false;
289
290 AbstractCompiler *compiler = ct->compiler();
291 int compiler_count = compiler->num_compiler_threads();
292 bool c1 = compiler->is_c1();
293
294 // Keep at least 1 compiler thread of each type.
295 if (compiler_count < 2) return false;
296
297 // Keep thread alive for at least some time.
298 if (ct->idle_time_millis() < (c1 ? 500 : 100)) return false;
299
300 #if INCLUDE_JVMCI
301 if (compiler->is_jvmci() && !UseJVMCINativeLibrary) {
302 // Handles for JVMCI thread objects may get released concurrently.
303 if (do_it) {
304 assert(CompileThread_lock->owner() == ct, "must be holding lock");
305 } else {
306 // Skip check if it's the last thread and let caller check again.
307 return true;
308 }
309 }
316 if (do_it) {
317 assert_locked_or_safepoint(CompileThread_lock); // Update must be consistent.
318 compiler->set_num_compiler_threads(compiler_count - 1);
319 #if INCLUDE_JVMCI
320 if (compiler->is_jvmci() && !UseJVMCINativeLibrary) {
321 // Old j.l.Thread object can die when no longer referenced elsewhere.
322 JNIHandles::destroy_global(compiler2_object(compiler_count - 1));
323 _compiler2_objects[compiler_count - 1] = nullptr;
324 }
325 #endif
326 }
327 return true;
328 }
329 return false;
330 }
331
332 /**
333 * Add a CompileTask to a CompileQueue.
334 */
335 void CompileQueue::add(CompileTask* task) {
336 assert(_lock->owned_by_self(), "must own lock");
337
338 task->set_next(nullptr);
339 task->set_prev(nullptr);
340
341 if (_last == nullptr) {
342 // The compile queue is empty.
343 assert(_first == nullptr, "queue is empty");
344 _first = task;
345 _last = task;
346 } else {
347 // Append the task to the queue.
348 assert(_last->next() == nullptr, "not last");
349 _last->set_next(task);
350 task->set_prev(_last);
351 _last = task;
352 }
353 ++_size;
354 ++_total_added;
355 if (_size > _peak_size) {
356 _peak_size = _size;
357 }
358
359 // Mark the method as being in the compile queue.
360 task->method()->set_queued_for_compilation();
361
362 task->mark_queued(os::elapsed_counter());
363
364 if (CIPrintCompileQueue) {
365 print_tty();
366 }
367
368 if (LogCompilation && xtty != nullptr) {
369 task->log_task_queued();
370 }
371
372 if (TrainingData::need_data() && !CDSConfig::is_dumping_final_static_archive()) {
373 CompileTrainingData* ctd = CompileTrainingData::make(task);
374 if (ctd != nullptr) {
375 task->set_training_data(ctd);
376 }
377 }
378
379 // Notify CompilerThreads that a task is available.
380 _lock->notify_all();
381 }
382
383 void CompileQueue::add_pending(CompileTask* task) {
384 assert(_lock->owned_by_self() == false, "must NOT own lock");
385 assert(UseLockFreeCompileQueues, "");
386 task->method()->set_queued_for_compilation();
387 _queue.push(*task);
388 // FIXME: additional coordination needed? e.g., is it possible for compiler thread to block w/o processing pending tasks?
389 if (is_empty()) {
390 MutexLocker ml(_lock);
391 _lock->notify_all();
392 }
393 }
394
395 static bool process_pending(CompileTask* task) {
396 // guarantee(task->method()->queued_for_compilation(), "");
397 if (task->is_unloaded()) {
398 return true; // unloaded
399 }
400 task->method()->set_queued_for_compilation(); // FIXME
401 if (task->method()->pending_queue_processed()) {
402 return true; // already queued
403 }
404 // Mark the method as being in the compile queue.
405 task->method()->set_pending_queue_processed();
406 if (CompileBroker::compilation_is_complete(task->method(), task->osr_bci(), task->comp_level(),
407 task->requires_online_compilation(), task->compile_reason())) {
408 return true; // already compiled
409 }
410 return false; // active
411 }
412
413 void CompileQueue::transfer_pending() {
414 assert(_lock->owned_by_self(), "must own lock");
415
416 CompileTask* task;
417 while ((task = _queue.pop()) != nullptr) {
418 bool is_stale = process_pending(task);
419 if (is_stale) {
420 task->set_next(_first_stale);
421 task->set_prev(nullptr);
422 _first_stale = task;
423 } else {
424 add(task);
425 }
426 }
427 }
428
429 /**
430 * Empties compilation queue by deleting all compilation tasks.
431 * Furthermore, the method wakes up all threads that are waiting
432 * on a compilation task to finish. This can happen if background
433 * compilation is disabled.
434 */
435 void CompileQueue::delete_all() {
436 MutexLocker mu(_lock);
437 transfer_pending();
438
439 CompileTask* current = _first;
440
441 // Iterate over all tasks in the compile queue
442 while (current != nullptr) {
443 CompileTask* next = current->next();
444 if (!current->is_blocking()) {
445 // Non-blocking task. No one is waiting for it, delete it now.
446 delete current;
447 } else {
448 // Blocking task. By convention, it is the waiters responsibility
449 // to delete the task. We cannot delete it here, because we do not
450 // coordinate with waiters. We will notify the waiters later.
451 }
452 current = next;
453 }
454 _first = nullptr;
455 _last = nullptr;
456
457 // Wake up all blocking task waiters to deal with remaining blocking
458 // tasks. This is not a performance sensitive path, so we do this
459 // unconditionally to simplify coding/testing.
460 {
461 MonitorLocker ml(Thread::current(), CompileTaskWait_lock);
462 ml.notify_all();
463 }
464
465 // Wake up all threads that block on the queue.
466 _lock->notify_all();
467 }
468
469 /**
470 * Get the next CompileTask from a CompileQueue
471 */
472 CompileTask* CompileQueue::get(CompilerThread* thread) {
473 // save methods from RedefineClasses across safepoint
474 // across compile queue lock below.
475 methodHandle save_method;
476
477 MonitorLocker locker(_lock);
478 transfer_pending();
479
480 RecompilationPolicy::sample_load_average();
481
482 // If _first is null we have no more compile jobs. There are two reasons for
483 // having no compile jobs: First, we compiled everything we wanted. Second,
484 // we ran out of code cache so compilation has been disabled. In the latter
485 // case we perform code cache sweeps to free memory such that we can re-enable
486 // compilation.
487 while (_first == nullptr) {
488 // Exit loop if compilation is disabled forever
489 if (CompileBroker::is_compilation_disabled_forever()) {
490 return nullptr;
491 }
492
493 AbstractCompiler* compiler = thread->compiler();
494 guarantee(compiler != nullptr, "Compiler object must exist");
495 compiler->on_empty_queue(this, thread);
496 if (_first != nullptr) {
497 // The call to on_empty_queue may have temporarily unlocked the MCQ lock
498 // so check again whether any tasks were added to the queue.
499 break;
500 }
501
502 // If we have added stale tasks, there might be waiters that want
503 // the notification these tasks have failed. Normally, this would
504 // be done by a compiler thread that would perform the purge at
505 // the end of some compilation. But, if compile queue is empty,
506 // there is no guarantee compilers would run and do the purge.
507 // Do the purge here and now to unblock the waiters.
508 // Perform this until we run out of stale tasks.
509 while (_first_stale != nullptr) {
510 purge_stale_tasks();
511 }
512 if (_first != nullptr) {
513 // Purge stale tasks may have transferred some new tasks,
514 // so check again.
515 break;
516 }
517
518 // If there are no compilation tasks and we can compile new jobs
519 // (i.e., there is enough free space in the code cache) there is
520 // no need to invoke the GC.
521 // We need a timed wait here, since compiler threads can exit if compilation
522 // is disabled forever. We use 5 seconds wait time; the exiting of compiler threads
523 // is not critical and we do not want idle compiler threads to wake up too often.
524 locker.wait(5*1000);
525
526 transfer_pending(); // reacquired lock
527
528 if (RecompilationPolicy::have_recompilation_work()) return nullptr;
529
530 if (UseDynamicNumberOfCompilerThreads && _first == nullptr) {
531 // Still nothing to compile. Give caller a chance to stop this thread.
532 if (CompileBroker::can_remove(CompilerThread::current(), false)) return nullptr;
533 }
534 }
535
536 if (CompileBroker::is_compilation_disabled_forever()) {
537 return nullptr;
538 }
539
540 CompileTask* task;
541 {
542 NoSafepointVerifier nsv;
543 task = CompilationPolicy::select_task(this, thread);
544 if (task != nullptr) {
545 task = task->select_for_compilation();
546 }
547 }
548
549 if (task != nullptr) {
550 // Save method pointers across unlock safepoint. The task is removed from
551 // the compilation queue, which is walked during RedefineClasses.
552 Thread* thread = Thread::current();
553 save_method = methodHandle(thread, task->method());
554
555 remove(task);
556 }
557 purge_stale_tasks(); // may temporarily release MCQ lock
558 return task;
559 }
560
561 // Clean & deallocate stale compile tasks.
562 // Temporarily releases MethodCompileQueue lock.
563 void CompileQueue::purge_stale_tasks() {
564 assert(_lock->owned_by_self(), "must own lock");
565 if (_first_stale != nullptr) {
566 // Stale tasks are purged when MCQ lock is released,
567 // but _first_stale updates are protected by MCQ lock.
568 // Once task processing starts and MCQ lock is released,
569 // other compiler threads can reuse _first_stale.
570 CompileTask* head = _first_stale;
571 _first_stale = nullptr;
572 {
573 MutexUnlocker ul(_lock);
574 for (CompileTask* task = head; task != nullptr; ) {
575 CompileTask* next_task = task->next();
576 task->set_next(nullptr);
577 CompileTaskWrapper ctw(task); // Frees the task
578 task->set_failure_reason("stale task");
579 task = next_task;
580 }
581 }
582 transfer_pending(); // transfer pending after reacquiring MCQ lock
583 }
584 }
585
586 void CompileQueue::remove(CompileTask* task) {
587 assert(_lock->owned_by_self(), "must own lock");
588 if (task->prev() != nullptr) {
589 task->prev()->set_next(task->next());
590 } else {
591 // max is the first element
592 assert(task == _first, "Sanity");
593 _first = task->next();
594 }
595
596 if (task->next() != nullptr) {
597 task->next()->set_prev(task->prev());
598 } else {
599 // max is the last element
600 assert(task == _last, "Sanity");
601 _last = task->prev();
602 }
603 task->set_next(nullptr);
604 task->set_prev(nullptr);
605 --_size;
606 ++_total_removed;
607 }
608
609 void CompileQueue::remove_and_mark_stale(CompileTask* task) {
610 assert(_lock->owned_by_self(), "must own lock");
611 remove(task);
612
613 // Enqueue the task for reclamation (should be done outside MCQ lock)
614 task->set_next(_first_stale);
615 task->set_prev(nullptr);
616 _first_stale = task;
617 }
618
619 // methods in the compile queue need to be marked as used on the stack
620 // so that they don't get reclaimed by Redefine Classes
621 void CompileQueue::mark_on_stack() {
622 for (CompileTask* task = _first; task != nullptr; task = task->next()) {
623 task->mark_on_stack();
624 }
625 for (CompileTask* task = _queue.first(); !_queue.is_end(task); task = task->next()) {
626 assert(task != nullptr, "");
627 task->mark_on_stack();
628 }
629 }
630
631
632 CompileQueue* CompileBroker::compile_queue(int comp_level, bool is_aot) {
633 if (is_c2_compile(comp_level)) return ((is_aot && (_ac_count > 0)) ? _ac2_compile_queue : _c2_compile_queue);
634 if (is_c1_compile(comp_level)) return ((is_aot && (_ac_count > 0)) ? _ac1_compile_queue : _c1_compile_queue);
635 return nullptr;
636 }
637
638 CompileQueue* CompileBroker::c1_compile_queue() {
639 return _c1_compile_queue;
640 }
641
642 CompileQueue* CompileBroker::c2_compile_queue() {
643 return _c2_compile_queue;
644 }
645
646 void CompileBroker::print_compile_queues(outputStream* st) {
647 st->print_cr("Current compiles: ");
648
649 char buf[2000];
650 int buflen = sizeof(buf);
651 Threads::print_threads_compiling(st, buf, buflen, /* short_form = */ true);
652
653 st->cr();
654 if (_c1_compile_queue != nullptr) {
655 _c1_compile_queue->print(st);
656 }
657 if (_c2_compile_queue != nullptr) {
658 _c2_compile_queue->print(st);
659 }
660 if (_ac1_compile_queue != nullptr) {
661 _ac1_compile_queue->print(st);
662 }
663 if (_ac2_compile_queue != nullptr) {
664 _ac2_compile_queue->print(st);
665 }
666 }
667
668 void CompileQueue::print(outputStream* st) {
669 assert_locked_or_safepoint(_lock);
670 st->print_cr("%s:", name());
671 CompileTask* task = _first;
672 if (task == nullptr) {
673 st->print_cr("Empty");
674 } else {
675 while (task != nullptr) {
676 task->print(st, nullptr, true, true);
677 task = task->next();
678 }
679 }
680 st->cr();
681 }
682
683 void CompileQueue::print_tty() {
684 stringStream ss;
685 // Dump the compile queue into a buffer before locking the tty
686 print(&ss);
687 {
688 ttyLocker ttyl;
689 tty->print("%s", ss.freeze());
716 CompilerEvent::PhaseEvent::get_phase_id(phase_name, false, false, false);
717 }
718 first_registration = false;
719 #endif // COMPILER2
720 }
721 }
722 #endif // INCLUDE_JFR && COMPILER2_OR_JVMCI
723
724 // ------------------------------------------------------------------
725 // CompileBroker::compilation_init
726 //
727 // Initialize the Compilation object
728 void CompileBroker::compilation_init(JavaThread* THREAD) {
729 // No need to initialize compilation system if we do not use it.
730 if (!UseCompiler) {
731 return;
732 }
733 // Set the interface to the current compiler(s).
734 _c1_count = CompilationPolicy::c1_count();
735 _c2_count = CompilationPolicy::c2_count();
736 _ac_count = CompilationPolicy::ac_count();
737
738 #if INCLUDE_JVMCI
739 if (EnableJVMCI) {
740 // This is creating a JVMCICompiler singleton.
741 JVMCICompiler* jvmci = new JVMCICompiler();
742
743 if (UseJVMCICompiler) {
744 _compilers[1] = jvmci;
745 if (FLAG_IS_DEFAULT(JVMCIThreads)) {
746 if (BootstrapJVMCI) {
747 // JVMCI will bootstrap so give it more threads
748 _c2_count = MIN2(32, os::active_processor_count());
749 }
750 } else {
751 _c2_count = JVMCIThreads;
752 }
753 if (FLAG_IS_DEFAULT(JVMCIHostThreads)) {
754 } else {
755 #ifdef COMPILER1
756 _c1_count = JVMCIHostThreads;
873 _perf_last_compile_size =
874 PerfDataManager::create_variable(SUN_CI, "lastSize",
875 PerfData::U_Bytes,
876 (jlong)CompileBroker::no_compile,
877 CHECK);
878
879
880 _perf_last_failed_type =
881 PerfDataManager::create_variable(SUN_CI, "lastFailedType",
882 PerfData::U_None,
883 (jlong)CompileBroker::no_compile,
884 CHECK);
885
886 _perf_last_invalidated_type =
887 PerfDataManager::create_variable(SUN_CI, "lastInvalidatedType",
888 PerfData::U_None,
889 (jlong)CompileBroker::no_compile,
890 CHECK);
891 }
892
893 log_info(aot, codecache, init)("CompileBroker is initialized");
894 _initialized = true;
895 }
896
897 Handle CompileBroker::create_thread_oop(const char* name, TRAPS) {
898 Handle thread_oop = JavaThread::create_system_thread_object(name, CHECK_NH);
899 return thread_oop;
900 }
901
902 void TrainingReplayThread::training_replay_thread_entry(JavaThread* thread, TRAPS) {
903 CompilationPolicy::replay_training_at_init_loop(thread);
904 }
905
906 #if defined(ASSERT) && COMPILER2_OR_JVMCI
907 // Entry for DeoptimizeObjectsALotThread. The threads are started in
908 // CompileBroker::init_compiler_threads() iff DeoptimizeObjectsALot is enabled
909 void DeoptimizeObjectsALotThread::deopt_objs_alot_thread_entry(JavaThread* thread, TRAPS) {
910 DeoptimizeObjectsALotThread* dt = ((DeoptimizeObjectsALotThread*) thread);
911 bool enter_single_loop;
912 {
913 MonitorLocker ml(dt, EscapeBarrier_lock, Mutex::_no_safepoint_check_flag);
914 static int single_thread_count = 0;
915 enter_single_loop = single_thread_count++ < DeoptimizeObjectsALotThreadCountSingle;
916 }
917 if (enter_single_loop) {
918 dt->deoptimize_objects_alot_loop_single();
919 } else {
920 dt->deoptimize_objects_alot_loop_all();
921 }
1045 }
1046
1047 static jobject create_compiler_thread(AbstractCompiler* compiler, int i, TRAPS) {
1048 char name_buffer[256];
1049 os::snprintf_checked(name_buffer, sizeof(name_buffer), "%s CompilerThread%d", compiler->name(), i);
1050 Handle thread_oop = JavaThread::create_system_thread_object(name_buffer, CHECK_NULL);
1051 return JNIHandles::make_global(thread_oop);
1052 }
1053
1054 static void print_compiler_threads(stringStream& msg) {
1055 if (TraceCompilerThreads) {
1056 tty->print_cr("%7d %s", (int)tty->time_stamp().milliseconds(), msg.as_string());
1057 }
1058 LogTarget(Debug, jit, thread) lt;
1059 if (lt.is_enabled()) {
1060 LogStream ls(lt);
1061 ls.print_cr("%s", msg.as_string());
1062 }
1063 }
1064
1065 static void print_compiler_thread(JavaThread *ct) {
1066 if (trace_compiler_threads()) {
1067 ResourceMark rm;
1068 ThreadsListHandle tlh; // name() depends on the TLH.
1069 assert(tlh.includes(ct), "ct=" INTPTR_FORMAT " exited unexpectedly.", p2i(ct));
1070 stringStream msg;
1071 msg.print("Added initial compiler thread %s", ct->name());
1072 print_compiler_threads(msg);
1073 }
1074 }
1075
1076 void CompileBroker::init_compiler_threads() {
1077 // Ensure any exceptions lead to vm_exit_during_initialization.
1078 EXCEPTION_MARK;
1079 #if !defined(ZERO)
1080 assert(_c2_count > 0 || _c1_count > 0, "No compilers?");
1081 #endif // !ZERO
1082 // Initialize the compilation queue
1083 if (_c2_count > 0) {
1084 const char* name = JVMCI_ONLY(UseJVMCICompiler ? "JVMCI compile queue" :) "C2 compile queue";
1085 _c2_compile_queue = new CompileQueue(name, MethodCompileQueueC2_lock);
1086 _compiler2_objects = NEW_C_HEAP_ARRAY(jobject, _c2_count, mtCompiler);
1087 _compiler2_logs = NEW_C_HEAP_ARRAY(CompileLog*, _c2_count, mtCompiler);
1088 }
1089 if (_c1_count > 0) {
1090 _c1_compile_queue = new CompileQueue("C1 compile queue", MethodCompileQueueC1_lock);
1091 _compiler1_objects = NEW_C_HEAP_ARRAY(jobject, _c1_count, mtCompiler);
1092 _compiler1_logs = NEW_C_HEAP_ARRAY(CompileLog*, _c1_count, mtCompiler);
1093 }
1094
1095 if (_ac_count > 0) {
1096 if (_c1_count > 0) { // C1 is present
1097 _ac1_compile_queue = new CompileQueue("C1 AOT code compile queue", MethodCompileQueueSC1_lock);
1098 }
1099 if (_c2_count > 0) { // C2 is present
1100 _ac2_compile_queue = new CompileQueue("C2 AOT code compile queue", MethodCompileQueueSC2_lock);
1101 }
1102 _ac_objects = NEW_C_HEAP_ARRAY(jobject, _ac_count, mtCompiler);
1103 _ac_logs = NEW_C_HEAP_ARRAY(CompileLog*, _ac_count, mtCompiler);
1104 }
1105 char name_buffer[256];
1106
1107 for (int i = 0; i < _c2_count; i++) {
1108 // Create a name for our thread.
1109 jobject thread_handle = create_compiler_thread(_compilers[1], i, CHECK);
1110 _compiler2_objects[i] = thread_handle;
1111 _compiler2_logs[i] = nullptr;
1112
1113 if (!UseDynamicNumberOfCompilerThreads || i == 0) {
1114 JavaThread *ct = make_thread(compiler_t, thread_handle, _c2_compile_queue, _compilers[1], THREAD);
1115 assert(ct != nullptr, "should have been handled for initial thread");
1116 _compilers[1]->set_num_compiler_threads(i + 1);
1117 print_compiler_thread(ct);
1118 }
1119 }
1120
1121 for (int i = 0; i < _c1_count; i++) {
1122 // Create a name for our thread.
1123 jobject thread_handle = create_compiler_thread(_compilers[0], i, CHECK);
1124 _compiler1_objects[i] = thread_handle;
1125 _compiler1_logs[i] = nullptr;
1126
1127 if (!UseDynamicNumberOfCompilerThreads || i == 0) {
1128 JavaThread *ct = make_thread(compiler_t, thread_handle, _c1_compile_queue, _compilers[0], THREAD);
1129 assert(ct != nullptr, "should have been handled for initial thread");
1130 _compilers[0]->set_num_compiler_threads(i + 1);
1131 print_compiler_thread(ct);
1132 }
1133 }
1134
1135 if (_ac_count > 0) {
1136 int i = 0;
1137 if (_c1_count > 0) { // C1 is present
1138 os::snprintf_checked(name_buffer, sizeof(name_buffer), "C%d AOT code caching CompilerThread", 1);
1139 Handle thread_oop = create_thread_oop(name_buffer, CHECK);
1140 jobject thread_handle = JNIHandles::make_global(thread_oop);
1141 _ac_objects[i] = thread_handle;
1142 _ac_logs[i] = nullptr;
1143 i++;
1144
1145 JavaThread *ct = make_thread(compiler_t, thread_handle, _ac1_compile_queue, _compilers[0], THREAD);
1146 assert(ct != nullptr, "should have been handled for initial thread");
1147 print_compiler_thread(ct);
1148 }
1149 if (_c2_count > 0) { // C2 is present
1150 os::snprintf_checked(name_buffer, sizeof(name_buffer), "C%d AOT code caching CompilerThread", 2);
1151 Handle thread_oop = create_thread_oop(name_buffer, CHECK);
1152 jobject thread_handle = JNIHandles::make_global(thread_oop);
1153 _ac_objects[i] = thread_handle;
1154 _ac_logs[i] = nullptr;
1155
1156 JavaThread *ct = make_thread(compiler_t, thread_handle, _ac2_compile_queue, _compilers[1], THREAD);
1157 assert(ct != nullptr, "should have been handled for initial thread");
1158 print_compiler_thread(ct);
1159 }
1160 }
1161
1162 if (UsePerfData) {
1163 PerfDataManager::create_constant(SUN_CI, "threads", PerfData::U_Bytes, _c1_count + _c2_count, CHECK);
1164 }
1165
1166 #if defined(ASSERT) && COMPILER2_OR_JVMCI
1167 if (DeoptimizeObjectsALot) {
1168 // Initialize and start the object deoptimizer threads
1169 const int total_count = DeoptimizeObjectsALotThreadCountSingle + DeoptimizeObjectsALotThreadCountAll;
1170 for (int count = 0; count < total_count; count++) {
1171 Handle thread_oop = JavaThread::create_system_thread_object("Deoptimize objects a lot single mode", CHECK);
1172 jobject thread_handle = JNIHandles::make_local(THREAD, thread_oop());
1173 make_thread(deoptimizer_t, thread_handle, nullptr, nullptr, THREAD);
1174 }
1175 }
1176 #endif // defined(ASSERT) && COMPILER2_OR_JVMCI
1177 }
1178
1179 void CompileBroker::init_training_replay() {
1180 // Ensure any exceptions lead to vm_exit_during_initialization.
1181 EXCEPTION_MARK;
1182 if (TrainingData::have_data()) {
1183 Handle thread_oop = create_thread_oop("Training replay thread", CHECK);
1184 jobject thread_handle = JNIHandles::make_local(THREAD, thread_oop());
1185 make_thread(training_replay_t, thread_handle, nullptr, nullptr, THREAD);
1186 }
1187 }
1188
1189 void CompileBroker::possibly_add_compiler_threads(JavaThread* THREAD) {
1190
1191 int old_c2_count = 0, new_c2_count = 0, old_c1_count = 0, new_c1_count = 0;
1192 const int c2_tasks_per_thread = 2, c1_tasks_per_thread = 4;
1193
1194 // Quick check if we already have enough compiler threads without taking the lock.
1195 // Numbers may change concurrently, so we read them again after we have the lock.
1196 if (_c2_compile_queue != nullptr) {
1197 old_c2_count = get_c2_thread_count();
1198 new_c2_count = MIN2(_c2_count, _c2_compile_queue->size() / c2_tasks_per_thread);
1199 }
1200 if (_c1_compile_queue != nullptr) {
1201 old_c1_count = get_c1_thread_count();
1202 new_c1_count = MIN2(_c1_count, _c1_compile_queue->size() / c1_tasks_per_thread);
1203 }
1299 }
1300
1301 CompileThread_lock->unlock();
1302 }
1303
1304
1305 /**
1306 * Set the methods on the stack as on_stack so that redefine classes doesn't
1307 * reclaim them. This method is executed at a safepoint.
1308 */
1309 void CompileBroker::mark_on_stack() {
1310 assert(SafepointSynchronize::is_at_safepoint(), "sanity check");
1311 // Since we are at a safepoint, we do not need a lock to access
1312 // the compile queues.
1313 if (_c2_compile_queue != nullptr) {
1314 _c2_compile_queue->mark_on_stack();
1315 }
1316 if (_c1_compile_queue != nullptr) {
1317 _c1_compile_queue->mark_on_stack();
1318 }
1319 if (_ac1_compile_queue != nullptr) {
1320 _ac1_compile_queue->mark_on_stack();
1321 }
1322 if (_ac2_compile_queue != nullptr) {
1323 _ac2_compile_queue->mark_on_stack();
1324 }
1325 }
1326
1327 // ------------------------------------------------------------------
1328 // CompileBroker::compile_method
1329 //
1330 // Request compilation of a method.
1331 void CompileBroker::compile_method_base(const methodHandle& method,
1332 int osr_bci,
1333 int comp_level,
1334 int hot_count,
1335 CompileTask::CompileReason compile_reason,
1336 bool requires_online_compilation,
1337 bool blocking,
1338 Thread* thread) {
1339 guarantee(!method->is_abstract(), "cannot compile abstract methods");
1340 assert(method->method_holder()->is_instance_klass(),
1341 "sanity check");
1342 assert(!method->method_holder()->is_not_initialized() ||
1343 compile_reason == CompileTask::Reason_Preload ||
1344 compile_reason == CompileTask::Reason_Precompile ||
1345 compile_reason == CompileTask::Reason_PrecompileForPreload, "method holder must be initialized");
1346 assert(!method->is_method_handle_intrinsic(), "do not enqueue these guys");
1347
1348 if (CIPrintRequests) {
1349 tty->print("request: ");
1350 method->print_short_name(tty);
1351 if (osr_bci != InvocationEntryBci) {
1352 tty->print(" osr_bci: %d", osr_bci);
1353 }
1354 tty->print(" level: %d comment: %s count: %d", comp_level, CompileTask::reason_name(compile_reason), hot_count);
1355 if (hot_count > 0) {
1356 tty->print(" hot: yes");
1357 }
1358 tty->cr();
1359 }
1360
1361 // A request has been made for compilation. Before we do any
1362 // real work, check to see if the method has been compiled
1363 // in the meantime with a definitive result.
1364 if (compilation_is_complete(method(), osr_bci, comp_level, requires_online_compilation, compile_reason)) {
1365 return;
1366 }
1367
1368 #ifndef PRODUCT
1369 if (osr_bci != -1 && !FLAG_IS_DEFAULT(OSROnlyBCI)) {
1370 if ((OSROnlyBCI > 0) ? (OSROnlyBCI != osr_bci) : (-OSROnlyBCI == osr_bci)) {
1371 // Positive OSROnlyBCI means only compile that bci. Negative means don't compile that BCI.
1372 return;
1373 }
1374 }
1375 #endif
1376
1377 // If this method is already in the compile queue, then
1378 // we do not block the current thread.
1379 if (compilation_is_in_queue(method)) {
1380 // We may want to decay our counter a bit here to prevent
1381 // multiple denied requests for compilation. This is an
1382 // open compilation policy issue. Note: The other possibility,
1383 // in the case that this is a blocking compile request, is to have
1384 // all subsequent blocking requesters wait for completion of
1385 // ongoing compiles. Note that in this case we'll need a protocol
1386 // for freeing the associated compile tasks. [Or we could have
1387 // a single static monitor on which all these waiters sleep.]
1388 return;
1389 }
1390
1391 // Tiered policy requires MethodCounters to exist before adding a method to
1392 // the queue. Create if we don't have them yet.
1393 if (compile_reason != CompileTask::Reason_Preload) {
1394 method->get_method_counters(thread);
1395 }
1396
1397 AOTCodeEntry* aot_code_entry = find_aot_code_entry(method, osr_bci, comp_level, compile_reason, requires_online_compilation);
1398 bool is_aot = (aot_code_entry != nullptr);
1399
1400 // Outputs from the following MutexLocker block:
1401 CompileTask* task = nullptr;
1402 CompileQueue* queue = compile_queue(comp_level, is_aot);
1403
1404 // Acquire our lock.
1405 {
1406 ConditionalMutexLocker locker(thread, queue->lock(), !UseLockFreeCompileQueues);
1407
1408 // Make sure the method has not slipped into the queues since
1409 // last we checked; note that those checks were "fast bail-outs".
1410 // Here we need to be more careful, see 14012000 below.
1411 if (compilation_is_in_queue(method)) {
1412 return;
1413 }
1414
1415 // We need to check again to see if the compilation has
1416 // completed. A previous compilation may have registered
1417 // some result.
1418 if (compilation_is_complete(method(), osr_bci, comp_level, requires_online_compilation, compile_reason)) {
1419 return;
1420 }
1421
1422 // We now know that this compilation is not pending, complete,
1423 // or prohibited. Assign a compile_id to this compilation
1424 // and check to see if it is in our [Start..Stop) range.
1425 int compile_id = assign_compile_id(method, osr_bci);
1426 if (compile_id == 0) {
1427 // The compilation falls outside the allowed range.
1428 return;
1429 }
1430
1431 #if INCLUDE_JVMCI
1432 if (UseJVMCICompiler && blocking) {
1433 // Don't allow blocking compiles for requests triggered by JVMCI.
1434 if (thread->is_Compiler_thread()) {
1435 blocking = false;
1436 }
1437
1438 // In libjvmci, JVMCI initialization should not deadlock with other threads
1488 // <RESULT, QUEUE> :
1489 // <0, 1> : in compile queue, but not yet compiled
1490 // <1, 1> : compiled but queue bit not cleared
1491 // <1, 0> : compiled and queue bit cleared
1492 // Because we first check the queue bits then check the result bits,
1493 // we are assured that we cannot introduce a duplicate task.
1494 // Note that if we did the tests in the reverse order (i.e. check
1495 // result then check queued bit), we could get the result bit before
1496 // the compilation completed, and the queue bit after the compilation
1497 // completed, and end up introducing a "duplicate" (redundant) task.
1498 // In that case, the compiler thread should first check if a method
1499 // has already been compiled before trying to compile it.
1500 // NOTE: in the event that there are multiple compiler threads and
1501 // there is de-optimization/recompilation, things will get hairy,
1502 // and in that case it's best to protect both the testing (here) of
1503 // these bits, and their updating (here and elsewhere) under a
1504 // common lock.
1505 task = create_compile_task(queue,
1506 compile_id, method,
1507 osr_bci, comp_level,
1508 hot_count, aot_code_entry, compile_reason,
1509 requires_online_compilation, blocking);
1510
1511 if (task->is_aot_load() && (_ac_count > 0)) {
1512 // Put it on AOT code caching queue
1513 queue = is_c1_compile(comp_level) ? _ac1_compile_queue : _ac2_compile_queue;
1514 }
1515
1516 if (UseLockFreeCompileQueues) {
1517 assert(queue->lock()->owned_by_self() == false, "");
1518 queue->add_pending(task);
1519 } else {
1520 queue->add(task);
1521 }
1522 }
1523
1524 if (blocking) {
1525 wait_for_completion(task);
1526 }
1527 }
1528
1529 AOTCodeEntry* CompileBroker::find_aot_code_entry(const methodHandle& method, int osr_bci, int comp_level,
1530 CompileTask::CompileReason compile_reason,
1531 bool requires_online_compilation) {
1532 if (requires_online_compilation || compile_reason == CompileTask::Reason_Whitebox) {
1533 return nullptr; // Need normal JIT compilation
1534 }
1535 AOTCodeEntry* aot_code_entry = nullptr;
1536 if (osr_bci == InvocationEntryBci && AOTCodeCache::is_using_code()) {
1537 // Check for AOT preload code first.
1538 if (compile_reason == CompileTask::Reason_Preload) {
1539 aot_code_entry = method->aot_code_entry();
1540 assert(aot_code_entry != nullptr && aot_code_entry->for_preload(), "sanity");
1541 } else {
1542 aot_code_entry = AOTCodeCache::find_code_entry(method, comp_level);
1543 }
1544 }
1545 return aot_code_entry;
1546 }
1547
1548 nmethod* CompileBroker::compile_method(const methodHandle& method, int osr_bci,
1549 int comp_level,
1550 int hot_count,
1551 bool requires_online_compilation,
1552 CompileTask::CompileReason compile_reason,
1553 TRAPS) {
1554 // Do nothing if compilebroker is not initialized or compiles are submitted on level none
1555 if (!_initialized || comp_level == CompLevel_none) {
1556 return nullptr;
1557 }
1558
1559 #if INCLUDE_JVMCI
1560 if (EnableJVMCI && UseJVMCICompiler &&
1561 comp_level == CompLevel_full_optimization && !AOTLinkedClassBulkLoader::class_preloading_finished()) {
1562 return nullptr;
1563 }
1564 #endif
1565
1566 AbstractCompiler *comp = CompileBroker::compiler(comp_level);
1567 assert(comp != nullptr, "Ensure we have a compiler");
1568
1569 #if INCLUDE_JVMCI
1570 if (comp->is_jvmci() && !JVMCI::can_initialize_JVMCI()) {
1571 // JVMCI compilation is not yet initializable.
1572 return nullptr;
1573 }
1574 #endif
1575
1576 DirectiveSet* directive = DirectivesStack::getMatchingDirective(method, comp);
1577 // CompileBroker::compile_method can trap and can have pending async exception.
1578 nmethod* nm = CompileBroker::compile_method(method, osr_bci, comp_level, hot_count, requires_online_compilation, compile_reason, directive, THREAD);
1579 DirectivesStack::release(directive);
1580 return nm;
1581 }
1582
1583 nmethod* CompileBroker::compile_method(const methodHandle& method, int osr_bci,
1584 int comp_level,
1585 int hot_count,
1586 bool requires_online_compilation,
1587 CompileTask::CompileReason compile_reason,
1588 DirectiveSet* directive,
1589 TRAPS) {
1590
1591 // make sure arguments make sense
1592 assert(method->method_holder()->is_instance_klass(), "not an instance method");
1593 assert(osr_bci == InvocationEntryBci || (0 <= osr_bci && osr_bci < method->code_size()), "bci out of range");
1594 assert(!method->is_abstract() && (osr_bci == InvocationEntryBci || !method->is_native()), "cannot compile abstract/native methods");
1595 assert(!method->method_holder()->is_not_initialized() ||
1596 compile_reason == CompileTask::Reason_Preload ||
1597 compile_reason == CompileTask::Reason_Precompile ||
1598 compile_reason == CompileTask::Reason_PrecompileForPreload, "method holder must be initialized");
1599 // return quickly if possible
1600 bool aot_compilation = (PrecompileCode && PrecompileOnlyAndExit) ||
1601 CDSConfig::is_dumping_aot_code();
1602 if (aot_compilation && !CompileTask::reason_is_precompile(compile_reason)) {
1603 // Skip normal compilations when compiling AOT code
1604 return nullptr;
1605 }
1606
1607 // lock, make sure that the compilation
1608 // isn't prohibited in a straightforward way.
1609 AbstractCompiler* comp = CompileBroker::compiler(comp_level);
1610 if (comp == nullptr || compilation_is_prohibited(method, osr_bci, comp_level, directive->ExcludeOption)) {
1611 return nullptr;
1612 }
1613
1614 if (osr_bci == InvocationEntryBci) {
1615 // standard compilation
1616 nmethod* method_code = method->code();
1617 if (method_code != nullptr) {
1618 if (compilation_is_complete(method(), osr_bci, comp_level, requires_online_compilation, compile_reason)) {
1619 return method_code;
1620 }
1621 }
1622 if (method->is_not_compilable(comp_level)) {
1623 return nullptr;
1624 }
1625 } else {
1626 // osr compilation
1627 // We accept a higher level osr method
1628 nmethod* nm = method->lookup_osr_nmethod_for(osr_bci, comp_level, false);
1629 if (nm != nullptr) return nm;
1630 if (method->is_not_osr_compilable(comp_level)) return nullptr;
1631 }
1632
1633 assert(!HAS_PENDING_EXCEPTION, "No exception should be present");
1634 // some prerequisites that are compiler specific
1635 if (compile_reason != CompileTask::Reason_Preload &&
1636 !CompileTask::reason_is_precompile(compile_reason) &&
1637 (comp->is_c2() || comp->is_jvmci())) {
1638 InternalOOMEMark iom(THREAD);
1639 method->constants()->resolve_string_constants(CHECK_AND_CLEAR_NONASYNC_NULL);
1640 // Resolve all classes seen in the signature of the method
1641 // we are compiling.
1642 Method::load_signature_classes(method, CHECK_AND_CLEAR_NONASYNC_NULL);
1643 }
1644
1645 // If the method is native, do the lookup in the thread requesting
1646 // the compilation. Native lookups can load code, which is not
1647 // permitted during compilation.
1648 //
1649 // Note: A native method implies non-osr compilation which is
1650 // checked with an assertion at the entry of this method.
1651 if (method->is_native() && !method->is_method_handle_intrinsic()) {
1652 address adr = NativeLookup::lookup(method, THREAD);
1653 if (HAS_PENDING_EXCEPTION) {
1654 // In case of an exception looking up the method, we just forget
1655 // about it. The interpreter will kick-in and throw the exception.
1656 method->set_not_compilable("NativeLookup::lookup failed"); // implies is_not_osr_compilable()
1657 CLEAR_PENDING_EXCEPTION;
1672 }
1673
1674 // do the compilation
1675 if (method->is_native()) {
1676 if (!PreferInterpreterNativeStubs || method->is_method_handle_intrinsic()) {
1677 // To properly handle the appendix argument for out-of-line calls we are using a small trampoline that
1678 // pops off the appendix argument and jumps to the target (see gen_special_dispatch in SharedRuntime).
1679 //
1680 // Since normal compiled-to-compiled calls are not able to handle such a thing we MUST generate an adapter
1681 // in this case. If we can't generate one and use it we can not execute the out-of-line method handle calls.
1682 AdapterHandlerLibrary::create_native_wrapper(method);
1683 } else {
1684 return nullptr;
1685 }
1686 } else {
1687 // If the compiler is shut off due to code cache getting full
1688 // fail out now so blocking compiles dont hang the java thread
1689 if (!should_compile_new_jobs()) {
1690 return nullptr;
1691 }
1692 bool is_blocking = ReplayCompiles ||
1693 !directive->BackgroundCompilationOption ||
1694 (PreloadBlocking && (compile_reason == CompileTask::Reason_Preload));
1695 compile_method_base(method, osr_bci, comp_level, hot_count, compile_reason, requires_online_compilation, is_blocking, THREAD);
1696 }
1697
1698 // return requested nmethod
1699 // We accept a higher level osr method
1700 if (osr_bci == InvocationEntryBci) {
1701 return method->code();
1702 }
1703 return method->lookup_osr_nmethod_for(osr_bci, comp_level, false);
1704 }
1705
1706
1707 // ------------------------------------------------------------------
1708 // CompileBroker::compilation_is_complete
1709 //
1710 // See if compilation of this method is already complete.
1711 bool CompileBroker::compilation_is_complete(Method* method,
1712 int osr_bci,
1713 int comp_level,
1714 bool online_only,
1715 CompileTask::CompileReason compile_reason) {
1716 if (compile_reason == CompileTask::Reason_Precompile ||
1717 compile_reason == CompileTask::Reason_PrecompileForPreload) {
1718 return false; // FIXME: any restrictions?
1719 }
1720 bool is_osr = (osr_bci != standard_entry_bci);
1721 if (is_osr) {
1722 if (method->is_not_osr_compilable(comp_level)) {
1723 return true;
1724 } else {
1725 nmethod* result = method->lookup_osr_nmethod_for(osr_bci, comp_level, true);
1726 return (result != nullptr);
1727 }
1728 } else {
1729 if (method->is_not_compilable(comp_level)) {
1730 return true;
1731 } else {
1732 nmethod* result = method->code();
1733 if (result == nullptr) {
1734 return false;
1735 }
1736 if (online_only && result->is_aot()) {
1737 return false;
1738 }
1739 bool same_level = (comp_level == result->comp_level());
1740 if (result->has_clinit_barriers()) {
1741 return !same_level; // Allow replace preloaded code with new code of the same level
1742 }
1743 return same_level;
1744 }
1745 }
1746 }
1747
1748
1749 /**
1750 * See if this compilation is already requested.
1751 *
1752 * Implementation note: there is only a single "is in queue" bit
1753 * for each method. This means that the check below is overly
1754 * conservative in the sense that an osr compilation in the queue
1755 * will block a normal compilation from entering the queue (and vice
1756 * versa). This can be remedied by a full queue search to disambiguate
1757 * cases. If it is deemed profitable, this may be done.
1758 */
1759 bool CompileBroker::compilation_is_in_queue(const methodHandle& method) {
1760 return method->queued_for_compilation();
1761 }
1762
1763 // ------------------------------------------------------------------
1823 if (CIStart <= id && id < CIStop) {
1824 return id;
1825 }
1826 }
1827
1828 // Method was not in the appropriate compilation range.
1829 method->set_not_compilable_quietly("Not in requested compile id range");
1830 return 0;
1831 #else
1832 // CICountOSR is a develop flag and set to 'false' by default. In a product built,
1833 // only _compilation_id is incremented.
1834 return Atomic::add(&_compilation_id, 1);
1835 #endif
1836 }
1837
1838 // ------------------------------------------------------------------
1839 // CompileBroker::assign_compile_id_unlocked
1840 //
1841 // Public wrapper for assign_compile_id that acquires the needed locks
1842 int CompileBroker::assign_compile_id_unlocked(Thread* thread, const methodHandle& method, int osr_bci) {
1843 return assign_compile_id(method, osr_bci);
1844 }
1845
1846 // ------------------------------------------------------------------
1847 // CompileBroker::create_compile_task
1848 //
1849 // Create a CompileTask object representing the current request for
1850 // compilation. Add this task to the queue.
1851 CompileTask* CompileBroker::create_compile_task(CompileQueue* queue,
1852 int compile_id,
1853 const methodHandle& method,
1854 int osr_bci,
1855 int comp_level,
1856 int hot_count,
1857 AOTCodeEntry* aot_code_entry,
1858 CompileTask::CompileReason compile_reason,
1859 bool requires_online_compilation,
1860 bool blocking) {
1861 CompileTask* new_task = new CompileTask(compile_id, method, osr_bci, comp_level,
1862 hot_count, aot_code_entry, compile_reason, queue,
1863 requires_online_compilation, blocking);
1864 return new_task;
1865 }
1866
1867 #if INCLUDE_JVMCI
1868 // The number of milliseconds to wait before checking if
1869 // JVMCI compilation has made progress.
1870 static const long JVMCI_COMPILATION_PROGRESS_WAIT_TIMESLICE = 1000;
1871
1872 // The number of JVMCI compilation progress checks that must fail
1873 // before unblocking a thread waiting for a blocking compilation.
1874 static const int JVMCI_COMPILATION_PROGRESS_WAIT_ATTEMPTS = 10;
1875
1876 /**
1877 * Waits for a JVMCI compiler to complete a given task. This thread
1878 * waits until either the task completes or it sees no JVMCI compilation
1879 * progress for N consecutive milliseconds where N is
1880 * JVMCI_COMPILATION_PROGRESS_WAIT_TIMESLICE *
1881 * JVMCI_COMPILATION_PROGRESS_WAIT_ATTEMPTS.
1882 *
1883 * @return true if this thread needs to delete the task
1997 * compiler threads can start compiling.
1998 */
1999 bool CompileBroker::init_compiler_runtime() {
2000 CompilerThread* thread = CompilerThread::current();
2001 AbstractCompiler* comp = thread->compiler();
2002 // Final sanity check - the compiler object must exist
2003 guarantee(comp != nullptr, "Compiler object must exist");
2004
2005 {
2006 // Must switch to native to allocate ci_env
2007 ThreadToNativeFromVM ttn(thread);
2008 ciEnv ci_env((CompileTask*)nullptr);
2009 // Cache Jvmti state
2010 ci_env.cache_jvmti_state();
2011 // Cache DTrace flags
2012 ci_env.cache_dtrace_flags();
2013
2014 // Switch back to VM state to do compiler initialization
2015 ThreadInVMfromNative tv(thread);
2016
2017 comp->initialize();
2018 }
2019
2020 if (comp->is_failed()) {
2021 disable_compilation_forever();
2022 // If compiler initialization failed, no compiler thread that is specific to a
2023 // particular compiler runtime will ever start to compile methods.
2024 shutdown_compiler_runtime(comp, thread);
2025 return false;
2026 }
2027
2028 // C1 specific check
2029 if (comp->is_c1() && (thread->get_buffer_blob() == nullptr)) {
2030 warning("Initialization of %s thread failed (no space to run compilers)", thread->name());
2031 return false;
2032 }
2033
2034 return true;
2035 }
2036
2037 void CompileBroker::free_buffer_blob_if_allocated(CompilerThread* thread) {
2038 BufferBlob* blob = thread->get_buffer_blob();
2039 if (blob != nullptr) {
2040 blob->purge();
2041 MutexLocker mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
2042 CodeCache::free(blob);
2043 }
2044 }
2045
2046 /**
2047 * If C1 and/or C2 initialization failed, we shut down all compilation.
2048 * We do this to keep things simple. This can be changed if it ever turns
2049 * out to be a problem.
2050 */
2051 void CompileBroker::shutdown_compiler_runtime(AbstractCompiler* comp, CompilerThread* thread) {
2052 free_buffer_blob_if_allocated(thread);
2053
2054 log_info(compilation)("shutdown_compiler_runtime: " INTPTR_FORMAT, p2i(thread));
2055
2056 if (comp->should_perform_shutdown()) {
2057 // There are two reasons for shutting down the compiler
2058 // 1) compiler runtime initialization failed
2059 // 2) The code cache is full and the following flag is set: -XX:-UseCodeCacheFlushing
2060 warning("%s initialization failed. Shutting down all compilers", comp->name());
2061
2062 // Only one thread per compiler runtime object enters here
2063 // Set state to shut down
2064 comp->set_shut_down();
2065
2066 // Delete all queued compilation tasks to make compiler threads exit faster.
2067 if (_c1_compile_queue != nullptr) {
2068 _c1_compile_queue->delete_all();
2069 }
2070
2071 if (_c2_compile_queue != nullptr) {
2072 _c2_compile_queue->delete_all();
2073 }
2074
2075 // Set flags so that we continue execution with using interpreter only.
2079 // We could delete compiler runtimes also. However, there are references to
2080 // the compiler runtime(s) (e.g., nmethod::is_compiled_by_c1()) which then
2081 // fail. This can be done later if necessary.
2082 }
2083 }
2084
2085 /**
2086 * Helper function to create new or reuse old CompileLog.
2087 */
2088 CompileLog* CompileBroker::get_log(CompilerThread* ct) {
2089 if (!LogCompilation) return nullptr;
2090
2091 AbstractCompiler *compiler = ct->compiler();
2092 bool c1 = compiler->is_c1();
2093 jobject* compiler_objects = c1 ? _compiler1_objects : _compiler2_objects;
2094 assert(compiler_objects != nullptr, "must be initialized at this point");
2095 CompileLog** logs = c1 ? _compiler1_logs : _compiler2_logs;
2096 assert(logs != nullptr, "must be initialized at this point");
2097 int count = c1 ? _c1_count : _c2_count;
2098
2099 if (ct->queue() == _ac1_compile_queue || ct->queue() == _ac2_compile_queue) {
2100 compiler_objects = _ac_objects;
2101 logs = _ac_logs;
2102 count = _ac_count;
2103 }
2104 // Find Compiler number by its threadObj.
2105 oop compiler_obj = ct->threadObj();
2106 int compiler_number = 0;
2107 bool found = false;
2108 for (; compiler_number < count; compiler_number++) {
2109 if (JNIHandles::resolve_non_null(compiler_objects[compiler_number]) == compiler_obj) {
2110 found = true;
2111 break;
2112 }
2113 }
2114 assert(found, "Compiler must exist at this point");
2115
2116 // Determine pointer for this thread's log.
2117 CompileLog** log_ptr = &logs[compiler_number];
2118
2119 // Return old one if it exists.
2120 CompileLog* log = *log_ptr;
2121 if (log != nullptr) {
2122 ct->init_log(log);
2123 return log;
2165 if (!thread->init_compilation_timeout()) {
2166 return;
2167 }
2168
2169 // If compiler thread/runtime initialization fails, exit the compiler thread
2170 if (!init_compiler_runtime()) {
2171 return;
2172 }
2173
2174 thread->start_idle_timer();
2175
2176 // Poll for new compilation tasks as long as the JVM runs. Compilation
2177 // should only be disabled if something went wrong while initializing the
2178 // compiler runtimes. This, in turn, should not happen. The only known case
2179 // when compiler runtime initialization fails is if there is not enough free
2180 // space in the code cache to generate the necessary stubs, etc.
2181 while (!is_compilation_disabled_forever()) {
2182 // We need this HandleMark to avoid leaking VM handles.
2183 HandleMark hm(thread);
2184
2185 RecompilationPolicy::recompilation_step(AOTRecompilationWorkUnitSize, thread);
2186
2187 CompileTask* task = queue->get(thread);
2188 if (task == nullptr) {
2189 if (UseDynamicNumberOfCompilerThreads) {
2190 // Access compiler_count under lock to enforce consistency.
2191 MutexLocker only_one(CompileThread_lock);
2192 if (can_remove(thread, true)) {
2193 if (trace_compiler_threads()) {
2194 ResourceMark rm;
2195 stringStream msg;
2196 msg.print("Removing compiler thread %s after " JLONG_FORMAT " ms idle time",
2197 thread->name(), thread->idle_time_millis());
2198 print_compiler_threads(msg);
2199 }
2200
2201 // Notify compiler that the compiler thread is about to stop
2202 thread->compiler()->stopping_compiler_thread(thread);
2203
2204 free_buffer_blob_if_allocated(thread);
2205 return; // Stop this thread.
2206 }
2207 }
2208 } else {
2209 // Assign the task to the current thread. Mark this compilation
2210 // thread as active for the profiler.
2211 // CompileTaskWrapper also keeps the Method* from being deallocated if redefinition
2212 // occurs after fetching the compile task off the queue.
2213 CompileTaskWrapper ctw(task);
2214 methodHandle method(thread, task->method());
2215
2216 // Never compile a method if breakpoints are present in it
2217 if (method()->number_of_breakpoints() == 0) {
2218 // Compile the method.
2219 if ((UseCompiler || AlwaysCompileLoopMethods) && CompileBroker::should_compile_new_jobs()) {
2220 invoke_compiler_on_method(task);
2221 thread->start_idle_timer();
2222 } else {
2223 // After compilation is disabled, remove remaining methods from queue
2224 method->clear_queued_for_compilation();
2225 method->set_pending_queue_processed(false);
2226 task->set_failure_reason("compilation is disabled");
2227 }
2228 } else {
2229 task->set_failure_reason("breakpoints are present");
2230 }
2231
2232 // Don't use AOT compielr threads for dynamic C1 and C2 threads creation.
2233 if (UseDynamicNumberOfCompilerThreads &&
2234 (queue == _c1_compile_queue || queue == _c2_compile_queue)) {
2235 possibly_add_compiler_threads(thread);
2236 assert(!thread->has_pending_exception(), "should have been handled");
2237 }
2238 }
2239 }
2240
2241 // Shut down compiler runtime
2242 shutdown_compiler_runtime(thread->compiler(), thread);
2243 }
2244
2245 // ------------------------------------------------------------------
2246 // CompileBroker::init_compiler_thread_log
2247 //
2248 // Set up state required by +LogCompilation.
2249 void CompileBroker::init_compiler_thread_log() {
2250 CompilerThread* thread = CompilerThread::current();
2251 char file_name[4*K];
2252 FILE* fp = nullptr;
2253 intx thread_id = os::current_thread_id();
2254 for (int try_temp_dir = 1; try_temp_dir >= 0; try_temp_dir--) {
2410
2411 // Acquires Compilation_lock and waits for it to be notified
2412 // as long as WhiteBox::compilation_locked is true.
2413 static void whitebox_lock_compilation() {
2414 MonitorLocker locker(Compilation_lock, Mutex::_no_safepoint_check_flag);
2415 while (WhiteBox::compilation_locked) {
2416 locker.wait();
2417 }
2418 }
2419
2420 // ------------------------------------------------------------------
2421 // CompileBroker::invoke_compiler_on_method
2422 //
2423 // Compile a method.
2424 //
2425 void CompileBroker::invoke_compiler_on_method(CompileTask* task) {
2426 task->print_ul();
2427 elapsedTimer time;
2428
2429 DirectiveSet* directive = task->directive();
2430
2431 CompilerThread* thread = CompilerThread::current();
2432 ResourceMark rm(thread);
2433
2434 if (CompilationLog::log() != nullptr) {
2435 CompilationLog::log()->log_compile(thread, task);
2436 }
2437
2438 // Common flags.
2439 int compile_id = task->compile_id();
2440 int osr_bci = task->osr_bci();
2441 bool is_osr = (osr_bci != standard_entry_bci);
2442 bool should_log = (thread->log() != nullptr);
2443 bool should_break = false;
2444 bool should_print_compilation = PrintCompilation || directive->PrintCompilationOption;
2445 const int task_level = task->comp_level();
2446 AbstractCompiler* comp = task->compiler();
2447 {
2448 // create the handle inside it's own block so it can't
2449 // accidentally be referenced once the thread transitions to
2450 // native. The NoHandleMark before the transition should catch
2451 // any cases where this occurs in the future.
2452 methodHandle method(thread, task->method());
2453
2454 assert(!method->is_native(), "no longer compile natives");
2455
2456 // Update compile information when using perfdata.
2457 if (UsePerfData) {
2458 update_compile_perf_data(thread, method, is_osr);
2459 }
2460
2461 DTRACE_METHOD_COMPILE_BEGIN_PROBE(method, compiler_name(task_level));
2462 }
2463
2464 should_break = directive->BreakAtCompileOption || task->check_break_at_flags();
2569
2570 if (comp == nullptr) {
2571 ci_env.record_method_not_compilable("no compiler");
2572 } else if (!ci_env.failing()) {
2573 if (WhiteBoxAPI && WhiteBox::compilation_locked) {
2574 whitebox_lock_compilation();
2575 }
2576 comp->compile_method(&ci_env, target, osr_bci, true, directive);
2577
2578 /* Repeat compilation without installing code for profiling purposes */
2579 int repeat_compilation_count = directive->RepeatCompilationOption;
2580 while (repeat_compilation_count > 0) {
2581 ResourceMark rm(thread);
2582 task->print_ul("NO CODE INSTALLED");
2583 comp->compile_method(&ci_env, target, osr_bci, false, directive);
2584 repeat_compilation_count--;
2585 }
2586 }
2587
2588
2589 if (!ci_env.failing() && !task->is_success() && !task->is_precompile()) {
2590 assert(ci_env.failure_reason() != nullptr, "expect failure reason");
2591 assert(false, "compiler should always document failure: %s", ci_env.failure_reason());
2592 // The compiler elected, without comment, not to register a result.
2593 // Do not attempt further compilations of this method.
2594 ci_env.record_method_not_compilable("compile failed");
2595 }
2596
2597 // Copy this bit to the enclosing block:
2598 compilable = ci_env.compilable();
2599
2600 if (ci_env.failing()) {
2601 // Duplicate the failure reason string, so that it outlives ciEnv
2602 failure_reason = os::strdup(ci_env.failure_reason(), mtCompiler);
2603 failure_reason_on_C_heap = true;
2604 retry_message = ci_env.retry_message();
2605 ci_env.report_failure(failure_reason);
2606 }
2607
2608 if (ci_env.failing()) {
2609 handle_compile_error(thread, task, &ci_env, compilable, failure_reason);
2610 }
2611 if (event.should_commit()) {
2612 post_compilation_event(event, task);
2613 }
2614 }
2615
2616 if (failure_reason != nullptr) {
2617 task->set_failure_reason(failure_reason, failure_reason_on_C_heap);
2618 if (CompilationLog::log() != nullptr) {
2619 CompilationLog::log()->log_failure(thread, task, failure_reason, retry_message);
2620 }
2621 if (PrintCompilation || directive->PrintCompilationOption) {
2622 FormatBufferResource msg = retry_message != nullptr ?
2623 FormatBufferResource("COMPILE SKIPPED: %s (%s)", failure_reason, retry_message) :
2624 FormatBufferResource("COMPILE SKIPPED: %s", failure_reason);
2625 task->print(tty, msg);
2626 }
2627 }
2628
2629 task->mark_finished(os::elapsed_counter());
2630 DirectivesStack::release(directive);
2631
2632 methodHandle method(thread, task->method());
2633
2634 DTRACE_METHOD_COMPILE_END_PROBE(method, compiler_name(task_level), task->is_success());
2635
2636 collect_statistics(thread, time, task);
2637
2638 if (PrintCompilation && PrintCompilation2) {
2639 tty->print("%7d ", (int) tty->time_stamp().milliseconds()); // print timestamp
2640 tty->print("%4d ", compile_id); // print compilation number
2641 tty->print("%s ", (is_osr ? "%" : (task->is_aot_load() ? (task->preload() ? "P" : "A") : " ")));
2642 if (task->is_success()) {
2643 tty->print("size: %d(%d) ", task->nm_total_size(), task->nm_insts_size());
2644 }
2645 tty->print_cr("time: %d inlined: %d bytes", (int)time.milliseconds(), task->num_inlined_bytecodes());
2646 }
2647
2648 Log(compilation, codecache) log;
2649 if (log.is_debug()) {
2650 LogStream ls(log.debug());
2651 codecache_print(&ls, /* detailed= */ false);
2652 }
2653 if (PrintCodeCacheOnCompilation) {
2654 codecache_print(/* detailed= */ false);
2655 }
2656 // Disable compilation, if required.
2657 switch (compilable) {
2658 case ciEnv::MethodCompilable_never:
2659 if (is_osr)
2660 method->set_not_osr_compilable_quietly("MethodCompilable_never");
2661 else
2662 method->set_not_compilable_quietly("MethodCompilable_never");
2663 break;
2664 case ciEnv::MethodCompilable_not_at_tier:
2665 if (is_osr)
2666 method->set_not_osr_compilable_quietly("MethodCompilable_not_at_tier", task_level);
2667 else
2668 method->set_not_compilable_quietly("MethodCompilable_not_at_tier", task_level);
2669 break;
2670 }
2671
2672 // Note that the queued_for_compilation bits are cleared without
2673 // protection of a mutex. [They were set by the requester thread,
2674 // when adding the task to the compile queue -- at which time the
2675 // compile queue lock was held. Subsequently, we acquired the compile
2676 // queue lock to get this task off the compile queue; thus (to belabour
2677 // the point somewhat) our clearing of the bits must be occurring
2678 // only after the setting of the bits. See also 14012000 above.
2679 method->clear_queued_for_compilation();
2680 method->set_pending_queue_processed(false);
2681
2682 if (should_print_compilation) {
2683 ResourceMark rm;
2684 task->print_tty();
2685 }
2686 }
2687
2688 /**
2689 * The CodeCache is full. Print warning and disable compilation.
2690 * Schedule code cache cleaning so compilation can continue later.
2691 * This function needs to be called only from CodeCache::allocate(),
2692 * since we currently handle a full code cache uniformly.
2693 */
2694 void CompileBroker::handle_full_code_cache(CodeBlobType code_blob_type) {
2695 UseInterpreter = true;
2696 if (UseCompiler || AlwaysCompileLoopMethods ) {
2697 if (xtty != nullptr) {
2698 stringStream s;
2699 // Dump code cache state into a buffer before locking the tty,
2700 // because log_state() will use locks causing lock conflicts.
2701 CodeCache::log_state(&s);
2702 // Lock to prevent tearing
2703 ttyLocker ttyl;
2704 xtty->begin_elem("code_cache_full");
2705 xtty->print("%s", s.freeze());
2778 // CompileBroker::collect_statistics
2779 //
2780 // Collect statistics about the compilation.
2781
2782 void CompileBroker::collect_statistics(CompilerThread* thread, elapsedTimer time, CompileTask* task) {
2783 bool success = task->is_success();
2784 methodHandle method (thread, task->method());
2785 int compile_id = task->compile_id();
2786 bool is_osr = (task->osr_bci() != standard_entry_bci);
2787 const int comp_level = task->comp_level();
2788 CompilerCounters* counters = thread->counters();
2789
2790 MutexLocker locker(CompileStatistics_lock);
2791
2792 // _perf variables are production performance counters which are
2793 // updated regardless of the setting of the CITime and CITimeEach flags
2794 //
2795
2796 // account all time, including bailouts and failures in this counter;
2797 // C1 and C2 counters are counting both successful and unsuccessful compiles
2798 _t_total_compilation.add(&time);
2799
2800 // Update compilation times. Used by the implementation of JFR CompilerStatistics
2801 // and java.lang.management.CompilationMXBean.
2802 _perf_total_compilation->inc(time.ticks());
2803 _peak_compilation_time = MAX2(time.milliseconds(), _peak_compilation_time);
2804
2805 if (!success) {
2806 _total_bailout_count++;
2807 if (UsePerfData) {
2808 _perf_last_failed_method->set_value(counters->current_method());
2809 _perf_last_failed_type->set_value(counters->compile_type());
2810 _perf_total_bailout_count->inc();
2811 }
2812 _t_bailedout_compilation.add(&time);
2813
2814 if (CITime || log_is_enabled(Info, init)) {
2815 CompilerStatistics* stats = nullptr;
2816 if (task->is_aot_load()) {
2817 int level = task->preload() ? CompLevel_full_optimization : (comp_level - 1);
2818 stats = &_aot_stats_per_level[level];
2819 } else {
2820 stats = &_stats_per_level[comp_level-1];
2821 }
2822 stats->_bailout.update(time, 0);
2823 }
2824 } else if (!task->is_success()) {
2825 if (UsePerfData) {
2826 _perf_last_invalidated_method->set_value(counters->current_method());
2827 _perf_last_invalidated_type->set_value(counters->compile_type());
2828 _perf_total_invalidated_count->inc();
2829 }
2830 _total_invalidated_count++;
2831 _t_invalidated_compilation.add(&time);
2832
2833 if (CITime || log_is_enabled(Info, init)) {
2834 CompilerStatistics* stats = nullptr;
2835 if (task->is_aot_load()) {
2836 int level = task->preload() ? CompLevel_full_optimization : (comp_level - 1);
2837 stats = &_aot_stats_per_level[level];
2838 } else {
2839 stats = &_stats_per_level[comp_level-1];
2840 }
2841 stats->_invalidated.update(time, 0);
2842 }
2843 } else {
2844 // Compilation succeeded
2845 if (CITime || log_is_enabled(Info, init)) {
2846 int bytes_compiled = method->code_size() + task->num_inlined_bytecodes();
2847 if (is_osr) {
2848 _t_osr_compilation.add(&time);
2849 _sum_osr_bytes_compiled += bytes_compiled;
2850 } else {
2851 _t_standard_compilation.add(&time);
2852 _sum_standard_bytes_compiled += method->code_size() + task->num_inlined_bytecodes();
2853 }
2854
2855 // Collect statistic per compilation level
2856 if (task->is_aot_load()) {
2857 _aot_stats._standard.update(time, bytes_compiled);
2858 _aot_stats._nmethods_size += task->nm_total_size();
2859 _aot_stats._nmethods_code_size += task->nm_insts_size();
2860 int level = task->preload() ? CompLevel_full_optimization : (comp_level - 1);
2861 CompilerStatistics* stats = &_aot_stats_per_level[level];
2862 stats->_standard.update(time, bytes_compiled);
2863 stats->_nmethods_size += task->nm_total_size();
2864 stats->_nmethods_code_size += task->nm_insts_size();
2865 } else if (comp_level > CompLevel_none && comp_level <= CompLevel_full_optimization) {
2866 CompilerStatistics* stats = &_stats_per_level[comp_level-1];
2867 if (is_osr) {
2868 stats->_osr.update(time, bytes_compiled);
2869 } else {
2870 stats->_standard.update(time, bytes_compiled);
2871 }
2872 stats->_nmethods_size += task->nm_total_size();
2873 stats->_nmethods_code_size += task->nm_insts_size();
2874 } else {
2875 assert(false, "CompilerStatistics object does not exist for compilation level %d", comp_level);
2876 }
2877
2878 // Collect statistic per compiler
2879 AbstractCompiler* comp = task->compiler();
2880 if (comp && !task->is_aot_load()) {
2881 CompilerStatistics* stats = comp->stats();
2882 if (is_osr) {
2883 stats->_osr.update(time, bytes_compiled);
2884 } else {
2885 stats->_standard.update(time, bytes_compiled);
2886 }
2887 stats->_nmethods_size += task->nm_total_size();
2888 stats->_nmethods_code_size += task->nm_insts_size();
2889 } else if (!task->is_aot_load()) { // if (!comp)
2890 assert(false, "Compiler object must exist");
2891 }
2892 }
2893
2894 if (UsePerfData) {
2895 // save the name of the last method compiled
2896 _perf_last_method->set_value(counters->current_method());
2897 _perf_last_compile_type->set_value(counters->compile_type());
2898 _perf_last_compile_size->set_value(method->code_size() +
2899 task->num_inlined_bytecodes());
2900 if (is_osr) {
2901 _perf_osr_compilation->inc(time.ticks());
2902 _perf_sum_osr_bytes_compiled->inc(method->code_size() + task->num_inlined_bytecodes());
2903 } else {
2904 _perf_standard_compilation->inc(time.ticks());
2905 _perf_sum_standard_bytes_compiled->inc(method->code_size() + task->num_inlined_bytecodes());
2906 }
2907 }
2908
2909 if (CITimeEach) {
2932 _total_standard_compile_count++;
2933 }
2934 }
2935 // set the current method for the thread to null
2936 if (UsePerfData) counters->set_current_method("");
2937 }
2938
2939 const char* CompileBroker::compiler_name(int comp_level) {
2940 AbstractCompiler *comp = CompileBroker::compiler(comp_level);
2941 if (comp == nullptr) {
2942 return "no compiler";
2943 } else {
2944 return (comp->name());
2945 }
2946 }
2947
2948 jlong CompileBroker::total_compilation_ticks() {
2949 return _perf_total_compilation != nullptr ? _perf_total_compilation->get_value() : 0;
2950 }
2951
2952 void CompileBroker::log_not_entrant(nmethod* nm) {
2953 _total_not_entrant_count++;
2954 if (CITime || log_is_enabled(Info, init)) {
2955 CompilerStatistics* stats = nullptr;
2956 int level = nm->comp_level();
2957 if (nm->is_aot()) {
2958 if (nm->preloaded()) {
2959 assert(level == CompLevel_full_optimization, "%d", level);
2960 level = CompLevel_full_optimization + 1;
2961 }
2962 stats = &_aot_stats_per_level[level - 1];
2963 } else {
2964 stats = &_stats_per_level[level - 1];
2965 }
2966 stats->_made_not_entrant._count++;
2967 }
2968 }
2969
2970 void CompileBroker::print_times(const char* name, CompilerStatistics* stats) {
2971 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}",
2972 name, stats->bytes_per_second(),
2973 stats->_standard._time.seconds(), stats->_standard._bytes, stats->_standard._count,
2974 stats->_osr._time.seconds(), stats->_osr._bytes, stats->_osr._count,
2975 stats->_nmethods_size, stats->_nmethods_code_size);
2976 }
2977
2978 static void print_helper(outputStream* st, const char* name, CompilerStatistics::Data data, bool print_time = true) {
2979 if (data._count > 0) {
2980 st->print("; %s: %4u methods", name, data._count);
2981 if (print_time) {
2982 st->print(" (in %.3fs)", data._time.seconds());
2983 }
2984 }
2985 }
2986
2987 static void print_tier_helper(outputStream* st, const char* prefix, int tier, CompilerStatistics* stats) {
2988 st->print(" %s%d: %5u methods", prefix, tier, stats->_standard._count);
2989 if (stats->_standard._count > 0) {
2990 st->print(" (in %.3fs)", stats->_standard._time.seconds());
2991 }
2992 print_helper(st, "osr", stats->_osr);
2993 print_helper(st, "bailout", stats->_bailout);
2994 print_helper(st, "invalid", stats->_invalidated);
2995 print_helper(st, "not_entrant", stats->_made_not_entrant, false);
2996 st->cr();
2997 }
2998
2999 static void print_queue_info(outputStream* st, CompileQueue* queue) {
3000 if (queue != nullptr) {
3001 MutexLocker ml(queue->lock());
3002
3003 uint total_cnt = 0;
3004 uint active_cnt = 0;
3005 for (JavaThread* jt : *ThreadsSMRSupport::get_java_thread_list()) {
3006 guarantee(jt != nullptr, "");
3007 if (jt->is_Compiler_thread()) {
3008 CompilerThread* ct = (CompilerThread*)jt;
3009
3010 guarantee(ct != nullptr, "");
3011 if (ct->queue() == queue) {
3012 ++total_cnt;
3013 CompileTask* task = ct->task();
3014 if (task != nullptr) {
3015 ++active_cnt;
3016 }
3017 }
3018 }
3019 }
3020
3021 st->print(" %s (%d active / %d total threads): %u tasks",
3022 queue->name(), active_cnt, total_cnt, queue->size());
3023 if (queue->size() > 0) {
3024 uint counts[] = {0, 0, 0, 0, 0}; // T1 ... T5
3025 for (CompileTask* task = queue->first(); task != nullptr; task = task->next()) {
3026 int tier = task->comp_level();
3027 if (task->is_aot_load() && task->preload()) {
3028 assert(tier == CompLevel_full_optimization, "%d", tier);
3029 tier = CompLevel_full_optimization + 1;
3030 }
3031 counts[tier-1]++;
3032 }
3033 st->print(":");
3034 for (int tier = CompLevel_simple; tier <= CompilationPolicy::highest_compile_level() + 1; tier++) {
3035 uint cnt = counts[tier-1];
3036 if (cnt > 0) {
3037 st->print(" T%d: %u tasks;", tier, cnt);
3038 }
3039 }
3040 }
3041 st->cr();
3042
3043 // for (JavaThread* jt : *ThreadsSMRSupport::get_java_thread_list()) {
3044 // guarantee(jt != nullptr, "");
3045 // if (jt->is_Compiler_thread()) {
3046 // CompilerThread* ct = (CompilerThread*)jt;
3047 //
3048 // guarantee(ct != nullptr, "");
3049 // if (ct->queue() == queue) {
3050 // ResourceMark rm;
3051 // CompileTask* task = ct->task();
3052 // st->print(" %s: ", ct->name_raw());
3053 // if (task != nullptr) {
3054 // task->print(st, nullptr, true /*short_form*/, false /*cr*/);
3055 // }
3056 // st->cr();
3057 // }
3058 // }
3059 // }
3060 }
3061 }
3062 void CompileBroker::print_statistics_on(outputStream* st) {
3063 st->print_cr(" Total: %u methods; %u bailouts, %u invalidated, %u non_entrant",
3064 _total_compile_count, _total_bailout_count, _total_invalidated_count, _total_not_entrant_count);
3065 for (int tier = CompLevel_simple; tier <= CompilationPolicy::highest_compile_level(); tier++) {
3066 print_tier_helper(st, "Tier", tier, &_stats_per_level[tier-1]);
3067 }
3068 st->cr();
3069
3070 if (AOTCodeCaching) {
3071 for (int tier = CompLevel_simple; tier <= CompilationPolicy::highest_compile_level() + 1; tier++) {
3072 if (tier != CompLevel_full_profile) {
3073 print_tier_helper(st, "AOT Code T", tier, &_aot_stats_per_level[tier - 1]);
3074 }
3075 }
3076 st->cr();
3077 }
3078
3079 print_queue_info(st, _c1_compile_queue);
3080 print_queue_info(st, _c2_compile_queue);
3081 print_queue_info(st, _ac1_compile_queue);
3082 print_queue_info(st, _ac2_compile_queue);
3083 }
3084
3085 void CompileBroker::print_times(bool per_compiler, bool aggregate) {
3086 if (per_compiler) {
3087 if (aggregate) {
3088 tty->cr();
3089 tty->print_cr("[%dms] Individual compiler times (for compiled methods only)", (int)tty->time_stamp().milliseconds());
3090 tty->print_cr("------------------------------------------------");
3091 tty->cr();
3092 }
3093 for (unsigned int i = 0; i < sizeof(_compilers) / sizeof(AbstractCompiler*); i++) {
3094 AbstractCompiler* comp = _compilers[i];
3095 if (comp != nullptr) {
3096 print_times(comp->name(), comp->stats());
3097 }
3098 }
3099 if (_aot_stats._standard._count > 0) {
3100 print_times("SC", &_aot_stats);
3101 }
3102 if (aggregate) {
3103 tty->cr();
3104 tty->print_cr("Individual compilation Tier times (for compiled methods only)");
3105 tty->print_cr("------------------------------------------------");
3106 tty->cr();
3107 }
3108 char tier_name[256];
3109 for (int tier = CompLevel_simple; tier <= CompilationPolicy::highest_compile_level(); tier++) {
3110 CompilerStatistics* stats = &_stats_per_level[tier-1];
3111 os::snprintf_checked(tier_name, sizeof(tier_name), "Tier%d", tier);
3112 print_times(tier_name, stats);
3113 }
3114 for (int tier = CompLevel_simple; tier <= CompilationPolicy::highest_compile_level() + 1; tier++) {
3115 CompilerStatistics* stats = &_aot_stats_per_level[tier-1];
3116 if (stats->_standard._bytes > 0) {
3117 os::snprintf_checked(tier_name, sizeof(tier_name), "AOT Code T%d", tier);
3118 print_times(tier_name, stats);
3119 }
3120 }
3121 }
3122
3123 if (!aggregate) {
3124 return;
3125 }
3126
3127 elapsedTimer standard_compilation = CompileBroker::_t_standard_compilation;
3128 elapsedTimer osr_compilation = CompileBroker::_t_osr_compilation;
3129 elapsedTimer total_compilation = CompileBroker::_t_total_compilation;
3130
3131 uint standard_bytes_compiled = CompileBroker::_sum_standard_bytes_compiled;
3132 uint osr_bytes_compiled = CompileBroker::_sum_osr_bytes_compiled;
3133
3134 uint standard_compile_count = CompileBroker::_total_standard_compile_count;
3135 uint osr_compile_count = CompileBroker::_total_osr_compile_count;
3136 uint total_compile_count = CompileBroker::_total_compile_count;
3137 uint total_bailout_count = CompileBroker::_total_bailout_count;
3138 uint total_invalidated_count = CompileBroker::_total_invalidated_count;
3139
3140 uint nmethods_code_size = CompileBroker::_sum_nmethod_code_size;
3142
3143 tty->cr();
3144 tty->print_cr("Accumulated compiler times");
3145 tty->print_cr("----------------------------------------------------------");
3146 //0000000000111111111122222222223333333333444444444455555555556666666666
3147 //0123456789012345678901234567890123456789012345678901234567890123456789
3148 tty->print_cr(" Total compilation time : %7.3f s", total_compilation.seconds());
3149 tty->print_cr(" Standard compilation : %7.3f s, Average : %2.3f s",
3150 standard_compilation.seconds(),
3151 standard_compile_count == 0 ? 0.0 : standard_compilation.seconds() / standard_compile_count);
3152 tty->print_cr(" Bailed out compilation : %7.3f s, Average : %2.3f s",
3153 CompileBroker::_t_bailedout_compilation.seconds(),
3154 total_bailout_count == 0 ? 0.0 : CompileBroker::_t_bailedout_compilation.seconds() / total_bailout_count);
3155 tty->print_cr(" On stack replacement : %7.3f s, Average : %2.3f s",
3156 osr_compilation.seconds(),
3157 osr_compile_count == 0 ? 0.0 : osr_compilation.seconds() / osr_compile_count);
3158 tty->print_cr(" Invalidated : %7.3f s, Average : %2.3f s",
3159 CompileBroker::_t_invalidated_compilation.seconds(),
3160 total_invalidated_count == 0 ? 0.0 : CompileBroker::_t_invalidated_compilation.seconds() / total_invalidated_count);
3161
3162 if (AOTCodeCaching) { // Check flags because AOT code cache could be closed already
3163 tty->cr();
3164 AOTCodeCache::print_timers_on(tty);
3165 }
3166 AbstractCompiler *comp = compiler(CompLevel_simple);
3167 if (comp != nullptr) {
3168 tty->cr();
3169 comp->print_timers();
3170 }
3171 comp = compiler(CompLevel_full_optimization);
3172 if (comp != nullptr) {
3173 tty->cr();
3174 comp->print_timers();
3175 }
3176 #if INCLUDE_JVMCI
3177 if (EnableJVMCI) {
3178 JVMCICompiler *jvmci_comp = JVMCICompiler::instance(false, JavaThread::current_or_null());
3179 if (jvmci_comp != nullptr && jvmci_comp != comp) {
3180 tty->cr();
3181 jvmci_comp->print_timers();
3182 }
3183 }
3184 #endif
3185
|