Bug Summary

File:jdk/src/hotspot/share/compiler/compileBroker.cpp
Warning:line 1418, column 13
Value stored to 'adr' during its initialization is never read

Annotated Source Code

Press '?' to see keyboard shortcuts

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