compileBroker.cpp revision 5946:b5c8a61d7fa0
1169695Skan/*
2169695Skan * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
3169695Skan * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4169695Skan *
5169695Skan * This code is free software; you can redistribute it and/or modify it
6169695Skan * under the terms of the GNU General Public License version 2 only, as
7169695Skan * published by the Free Software Foundation.
8169695Skan *
9169695Skan * This code is distributed in the hope that it will be useful, but WITHOUT
10169695Skan * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11169695Skan * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
12169695Skan * version 2 for more details (a copy is included in the LICENSE file that
13169695Skan * accompanied this code).
14169695Skan *
15169695Skan * You should have received a copy of the GNU General Public License version
16169695Skan * 2 along with this work; if not, write to the Free Software Foundation,
17169695Skan * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18169695Skan *
19169695Skan * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20169695Skan * or visit www.oracle.com if you need additional information or have any
21169695Skan * questions.
22169695Skan *
23169695Skan */
24169695Skan
25169695Skan#include "precompiled.hpp"
26169695Skan#include "classfile/systemDictionary.hpp"
27169695Skan#include "classfile/vmSymbols.hpp"
28169695Skan#include "code/codeCache.hpp"
29169695Skan#include "compiler/compileBroker.hpp"
30169695Skan#include "compiler/compileLog.hpp"
31169695Skan#include "compiler/compilerOracle.hpp"
32169695Skan#include "interpreter/linkResolver.hpp"
33169695Skan#include "memory/allocation.inline.hpp"
34169695Skan#include "oops/methodData.hpp"
35169695Skan#include "oops/method.hpp"
36169695Skan#include "oops/oop.inline.hpp"
37169695Skan#include "prims/nativeLookup.hpp"
38169695Skan#include "runtime/arguments.hpp"
39169695Skan#include "runtime/compilationPolicy.hpp"
40169695Skan#include "runtime/init.hpp"
41169695Skan#include "runtime/interfaceSupport.hpp"
42169695Skan#include "runtime/javaCalls.hpp"
43169695Skan#include "runtime/os.hpp"
44169695Skan#include "runtime/sharedRuntime.hpp"
45169695Skan#include "runtime/sweeper.hpp"
46169695Skan#include "trace/tracing.hpp"
47169695Skan#include "utilities/dtrace.hpp"
48169695Skan#include "utilities/events.hpp"
49169695Skan#ifdef COMPILER1
50169695Skan#include "c1/c1_Compiler.hpp"
51169695Skan#endif
52169695Skan#ifdef COMPILER2
53169695Skan#include "opto/c2compiler.hpp"
54169695Skan#endif
55169695Skan#ifdef SHARK
56169695Skan#include "shark/sharkCompiler.hpp"
57169695Skan#endif
58169695Skan
59169695Skan#ifdef DTRACE_ENABLED
60169695Skan
61169695Skan// Only bother with this argument setup if dtrace is available
62169695Skan
63169695Skan#ifndef USDT2
64169695SkanHS_DTRACE_PROBE_DECL8(hotspot, method__compile__begin,
65169695Skan  char*, intptr_t, char*, intptr_t, char*, intptr_t, char*, intptr_t);
66169695SkanHS_DTRACE_PROBE_DECL9(hotspot, method__compile__end,
67169695Skan  char*, intptr_t, char*, intptr_t, char*, intptr_t, char*, intptr_t, bool);
68169695Skan
69169695Skan#define DTRACE_METHOD_COMPILE_BEGIN_PROBE(method, comp_name)             \
70169695Skan  {                                                                      \
71169695Skan    Symbol* klass_name = (method)->klass_name();                         \
72169695Skan    Symbol* name = (method)->name();                                     \
73169695Skan    Symbol* signature = (method)->signature();                           \
74169695Skan    HS_DTRACE_PROBE8(hotspot, method__compile__begin,                    \
75169695Skan      comp_name, strlen(comp_name),                                      \
76169695Skan      klass_name->bytes(), klass_name->utf8_length(),                    \
77169695Skan      name->bytes(), name->utf8_length(),                                \
78169695Skan      signature->bytes(), signature->utf8_length());                     \
79169695Skan  }
80169695Skan
81169695Skan#define DTRACE_METHOD_COMPILE_END_PROBE(method, comp_name, success)      \
82169695Skan  {                                                                      \
83169695Skan    Symbol* klass_name = (method)->klass_name();                         \
84169695Skan    Symbol* name = (method)->name();                                     \
85169695Skan    Symbol* signature = (method)->signature();                           \
86169695Skan    HS_DTRACE_PROBE9(hotspot, method__compile__end,                      \
87169695Skan      comp_name, strlen(comp_name),                                      \
88169695Skan      klass_name->bytes(), klass_name->utf8_length(),                    \
89169695Skan      name->bytes(), name->utf8_length(),                                \
90169695Skan      signature->bytes(), signature->utf8_length(), (success));          \
91169695Skan  }
92169695Skan
93169695Skan#else /* USDT2 */
94169695Skan
95169695Skan#define DTRACE_METHOD_COMPILE_BEGIN_PROBE(method, comp_name)             \
96169695Skan  {                                                                      \
97169695Skan    Symbol* klass_name = (method)->klass_name();                         \
98169695Skan    Symbol* name = (method)->name();                                     \
99169695Skan    Symbol* signature = (method)->signature();                           \
100169695Skan    HOTSPOT_METHOD_COMPILE_BEGIN(                                        \
101169695Skan      comp_name, strlen(comp_name),                                      \
102169695Skan      (char *) klass_name->bytes(), klass_name->utf8_length(),           \
103169695Skan      (char *) name->bytes(), name->utf8_length(),                       \
104169695Skan      (char *) signature->bytes(), signature->utf8_length());            \
105169695Skan  }
106169695Skan
107169695Skan#define DTRACE_METHOD_COMPILE_END_PROBE(method, comp_name, success)      \
108169695Skan  {                                                                      \
109169695Skan    Symbol* klass_name = (method)->klass_name();                         \
110169695Skan    Symbol* name = (method)->name();                                     \
111169695Skan    Symbol* signature = (method)->signature();                           \
112169695Skan    HOTSPOT_METHOD_COMPILE_END(                                          \
113169695Skan      comp_name, strlen(comp_name),                                      \
114169695Skan      (char *) klass_name->bytes(), klass_name->utf8_length(),           \
115169695Skan      (char *) name->bytes(), name->utf8_length(),                       \
116169695Skan      (char *) signature->bytes(), signature->utf8_length(), (success)); \
117169695Skan  }
118169695Skan#endif /* USDT2 */
119169695Skan
120169695Skan#else //  ndef DTRACE_ENABLED
121169695Skan
122169695Skan#define DTRACE_METHOD_COMPILE_BEGIN_PROBE(method, comp_name)
123169695Skan#define DTRACE_METHOD_COMPILE_END_PROBE(method, comp_name, success)
124169695Skan
125169695Skan#endif // ndef DTRACE_ENABLED
126169695Skan
127169695Skanbool CompileBroker::_initialized = false;
128169695Skanvolatile bool CompileBroker::_should_block = false;
129169695Skanvolatile jint CompileBroker::_should_compile_new_jobs = run_compilation;
130169695Skan
131169695Skan// The installed compiler(s)
132169695SkanAbstractCompiler* CompileBroker::_compilers[2];
133169695Skan
134169695Skan// These counters are used for assigning id's to each compilation
135169695Skanuint CompileBroker::_compilation_id        = 0;
136169695Skanuint CompileBroker::_osr_compilation_id    = 0;
137169695Skan
138169695Skan// Debugging information
139169695Skanint  CompileBroker::_last_compile_type     = no_compile;
140169695Skanint  CompileBroker::_last_compile_level    = CompLevel_none;
141169695Skanchar CompileBroker::_last_method_compiled[CompileBroker::name_buffer_length];
142169695Skan
143169695Skan// Performance counters
144169695SkanPerfCounter* CompileBroker::_perf_total_compilation = NULL;
145169695SkanPerfCounter* CompileBroker::_perf_osr_compilation = NULL;
146169695SkanPerfCounter* CompileBroker::_perf_standard_compilation = NULL;
147169695Skan
148169695SkanPerfCounter* CompileBroker::_perf_total_bailout_count = NULL;
149169695SkanPerfCounter* CompileBroker::_perf_total_invalidated_count = NULL;
150169695SkanPerfCounter* CompileBroker::_perf_total_compile_count = NULL;
151169695SkanPerfCounter* CompileBroker::_perf_total_osr_compile_count = NULL;
152169695SkanPerfCounter* CompileBroker::_perf_total_standard_compile_count = NULL;
153169695Skan
154169695SkanPerfCounter* CompileBroker::_perf_sum_osr_bytes_compiled = NULL;
155169695SkanPerfCounter* CompileBroker::_perf_sum_standard_bytes_compiled = NULL;
156169695SkanPerfCounter* CompileBroker::_perf_sum_nmethod_size = NULL;
157169695SkanPerfCounter* CompileBroker::_perf_sum_nmethod_code_size = NULL;
158169695Skan
159169695SkanPerfStringVariable* CompileBroker::_perf_last_method = NULL;
160169695SkanPerfStringVariable* CompileBroker::_perf_last_failed_method = NULL;
161169695SkanPerfStringVariable* CompileBroker::_perf_last_invalidated_method = NULL;
162169695SkanPerfVariable*       CompileBroker::_perf_last_compile_type = NULL;
163169695SkanPerfVariable*       CompileBroker::_perf_last_compile_size = NULL;
164169695SkanPerfVariable*       CompileBroker::_perf_last_failed_type = NULL;
165169695SkanPerfVariable*       CompileBroker::_perf_last_invalidated_type = NULL;
166169695Skan
167169695Skan// Timers and counters for generating statistics
168169695SkanelapsedTimer CompileBroker::_t_total_compilation;
169169695SkanelapsedTimer CompileBroker::_t_osr_compilation;
170169695SkanelapsedTimer CompileBroker::_t_standard_compilation;
171169695Skan
172169695Skanint CompileBroker::_total_bailout_count          = 0;
173169695Skanint CompileBroker::_total_invalidated_count      = 0;
174169695Skanint CompileBroker::_total_compile_count          = 0;
175169695Skanint CompileBroker::_total_osr_compile_count      = 0;
176169695Skanint CompileBroker::_total_standard_compile_count = 0;
177169695Skan
178169695Skanint CompileBroker::_sum_osr_bytes_compiled       = 0;
179169695Skanint CompileBroker::_sum_standard_bytes_compiled  = 0;
180169695Skanint CompileBroker::_sum_nmethod_size             = 0;
181169695Skanint CompileBroker::_sum_nmethod_code_size        = 0;
182169695Skan
183169695Skanlong CompileBroker::_peak_compilation_time       = 0;
184169695Skan
185169695SkanCompileQueue* CompileBroker::_c2_method_queue    = NULL;
186169695SkanCompileQueue* CompileBroker::_c1_method_queue    = NULL;
187169695SkanCompileTask*  CompileBroker::_task_free_list     = NULL;
188169695Skan
189169695SkanGrowableArray<CompilerThread*>* CompileBroker::_method_threads = NULL;
190169695Skan
191169695Skan
192169695Skanclass CompilationLog : public StringEventLog {
193169695Skan public:
194169695Skan  CompilationLog() : StringEventLog("Compilation events") {
195169695Skan  }
196169695Skan
197169695Skan  void log_compile(JavaThread* thread, CompileTask* task) {
198169695Skan    StringLogMessage lm;
199169695Skan    stringStream sstr = lm.stream();
200169695Skan    // msg.time_stamp().update_to(tty->time_stamp().ticks());
201169695Skan    task->print_compilation(&sstr, NULL, true);
202169695Skan    log(thread, "%s", (const char*)lm);
203169695Skan  }
204169695Skan
205169695Skan  void log_nmethod(JavaThread* thread, nmethod* nm) {
206169695Skan    log(thread, "nmethod %d%s " INTPTR_FORMAT " code ["INTPTR_FORMAT ", " INTPTR_FORMAT "]",
207169695Skan        nm->compile_id(), nm->is_osr_method() ? "%" : "",
208169695Skan        nm, nm->code_begin(), nm->code_end());
209169695Skan  }
210169695Skan
211169695Skan  void log_failure(JavaThread* thread, CompileTask* task, const char* reason, const char* retry_message) {
212169695Skan    StringLogMessage lm;
213169695Skan    lm.print("%4d   COMPILE SKIPPED: %s", task->compile_id(), reason);
214169695Skan    if (retry_message != NULL) {
215169695Skan      lm.append(" (%s)", retry_message);
216169695Skan    }
217169695Skan    lm.print("\n");
218169695Skan    log(thread, "%s", (const char*)lm);
219169695Skan  }
220169695Skan};
221169695Skan
222169695Skanstatic CompilationLog* _compilation_log = NULL;
223169695Skan
224169695Skanvoid compileBroker_init() {
225169695Skan  if (LogEvents) {
226169695Skan    _compilation_log = new CompilationLog();
227169695Skan  }
228169695Skan}
229169695Skan
230169695SkanCompileTaskWrapper::CompileTaskWrapper(CompileTask* task) {
231169695Skan  CompilerThread* thread = CompilerThread::current();
232169695Skan  thread->set_task(task);
233169695Skan  CompileLog*     log  = thread->log();
234169695Skan  if (log != NULL)  task->log_task_start(log);
235169695Skan}
236169695Skan
237169695SkanCompileTaskWrapper::~CompileTaskWrapper() {
238169695Skan  CompilerThread* thread = CompilerThread::current();
239169695Skan  CompileTask* task = thread->task();
240169695Skan  CompileLog*  log  = thread->log();
241169695Skan  if (log != NULL)  task->log_task_done(log);
242169695Skan  thread->set_task(NULL);
243169695Skan  task->set_code_handle(NULL);
244282152Spfg  thread->set_env(NULL);
245282152Spfg  if (task->is_blocking()) {
246282152Spfg    MutexLocker notifier(task->lock(), thread);
247282152Spfg    task->mark_complete();
248282152Spfg    // Notify the waiting thread that the compilation has completed.
249282152Spfg    task->lock()->notify_all();
250282152Spfg  } else {
251282152Spfg    task->mark_complete();
252282152Spfg
253282152Spfg    // By convention, the compiling thread is responsible for
254282152Spfg    // recycling a non-blocking CompileTask.
255282152Spfg    CompileBroker::free_task(task);
256282152Spfg  }
257282152Spfg}
258282152Spfg
259282152Spfg
260282152Spfg// ------------------------------------------------------------------
261282152Spfg// CompileTask::initialize
262282152Spfgvoid CompileTask::initialize(int compile_id,
263282152Spfg                             methodHandle method,
264282152Spfg                             int osr_bci,
265282152Spfg                             int comp_level,
266282152Spfg                             methodHandle hot_method,
267282152Spfg                             int hot_count,
268282152Spfg                             const char* comment,
269282152Spfg                             bool is_blocking) {
270282152Spfg  assert(!_lock->is_locked(), "bad locking");
271282152Spfg
272282152Spfg  _compile_id = compile_id;
273282152Spfg  _method = method();
274282152Spfg  _method_holder = JNIHandles::make_global(method->method_holder()->klass_holder());
275282152Spfg  _osr_bci = osr_bci;
276282152Spfg  _is_blocking = is_blocking;
277282152Spfg  _comp_level = comp_level;
278282152Spfg  _num_inlined_bytecodes = 0;
279282152Spfg
280282152Spfg  _is_complete = false;
281282152Spfg  _is_success = false;
282282152Spfg  _code_handle = NULL;
283282152Spfg
284282152Spfg  _hot_method = NULL;
285282152Spfg  _hot_method_holder = NULL;
286282152Spfg  _hot_count = hot_count;
287282152Spfg  _time_queued = 0;  // tidy
288282152Spfg  _comment = comment;
289282152Spfg
290282152Spfg  if (LogCompilation) {
291282152Spfg    _time_queued = os::elapsed_counter();
292282152Spfg    if (hot_method.not_null()) {
293282152Spfg      if (hot_method == method) {
294282152Spfg        _hot_method = _method;
295282152Spfg      } else {
296282152Spfg        _hot_method = hot_method();
297282152Spfg        // only add loader or mirror if different from _method_holder
298282152Spfg        _hot_method_holder = JNIHandles::make_global(hot_method->method_holder()->klass_holder());
299282152Spfg      }
300282152Spfg    }
301282152Spfg  }
302282152Spfg
303282152Spfg  _next = NULL;
304282152Spfg}
305282152Spfg
306282152Spfg// ------------------------------------------------------------------
307282152Spfg// CompileTask::code/set_code
308282152Spfgnmethod* CompileTask::code() const {
309282152Spfg  if (_code_handle == NULL)  return NULL;
310282152Spfg  return _code_handle->code();
311282152Spfg}
312282152Spfgvoid CompileTask::set_code(nmethod* nm) {
313282152Spfg  if (_code_handle == NULL && nm == NULL)  return;
314282152Spfg  guarantee(_code_handle != NULL, "");
315282152Spfg  _code_handle->set_code(nm);
316282152Spfg  if (nm == NULL)  _code_handle = NULL;  // drop the handle also
317282152Spfg}
318282152Spfg
319282152Spfg// ------------------------------------------------------------------
320282152Spfg// CompileTask::free
321282152Spfgvoid CompileTask::free() {
322282152Spfg  set_code(NULL);
323282152Spfg  assert(!_lock->is_locked(), "Should not be locked when freed");
324282152Spfg  JNIHandles::destroy_global(_method_holder);
325282152Spfg  JNIHandles::destroy_global(_hot_method_holder);
326282152Spfg}
327282152Spfg
328282152Spfg
329282152Spfgvoid CompileTask::mark_on_stack() {
330282152Spfg  // Mark these methods as something redefine classes cannot remove.
331282152Spfg  _method->set_on_stack(true);
332282152Spfg  if (_hot_method != NULL) {
333282152Spfg    _hot_method->set_on_stack(true);
334282152Spfg  }
335282152Spfg}
336282152Spfg
337282152Spfg// ------------------------------------------------------------------
338282152Spfg// CompileTask::print
339282152Spfgvoid CompileTask::print() {
340282152Spfg  tty->print("<CompileTask compile_id=%d ", _compile_id);
341282152Spfg  tty->print("method=");
342282152Spfg  _method->print_name(tty);
343282152Spfg  tty->print_cr(" osr_bci=%d is_blocking=%s is_complete=%s is_success=%s>",
344282152Spfg             _osr_bci, bool_to_str(_is_blocking),
345282152Spfg             bool_to_str(_is_complete), bool_to_str(_is_success));
346282152Spfg}
347282152Spfg
348282152Spfg
349282152Spfg// ------------------------------------------------------------------
350282152Spfg// CompileTask::print_line_on_error
351282152Spfg//
352282152Spfg// This function is called by fatal error handler when the thread
353282152Spfg// causing troubles is a compiler thread.
354282152Spfg//
355282152Spfg// Do not grab any lock, do not allocate memory.
356282152Spfg//
357282152Spfg// Otherwise it's the same as CompileTask::print_line()
358282152Spfg//
359282152Spfgvoid CompileTask::print_line_on_error(outputStream* st, char* buf, int buflen) {
360282152Spfg  // print compiler name
361282152Spfg  st->print("%s:", CompileBroker::compiler_name(comp_level()));
362282152Spfg  print_compilation(st);
363282152Spfg}
364282152Spfg
365282152Spfg// ------------------------------------------------------------------
366282152Spfg// CompileTask::print_line
367282152Spfgvoid CompileTask::print_line() {
368282152Spfg  ttyLocker ttyl;  // keep the following output all in one block
369282152Spfg  // print compiler name if requested
370282152Spfg  if (CIPrintCompilerName) tty->print("%s:", CompileBroker::compiler_name(comp_level()));
371282152Spfg  print_compilation();
372282152Spfg}
373282152Spfg
374282152Spfg
375282152Spfg// ------------------------------------------------------------------
376282152Spfg// CompileTask::print_compilation_impl
377282152Spfgvoid CompileTask::print_compilation_impl(outputStream* st, Method* method, int compile_id, int comp_level,
378282152Spfg                                         bool is_osr_method, int osr_bci, bool is_blocking,
379282152Spfg                                         const char* msg, bool short_form) {
380282152Spfg  if (!short_form) {
381282152Spfg    st->print("%7d ", (int) st->time_stamp().milliseconds());  // print timestamp
382282152Spfg  }
383282152Spfg  st->print("%4d ", compile_id);    // print compilation number
384282152Spfg
385282152Spfg  // For unloaded methods the transition to zombie occurs after the
386282152Spfg  // method is cleared so it's impossible to report accurate
387282152Spfg  // information for that case.
388282152Spfg  bool is_synchronized = false;
389282152Spfg  bool has_exception_handler = false;
390282152Spfg  bool is_native = false;
391282152Spfg  if (method != NULL) {
392282152Spfg    is_synchronized       = method->is_synchronized();
393169695Skan    has_exception_handler = method->has_exception_handler();
394169695Skan    is_native             = method->is_native();
395169695Skan  }
396169695Skan  // method attributes
397169695Skan  const char compile_type   = is_osr_method                   ? '%' : ' ';
398169695Skan  const char sync_char      = is_synchronized                 ? 's' : ' ';
399169695Skan  const char exception_char = has_exception_handler           ? '!' : ' ';
400169695Skan  const char blocking_char  = is_blocking                     ? 'b' : ' ';
401169695Skan  const char native_char    = is_native                       ? 'n' : ' ';
402169695Skan
403169695Skan  // print method attributes
404169695Skan  st->print("%c%c%c%c%c ", compile_type, sync_char, exception_char, blocking_char, native_char);
405169695Skan
406169695Skan  if (TieredCompilation) {
407169695Skan    if (comp_level != -1)  st->print("%d ", comp_level);
408169695Skan    else                   st->print("- ");
409169695Skan  }
410169695Skan  st->print("     ");  // more indent
411169695Skan
412169695Skan  if (method == NULL) {
413169695Skan    st->print("(method)");
414169695Skan  } else {
415169695Skan    method->print_short_name(st);
416169695Skan    if (is_osr_method) {
417169695Skan      st->print(" @ %d", osr_bci);
418169695Skan    }
419169695Skan    if (method->is_native())
420169695Skan      st->print(" (native)");
421169695Skan    else
422169695Skan      st->print(" (%d bytes)", method->code_size());
423169695Skan  }
424169695Skan
425169695Skan  if (msg != NULL) {
426169695Skan    st->print("   %s", msg);
427169695Skan  }
428169695Skan  if (!short_form) {
429169695Skan    st->cr();
430169695Skan  }
431169695Skan}
432169695Skan
433169695Skan// ------------------------------------------------------------------
434169695Skan// CompileTask::print_inlining
435169695Skanvoid CompileTask::print_inlining(outputStream* st, ciMethod* method, int inline_level, int bci, const char* msg) {
436169695Skan  //         1234567
437169695Skan  st->print("        ");     // print timestamp
438169695Skan  //         1234
439169695Skan  st->print("     ");        // print compilation number
440169695Skan
441169695Skan  // method attributes
442169695Skan  if (method->is_loaded()) {
443169695Skan    const char sync_char      = method->is_synchronized()        ? 's' : ' ';
444169695Skan    const char exception_char = method->has_exception_handlers() ? '!' : ' ';
445169695Skan    const char monitors_char  = method->has_monitor_bytecodes()  ? 'm' : ' ';
446169695Skan
447169695Skan    // print method attributes
448169695Skan    st->print(" %c%c%c  ", sync_char, exception_char, monitors_char);
449169695Skan  } else {
450169695Skan    //         %s!bn
451169695Skan    st->print("      ");     // print method attributes
452169695Skan  }
453169695Skan
454169695Skan  if (TieredCompilation) {
455169695Skan    st->print("  ");
456169695Skan  }
457169695Skan  st->print("     ");        // more indent
458169695Skan  st->print("    ");         // initial inlining indent
459169695Skan
460282152Spfg  for (int i = 0; i < inline_level; i++)  st->print("  ");
461169695Skan
462169695Skan  st->print("@ %d  ", bci);  // print bci
463169695Skan  method->print_short_name(st);
464169695Skan  if (method->is_loaded())
465169695Skan    st->print(" (%d bytes)", method->code_size());
466169695Skan  else
467169695Skan    st->print(" (not loaded)");
468169695Skan
469169695Skan  if (msg != NULL) {
470169695Skan    st->print("   %s", msg);
471169695Skan  }
472169695Skan  st->cr();
473169695Skan}
474169695Skan
475169695Skan// ------------------------------------------------------------------
476169695Skan// CompileTask::print_inline_indent
477169695Skanvoid CompileTask::print_inline_indent(int inline_level, outputStream* st) {
478169695Skan  //         1234567
479169695Skan  st->print("        ");     // print timestamp
480169695Skan  //         1234
481169695Skan  st->print("     ");        // print compilation number
482169695Skan  //         %s!bn
483169695Skan  st->print("      ");       // print method attributes
484169695Skan  if (TieredCompilation) {
485169695Skan    st->print("  ");
486169695Skan  }
487169695Skan  st->print("     ");        // more indent
488169695Skan  st->print("    ");         // initial inlining indent
489169695Skan  for (int i = 0; i < inline_level; i++)  st->print("  ");
490169695Skan}
491169695Skan
492169695Skan// ------------------------------------------------------------------
493169695Skan// CompileTask::print_compilation
494169695Skanvoid CompileTask::print_compilation(outputStream* st, const char* msg, bool short_form) {
495169695Skan  bool is_osr_method = osr_bci() != InvocationEntryBci;
496169695Skan  print_compilation_impl(st, method(), compile_id(), comp_level(), is_osr_method, osr_bci(), is_blocking(), msg, short_form);
497169695Skan}
498169695Skan
499169695Skan// ------------------------------------------------------------------
500169695Skan// CompileTask::log_task
501169695Skanvoid CompileTask::log_task(xmlStream* log) {
502169695Skan  Thread* thread = Thread::current();
503169695Skan  methodHandle method(thread, this->method());
504169695Skan  ResourceMark rm(thread);
505169695Skan
506169695Skan  // <task id='9' method='M' osr_bci='X' level='1' blocking='1' stamp='1.234'>
507169695Skan  log->print(" compile_id='%d'", _compile_id);
508169695Skan  if (_osr_bci != CompileBroker::standard_entry_bci) {
509169695Skan    log->print(" compile_kind='osr'");  // same as nmethod::compile_kind
510169695Skan  } // else compile_kind='c2c'
511169695Skan  if (!method.is_null())  log->method(method);
512169695Skan  if (_osr_bci != CompileBroker::standard_entry_bci) {
513169695Skan    log->print(" osr_bci='%d'", _osr_bci);
514169695Skan  }
515169695Skan  if (_comp_level != CompLevel_highest_tier) {
516169695Skan    log->print(" level='%d'", _comp_level);
517169695Skan  }
518169695Skan  if (_is_blocking) {
519169695Skan    log->print(" blocking='1'");
520169695Skan  }
521169695Skan  log->stamp();
522169695Skan}
523169695Skan
524169695Skan
525169695Skan// ------------------------------------------------------------------
526169695Skan// CompileTask::log_task_queued
527169695Skanvoid CompileTask::log_task_queued() {
528169695Skan  Thread* thread = Thread::current();
529169695Skan  ttyLocker ttyl;
530169695Skan  ResourceMark rm(thread);
531169695Skan
532169695Skan  xtty->begin_elem("task_queued");
533169695Skan  log_task(xtty);
534169695Skan  if (_comment != NULL) {
535169695Skan    xtty->print(" comment='%s'", _comment);
536169695Skan  }
537169695Skan  if (_hot_method != NULL) {
538169695Skan    methodHandle hot(thread, _hot_method);
539169695Skan    methodHandle method(thread, _method);
540169695Skan    if (hot() != method()) {
541169695Skan      xtty->method(hot);
542169695Skan    }
543169695Skan  }
544169695Skan  if (_hot_count != 0) {
545169695Skan    xtty->print(" hot_count='%d'", _hot_count);
546169695Skan  }
547169695Skan  xtty->end_elem();
548169695Skan}
549169695Skan
550169695Skan
551169695Skan// ------------------------------------------------------------------
552169695Skan// CompileTask::log_task_start
553169695Skanvoid CompileTask::log_task_start(CompileLog* log)   {
554169695Skan  log->begin_head("task");
555169695Skan  log_task(log);
556169695Skan  log->end_head();
557169695Skan}
558169695Skan
559169695Skan
560169695Skan// ------------------------------------------------------------------
561169695Skan// CompileTask::log_task_done
562169695Skanvoid CompileTask::log_task_done(CompileLog* log) {
563169695Skan  Thread* thread = Thread::current();
564169695Skan  methodHandle method(thread, this->method());
565169695Skan  ResourceMark rm(thread);
566169695Skan
567169695Skan  // <task_done ... stamp='1.234'>  </task>
568169695Skan  nmethod* nm = code();
569169695Skan  log->begin_elem("task_done success='%d' nmsize='%d' count='%d'",
570169695Skan                  _is_success, nm == NULL ? 0 : nm->content_size(),
571169695Skan                  method->invocation_count());
572169695Skan  int bec = method->backedge_count();
573169695Skan  if (bec != 0)  log->print(" backedge_count='%d'", bec);
574169695Skan  // Note:  "_is_complete" is about to be set, but is not.
575169695Skan  if (_num_inlined_bytecodes != 0) {
576169695Skan    log->print(" inlined_bytes='%d'", _num_inlined_bytecodes);
577169695Skan  }
578169695Skan  log->stamp();
579169695Skan  log->end_elem();
580169695Skan  log->tail("task");
581169695Skan  log->clear_identities();   // next task will have different CI
582169695Skan  if (log->unflushed_count() > 2000) {
583169695Skan    log->flush();
584169695Skan  }
585169695Skan  log->mark_file_end();
586169695Skan}
587169695Skan
588169695Skan
589169695Skan
590169695Skan// ------------------------------------------------------------------
591169695Skan// CompileQueue::add
592169695Skan//
593169695Skan// Add a CompileTask to a CompileQueue
594169695Skanvoid CompileQueue::add(CompileTask* task) {
595169695Skan  assert(lock()->owned_by_self(), "must own lock");
596169695Skan
597169695Skan  task->set_next(NULL);
598169695Skan  task->set_prev(NULL);
599169695Skan
600169695Skan  if (_last == NULL) {
601169695Skan    // The compile queue is empty.
602169695Skan    assert(_first == NULL, "queue is empty");
603169695Skan    _first = task;
604169695Skan    _last = task;
605169695Skan  } else {
606169695Skan    // Append the task to the queue.
607169695Skan    assert(_last->next() == NULL, "not last");
608169695Skan    _last->set_next(task);
609169695Skan    task->set_prev(_last);
610169695Skan    _last = task;
611169695Skan  }
612169695Skan  ++_size;
613169695Skan
614169695Skan  // Mark the method as being in the compile queue.
615169695Skan  task->method()->set_queued_for_compilation();
616169695Skan
617169695Skan  if (CIPrintCompileQueue) {
618169695Skan    print();
619169695Skan  }
620169695Skan
621169695Skan  if (LogCompilation && xtty != NULL) {
622169695Skan    task->log_task_queued();
623169695Skan  }
624169695Skan
625169695Skan  // Notify CompilerThreads that a task is available.
626169695Skan  lock()->notify_all();
627169695Skan}
628169695Skan
629169695Skan// ------------------------------------------------------------------
630169695Skan// CompileQueue::get
631169695Skan//
632169695Skan// Get the next CompileTask from a CompileQueue
633169695SkanCompileTask* CompileQueue::get() {
634169695Skan  NMethodSweeper::possibly_sweep();
635169695Skan
636169695Skan  MutexLocker locker(lock());
637169695Skan  // Wait for an available CompileTask.
638169695Skan  while (_first == NULL) {
639169695Skan    // There is no work to be done right now.  Wait.
640169695Skan    if (UseCodeCacheFlushing && (!CompileBroker::should_compile_new_jobs() || CodeCache::needs_flushing())) {
641169695Skan      // During the emergency sweeping periods, wake up and sweep occasionally
642169695Skan      bool timedout = lock()->wait(!Mutex::_no_safepoint_check_flag, NmethodSweepCheckInterval*1000);
643169695Skan      if (timedout) {
644169695Skan        MutexUnlocker ul(lock());
645169695Skan        // When otherwise not busy, run nmethod sweeping
646169695Skan        NMethodSweeper::possibly_sweep();
647169695Skan      }
648169695Skan    } else {
649169695Skan      // During normal operation no need to wake up on timer
650169695Skan      lock()->wait();
651169695Skan    }
652169695Skan  }
653169695Skan  CompileTask* task = CompilationPolicy::policy()->select_task(this);
654169695Skan  remove(task);
655169695Skan  return task;
656169695Skan}
657169695Skan
658169695Skanvoid CompileQueue::remove(CompileTask* task)
659169695Skan{
660169695Skan   assert(lock()->owned_by_self(), "must own lock");
661169695Skan  if (task->prev() != NULL) {
662169695Skan    task->prev()->set_next(task->next());
663169695Skan  } else {
664169695Skan    // max is the first element
665169695Skan    assert(task == _first, "Sanity");
666169695Skan    _first = task->next();
667169695Skan  }
668169695Skan
669169695Skan  if (task->next() != NULL) {
670169695Skan    task->next()->set_prev(task->prev());
671169695Skan  } else {
672169695Skan    // max is the last element
673169695Skan    assert(task == _last, "Sanity");
674169695Skan    _last = task->prev();
675169695Skan  }
676169695Skan  --_size;
677169695Skan}
678169695Skan
679169695Skan// methods in the compile queue need to be marked as used on the stack
680169695Skan// so that they don't get reclaimed by Redefine Classes
681169695Skanvoid CompileQueue::mark_on_stack() {
682169695Skan  CompileTask* task = _first;
683169695Skan  while (task != NULL) {
684169695Skan    task->mark_on_stack();
685169695Skan    task = task->next();
686169695Skan  }
687169695Skan}
688169695Skan
689169695Skan// ------------------------------------------------------------------
690169695Skan// CompileQueue::print
691169695Skanvoid CompileQueue::print() {
692169695Skan  tty->print_cr("Contents of %s", name());
693169695Skan  tty->print_cr("----------------------");
694169695Skan  CompileTask* task = _first;
695169695Skan  while (task != NULL) {
696169695Skan    task->print_line();
697169695Skan    task = task->next();
698169695Skan  }
699169695Skan  tty->print_cr("----------------------");
700169695Skan}
701169695Skan
702169695SkanCompilerCounters::CompilerCounters(const char* thread_name, int instance, TRAPS) {
703169695Skan
704169695Skan  _current_method[0] = '\0';
705169695Skan  _compile_type = CompileBroker::no_compile;
706169695Skan
707169695Skan  if (UsePerfData) {
708169695Skan    ResourceMark rm;
709169695Skan
710169695Skan    // create the thread instance name space string - don't create an
711169695Skan    // instance subspace if instance is -1 - keeps the adapterThread
712169695Skan    // counters  from having a ".0" namespace.
713169695Skan    const char* thread_i = (instance == -1) ? thread_name :
714169695Skan                      PerfDataManager::name_space(thread_name, instance);
715169695Skan
716169695Skan
717169695Skan    char* name = PerfDataManager::counter_name(thread_i, "method");
718169695Skan    _perf_current_method =
719169695Skan               PerfDataManager::create_string_variable(SUN_CI, name,
720169695Skan                                                       cmname_buffer_length,
721169695Skan                                                       _current_method, CHECK);
722169695Skan
723169695Skan    name = PerfDataManager::counter_name(thread_i, "type");
724169695Skan    _perf_compile_type = PerfDataManager::create_variable(SUN_CI, name,
725169695Skan                                                          PerfData::U_None,
726169695Skan                                                         (jlong)_compile_type,
727169695Skan                                                          CHECK);
728169695Skan
729169695Skan    name = PerfDataManager::counter_name(thread_i, "time");
730169695Skan    _perf_time = PerfDataManager::create_counter(SUN_CI, name,
731169695Skan                                                 PerfData::U_Ticks, CHECK);
732169695Skan
733169695Skan    name = PerfDataManager::counter_name(thread_i, "compiles");
734169695Skan    _perf_compiles = PerfDataManager::create_counter(SUN_CI, name,
735169695Skan                                                     PerfData::U_Events, CHECK);
736169695Skan  }
737169695Skan}
738169695Skan
739169695Skan// ------------------------------------------------------------------
740169695Skan// CompileBroker::compilation_init
741169695Skan//
742169695Skan// Initialize the Compilation object
743169695Skanvoid CompileBroker::compilation_init() {
744169695Skan  _last_method_compiled[0] = '\0';
745169695Skan
746169695Skan#ifndef SHARK
747169695Skan  // Set the interface to the current compiler(s).
748169695Skan  int c1_count = CompilationPolicy::policy()->compiler_count(CompLevel_simple);
749169695Skan  int c2_count = CompilationPolicy::policy()->compiler_count(CompLevel_full_optimization);
750169695Skan#ifdef COMPILER1
751169695Skan  if (c1_count > 0) {
752169695Skan    _compilers[0] = new Compiler();
753169695Skan  }
754169695Skan#endif // COMPILER1
755169695Skan
756169695Skan#ifdef COMPILER2
757169695Skan  if (c2_count > 0) {
758169695Skan    _compilers[1] = new C2Compiler();
759169695Skan  }
760169695Skan#endif // COMPILER2
761169695Skan
762169695Skan#else // SHARK
763169695Skan  int c1_count = 0;
764169695Skan  int c2_count = 1;
765169695Skan
766169695Skan  _compilers[1] = new SharkCompiler();
767169695Skan#endif // SHARK
768169695Skan
769169695Skan  // Initialize the CompileTask free list
770169695Skan  _task_free_list = NULL;
771169695Skan
772169695Skan  // Start the CompilerThreads
773169695Skan  init_compiler_threads(c1_count, c2_count);
774169695Skan  // totalTime performance counter is always created as it is required
775169695Skan  // by the implementation of java.lang.management.CompilationMBean.
776169695Skan  {
777169695Skan    EXCEPTION_MARK;
778169695Skan    _perf_total_compilation =
779169695Skan                 PerfDataManager::create_counter(JAVA_CI, "totalTime",
780169695Skan                                                 PerfData::U_Ticks, CHECK);
781169695Skan  }
782169695Skan
783169695Skan
784169695Skan  if (UsePerfData) {
785169695Skan
786169695Skan    EXCEPTION_MARK;
787169695Skan
788169695Skan    // create the jvmstat performance counters
789169695Skan    _perf_osr_compilation =
790169695Skan                 PerfDataManager::create_counter(SUN_CI, "osrTime",
791169695Skan                                                 PerfData::U_Ticks, CHECK);
792169695Skan
793169695Skan    _perf_standard_compilation =
794169695Skan                 PerfDataManager::create_counter(SUN_CI, "standardTime",
795169695Skan                                                 PerfData::U_Ticks, CHECK);
796169695Skan
797169695Skan    _perf_total_bailout_count =
798169695Skan                 PerfDataManager::create_counter(SUN_CI, "totalBailouts",
799169695Skan                                                 PerfData::U_Events, CHECK);
800169695Skan
801169695Skan    _perf_total_invalidated_count =
802169695Skan                 PerfDataManager::create_counter(SUN_CI, "totalInvalidates",
803169695Skan                                                 PerfData::U_Events, CHECK);
804169695Skan
805169695Skan    _perf_total_compile_count =
806169695Skan                 PerfDataManager::create_counter(SUN_CI, "totalCompiles",
807169695Skan                                                 PerfData::U_Events, CHECK);
808169695Skan    _perf_total_osr_compile_count =
809169695Skan                 PerfDataManager::create_counter(SUN_CI, "osrCompiles",
810169695Skan                                                 PerfData::U_Events, CHECK);
811169695Skan
812169695Skan    _perf_total_standard_compile_count =
813169695Skan                 PerfDataManager::create_counter(SUN_CI, "standardCompiles",
814169695Skan                                                 PerfData::U_Events, CHECK);
815169695Skan
816169695Skan    _perf_sum_osr_bytes_compiled =
817169695Skan                 PerfDataManager::create_counter(SUN_CI, "osrBytes",
818169695Skan                                                 PerfData::U_Bytes, CHECK);
819169695Skan
820169695Skan    _perf_sum_standard_bytes_compiled =
821169695Skan                 PerfDataManager::create_counter(SUN_CI, "standardBytes",
822169695Skan                                                 PerfData::U_Bytes, CHECK);
823169695Skan
824169695Skan    _perf_sum_nmethod_size =
825169695Skan                 PerfDataManager::create_counter(SUN_CI, "nmethodSize",
826169695Skan                                                 PerfData::U_Bytes, CHECK);
827169695Skan
828169695Skan    _perf_sum_nmethod_code_size =
829169695Skan                 PerfDataManager::create_counter(SUN_CI, "nmethodCodeSize",
830169695Skan                                                 PerfData::U_Bytes, CHECK);
831169695Skan
832169695Skan    _perf_last_method =
833169695Skan                 PerfDataManager::create_string_variable(SUN_CI, "lastMethod",
834169695Skan                                       CompilerCounters::cmname_buffer_length,
835169695Skan                                       "", CHECK);
836169695Skan
837169695Skan    _perf_last_failed_method =
838169695Skan            PerfDataManager::create_string_variable(SUN_CI, "lastFailedMethod",
839169695Skan                                       CompilerCounters::cmname_buffer_length,
840169695Skan                                       "", CHECK);
841169695Skan
842169695Skan    _perf_last_invalidated_method =
843169695Skan        PerfDataManager::create_string_variable(SUN_CI, "lastInvalidatedMethod",
844169695Skan                                     CompilerCounters::cmname_buffer_length,
845169695Skan                                     "", CHECK);
846169695Skan
847169695Skan    _perf_last_compile_type =
848169695Skan             PerfDataManager::create_variable(SUN_CI, "lastType",
849169695Skan                                              PerfData::U_None,
850169695Skan                                              (jlong)CompileBroker::no_compile,
851169695Skan                                              CHECK);
852169695Skan
853169695Skan    _perf_last_compile_size =
854169695Skan             PerfDataManager::create_variable(SUN_CI, "lastSize",
855169695Skan                                              PerfData::U_Bytes,
856169695Skan                                              (jlong)CompileBroker::no_compile,
857169695Skan                                              CHECK);
858169695Skan
859169695Skan
860169695Skan    _perf_last_failed_type =
861169695Skan             PerfDataManager::create_variable(SUN_CI, "lastFailedType",
862169695Skan                                              PerfData::U_None,
863169695Skan                                              (jlong)CompileBroker::no_compile,
864169695Skan                                              CHECK);
865169695Skan
866169695Skan    _perf_last_invalidated_type =
867169695Skan         PerfDataManager::create_variable(SUN_CI, "lastInvalidatedType",
868169695Skan                                          PerfData::U_None,
869169695Skan                                          (jlong)CompileBroker::no_compile,
870282152Spfg                                          CHECK);
871169695Skan  }
872169695Skan
873169695Skan  _initialized = true;
874169695Skan}
875169695Skan
876282152Spfg
877169695Skan
878169695Skan// ------------------------------------------------------------------
879169695Skan// CompileBroker::make_compiler_thread
880169695SkanCompilerThread* CompileBroker::make_compiler_thread(const char* name, CompileQueue* queue, CompilerCounters* counters, TRAPS) {
881169695Skan  CompilerThread* compiler_thread = NULL;
882169695Skan
883169695Skan  Klass* k =
884169695Skan    SystemDictionary::resolve_or_fail(vmSymbols::java_lang_Thread(),
885282152Spfg                                      true, CHECK_0);
886169695Skan  instanceKlassHandle klass (THREAD, k);
887169695Skan  instanceHandle thread_oop = klass->allocate_instance_handle(CHECK_0);
888169695Skan  Handle string = java_lang_String::create_from_str(name, CHECK_0);
889169695Skan
890169695Skan  // Initialize thread_oop to put it into the system threadGroup
891169695Skan  Handle thread_group (THREAD,  Universe::system_thread_group());
892169695Skan  JavaValue result(T_VOID);
893169695Skan  JavaCalls::call_special(&result, thread_oop,
894169695Skan                       klass,
895169695Skan                       vmSymbols::object_initializer_name(),
896169695Skan                       vmSymbols::threadgroup_string_void_signature(),
897169695Skan                       thread_group,
898169695Skan                       string,
899169695Skan                       CHECK_0);
900169695Skan
901282152Spfg  {
902282152Spfg    MutexLocker mu(Threads_lock, THREAD);
903282152Spfg    compiler_thread = new CompilerThread(queue, counters);
904282152Spfg    // At this point the new CompilerThread data-races with this startup
905282152Spfg    // thread (which I believe is the primoridal thread and NOT the VM
906282152Spfg    // thread).  This means Java bytecodes being executed at startup can
907282152Spfg    // queue compile jobs which will run at whatever default priority the
908282152Spfg    // newly created CompilerThread runs at.
909169695Skan
910169695Skan
911169695Skan    // At this point it may be possible that no osthread was created for the
912169695Skan    // JavaThread due to lack of memory. We would have to throw an exception
913169695Skan    // in that case. However, since this must work and we do not allow
914169695Skan    // exceptions anyway, check and abort if this fails.
915169695Skan
916169695Skan    if (compiler_thread == NULL || compiler_thread->osthread() == NULL){
917169695Skan      vm_exit_during_initialization("java.lang.OutOfMemoryError",
918169695Skan                                    "unable to create new native thread");
919169695Skan    }
920169695Skan
921169695Skan    java_lang_Thread::set_thread(thread_oop(), compiler_thread);
922169695Skan
923169695Skan    // Note that this only sets the JavaThread _priority field, which by
924169695Skan    // definition is limited to Java priorities and not OS priorities.
925169695Skan    // The os-priority is set in the CompilerThread startup code itself
926169695Skan
927169695Skan    java_lang_Thread::set_priority(thread_oop(), NearMaxPriority);
928169695Skan
929169695Skan    // Note that we cannot call os::set_priority because it expects Java
930169695Skan    // priorities and we are *explicitly* using OS priorities so that it's
931169695Skan    // possible to set the compiler thread priority higher than any Java
932169695Skan    // thread.
933169695Skan
934169695Skan    int native_prio = CompilerThreadPriority;
935169695Skan    if (native_prio == -1) {
936169695Skan      if (UseCriticalCompilerThreadPriority) {
937169695Skan        native_prio = os::java_to_os_priority[CriticalPriority];
938169695Skan      } else {
939169695Skan        native_prio = os::java_to_os_priority[NearMaxPriority];
940169695Skan      }
941169695Skan    }
942169695Skan    os::set_native_priority(compiler_thread, native_prio);
943169695Skan
944169695Skan    java_lang_Thread::set_daemon(thread_oop());
945169695Skan
946169695Skan    compiler_thread->set_threadObj(thread_oop());
947169695Skan    Threads::add(compiler_thread);
948169695Skan    Thread::start(compiler_thread);
949169695Skan  }
950169695Skan
951169695Skan  // Let go of Threads_lock before yielding
952169695Skan  os::yield(); // make sure that the compiler thread is started early (especially helpful on SOLARIS)
953169695Skan
954169695Skan  return compiler_thread;
955169695Skan}
956169695Skan
957169695Skan
958169695Skan// ------------------------------------------------------------------
959169695Skan// CompileBroker::init_compiler_threads
960169695Skan//
961169695Skan// Initialize the compilation queue
962169695Skanvoid CompileBroker::init_compiler_threads(int c1_compiler_count, int c2_compiler_count) {
963169695Skan  EXCEPTION_MARK;
964169695Skan#if !defined(ZERO) && !defined(SHARK) && !defined(PPC64)
965169695Skan  assert(c2_compiler_count > 0 || c1_compiler_count > 0, "No compilers?");
966169695Skan#endif // !ZERO && !SHARK
967169695Skan  if (c2_compiler_count > 0) {
968169695Skan    _c2_method_queue  = new CompileQueue("C2MethodQueue",  MethodCompileQueue_lock);
969169695Skan  }
970169695Skan  if (c1_compiler_count > 0) {
971169695Skan    _c1_method_queue  = new CompileQueue("C1MethodQueue",  MethodCompileQueue_lock);
972169695Skan  }
973169695Skan
974169695Skan  int compiler_count = c1_compiler_count + c2_compiler_count;
975169695Skan
976169695Skan  _method_threads =
977169695Skan    new (ResourceObj::C_HEAP, mtCompiler) GrowableArray<CompilerThread*>(compiler_count, true);
978169695Skan
979169695Skan  char name_buffer[256];
980169695Skan  for (int i = 0; i < c2_compiler_count; i++) {
981169695Skan    // Create a name for our thread.
982169695Skan    sprintf(name_buffer, "C2 CompilerThread%d", i);
983169695Skan    CompilerCounters* counters = new CompilerCounters("compilerThread", i, CHECK);
984169695Skan    CompilerThread* new_thread = make_compiler_thread(name_buffer, _c2_method_queue, counters, CHECK);
985169695Skan    _method_threads->append(new_thread);
986169695Skan  }
987169695Skan
988169695Skan  for (int i = c2_compiler_count; i < compiler_count; i++) {
989169695Skan    // Create a name for our thread.
990169695Skan    sprintf(name_buffer, "C1 CompilerThread%d", i);
991169695Skan    CompilerCounters* counters = new CompilerCounters("compilerThread", i, CHECK);
992169695Skan    CompilerThread* new_thread = make_compiler_thread(name_buffer, _c1_method_queue, counters, CHECK);
993169695Skan    _method_threads->append(new_thread);
994169695Skan  }
995169695Skan
996169695Skan  if (UsePerfData) {
997169695Skan    PerfDataManager::create_constant(SUN_CI, "threads", PerfData::U_Bytes,
998169695Skan                                     compiler_count, CHECK);
999169695Skan  }
1000169695Skan}
1001169695Skan
1002169695Skan
1003169695Skan// Set the methods on the stack as on_stack so that redefine classes doesn't
1004169695Skan// reclaim them
1005169695Skanvoid CompileBroker::mark_on_stack() {
1006169695Skan  if (_c2_method_queue != NULL) {
1007169695Skan    _c2_method_queue->mark_on_stack();
1008169695Skan  }
1009169695Skan  if (_c1_method_queue != NULL) {
1010169695Skan    _c1_method_queue->mark_on_stack();
1011169695Skan  }
1012169695Skan}
1013282152Spfg
1014282152Spfg// ------------------------------------------------------------------
1015282152Spfg// CompileBroker::is_idle
1016282152Spfgbool CompileBroker::is_idle() {
1017282152Spfg  if (_c2_method_queue != NULL && !_c2_method_queue->is_empty()) {
1018282152Spfg    return false;
1019169695Skan  } else if (_c1_method_queue != NULL && !_c1_method_queue->is_empty()) {
1020169695Skan    return false;
1021169695Skan  } else {
1022282152Spfg    int num_threads = _method_threads->length();
1023282152Spfg    for (int i=0; i<num_threads; i++) {
1024169695Skan      if (_method_threads->at(i)->task() != NULL) {
1025169695Skan        return false;
1026169695Skan      }
1027169695Skan    }
1028169695Skan
1029169695Skan    // No pending or active compilations.
1030169695Skan    return true;
1031282152Spfg  }
1032282152Spfg}
1033282152Spfg
1034169695Skan
1035169695Skan// ------------------------------------------------------------------
1036169695Skan// CompileBroker::compile_method
1037169695Skan//
1038169695Skan// Request compilation of a method.
1039169695Skanvoid CompileBroker::compile_method_base(methodHandle method,
1040169695Skan                                        int osr_bci,
1041169695Skan                                        int comp_level,
1042282152Spfg                                        methodHandle hot_method,
1043169695Skan                                        int hot_count,
1044169695Skan                                        const char* comment,
1045169695Skan                                        Thread* thread) {
1046169695Skan  // do nothing if compiler thread(s) is not available
1047169695Skan  if (!_initialized ) {
1048169695Skan    return;
1049169695Skan  }
1050169695Skan
1051169695Skan  guarantee(!method->is_abstract(), "cannot compile abstract methods");
1052169695Skan  assert(method->method_holder()->oop_is_instance(),
1053169695Skan         "sanity check");
1054169695Skan  assert(!method->method_holder()->is_not_initialized(),
1055169695Skan         "method holder must be initialized");
1056169695Skan  assert(!method->is_method_handle_intrinsic(), "do not enqueue these guys");
1057169695Skan
1058169695Skan  if (CIPrintRequests) {
1059169695Skan    tty->print("request: ");
1060169695Skan    method->print_short_name(tty);
1061169695Skan    if (osr_bci != InvocationEntryBci) {
1062169695Skan      tty->print(" osr_bci: %d", osr_bci);
1063169695Skan    }
1064169695Skan    tty->print(" comment: %s count: %d", comment, hot_count);
1065169695Skan    if (!hot_method.is_null()) {
1066169695Skan      tty->print(" hot: ");
1067169695Skan      if (hot_method() != method()) {
1068169695Skan          hot_method->print_short_name(tty);
1069169695Skan      } else {
1070169695Skan        tty->print("yes");
1071169695Skan      }
1072169695Skan    }
1073169695Skan    tty->cr();
1074169695Skan  }
1075169695Skan
1076169695Skan  // A request has been made for compilation.  Before we do any
1077169695Skan  // real work, check to see if the method has been compiled
1078169695Skan  // in the meantime with a definitive result.
1079169695Skan  if (compilation_is_complete(method, osr_bci, comp_level)) {
1080169695Skan    return;
1081169695Skan  }
1082169695Skan
1083169695Skan#ifndef PRODUCT
1084169695Skan  if (osr_bci != -1 && !FLAG_IS_DEFAULT(OSROnlyBCI)) {
1085169695Skan    if ((OSROnlyBCI > 0) ? (OSROnlyBCI != osr_bci) : (-OSROnlyBCI == osr_bci)) {
1086169695Skan      // Positive OSROnlyBCI means only compile that bci.  Negative means don't compile that BCI.
1087169695Skan      return;
1088169695Skan    }
1089169695Skan  }
1090169695Skan#endif
1091169695Skan
1092169695Skan  // If this method is already in the compile queue, then
1093169695Skan  // we do not block the current thread.
1094169695Skan  if (compilation_is_in_queue(method, osr_bci)) {
1095169695Skan    // We may want to decay our counter a bit here to prevent
1096169695Skan    // multiple denied requests for compilation.  This is an
1097169695Skan    // open compilation policy issue. Note: The other possibility,
1098169695Skan    // in the case that this is a blocking compile request, is to have
1099169695Skan    // all subsequent blocking requesters wait for completion of
1100169695Skan    // ongoing compiles. Note that in this case we'll need a protocol
1101169695Skan    // for freeing the associated compile tasks. [Or we could have
1102169695Skan    // a single static monitor on which all these waiters sleep.]
1103169695Skan    return;
1104169695Skan  }
1105169695Skan
1106169695Skan  // If the requesting thread is holding the pending list lock
1107169695Skan  // then we just return. We can't risk blocking while holding
1108169695Skan  // the pending list lock or a 3-way deadlock may occur
1109169695Skan  // between the reference handler thread, a GC (instigated
1110169695Skan  // by a compiler thread), and compiled method registration.
1111169695Skan  if (InstanceRefKlass::owns_pending_list_lock(JavaThread::current())) {
1112169695Skan    return;
1113169695Skan  }
1114169695Skan
1115169695Skan  // Outputs from the following MutexLocker block:
1116169695Skan  CompileTask* task     = NULL;
1117169695Skan  bool         blocking = false;
1118169695Skan  CompileQueue* queue  = compile_queue(comp_level);
1119169695Skan
1120169695Skan  // Acquire our lock.
1121169695Skan  {
1122169695Skan    MutexLocker locker(queue->lock(), thread);
1123169695Skan
1124169695Skan    // Make sure the method has not slipped into the queues since
1125169695Skan    // last we checked; note that those checks were "fast bail-outs".
1126169695Skan    // Here we need to be more careful, see 14012000 below.
1127169695Skan    if (compilation_is_in_queue(method, osr_bci)) {
1128169695Skan      return;
1129169695Skan    }
1130169695Skan
1131169695Skan    // We need to check again to see if the compilation has
1132169695Skan    // completed.  A previous compilation may have registered
1133169695Skan    // some result.
1134169695Skan    if (compilation_is_complete(method, osr_bci, comp_level)) {
1135169695Skan      return;
1136169695Skan    }
1137169695Skan
1138169695Skan    // We now know that this compilation is not pending, complete,
1139169695Skan    // or prohibited.  Assign a compile_id to this compilation
1140169695Skan    // and check to see if it is in our [Start..Stop) range.
1141169695Skan    uint compile_id = assign_compile_id(method, osr_bci);
1142169695Skan    if (compile_id == 0) {
1143169695Skan      // The compilation falls outside the allowed range.
1144169695Skan      return;
1145169695Skan    }
1146169695Skan
1147169695Skan    // Should this thread wait for completion of the compile?
1148169695Skan    blocking = is_compile_blocking(method, osr_bci);
1149169695Skan
1150169695Skan    // We will enter the compilation in the queue.
1151169695Skan    // 14012000: Note that this sets the queued_for_compile bits in
1152169695Skan    // the target method. We can now reason that a method cannot be
1153169695Skan    // queued for compilation more than once, as follows:
1154169695Skan    // Before a thread queues a task for compilation, it first acquires
1155169695Skan    // the compile queue lock, then checks if the method's queued bits
1156169695Skan    // are set or it has already been compiled. Thus there can not be two
1157169695Skan    // instances of a compilation task for the same method on the
1158169695Skan    // compilation queue. Consider now the case where the compilation
1159169695Skan    // thread has already removed a task for that method from the queue
1160169695Skan    // and is in the midst of compiling it. In this case, the
1161169695Skan    // queued_for_compile bits must be set in the method (and these
1162169695Skan    // will be visible to the current thread, since the bits were set
1163169695Skan    // under protection of the compile queue lock, which we hold now.
1164169695Skan    // When the compilation completes, the compiler thread first sets
1165169695Skan    // the compilation result and then clears the queued_for_compile
1166169695Skan    // bits. Neither of these actions are protected by a barrier (or done
1167169695Skan    // under the protection of a lock), so the only guarantee we have
1168169695Skan    // (on machines with TSO (Total Store Order)) is that these values
1169169695Skan    // will update in that order. As a result, the only combinations of
1170169695Skan    // these bits that the current thread will see are, in temporal order:
1171169695Skan    // <RESULT, QUEUE> :
1172169695Skan    //     <0, 1> : in compile queue, but not yet compiled
1173169695Skan    //     <1, 1> : compiled but queue bit not cleared
1174169695Skan    //     <1, 0> : compiled and queue bit cleared
1175169695Skan    // Because we first check the queue bits then check the result bits,
1176169695Skan    // we are assured that we cannot introduce a duplicate task.
1177169695Skan    // Note that if we did the tests in the reverse order (i.e. check
1178169695Skan    // result then check queued bit), we could get the result bit before
1179169695Skan    // the compilation completed, and the queue bit after the compilation
1180169695Skan    // completed, and end up introducing a "duplicate" (redundant) task.
1181169695Skan    // In that case, the compiler thread should first check if a method
1182169695Skan    // has already been compiled before trying to compile it.
1183169695Skan    // NOTE: in the event that there are multiple compiler threads and
1184169695Skan    // there is de-optimization/recompilation, things will get hairy,
1185169695Skan    // and in that case it's best to protect both the testing (here) of
1186169695Skan    // these bits, and their updating (here and elsewhere) under a
1187169695Skan    // common lock.
1188169695Skan    task = create_compile_task(queue,
1189169695Skan                               compile_id, method,
1190169695Skan                               osr_bci, comp_level,
1191169695Skan                               hot_method, hot_count, comment,
1192169695Skan                               blocking);
1193169695Skan  }
1194169695Skan
1195169695Skan  if (blocking) {
1196169695Skan    wait_for_completion(task);
1197169695Skan  }
1198169695Skan}
1199169695Skan
1200169695Skan
1201169695Skannmethod* CompileBroker::compile_method(methodHandle method, int osr_bci,
1202169695Skan                                       int comp_level,
1203169695Skan                                       methodHandle hot_method, int hot_count,
1204169695Skan                                       const char* comment, Thread* THREAD) {
1205169695Skan  // make sure arguments make sense
1206169695Skan  assert(method->method_holder()->oop_is_instance(), "not an instance method");
1207169695Skan  assert(osr_bci == InvocationEntryBci || (0 <= osr_bci && osr_bci < method->code_size()), "bci out of range");
1208169695Skan  assert(!method->is_abstract() && (osr_bci == InvocationEntryBci || !method->is_native()), "cannot compile abstract/native methods");
1209169695Skan  assert(!method->method_holder()->is_not_initialized(), "method holder must be initialized");
1210169695Skan  // allow any levels for WhiteBox
1211169695Skan  assert(WhiteBoxAPI || TieredCompilation || comp_level == CompLevel_highest_tier, "only CompLevel_highest_tier must be used in non-tiered");
1212169695Skan  // return quickly if possible
1213169695Skan
1214169695Skan  // lock, make sure that the compilation
1215169695Skan  // isn't prohibited in a straightforward way.
1216169695Skan  AbstractCompiler *comp = CompileBroker::compiler(comp_level);
1217169695Skan  if (comp == NULL || !comp->can_compile_method(method) ||
1218169695Skan      compilation_is_prohibited(method, osr_bci, comp_level)) {
1219169695Skan    return NULL;
1220169695Skan  }
1221169695Skan
1222169695Skan  if (osr_bci == InvocationEntryBci) {
1223169695Skan    // standard compilation
1224169695Skan    nmethod* method_code = method->code();
1225169695Skan    if (method_code != NULL) {
1226169695Skan      if (compilation_is_complete(method, osr_bci, comp_level)) {
1227169695Skan        return method_code;
1228169695Skan      }
1229169695Skan    }
1230169695Skan    if (method->is_not_compilable(comp_level)) return NULL;
1231169695Skan
1232169695Skan    if (UseCodeCacheFlushing) {
1233169695Skan      nmethod* saved = CodeCache::reanimate_saved_code(method());
1234169695Skan      if (saved != NULL) {
1235169695Skan        method->set_code(method, saved);
1236169695Skan        return saved;
1237169695Skan      }
1238169695Skan    }
1239169695Skan
1240169695Skan  } else {
1241169695Skan    // osr compilation
1242169695Skan#ifndef TIERED
1243169695Skan    // seems like an assert of dubious value
1244169695Skan    assert(comp_level == CompLevel_highest_tier,
1245169695Skan           "all OSR compiles are assumed to be at a single compilation lavel");
1246169695Skan#endif // TIERED
1247169695Skan    // We accept a higher level osr method
1248169695Skan    nmethod* nm = method->lookup_osr_nmethod_for(osr_bci, comp_level, false);
1249169695Skan    if (nm != NULL) return nm;
1250169695Skan    if (method->is_not_osr_compilable(comp_level)) return NULL;
1251169695Skan  }
1252169695Skan
1253169695Skan  assert(!HAS_PENDING_EXCEPTION, "No exception should be present");
1254169695Skan  // some prerequisites that are compiler specific
1255169695Skan  if (comp->is_c2() || comp->is_shark()) {
1256169695Skan    method->constants()->resolve_string_constants(CHECK_AND_CLEAR_NULL);
1257169695Skan    // Resolve all classes seen in the signature of the method
1258169695Skan    // we are compiling.
1259169695Skan    Method::load_signature_classes(method, CHECK_AND_CLEAR_NULL);
1260169695Skan  }
1261169695Skan
1262169695Skan  // If the method is native, do the lookup in the thread requesting
1263169695Skan  // the compilation. Native lookups can load code, which is not
1264169695Skan  // permitted during compilation.
1265169695Skan  //
1266169695Skan  // Note: A native method implies non-osr compilation which is
1267169695Skan  //       checked with an assertion at the entry of this method.
1268169695Skan  if (method->is_native() && !method->is_method_handle_intrinsic()) {
1269169695Skan    bool in_base_library;
1270169695Skan    address adr = NativeLookup::lookup(method, in_base_library, THREAD);
1271169695Skan    if (HAS_PENDING_EXCEPTION) {
1272169695Skan      // In case of an exception looking up the method, we just forget
1273169695Skan      // about it. The interpreter will kick-in and throw the exception.
1274169695Skan      method->set_not_compilable(); // implies is_not_osr_compilable()
1275169695Skan      CLEAR_PENDING_EXCEPTION;
1276169695Skan      return NULL;
1277169695Skan    }
1278169695Skan    assert(method->has_native_function(), "must have native code by now");
1279169695Skan  }
1280169695Skan
1281169695Skan  // RedefineClasses() has replaced this method; just return
1282169695Skan  if (method->is_old()) {
1283169695Skan    return NULL;
1284169695Skan  }
1285169695Skan
1286169695Skan  // JVMTI -- post_compile_event requires jmethod_id() that may require
1287169695Skan  // a lock the compiling thread can not acquire. Prefetch it here.
1288169695Skan  if (JvmtiExport::should_post_compiled_method_load()) {
1289169695Skan    method->jmethod_id();
1290169695Skan  }
1291169695Skan
1292169695Skan  // If the compiler is shut off due to code cache getting full
1293169695Skan  // fail out now so blocking compiles dont hang the java thread
1294169695Skan  if (!should_compile_new_jobs()) {
1295169695Skan    CompilationPolicy::policy()->delay_compilation(method());
1296169695Skan    return NULL;
1297169695Skan  }
1298169695Skan
1299169695Skan  // do the compilation
1300169695Skan  if (method->is_native()) {
1301169695Skan    if (!PreferInterpreterNativeStubs || method->is_method_handle_intrinsic()) {
1302169695Skan      // Acquire our lock.
1303169695Skan      int compile_id;
1304169695Skan      {
1305169695Skan        MutexLocker locker(MethodCompileQueue_lock, THREAD);
1306169695Skan        compile_id = assign_compile_id(method, standard_entry_bci);
1307169695Skan      }
1308169695Skan      (void) AdapterHandlerLibrary::create_native_wrapper(method, compile_id);
1309169695Skan    } else {
1310169695Skan      return NULL;
1311169695Skan    }
1312169695Skan  } else {
1313169695Skan    compile_method_base(method, osr_bci, comp_level, hot_method, hot_count, comment, THREAD);
1314169695Skan  }
1315169695Skan
1316169695Skan  // return requested nmethod
1317169695Skan  // We accept a higher level osr method
1318169695Skan  return osr_bci  == InvocationEntryBci ? method->code() : method->lookup_osr_nmethod_for(osr_bci, comp_level, false);
1319169695Skan}
1320169695Skan
1321169695Skan
1322169695Skan// ------------------------------------------------------------------
1323169695Skan// CompileBroker::compilation_is_complete
1324169695Skan//
1325169695Skan// See if compilation of this method is already complete.
1326169695Skanbool CompileBroker::compilation_is_complete(methodHandle method,
1327169695Skan                                            int          osr_bci,
1328169695Skan                                            int          comp_level) {
1329169695Skan  bool is_osr = (osr_bci != standard_entry_bci);
1330169695Skan  if (is_osr) {
1331169695Skan    if (method->is_not_osr_compilable(comp_level)) {
1332169695Skan      return true;
1333169695Skan    } else {
1334169695Skan      nmethod* result = method->lookup_osr_nmethod_for(osr_bci, comp_level, true);
1335169695Skan      return (result != NULL);
1336169695Skan    }
1337169695Skan  } else {
1338169695Skan    if (method->is_not_compilable(comp_level)) {
1339169695Skan      return true;
1340169695Skan    } else {
1341169695Skan      nmethod* result = method->code();
1342169695Skan      if (result == NULL) return false;
1343169695Skan      return comp_level == result->comp_level();
1344169695Skan    }
1345169695Skan  }
1346169695Skan}
1347169695Skan
1348169695Skan
1349169695Skan// ------------------------------------------------------------------
1350169695Skan// CompileBroker::compilation_is_in_queue
1351169695Skan//
1352169695Skan// See if this compilation is already requested.
1353169695Skan//
1354169695Skan// Implementation note: there is only a single "is in queue" bit
1355169695Skan// for each method.  This means that the check below is overly
1356169695Skan// conservative in the sense that an osr compilation in the queue
1357169695Skan// will block a normal compilation from entering the queue (and vice
1358169695Skan// versa).  This can be remedied by a full queue search to disambiguate
1359169695Skan// cases.  If it is deemed profitible, this may be done.
1360169695Skanbool CompileBroker::compilation_is_in_queue(methodHandle method,
1361169695Skan                                            int          osr_bci) {
1362169695Skan  return method->queued_for_compilation();
1363169695Skan}
1364169695Skan
1365169695Skan// ------------------------------------------------------------------
1366169695Skan// CompileBroker::compilation_is_prohibited
1367169695Skan//
1368169695Skan// See if this compilation is not allowed.
1369169695Skanbool CompileBroker::compilation_is_prohibited(methodHandle method, int osr_bci, int comp_level) {
1370169695Skan  bool is_native = method->is_native();
1371169695Skan  // Some compilers may not support the compilation of natives.
1372169695Skan  AbstractCompiler *comp = compiler(comp_level);
1373169695Skan  if (is_native &&
1374169695Skan      (!CICompileNatives || comp == NULL || !comp->supports_native())) {
1375169695Skan    method->set_not_compilable_quietly(comp_level);
1376169695Skan    return true;
1377169695Skan  }
1378169695Skan
1379169695Skan  bool is_osr = (osr_bci != standard_entry_bci);
1380169695Skan  // Some compilers may not support on stack replacement.
1381169695Skan  if (is_osr &&
1382169695Skan      (!CICompileOSR || comp == NULL || !comp->supports_osr())) {
1383169695Skan    method->set_not_osr_compilable(comp_level);
1384169695Skan    return true;
1385169695Skan  }
1386169695Skan
1387169695Skan  // The method may be explicitly excluded by the user.
1388169695Skan  bool quietly;
1389169695Skan  if (CompilerOracle::should_exclude(method, quietly)) {
1390169695Skan    if (!quietly) {
1391169695Skan      // This does not happen quietly...
1392169695Skan      ResourceMark rm;
1393169695Skan      tty->print("### Excluding %s:%s",
1394169695Skan                 method->is_native() ? "generation of native wrapper" : "compile",
1395169695Skan                 (method->is_static() ? " static" : ""));
1396169695Skan      method->print_short_name(tty);
1397169695Skan      tty->cr();
1398169695Skan    }
1399169695Skan    method->set_not_compilable(CompLevel_all, !quietly, "excluded by CompilerOracle");
1400169695Skan  }
1401169695Skan
1402169695Skan  return false;
1403169695Skan}
1404169695Skan
1405169695Skan
1406169695Skan// ------------------------------------------------------------------
1407169695Skan// CompileBroker::assign_compile_id
1408169695Skan//
1409169695Skan// Assign a serialized id number to this compilation request.  If the
1410169695Skan// number falls out of the allowed range, return a 0.  OSR
1411169695Skan// compilations may be numbered separately from regular compilations
1412169695Skan// if certain debugging flags are used.
1413169695Skanuint CompileBroker::assign_compile_id(methodHandle method, int osr_bci) {
1414169695Skan  assert(MethodCompileQueue_lock->owner() == Thread::current(),
1415169695Skan         "must hold the compilation queue lock");
1416169695Skan  bool is_osr = (osr_bci != standard_entry_bci);
1417169695Skan  uint id;
1418169695Skan  if (CICountOSR && is_osr) {
1419169695Skan    id = ++_osr_compilation_id;
1420169695Skan    if ((uint)CIStartOSR <= id && id < (uint)CIStopOSR) {
1421169695Skan      return id;
1422169695Skan    }
1423169695Skan  } else {
1424169695Skan    id = ++_compilation_id;
1425169695Skan    if ((uint)CIStart <= id && id < (uint)CIStop) {
1426169695Skan      return id;
1427169695Skan    }
1428169695Skan  }
1429169695Skan
1430169695Skan  // Method was not in the appropriate compilation range.
1431169695Skan  method->set_not_compilable_quietly();
1432169695Skan  return 0;
1433169695Skan}
1434169695Skan
1435169695Skan
1436169695Skan// ------------------------------------------------------------------
1437169695Skan// CompileBroker::is_compile_blocking
1438169695Skan//
1439169695Skan// Should the current thread be blocked until this compilation request
1440169695Skan// has been fulfilled?
1441169695Skanbool CompileBroker::is_compile_blocking(methodHandle method, int osr_bci) {
1442169695Skan  assert(!InstanceRefKlass::owns_pending_list_lock(JavaThread::current()), "possible deadlock");
1443169695Skan  return !BackgroundCompilation;
1444169695Skan}
1445169695Skan
1446169695Skan
1447169695Skan// ------------------------------------------------------------------
1448169695Skan// CompileBroker::preload_classes
1449169695Skanvoid CompileBroker::preload_classes(methodHandle method, TRAPS) {
1450169695Skan  // Move this code over from c1_Compiler.cpp
1451169695Skan  ShouldNotReachHere();
1452169695Skan}
1453169695Skan
1454169695Skan
1455169695Skan// ------------------------------------------------------------------
1456169695Skan// CompileBroker::create_compile_task
1457169695Skan//
1458169695Skan// Create a CompileTask object representing the current request for
1459169695Skan// compilation.  Add this task to the queue.
1460169695SkanCompileTask* CompileBroker::create_compile_task(CompileQueue* queue,
1461169695Skan                                              int           compile_id,
1462169695Skan                                              methodHandle  method,
1463169695Skan                                              int           osr_bci,
1464169695Skan                                              int           comp_level,
1465169695Skan                                              methodHandle  hot_method,
1466169695Skan                                              int           hot_count,
1467169695Skan                                              const char*   comment,
1468169695Skan                                              bool          blocking) {
1469169695Skan  CompileTask* new_task = allocate_task();
1470169695Skan  new_task->initialize(compile_id, method, osr_bci, comp_level,
1471169695Skan                       hot_method, hot_count, comment,
1472169695Skan                       blocking);
1473169695Skan  queue->add(new_task);
1474169695Skan  return new_task;
1475169695Skan}
1476169695Skan
1477169695Skan
1478169695Skan// ------------------------------------------------------------------
1479169695Skan// CompileBroker::allocate_task
1480169695Skan//
1481169695Skan// Allocate a CompileTask, from the free list if possible.
1482169695SkanCompileTask* CompileBroker::allocate_task() {
1483169695Skan  MutexLocker locker(CompileTaskAlloc_lock);
1484169695Skan  CompileTask* task = NULL;
1485169695Skan  if (_task_free_list != NULL) {
1486169695Skan    task = _task_free_list;
1487169695Skan    _task_free_list = task->next();
1488169695Skan    task->set_next(NULL);
1489169695Skan  } else {
1490169695Skan    task = new CompileTask();
1491169695Skan    task->set_next(NULL);
1492169695Skan  }
1493169695Skan  return task;
1494169695Skan}
1495169695Skan
1496169695Skan
1497169695Skan// ------------------------------------------------------------------
1498169695Skan// CompileBroker::free_task
1499169695Skan//
1500169695Skan// Add a task to the free list.
1501169695Skanvoid CompileBroker::free_task(CompileTask* task) {
1502169695Skan  MutexLocker locker(CompileTaskAlloc_lock);
1503169695Skan  task->free();
1504169695Skan  task->set_next(_task_free_list);
1505169695Skan  _task_free_list = task;
1506169695Skan}
1507169695Skan
1508169695Skan
1509169695Skan// ------------------------------------------------------------------
1510169695Skan// CompileBroker::wait_for_completion
1511169695Skan//
1512169695Skan// Wait for the given method CompileTask to complete.
1513169695Skanvoid CompileBroker::wait_for_completion(CompileTask* task) {
1514169695Skan  if (CIPrintCompileQueue) {
1515169695Skan    tty->print_cr("BLOCKING FOR COMPILE");
1516169695Skan  }
1517169695Skan
1518169695Skan  assert(task->is_blocking(), "can only wait on blocking task");
1519169695Skan
1520169695Skan  JavaThread *thread = JavaThread::current();
1521169695Skan  thread->set_blocked_on_compilation(true);
1522169695Skan
1523169695Skan  methodHandle method(thread, task->method());
1524169695Skan  {
1525169695Skan    MutexLocker waiter(task->lock(), thread);
1526169695Skan
1527169695Skan    while (!task->is_complete())
1528169695Skan      task->lock()->wait();
1529169695Skan  }
1530169695Skan  // It is harmless to check this status without the lock, because
1531169695Skan  // completion is a stable property (until the task object is recycled).
1532169695Skan  assert(task->is_complete(), "Compilation should have completed");
1533169695Skan  assert(task->code_handle() == NULL, "must be reset");
1534169695Skan
1535169695Skan  thread->set_blocked_on_compilation(false);
1536169695Skan
1537169695Skan  // By convention, the waiter is responsible for recycling a
1538169695Skan  // blocking CompileTask. Since there is only one waiter ever
1539169695Skan  // waiting on a CompileTask, we know that no one else will
1540169695Skan  // be using this CompileTask; we can free it.
1541169695Skan  free_task(task);
1542169695Skan}
1543169695Skan
1544169695Skan// ------------------------------------------------------------------
1545169695Skan// CompileBroker::compiler_thread_loop
1546169695Skan//
1547169695Skan// The main loop run by a CompilerThread.
1548169695Skanvoid CompileBroker::compiler_thread_loop() {
1549169695Skan  CompilerThread* thread = CompilerThread::current();
1550169695Skan  CompileQueue* queue = thread->queue();
1551169695Skan
1552169695Skan  // For the thread that initializes the ciObjectFactory
1553169695Skan  // this resource mark holds all the shared objects
1554169695Skan  ResourceMark rm;
1555169695Skan
1556169695Skan  // First thread to get here will initialize the compiler interface
1557169695Skan
1558169695Skan  if (!ciObjectFactory::is_initialized()) {
1559169695Skan    ASSERT_IN_VM;
1560169695Skan    MutexLocker only_one (CompileThread_lock, thread);
1561169695Skan    if (!ciObjectFactory::is_initialized()) {
1562169695Skan      ciObjectFactory::initialize();
1563169695Skan    }
1564169695Skan  }
1565169695Skan
1566169695Skan  // Open a log.
1567169695Skan  if (LogCompilation) {
1568169695Skan    init_compiler_thread_log();
1569169695Skan  }
1570169695Skan  CompileLog* log = thread->log();
1571169695Skan  if (log != NULL) {
1572169695Skan    log->begin_elem("start_compile_thread name='%s' thread='" UINTX_FORMAT "' process='%d'",
1573169695Skan                    thread->name(),
1574169695Skan                    os::current_thread_id(),
1575169695Skan                    os::current_process_id());
1576169695Skan    log->stamp();
1577169695Skan    log->end_elem();
1578169695Skan  }
1579169695Skan
1580169695Skan  while (true) {
1581169695Skan    {
1582169695Skan      // We need this HandleMark to avoid leaking VM handles.
1583169695Skan      HandleMark hm(thread);
1584169695Skan
1585169695Skan      if (CodeCache::unallocated_capacity() < CodeCacheMinimumFreeSpace) {
1586169695Skan        // the code cache is really full
1587169695Skan        handle_full_code_cache();
1588169695Skan      } else if (UseCodeCacheFlushing && CodeCache::needs_flushing()) {
1589169695Skan        // Attempt to start cleaning the code cache while there is still a little headroom
1590169695Skan        NMethodSweeper::handle_full_code_cache(false);
1591169695Skan      }
1592169695Skan
1593169695Skan      CompileTask* task = queue->get();
1594169695Skan
1595169695Skan      // Give compiler threads an extra quanta.  They tend to be bursty and
1596169695Skan      // this helps the compiler to finish up the job.
1597169695Skan      if( CompilerThreadHintNoPreempt )
1598169695Skan        os::hint_no_preempt();
1599169695Skan
1600169695Skan      // trace per thread time and compile statistics
1601169695Skan      CompilerCounters* counters = ((CompilerThread*)thread)->counters();
1602169695Skan      PerfTraceTimedEvent(counters->time_counter(), counters->compile_counter());
1603169695Skan
1604169695Skan      // Assign the task to the current thread.  Mark this compilation
1605169695Skan      // thread as active for the profiler.
1606169695Skan      CompileTaskWrapper ctw(task);
1607169695Skan      nmethodLocker result_handle;  // (handle for the nmethod produced by this task)
1608169695Skan      task->set_code_handle(&result_handle);
1609169695Skan      methodHandle method(thread, task->method());
1610169695Skan
1611169695Skan      // Never compile a method if breakpoints are present in it
1612169695Skan      if (method()->number_of_breakpoints() == 0) {
1613169695Skan        // Compile the method.
1614169695Skan        if ((UseCompiler || AlwaysCompileLoopMethods) && CompileBroker::should_compile_new_jobs()) {
1615169695Skan#ifdef COMPILER1
1616169695Skan          // Allow repeating compilations for the purpose of benchmarking
1617169695Skan          // compile speed. This is not useful for customers.
1618169695Skan          if (CompilationRepeat != 0) {
1619169695Skan            int compile_count = CompilationRepeat;
1620169695Skan            while (compile_count > 0) {
1621169695Skan              invoke_compiler_on_method(task);
1622169695Skan              nmethod* nm = method->code();
1623169695Skan              if (nm != NULL) {
1624169695Skan                nm->make_zombie();
1625169695Skan                method->clear_code();
1626169695Skan              }
1627169695Skan              compile_count--;
1628169695Skan            }
1629169695Skan          }
1630169695Skan#endif /* COMPILER1 */
1631169695Skan          invoke_compiler_on_method(task);
1632169695Skan        } else {
1633169695Skan          // After compilation is disabled, remove remaining methods from queue
1634169695Skan          method->clear_queued_for_compilation();
1635169695Skan        }
1636169695Skan      }
1637169695Skan    }
1638169695Skan  }
1639169695Skan}
1640169695Skan
1641169695Skan
1642169695Skan// ------------------------------------------------------------------
1643169695Skan// CompileBroker::init_compiler_thread_log
1644169695Skan//
1645169695Skan// Set up state required by +LogCompilation.
1646169695Skanvoid CompileBroker::init_compiler_thread_log() {
1647169695Skan    CompilerThread* thread = CompilerThread::current();
1648169695Skan    char  file_name[4*K];
1649169695Skan    FILE* fp = NULL;
1650169695Skan    intx thread_id = os::current_thread_id();
1651169695Skan    for (int try_temp_dir = 1; try_temp_dir >= 0; try_temp_dir--) {
1652169695Skan      const char* dir = (try_temp_dir ? os::get_temp_directory() : NULL);
1653169695Skan      if (dir == NULL) {
1654169695Skan        jio_snprintf(file_name, sizeof(file_name), "hs_c" UINTX_FORMAT "_pid%u.log",
1655169695Skan                     thread_id, os::current_process_id());
1656169695Skan      } else {
1657169695Skan        jio_snprintf(file_name, sizeof(file_name),
1658169695Skan                     "%s%shs_c" UINTX_FORMAT "_pid%u.log", dir,
1659169695Skan                     os::file_separator(), thread_id, os::current_process_id());
1660169695Skan      }
1661169695Skan
1662169695Skan      fp = fopen(file_name, "at");
1663169695Skan      if (fp != NULL) {
1664169695Skan        if (LogCompilation && Verbose) {
1665169695Skan          tty->print_cr("Opening compilation log %s", file_name);
1666169695Skan        }
1667169695Skan        CompileLog* log = new(ResourceObj::C_HEAP, mtCompiler) CompileLog(file_name, fp, thread_id);
1668169695Skan        thread->init_log(log);
1669169695Skan
1670169695Skan        if (xtty != NULL) {
1671169695Skan          ttyLocker ttyl;
1672169695Skan          // Record any per thread log files
1673169695Skan          xtty->elem("thread_logfile thread='%d' filename='%s'", thread_id, file_name);
1674169695Skan        }
1675169695Skan        return;
1676169695Skan      }
1677169695Skan    }
1678169695Skan    warning("Cannot open log file: %s", file_name);
1679169695Skan}
1680169695Skan
1681169695Skan// ------------------------------------------------------------------
1682169695Skan// CompileBroker::set_should_block
1683169695Skan//
1684169695Skan// Set _should_block.
1685169695Skan// Call this from the VM, with Threads_lock held and a safepoint requested.
1686169695Skanvoid CompileBroker::set_should_block() {
1687169695Skan  assert(Threads_lock->owner() == Thread::current(), "must have threads lock");
1688169695Skan  assert(SafepointSynchronize::is_at_safepoint(), "must be at a safepoint already");
1689169695Skan#ifndef PRODUCT
1690169695Skan  if (PrintCompilation && (Verbose || WizardMode))
1691169695Skan    tty->print_cr("notifying compiler thread pool to block");
1692282152Spfg#endif
1693169695Skan  _should_block = true;
1694169695Skan}
1695169695Skan
1696169695Skan// ------------------------------------------------------------------
1697169695Skan// CompileBroker::maybe_block
1698169695Skan//
1699169695Skan// Call this from the compiler at convenient points, to poll for _should_block.
1700169695Skanvoid CompileBroker::maybe_block() {
1701169695Skan  if (_should_block) {
1702169695Skan#ifndef PRODUCT
1703169695Skan    if (PrintCompilation && (Verbose || WizardMode))
1704169695Skan      tty->print_cr("compiler thread " INTPTR_FORMAT " poll detects block request", Thread::current());
1705169695Skan#endif
1706169695Skan    ThreadInVMfromNative tivfn(JavaThread::current());
1707169695Skan  }
1708169695Skan}
1709169695Skan
1710169695Skan// wrapper for CodeCache::print_summary()
1711169695Skanstatic void codecache_print(bool detailed)
1712169695Skan{
1713169695Skan  ResourceMark rm;
1714169695Skan  stringStream s;
1715169695Skan  // Dump code cache  into a buffer before locking the tty,
1716169695Skan  {
1717169695Skan    MutexLockerEx mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
1718169695Skan    CodeCache::print_summary(&s, detailed);
1719169695Skan  }
1720169695Skan  ttyLocker ttyl;
1721169695Skan  tty->print_cr(s.as_string());
1722169695Skan}
1723169695Skan
1724169695Skan// ------------------------------------------------------------------
1725169695Skan// CompileBroker::invoke_compiler_on_method
1726169695Skan//
1727169695Skan// Compile a method.
1728169695Skan//
1729169695Skanvoid CompileBroker::invoke_compiler_on_method(CompileTask* task) {
1730169695Skan  if (PrintCompilation) {
1731169695Skan    ResourceMark rm;
1732169695Skan    task->print_line();
1733169695Skan  }
1734169695Skan  elapsedTimer time;
1735169695Skan
1736169695Skan  CompilerThread* thread = CompilerThread::current();
1737169695Skan  ResourceMark rm(thread);
1738169695Skan
1739169695Skan  if (LogEvents) {
1740169695Skan    _compilation_log->log_compile(thread, task);
1741169695Skan  }
1742169695Skan
1743169695Skan  // Common flags.
1744169695Skan  uint compile_id = task->compile_id();
1745169695Skan  int osr_bci = task->osr_bci();
1746169695Skan  bool is_osr = (osr_bci != standard_entry_bci);
1747169695Skan  bool should_log = (thread->log() != NULL);
1748169695Skan  bool should_break = false;
1749169695Skan  int task_level = task->comp_level();
1750169695Skan  {
1751169695Skan    // create the handle inside it's own block so it can't
1752169695Skan    // accidentally be referenced once the thread transitions to
1753169695Skan    // native.  The NoHandleMark before the transition should catch
1754169695Skan    // any cases where this occurs in the future.
1755169695Skan    methodHandle method(thread, task->method());
1756169695Skan    should_break = check_break_at(method, compile_id, is_osr);
1757169695Skan    if (should_log && !CompilerOracle::should_log(method)) {
1758169695Skan      should_log = false;
1759169695Skan    }
1760169695Skan    assert(!method->is_native(), "no longer compile natives");
1761169695Skan
1762169695Skan    // Save information about this method in case of failure.
1763169695Skan    set_last_compile(thread, method, is_osr, task_level);
1764169695Skan
1765169695Skan    DTRACE_METHOD_COMPILE_BEGIN_PROBE(method, compiler_name(task_level));
1766169695Skan  }
1767169695Skan
1768169695Skan  // Allocate a new set of JNI handles.
1769169695Skan  push_jni_handle_block();
1770169695Skan  Method* target_handle = task->method();
1771169695Skan  int compilable = ciEnv::MethodCompilable;
1772169695Skan  {
1773169695Skan    int system_dictionary_modification_counter;
1774169695Skan    {
1775169695Skan      MutexLocker locker(Compile_lock, thread);
1776169695Skan      system_dictionary_modification_counter = SystemDictionary::number_of_modifications();
1777169695Skan    }
1778169695Skan
1779169695Skan    NoHandleMark  nhm;
1780169695Skan    ThreadToNativeFromVM ttn(thread);
1781169695Skan
1782169695Skan    ciEnv ci_env(task, system_dictionary_modification_counter);
1783169695Skan    if (should_break) {
1784169695Skan      ci_env.set_break_at_compile(true);
1785169695Skan    }
1786169695Skan    if (should_log) {
1787169695Skan      ci_env.set_log(thread->log());
1788169695Skan    }
1789169695Skan    assert(thread->env() == &ci_env, "set by ci_env");
1790169695Skan    // The thread-env() field is cleared in ~CompileTaskWrapper.
1791169695Skan
1792169695Skan    // Cache Jvmti state
1793169695Skan    ci_env.cache_jvmti_state();
1794169695Skan
1795169695Skan    // Cache DTrace flags
1796169695Skan    ci_env.cache_dtrace_flags();
1797169695Skan
1798169695Skan    ciMethod* target = ci_env.get_method_from_handle(target_handle);
1799169695Skan
1800169695Skan    TraceTime t1("compilation", &time);
1801169695Skan    EventCompilation event;
1802169695Skan
1803169695Skan    AbstractCompiler *comp = compiler(task_level);
1804169695Skan    if (comp == NULL) {
1805169695Skan      ci_env.record_method_not_compilable("no compiler", !TieredCompilation);
1806169695Skan    } else {
1807169695Skan      comp->compile_method(&ci_env, target, osr_bci);
1808169695Skan    }
1809169695Skan
1810169695Skan    if (!ci_env.failing() && task->code() == NULL) {
1811169695Skan      //assert(false, "compiler should always document failure");
1812169695Skan      // The compiler elected, without comment, not to register a result.
1813169695Skan      // Do not attempt further compilations of this method.
1814169695Skan      ci_env.record_method_not_compilable("compile failed", !TieredCompilation);
1815169695Skan    }
1816169695Skan
1817169695Skan    // Copy this bit to the enclosing block:
1818169695Skan    compilable = ci_env.compilable();
1819169695Skan
1820169695Skan    if (ci_env.failing()) {
1821169695Skan      const char* retry_message = ci_env.retry_message();
1822169695Skan      if (_compilation_log != NULL) {
1823169695Skan        _compilation_log->log_failure(thread, task, ci_env.failure_reason(), retry_message);
1824169695Skan      }
1825169695Skan      if (PrintCompilation) {
1826169695Skan        FormatBufferResource msg = retry_message != NULL ?
1827169695Skan            err_msg_res("COMPILE SKIPPED: %s (%s)", ci_env.failure_reason(), retry_message) :
1828169695Skan            err_msg_res("COMPILE SKIPPED: %s",      ci_env.failure_reason());
1829169695Skan        task->print_compilation(tty, msg);
1830169695Skan      }
1831169695Skan    } else {
1832169695Skan      task->mark_success();
1833169695Skan      task->set_num_inlined_bytecodes(ci_env.num_inlined_bytecodes());
1834169695Skan      if (_compilation_log != NULL) {
1835169695Skan        nmethod* code = task->code();
1836169695Skan        if (code != NULL) {
1837169695Skan          _compilation_log->log_nmethod(thread, code);
1838169695Skan        }
1839169695Skan      }
1840169695Skan    }
1841169695Skan    // simulate crash during compilation
1842169695Skan    assert(task->compile_id() != CICrashAt, "just as planned");
1843169695Skan    if (event.should_commit()) {
1844169695Skan      event.set_method(target->get_Method());
1845169695Skan      event.set_compileID(compile_id);
1846169695Skan      event.set_compileLevel(task->comp_level());
1847169695Skan      event.set_succeded(task->is_success());
1848169695Skan      event.set_isOsr(is_osr);
1849169695Skan      event.set_codeSize((task->code() == NULL) ? 0 : task->code()->total_size());
1850169695Skan      event.set_inlinedBytes(task->num_inlined_bytecodes());
1851169695Skan      event.commit();
1852169695Skan    }
1853169695Skan  }
1854169695Skan  pop_jni_handle_block();
1855169695Skan
1856169695Skan  methodHandle method(thread, task->method());
1857169695Skan
1858169695Skan  DTRACE_METHOD_COMPILE_END_PROBE(method, compiler_name(task_level), task->is_success());
1859169695Skan
1860169695Skan  collect_statistics(thread, time, task);
1861169695Skan
1862169695Skan  if (PrintCompilation && PrintCompilation2) {
1863169695Skan    tty->print("%7d ", (int) tty->time_stamp().milliseconds());  // print timestamp
1864169695Skan    tty->print("%4d ", compile_id);    // print compilation number
1865169695Skan    tty->print("%s ", (is_osr ? "%" : " "));
1866169695Skan    if (task->code() != NULL) {
1867169695Skan      tty->print("size: %d(%d) ", task->code()->total_size(), task->code()->insts_size());
1868169695Skan    }
1869169695Skan    tty->print_cr("time: %d inlined: %d bytes", (int)time.milliseconds(), task->num_inlined_bytecodes());
1870169695Skan  }
1871169695Skan
1872169695Skan  if (PrintCodeCacheOnCompilation)
1873169695Skan    codecache_print(/* detailed= */ false);
1874169695Skan
1875169695Skan  // Disable compilation, if required.
1876169695Skan  switch (compilable) {
1877169695Skan  case ciEnv::MethodCompilable_never:
1878169695Skan    if (is_osr)
1879169695Skan      method->set_not_osr_compilable_quietly();
1880169695Skan    else
1881169695Skan      method->set_not_compilable_quietly();
1882169695Skan    break;
1883169695Skan  case ciEnv::MethodCompilable_not_at_tier:
1884169695Skan    if (is_osr)
1885169695Skan      method->set_not_osr_compilable_quietly(task_level);
1886169695Skan    else
1887169695Skan      method->set_not_compilable_quietly(task_level);
1888169695Skan    break;
1889169695Skan  }
1890169695Skan
1891169695Skan  // Note that the queued_for_compilation bits are cleared without
1892169695Skan  // protection of a mutex. [They were set by the requester thread,
1893169695Skan  // when adding the task to the complie queue -- at which time the
1894169695Skan  // compile queue lock was held. Subsequently, we acquired the compile
1895169695Skan  // queue lock to get this task off the compile queue; thus (to belabour
1896169695Skan  // the point somewhat) our clearing of the bits must be occurring
1897169695Skan  // only after the setting of the bits. See also 14012000 above.
1898169695Skan  method->clear_queued_for_compilation();
1899169695Skan
1900169695Skan#ifdef ASSERT
1901169695Skan  if (CollectedHeap::fired_fake_oom()) {
1902169695Skan    // The current compile received a fake OOM during compilation so
1903169695Skan    // go ahead and exit the VM since the test apparently succeeded
1904169695Skan    tty->print_cr("*** Shutting down VM after successful fake OOM");
1905169695Skan    vm_exit(0);
1906169695Skan  }
1907169695Skan#endif
1908169695Skan}
1909169695Skan
1910169695Skan// ------------------------------------------------------------------
1911169695Skan// CompileBroker::handle_full_code_cache
1912169695Skan//
1913169695Skan// The CodeCache is full.  Print out warning and disable compilation or
1914169695Skan// try code cache cleaning so compilation can continue later.
1915169695Skanvoid CompileBroker::handle_full_code_cache() {
1916169695Skan  UseInterpreter = true;
1917169695Skan  if (UseCompiler || AlwaysCompileLoopMethods ) {
1918169695Skan    if (xtty != NULL) {
1919169695Skan      ResourceMark rm;
1920169695Skan      stringStream s;
1921169695Skan      // Dump code cache state into a buffer before locking the tty,
1922169695Skan      // because log_state() will use locks causing lock conflicts.
1923169695Skan      CodeCache::log_state(&s);
1924169695Skan      // Lock to prevent tearing
1925169695Skan      ttyLocker ttyl;
1926169695Skan      xtty->begin_elem("code_cache_full");
1927169695Skan      xtty->print(s.as_string());
1928169695Skan      xtty->stamp();
1929169695Skan      xtty->end_elem();
1930169695Skan    }
1931169695Skan    warning("CodeCache is full. Compiler has been disabled.");
1932169695Skan    warning("Try increasing the code cache size using -XX:ReservedCodeCacheSize=");
1933169695Skan
1934169695Skan    CodeCache::report_codemem_full();
1935169695Skan
1936169695Skan
1937169695Skan#ifndef PRODUCT
1938169695Skan    if (CompileTheWorld || ExitOnFullCodeCache) {
1939169695Skan      codecache_print(/* detailed= */ true);
1940169695Skan      before_exit(JavaThread::current());
1941169695Skan      exit_globals(); // will delete tty
1942169695Skan      vm_direct_exit(CompileTheWorld ? 0 : 1);
1943169695Skan    }
1944169695Skan#endif
1945169695Skan    if (UseCodeCacheFlushing) {
1946169695Skan      NMethodSweeper::handle_full_code_cache(true);
1947169695Skan    } else {
1948169695Skan      UseCompiler               = false;
1949169695Skan      AlwaysCompileLoopMethods  = false;
1950169695Skan    }
1951169695Skan  }
1952169695Skan  codecache_print(/* detailed= */ true);
1953169695Skan}
1954169695Skan
1955169695Skan// ------------------------------------------------------------------
1956169695Skan// CompileBroker::set_last_compile
1957169695Skan//
1958169695Skan// Record this compilation for debugging purposes.
1959169695Skanvoid CompileBroker::set_last_compile(CompilerThread* thread, methodHandle method, bool is_osr, int comp_level) {
1960169695Skan  ResourceMark rm;
1961169695Skan  char* method_name = method->name()->as_C_string();
1962169695Skan  strncpy(_last_method_compiled, method_name, CompileBroker::name_buffer_length);
1963169695Skan  char current_method[CompilerCounters::cmname_buffer_length];
1964169695Skan  size_t maxLen = CompilerCounters::cmname_buffer_length;
1965169695Skan
1966169695Skan  if (UsePerfData) {
1967169695Skan    const char* class_name = method->method_holder()->name()->as_C_string();
1968169695Skan
1969169695Skan    size_t s1len = strlen(class_name);
1970169695Skan    size_t s2len = strlen(method_name);
1971169695Skan
1972169695Skan    // check if we need to truncate the string
1973169695Skan    if (s1len + s2len + 2 > maxLen) {
1974169695Skan
1975169695Skan      // the strategy is to lop off the leading characters of the
1976169695Skan      // class name and the trailing characters of the method name.
1977169695Skan
1978169695Skan      if (s2len + 2 > maxLen) {
1979169695Skan        // lop of the entire class name string, let snprintf handle
1980169695Skan        // truncation of the method name.
1981169695Skan        class_name += s1len; // null string
1982169695Skan      }
1983169695Skan      else {
1984169695Skan        // lop off the extra characters from the front of the class name
1985169695Skan        class_name += ((s1len + s2len + 2) - maxLen);
1986169695Skan      }
1987169695Skan    }
1988169695Skan
1989169695Skan    jio_snprintf(current_method, maxLen, "%s %s", class_name, method_name);
1990169695Skan  }
1991169695Skan
1992169695Skan  if (CICountOSR && is_osr) {
1993169695Skan    _last_compile_type = osr_compile;
1994169695Skan  } else {
1995169695Skan    _last_compile_type = normal_compile;
1996169695Skan  }
1997169695Skan  _last_compile_level = comp_level;
1998169695Skan
1999169695Skan  if (UsePerfData) {
2000169695Skan    CompilerCounters* counters = thread->counters();
2001169695Skan    counters->set_current_method(current_method);
2002169695Skan    counters->set_compile_type((jlong)_last_compile_type);
2003169695Skan  }
2004169695Skan}
2005169695Skan
2006169695Skan
2007169695Skan// ------------------------------------------------------------------
2008169695Skan// CompileBroker::push_jni_handle_block
2009169695Skan//
2010169695Skan// Push on a new block of JNI handles.
2011169695Skanvoid CompileBroker::push_jni_handle_block() {
2012169695Skan  JavaThread* thread = JavaThread::current();
2013169695Skan
2014169695Skan  // Allocate a new block for JNI handles.
2015169695Skan  // Inlined code from jni_PushLocalFrame()
2016169695Skan  JNIHandleBlock* java_handles = thread->active_handles();
2017169695Skan  JNIHandleBlock* compile_handles = JNIHandleBlock::allocate_block(thread);
2018169695Skan  assert(compile_handles != NULL && java_handles != NULL, "should not be NULL");
2019169695Skan  compile_handles->set_pop_frame_link(java_handles);  // make sure java handles get gc'd.
2020169695Skan  thread->set_active_handles(compile_handles);
2021169695Skan}
2022169695Skan
2023169695Skan
2024169695Skan// ------------------------------------------------------------------
2025169695Skan// CompileBroker::pop_jni_handle_block
2026169695Skan//
2027169695Skan// Pop off the current block of JNI handles.
2028169695Skanvoid CompileBroker::pop_jni_handle_block() {
2029169695Skan  JavaThread* thread = JavaThread::current();
2030169695Skan
2031169695Skan  // Release our JNI handle block
2032169695Skan  JNIHandleBlock* compile_handles = thread->active_handles();
2033169695Skan  JNIHandleBlock* java_handles = compile_handles->pop_frame_link();
2034169695Skan  thread->set_active_handles(java_handles);
2035169695Skan  compile_handles->set_pop_frame_link(NULL);
2036169695Skan  JNIHandleBlock::release_block(compile_handles, thread); // may block
2037169695Skan}
2038169695Skan
2039169695Skan
2040169695Skan// ------------------------------------------------------------------
2041169695Skan// CompileBroker::check_break_at
2042169695Skan//
2043169695Skan// Should the compilation break at the current compilation.
2044169695Skanbool CompileBroker::check_break_at(methodHandle method, int compile_id, bool is_osr) {
2045169695Skan  if (CICountOSR && is_osr && (compile_id == CIBreakAtOSR)) {
2046169695Skan    return true;
2047169695Skan  } else if( CompilerOracle::should_break_at(method) ) { // break when compiling
2048169695Skan    return true;
2049169695Skan  } else {
2050169695Skan    return (compile_id == CIBreakAt);
2051169695Skan  }
2052169695Skan}
2053169695Skan
2054169695Skan// ------------------------------------------------------------------
2055169695Skan// CompileBroker::collect_statistics
2056169695Skan//
2057169695Skan// Collect statistics about the compilation.
2058169695Skan
2059169695Skanvoid CompileBroker::collect_statistics(CompilerThread* thread, elapsedTimer time, CompileTask* task) {
2060169695Skan  bool success = task->is_success();
2061169695Skan  methodHandle method (thread, task->method());
2062169695Skan  uint compile_id = task->compile_id();
2063169695Skan  bool is_osr = (task->osr_bci() != standard_entry_bci);
2064169695Skan  nmethod* code = task->code();
2065169695Skan  CompilerCounters* counters = thread->counters();
2066169695Skan
2067169695Skan  assert(code == NULL || code->is_locked_by_vm(), "will survive the MutexLocker");
2068169695Skan  MutexLocker locker(CompileStatistics_lock);
2069169695Skan
2070169695Skan  // _perf variables are production performance counters which are
2071169695Skan  // updated regardless of the setting of the CITime and CITimeEach flags
2072169695Skan  //
2073169695Skan  if (!success) {
2074169695Skan    _total_bailout_count++;
2075169695Skan    if (UsePerfData) {
2076169695Skan      _perf_last_failed_method->set_value(counters->current_method());
2077169695Skan      _perf_last_failed_type->set_value(counters->compile_type());
2078169695Skan      _perf_total_bailout_count->inc();
2079169695Skan    }
2080169695Skan  } else if (code == NULL) {
2081169695Skan    if (UsePerfData) {
2082169695Skan      _perf_last_invalidated_method->set_value(counters->current_method());
2083169695Skan      _perf_last_invalidated_type->set_value(counters->compile_type());
2084169695Skan      _perf_total_invalidated_count->inc();
2085169695Skan    }
2086169695Skan    _total_invalidated_count++;
2087169695Skan  } else {
2088169695Skan    // Compilation succeeded
2089169695Skan
2090169695Skan    // update compilation ticks - used by the implementation of
2091169695Skan    // java.lang.management.CompilationMBean
2092169695Skan    _perf_total_compilation->inc(time.ticks());
2093169695Skan
2094169695Skan    _t_total_compilation.add(time);
2095169695Skan    _peak_compilation_time = time.milliseconds() > _peak_compilation_time ? time.milliseconds() : _peak_compilation_time;
2096169695Skan
2097169695Skan    if (CITime) {
2098169695Skan      if (is_osr) {
2099169695Skan        _t_osr_compilation.add(time);
2100169695Skan        _sum_osr_bytes_compiled += method->code_size() + task->num_inlined_bytecodes();
2101169695Skan      } else {
2102169695Skan        _t_standard_compilation.add(time);
2103169695Skan        _sum_standard_bytes_compiled += method->code_size() + task->num_inlined_bytecodes();
2104169695Skan      }
2105169695Skan    }
2106169695Skan
2107169695Skan    if (UsePerfData) {
2108169695Skan      // save the name of the last method compiled
2109169695Skan      _perf_last_method->set_value(counters->current_method());
2110169695Skan      _perf_last_compile_type->set_value(counters->compile_type());
2111169695Skan      _perf_last_compile_size->set_value(method->code_size() +
2112169695Skan                                         task->num_inlined_bytecodes());
2113169695Skan      if (is_osr) {
2114169695Skan        _perf_osr_compilation->inc(time.ticks());
2115169695Skan        _perf_sum_osr_bytes_compiled->inc(method->code_size() + task->num_inlined_bytecodes());
2116169695Skan      } else {
2117169695Skan        _perf_standard_compilation->inc(time.ticks());
2118169695Skan        _perf_sum_standard_bytes_compiled->inc(method->code_size() + task->num_inlined_bytecodes());
2119169695Skan      }
2120169695Skan    }
2121169695Skan
2122169695Skan    if (CITimeEach) {
2123169695Skan      float bytes_per_sec = 1.0 * (method->code_size() + task->num_inlined_bytecodes()) / time.seconds();
2124169695Skan      tty->print_cr("%3d   seconds: %f bytes/sec : %f (bytes %d + %d inlined)",
2125169695Skan                    compile_id, time.seconds(), bytes_per_sec, method->code_size(), task->num_inlined_bytecodes());
2126169695Skan    }
2127169695Skan
2128169695Skan    // Collect counts of successful compilations
2129169695Skan    _sum_nmethod_size      += code->total_size();
2130169695Skan    _sum_nmethod_code_size += code->insts_size();
2131169695Skan    _total_compile_count++;
2132169695Skan
2133169695Skan    if (UsePerfData) {
2134169695Skan      _perf_sum_nmethod_size->inc(     code->total_size());
2135169695Skan      _perf_sum_nmethod_code_size->inc(code->insts_size());
2136169695Skan      _perf_total_compile_count->inc();
2137169695Skan    }
2138169695Skan
2139169695Skan    if (is_osr) {
2140169695Skan      if (UsePerfData) _perf_total_osr_compile_count->inc();
2141169695Skan      _total_osr_compile_count++;
2142169695Skan    } else {
2143169695Skan      if (UsePerfData) _perf_total_standard_compile_count->inc();
2144169695Skan      _total_standard_compile_count++;
2145169695Skan    }
2146169695Skan  }
2147169695Skan  // set the current method for the thread to null
2148169695Skan  if (UsePerfData) counters->set_current_method("");
2149169695Skan}
2150169695Skan
2151169695Skanconst char* CompileBroker::compiler_name(int comp_level) {
2152169695Skan  AbstractCompiler *comp = CompileBroker::compiler(comp_level);
2153169695Skan  if (comp == NULL) {
2154169695Skan    return "no compiler";
2155169695Skan  } else {
2156169695Skan    return (comp->name());
2157169695Skan  }
2158169695Skan}
2159169695Skan
2160169695Skanvoid CompileBroker::print_times() {
2161169695Skan  tty->cr();
2162169695Skan  tty->print_cr("Accumulated compiler times (for compiled methods only)");
2163169695Skan  tty->print_cr("------------------------------------------------");
2164169695Skan               //0000000000111111111122222222223333333333444444444455555555556666666666
2165169695Skan               //0123456789012345678901234567890123456789012345678901234567890123456789
2166169695Skan  tty->print_cr("  Total compilation time   : %6.3f s", CompileBroker::_t_total_compilation.seconds());
2167169695Skan  tty->print_cr("    Standard compilation   : %6.3f s, Average : %2.3f",
2168169695Skan                CompileBroker::_t_standard_compilation.seconds(),
2169169695Skan                CompileBroker::_t_standard_compilation.seconds() / CompileBroker::_total_standard_compile_count);
2170169695Skan  tty->print_cr("    On stack replacement   : %6.3f s, Average : %2.3f", CompileBroker::_t_osr_compilation.seconds(), CompileBroker::_t_osr_compilation.seconds() / CompileBroker::_total_osr_compile_count);
2171169695Skan
2172169695Skan  AbstractCompiler *comp = compiler(CompLevel_simple);
2173169695Skan  if (comp != NULL) {
2174169695Skan    comp->print_timers();
2175169695Skan  }
2176169695Skan  comp = compiler(CompLevel_full_optimization);
2177169695Skan  if (comp != NULL) {
2178169695Skan    comp->print_timers();
2179169695Skan  }
2180169695Skan  tty->cr();
2181169695Skan  tty->print_cr("  Total compiled methods   : %6d methods", CompileBroker::_total_compile_count);
2182169695Skan  tty->print_cr("    Standard compilation   : %6d methods", CompileBroker::_total_standard_compile_count);
2183169695Skan  tty->print_cr("    On stack replacement   : %6d methods", CompileBroker::_total_osr_compile_count);
2184169695Skan  int tcb = CompileBroker::_sum_osr_bytes_compiled + CompileBroker::_sum_standard_bytes_compiled;
2185169695Skan  tty->print_cr("  Total compiled bytecodes : %6d bytes", tcb);
2186169695Skan  tty->print_cr("    Standard compilation   : %6d bytes", CompileBroker::_sum_standard_bytes_compiled);
2187169695Skan  tty->print_cr("    On stack replacement   : %6d bytes", CompileBroker::_sum_osr_bytes_compiled);
2188169695Skan  int bps = (int)(tcb / CompileBroker::_t_total_compilation.seconds());
2189169695Skan  tty->print_cr("  Average compilation speed: %6d bytes/s", bps);
2190169695Skan  tty->cr();
2191169695Skan  tty->print_cr("  nmethod code size        : %6d bytes", CompileBroker::_sum_nmethod_code_size);
2192169695Skan  tty->print_cr("  nmethod total size       : %6d bytes", CompileBroker::_sum_nmethod_size);
2193169695Skan}
2194169695Skan
2195169695Skan// Debugging output for failure
2196169695Skanvoid CompileBroker::print_last_compile() {
2197169695Skan  if ( _last_compile_level != CompLevel_none &&
2198169695Skan       compiler(_last_compile_level) != NULL &&
2199169695Skan       _last_method_compiled != NULL &&
2200169695Skan       _last_compile_type != no_compile) {
2201169695Skan    if (_last_compile_type == osr_compile) {
2202169695Skan      tty->print_cr("Last parse:  [osr]%d+++(%d) %s",
2203169695Skan                    _osr_compilation_id, _last_compile_level, _last_method_compiled);
2204169695Skan    } else {
2205169695Skan      tty->print_cr("Last parse:  %d+++(%d) %s",
2206169695Skan                    _compilation_id, _last_compile_level, _last_method_compiled);
2207169695Skan    }
2208169695Skan  }
2209169695Skan}
2210169695Skan
2211169695Skan
2212169695Skanvoid CompileBroker::print_compiler_threads_on(outputStream* st) {
2213169695Skan#ifndef PRODUCT
2214169695Skan  st->print_cr("Compiler thread printing unimplemented.");
2215169695Skan  st->cr();
2216169695Skan#endif
2217169695Skan}
2218169695Skan