1 /*
  2  * Copyright (c) 1998, 2025, Oracle and/or its affiliates. All rights reserved.
  3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  4  *
  5  * This code is free software; you can redistribute it and/or modify it
  6  * under the terms of the GNU General Public License version 2 only, as
  7  * published by the Free Software Foundation.
  8  *
  9  * This code is distributed in the hope that it will be useful, but WITHOUT
 10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 12  * version 2 for more details (a copy is included in the LICENSE file that
 13  * accompanied this code).
 14  *
 15  * You should have received a copy of the GNU General Public License version
 16  * 2 along with this work; if not, write to the Free Software Foundation,
 17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 18  *
 19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 20  * or visit www.oracle.com if you need additional information or have any
 21  * questions.
 22  *
 23  */
 24 
 25 #include "compiler/compilationPolicy.hpp"
 26 #include "compiler/compileBroker.hpp"
 27 #include "compiler/compileLog.hpp"
 28 #include "compiler/compilerDirectives.hpp"
 29 #include "compiler/compileTask.hpp"
 30 #include "logging/log.hpp"
 31 #include "logging/logStream.hpp"
 32 #include "memory/resourceArea.hpp"
 33 #include "oops/klass.inline.hpp"
 34 #include "oops/method.inline.hpp"
 35 #include "runtime/handles.inline.hpp"
 36 #include "runtime/jniHandles.hpp"
 37 #include "runtime/mutexLocker.hpp"
 38 
 39 int CompileTask::_active_tasks = 0;
 40 
 41 CompileTask::CompileTask(int compile_id,
 42                          const methodHandle& method,
 43                          int osr_bci,
 44                          int comp_level,
 45                          int hot_count,
 46                          CompileReason compile_reason,
 47                          bool is_blocking) {
 48   Thread* thread = Thread::current();
 49   _compile_id = compile_id;
 50   _method = method();
 51   _method_holder = JNIHandles::make_weak_global(Handle(thread, method->method_holder()->klass_holder()));
 52   _osr_bci = osr_bci;
 53   _is_blocking = is_blocking;
 54   JVMCI_ONLY(_has_waiter = CompileBroker::compiler(comp_level)->is_jvmci();)
 55   JVMCI_ONLY(_blocking_jvmci_compile_state = nullptr;)
 56   _comp_level = comp_level;
 57   _num_inlined_bytecodes = 0;
 58 
 59   _is_complete = false;
 60   _is_success = false;
 61 
 62   _hot_count = hot_count;
 63   _time_queued = os::elapsed_counter();
 64   _time_started = 0;
 65   _compile_reason = compile_reason;
 66   _nm_content_size = 0;
 67   AbstractCompiler* comp = compiler();
 68   _directive = DirectivesStack::getMatchingDirective(method, comp);
 69   _nm_insts_size = 0;
 70   _nm_total_size = 0;
 71   _failure_reason = nullptr;
 72   _failure_reason_on_C_heap = false;
 73   _training_data = nullptr;
 74   _arena_bytes = 0;
 75 
 76   _next = nullptr;
 77   _prev = nullptr;
 78 
 79   Atomic::add(&_active_tasks, 1, memory_order_relaxed);
 80 }
 81 
 82 CompileTask::~CompileTask() {
 83   if (_method_holder != nullptr && JNIHandles::is_weak_global_handle(_method_holder)) {
 84     JNIHandles::destroy_weak_global(_method_holder);
 85   } else {
 86     JNIHandles::destroy_global(_method_holder);
 87   }
 88   if (_failure_reason_on_C_heap && _failure_reason != nullptr) {
 89     os::free((void*) _failure_reason);
 90     _failure_reason = nullptr;
 91     _failure_reason_on_C_heap = false;
 92   }
 93 
 94   if (Atomic::sub(&_active_tasks, 1, memory_order_relaxed) == 0) {
 95     MonitorLocker wait_ml(CompileTaskWait_lock);
 96     wait_ml.notify_all();
 97   }
 98 }
 99 
100 void CompileTask::wait_for_no_active_tasks() {
101   MonitorLocker locker(CompileTaskWait_lock);
102   while (Atomic::load(&_active_tasks) > 0) {
103     locker.wait();
104   }
105 }
106 
107 /**
108  * Returns the compiler for this task.
109  */
110 AbstractCompiler* CompileTask::compiler() const {
111   return CompileBroker::compiler(_comp_level);
112 }
113 
114 // Replace weak handles by strong handles to avoid unloading during compilation.
115 CompileTask* CompileTask::select_for_compilation() {
116   if (is_unloaded()) {
117     // Guard against concurrent class unloading
118     return nullptr;
119   }
120   Thread* thread = Thread::current();
121   assert(_method->method_holder()->is_loader_alive(), "should be alive");
122   Handle method_holder(thread, _method->method_holder()->klass_holder());
123   JNIHandles::destroy_weak_global(_method_holder);
124   _method_holder = JNIHandles::make_global(method_holder);
125   return this;
126 }
127 
128 void CompileTask::mark_on_stack() {
129   if (is_unloaded()) {
130     return;
131   }
132   // Mark these methods as something redefine classes cannot remove.
133   _method->set_on_stack(true);
134 }
135 
136 bool CompileTask::is_unloaded() const {
137   return _method_holder != nullptr && JNIHandles::is_weak_global_handle(_method_holder) && JNIHandles::is_weak_global_cleared(_method_holder);
138 }
139 
140 // RedefineClasses support
141 void CompileTask::metadata_do(MetadataClosure* f) {
142   if (is_unloaded()) {
143     return;
144   }
145   f->do_metadata(method());
146 }
147 
148 // ------------------------------------------------------------------
149 // CompileTask::print_line_on_error
150 //
151 // This function is called by fatal error handler when the thread
152 // causing troubles is a compiler thread.
153 //
154 // Do not grab any lock, do not allocate memory.
155 //
156 // Otherwise it's the same as CompileTask::print_line()
157 //
158 void CompileTask::print_line_on_error(outputStream* st, char* buf, int buflen) {
159   // print compiler name
160   st->print("%s:", CompileBroker::compiler_name(comp_level()));
161   print(st);
162 }
163 
164 // ------------------------------------------------------------------
165 // CompileTask::print_tty
166 void CompileTask::print_tty() {
167   ttyLocker ttyl;  // keep the following output all in one block
168   print(tty);
169 }
170 
171 // ------------------------------------------------------------------
172 // CompileTask::print_impl
173 void CompileTask::print_impl(outputStream* st, Method* method, int compile_id, int comp_level,
174                              bool is_osr_method, int osr_bci, bool is_blocking,
175                              const char* msg, bool short_form, bool cr,
176                              jlong time_queued, jlong time_started) {
177   if (!short_form) {
178     // Print current time
179     st->print(UINT64_FORMAT " ", (uint64_t) tty->time_stamp().milliseconds());
180     if (Verbose && time_queued != 0) {
181       // Print time in queue and time being processed by compiler thread
182       jlong now = os::elapsed_counter();
183       st->print("%.0f ", TimeHelper::counter_to_millis(now-time_queued));
184       if (time_started != 0) {
185         st->print("%.0f ", TimeHelper::counter_to_millis(now-time_started));
186       }
187     }
188   }
189   // print compiler name if requested
190   if (CIPrintCompilerName) {
191     st->print("%s:", CompileBroker::compiler_name(comp_level));
192   }
193   st->print("%4d ", compile_id);    // print compilation number
194 
195   bool is_synchronized = false;
196   bool has_exception_handler = false;
197   bool is_native = false;
198   if (method != nullptr) {
199     is_synchronized       = method->is_synchronized();
200     has_exception_handler = method->has_exception_handler();
201     is_native             = method->is_native();
202   }
203   // method attributes
204   const char compile_type   = is_osr_method                   ? '%' : ' ';
205   const char sync_char      = is_synchronized                 ? 's' : ' ';
206   const char exception_char = has_exception_handler           ? '!' : ' ';
207   const char blocking_char  = is_blocking                     ? 'b' : ' ';
208   const char native_char    = is_native                       ? 'n' : ' ';
209 
210   // print method attributes
211   st->print("%c%c%c%c%c ", compile_type, sync_char, exception_char, blocking_char, native_char);
212 
213   if (TieredCompilation) {
214     if (comp_level != -1)  st->print("%d ", comp_level);
215     else                   st->print("- ");
216   }
217   st->print("     ");  // more indent
218 
219   if (method == nullptr) {
220     st->print("(method)");
221   } else {
222     method->print_short_name(st);
223     if (is_osr_method) {
224       st->print(" @ %d", osr_bci);
225     }
226     if (method->is_native())
227       st->print(" (native)");
228     else
229       st->print(" (%d bytes)", method->code_size());
230   }
231 
232   if (msg != nullptr) {
233     st->print("   %s", msg);
234   }
235   if (cr) {
236     st->cr();
237   }
238 }
239 
240 // ------------------------------------------------------------------
241 // CompileTask::print_compilation
242 void CompileTask::print(outputStream* st, const char* msg, bool short_form, bool cr) {
243   bool is_osr_method = osr_bci() != InvocationEntryBci;
244   print_impl(st, is_unloaded() ? nullptr : method(), compile_id(), comp_level(), is_osr_method, osr_bci(), is_blocking(), msg, short_form, cr, _time_queued, _time_started);
245 }
246 
247 // ------------------------------------------------------------------
248 // CompileTask::log_task
249 void CompileTask::log_task(xmlStream* log) {
250   Thread* thread = Thread::current();
251   methodHandle method(thread, this->method());
252   ResourceMark rm(thread);
253 
254   // <task id='9' method='M' osr_bci='X' level='1' blocking='1' stamp='1.234'>
255   log->print(" compile_id='%d'", _compile_id);
256   if (_osr_bci != CompileBroker::standard_entry_bci) {
257     log->print(" compile_kind='osr'");  // same as nmethod::compile_kind
258   } // else compile_kind='c2c'
259   if (!method.is_null())  log->method(method());
260   if (_osr_bci != CompileBroker::standard_entry_bci) {
261     log->print(" osr_bci='%d'", _osr_bci);
262   }
263   if (_comp_level != CompilationPolicy::highest_compile_level()) {
264     log->print(" level='%d'", _comp_level);
265   }
266   if (_is_blocking) {
267     log->print(" blocking='1'");
268   }
269   log->stamp();
270 }
271 
272 // ------------------------------------------------------------------
273 // CompileTask::log_task_queued
274 void CompileTask::log_task_queued() {
275   ttyLocker ttyl;
276   ResourceMark rm;
277   NoSafepointVerifier nsv;
278 
279   xtty->begin_elem("task_queued");
280   log_task(xtty);
281   assert(_compile_reason > CompileTask::Reason_None && _compile_reason < CompileTask::Reason_Count, "Valid values");
282   xtty->print(" comment='%s'", reason_name(_compile_reason));
283 
284   if (_hot_count != 0) {
285     xtty->print(" hot_count='%d'", _hot_count);
286   }
287   xtty->end_elem();
288 }
289 
290 
291 // ------------------------------------------------------------------
292 // CompileTask::log_task_start
293 void CompileTask::log_task_start(CompileLog* log)   {
294   log->begin_head("task");
295   log_task(log);
296   log->end_head();
297 }
298 
299 
300 // ------------------------------------------------------------------
301 // CompileTask::log_task_done
302 void CompileTask::log_task_done(CompileLog* log) {
303   Thread* thread = Thread::current();
304   methodHandle method(thread, this->method());
305   ResourceMark rm(thread);
306 
307   if (!_is_success) {
308     assert(_failure_reason != nullptr, "missing");
309     const char* reason = _failure_reason != nullptr ? _failure_reason : "unknown";
310     log->begin_elem("failure reason='");
311     log->text("%s", reason);
312     log->print("'");
313     log->end_elem();
314   }
315 
316   // <task_done ... stamp='1.234'>  </task>
317   log->begin_elem("task_done success='%d' nmsize='%d' count='%d'",
318                   _is_success, _nm_content_size,
319                   method->invocation_count());
320   int bec = method->backedge_count();
321   if (bec != 0)  log->print(" backedge_count='%d'", bec);
322   // Note:  "_is_complete" is about to be set, but is not.
323   if (_num_inlined_bytecodes != 0) {
324     log->print(" inlined_bytes='%d'", _num_inlined_bytecodes);
325   }
326   log->stamp();
327   log->end_elem();
328   log->clear_identities();   // next task will have different CI
329   log->tail("task");
330   log->flush();
331   log->mark_file_end();
332 }
333 
334 // ------------------------------------------------------------------
335 // CompileTask::check_break_at_flags
336 bool CompileTask::check_break_at_flags() {
337   int compile_id = this->_compile_id;
338   bool is_osr = (_osr_bci != CompileBroker::standard_entry_bci);
339 
340   if (CICountOSR && is_osr && (compile_id == CIBreakAtOSR)) {
341     return true;
342   } else {
343     return (compile_id == CIBreakAt);
344   }
345 }
346 
347 // ------------------------------------------------------------------
348 // CompileTask::print_inlining
349 void CompileTask::print_inlining_inner(outputStream* st, ciMethod* method, int inline_level, int bci, InliningResult result, const char* msg) {
350   print_inlining_header(st, method, inline_level, bci);
351   print_inlining_inner_message(st, result, msg);
352   st->cr();
353 }
354 
355 void CompileTask::print_inlining_header(outputStream* st, ciMethod* method, int inline_level, int bci) {
356   //         1234567
357   st->print("        "); // print timestamp
358   //         1234
359   st->print("     "); // print compilation number
360 
361   // method attributes
362   if (method->is_loaded()) {
363     const char sync_char = method->is_synchronized() ? 's' : ' ';
364     const char exception_char = method->has_exception_handlers() ? '!' : ' ';
365     const char monitors_char = method->has_monitor_bytecodes() ? 'm' : ' ';
366 
367     // print method attributes
368     st->print(" %c%c%c  ", sync_char, exception_char, monitors_char);
369   } else {
370     //         %s!bn
371     st->print("      "); // print method attributes
372   }
373 
374   if (TieredCompilation) {
375     st->print("  ");
376   }
377   st->print("     "); // more indent
378   st->print("    ");  // initial inlining indent
379 
380   for (int i = 0; i < inline_level; i++) {
381     st->print("  ");
382   }
383 
384   st->print("@ %d  ", bci); // print bci
385   print_inline_inner_method_info(st, method);
386 }
387 
388 void CompileTask::print_inline_inner_method_info(outputStream* st, ciMethod* method) {
389   method->print_short_name(st);
390   if (method->is_loaded()) {
391     st->print(" (%d bytes)", method->code_size());
392   } else {
393     st->print(" (not loaded)");
394   }
395 }
396 
397 void CompileTask::print_inline_indent(int inline_level, outputStream* st) {
398   //         1234567
399   st->print("        "); // print timestamp
400   //         1234
401   st->print("     "); // print compilation number
402   //         %s!bn
403   st->print("      "); // print method attributes
404   if (TieredCompilation) {
405     st->print("  ");
406   }
407   st->print("     "); // more indent
408   st->print("    ");  // initial inlining indent
409   for (int i = 0; i < inline_level; i++) {
410     st->print("  ");
411   }
412 }
413 
414 void CompileTask::print_inlining_inner_message(outputStream* st, InliningResult result, const char* msg) {
415   if (msg != nullptr) {
416     st->print("   %s%s", result == InliningResult::SUCCESS ? "" : "failed to inline: ", msg);
417   } else if (result == InliningResult::FAILURE) {
418     st->print("   %s", "failed to inline");
419   }
420 }
421 
422 void CompileTask::print_ul(const char* msg){
423   LogTarget(Info, jit, compilation) lt;
424   if (lt.is_enabled()) {
425     LogStream ls(lt);
426     print(&ls, msg, /* short form */ true, /* cr */ true);
427   }
428 }
429 
430 void CompileTask::print_ul(const nmethod* nm, const char* msg) {
431   LogTarget(Info, jit, compilation) lt;
432   if (lt.is_enabled()) {
433     LogStream ls(lt);
434     print_impl(&ls, nm->method(), nm->compile_id(),
435                nm->comp_level(), nm->is_osr_method(),
436                nm->is_osr_method() ? nm->osr_entry_bci() : -1,
437                /*is_blocking*/ false,
438                msg, /* short form */ true, /* cr */ true);
439   }
440 }
441 
442 void CompileTask::print_inlining_ul(ciMethod* method, int inline_level, int bci, InliningResult result, const char* msg) {
443   LogTarget(Debug, jit, inlining) lt;
444   if (lt.is_enabled()) {
445     LogStream ls(lt);
446     print_inlining_inner(&ls, method, inline_level, bci, result, msg);
447   }
448 }
449