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/compileTask.hpp"
 27 #include "compiler/compileLog.hpp"
 28 #include "compiler/compileBroker.hpp"
 29 #include "compiler/compilerDirectives.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 CompileTask*  CompileTask::_task_free_list = nullptr;
 40 
 41 /**
 42  * Allocate a CompileTask, from the free list if possible.
 43  */
 44 CompileTask* CompileTask::allocate() {
 45   MutexLocker locker(CompileTaskAlloc_lock);
 46   CompileTask* task = nullptr;
 47 
 48   if (_task_free_list != nullptr) {
 49     task = _task_free_list;
 50     _task_free_list = task->next();
 51     task->set_next(nullptr);
 52   } else {
 53     task = new CompileTask();
 54     task->set_next(nullptr);
 55     task->set_is_free(true);
 56   }
 57   assert(task->is_free(), "Task must be free.");
 58   task->set_is_free(false);
 59   return task;
 60 }
 61 
 62 /**
 63 * Add a task to the free list.
 64 */
 65 void CompileTask::free(CompileTask* task) {
 66   MutexLocker locker(CompileTaskAlloc_lock);
 67   if (!task->is_free()) {
 68     assert(!task->lock()->is_locked(), "Should not be locked when freed");
 69     if ((task->_method_holder != nullptr && JNIHandles::is_weak_global_handle(task->_method_holder)) ||
 70         (task->_hot_method_holder != nullptr && JNIHandles::is_weak_global_handle(task->_hot_method_holder))) {
 71       JNIHandles::destroy_weak_global(task->_method_holder);
 72       JNIHandles::destroy_weak_global(task->_hot_method_holder);
 73     } else {
 74       JNIHandles::destroy_global(task->_method_holder);
 75       JNIHandles::destroy_global(task->_hot_method_holder);
 76     }
 77     if (task->_failure_reason_on_C_heap && task->_failure_reason != nullptr) {
 78       os::free((void*) task->_failure_reason);
 79     }
 80     task->_failure_reason = nullptr;
 81     task->_failure_reason_on_C_heap = false;
 82 
 83     task->set_is_free(true);
 84     task->set_next(_task_free_list);
 85     _task_free_list = task;
 86   }
 87 }
 88 
 89 void CompileTask::initialize(int compile_id,
 90                              const methodHandle& method,
 91                              int osr_bci,
 92                              int comp_level,
 93                              const methodHandle& hot_method,
 94                              int hot_count,
 95                              CompileTask::CompileReason compile_reason,
 96                              bool is_blocking) {
 97   assert(!_lock->is_locked(), "bad locking");
 98 
 99   Thread* thread = Thread::current();
100   _compile_id = compile_id;
101   _method = method();
102   _method_holder = JNIHandles::make_weak_global(Handle(thread, method->method_holder()->klass_holder()));
103   _osr_bci = osr_bci;
104   _is_blocking = is_blocking;
105   JVMCI_ONLY(_has_waiter = CompileBroker::compiler(comp_level)->is_jvmci();)
106   JVMCI_ONLY(_blocking_jvmci_compile_state = nullptr;)
107   _comp_level = comp_level;
108   _num_inlined_bytecodes = 0;
109 
110   _waiting_count = 0;
111 
112   _is_complete = false;
113   _is_success = false;
114 
115   _hot_method = nullptr;
116   _hot_method_holder = nullptr;
117   _hot_count = hot_count;
118   _time_queued = os::elapsed_counter();
119   _time_started = 0;
120   _compile_reason = compile_reason;
121   _nm_content_size = 0;
122   AbstractCompiler* comp = compiler();
123   _directive = DirectivesStack::getMatchingDirective(method, comp);
124   _nm_insts_size = 0;
125   _nm_total_size = 0;
126   _failure_reason = nullptr;
127   _failure_reason_on_C_heap = false;
128   _arena_bytes = 0;
129 
130   if (LogCompilation) {
131     if (hot_method.not_null()) {
132       if (hot_method == method) {
133         _hot_method = _method;
134       } else {
135         _hot_method = hot_method();
136         // only add loader or mirror if different from _method_holder
137         _hot_method_holder = JNIHandles::make_weak_global(Handle(thread, hot_method->method_holder()->klass_holder()));
138       }
139     }
140   }
141 
142   _next = nullptr;
143 }
144 
145 /**
146  * Returns the compiler for this task.
147  */
148 AbstractCompiler* CompileTask::compiler() const {
149   return CompileBroker::compiler(_comp_level);
150 }
151 
152 // Replace weak handles by strong handles to avoid unloading during compilation.
153 CompileTask* CompileTask::select_for_compilation() {
154   if (is_unloaded()) {
155     // Guard against concurrent class unloading
156     return nullptr;
157   }
158   Thread* thread = Thread::current();
159   assert(_method->method_holder()->is_loader_alive(), "should be alive");
160   Handle method_holder(thread, _method->method_holder()->klass_holder());
161   JNIHandles::destroy_weak_global(_method_holder);
162   JNIHandles::destroy_weak_global(_hot_method_holder);
163   _method_holder = JNIHandles::make_global(method_holder);
164   if (_hot_method != nullptr) {
165     _hot_method_holder = JNIHandles::make_global(Handle(thread, _hot_method->method_holder()->klass_holder()));
166   }
167   return this;
168 }
169 
170 void CompileTask::mark_on_stack() {
171   if (is_unloaded()) {
172     return;
173   }
174   // Mark these methods as something redefine classes cannot remove.
175   _method->set_on_stack(true);
176   if (_hot_method != nullptr) {
177     _hot_method->set_on_stack(true);
178   }
179 }
180 
181 bool CompileTask::is_unloaded() const {
182   return _method_holder != nullptr && JNIHandles::is_weak_global_handle(_method_holder) && JNIHandles::is_weak_global_cleared(_method_holder);
183 }
184 
185 // RedefineClasses support
186 void CompileTask::metadata_do(MetadataClosure* f) {
187   if (is_unloaded()) {
188     return;
189   }
190   f->do_metadata(method());
191   if (hot_method() != nullptr && hot_method() != method()) {
192     f->do_metadata(hot_method());
193   }
194 }
195 
196 // ------------------------------------------------------------------
197 // CompileTask::print_line_on_error
198 //
199 // This function is called by fatal error handler when the thread
200 // causing troubles is a compiler thread.
201 //
202 // Do not grab any lock, do not allocate memory.
203 //
204 // Otherwise it's the same as CompileTask::print_line()
205 //
206 void CompileTask::print_line_on_error(outputStream* st, char* buf, int buflen) {
207   // print compiler name
208   st->print("%s:", CompileBroker::compiler_name(comp_level()));
209   print(st);
210 }
211 
212 // ------------------------------------------------------------------
213 // CompileTask::print_tty
214 void CompileTask::print_tty() {
215   ttyLocker ttyl;  // keep the following output all in one block
216   print(tty);
217 }
218 
219 // ------------------------------------------------------------------
220 // CompileTask::print_impl
221 void CompileTask::print_impl(outputStream* st, Method* method, int compile_id, int comp_level,
222                              bool is_osr_method, int osr_bci, bool is_blocking,
223                              const char* msg, bool short_form, bool cr,
224                              jlong time_queued, jlong time_started) {
225   if (!short_form) {
226     // Print current time
227     st->print(UINT64_FORMAT " ", (uint64_t) tty->time_stamp().milliseconds());
228     if (Verbose && time_queued != 0) {
229       // Print time in queue and time being processed by compiler thread
230       jlong now = os::elapsed_counter();
231       st->print("%.0f ", TimeHelper::counter_to_millis(now-time_queued));
232       if (time_started != 0) {
233         st->print("%.0f ", TimeHelper::counter_to_millis(now-time_started));
234       }
235     }
236   }
237   // print compiler name if requested
238   if (CIPrintCompilerName) {
239     st->print("%s:", CompileBroker::compiler_name(comp_level));
240   }
241   st->print("%4d ", compile_id);    // print compilation number
242 
243   bool is_synchronized = false;
244   bool has_exception_handler = false;
245   bool is_native = false;
246   if (method != nullptr) {
247     is_synchronized       = method->is_synchronized();
248     has_exception_handler = method->has_exception_handler();
249     is_native             = method->is_native();
250   }
251   // method attributes
252   const char compile_type   = is_osr_method                   ? '%' : ' ';
253   const char sync_char      = is_synchronized                 ? 's' : ' ';
254   const char exception_char = has_exception_handler           ? '!' : ' ';
255   const char blocking_char  = is_blocking                     ? 'b' : ' ';
256   const char native_char    = is_native                       ? 'n' : ' ';
257 
258   // print method attributes
259   st->print("%c%c%c%c%c ", compile_type, sync_char, exception_char, blocking_char, native_char);
260 
261   if (TieredCompilation) {
262     if (comp_level != -1)  st->print("%d ", comp_level);
263     else                   st->print("- ");
264   }
265   st->print("     ");  // more indent
266 
267   if (method == nullptr) {
268     st->print("(method)");
269   } else {
270     method->print_short_name(st);
271     if (is_osr_method) {
272       st->print(" @ %d", osr_bci);
273     }
274     if (method->is_native())
275       st->print(" (native)");
276     else
277       st->print(" (%d bytes)", method->code_size());
278   }
279 
280   if (msg != nullptr) {
281     st->print("   %s", msg);
282   }
283   if (cr) {
284     st->cr();
285   }
286 }
287 
288 // ------------------------------------------------------------------
289 // CompileTask::print_compilation
290 void CompileTask::print(outputStream* st, const char* msg, bool short_form, bool cr) {
291   bool is_osr_method = osr_bci() != InvocationEntryBci;
292   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);
293 }
294 
295 // ------------------------------------------------------------------
296 // CompileTask::log_task
297 void CompileTask::log_task(xmlStream* log) {
298   Thread* thread = Thread::current();
299   methodHandle method(thread, this->method());
300   ResourceMark rm(thread);
301 
302   // <task id='9' method='M' osr_bci='X' level='1' blocking='1' stamp='1.234'>
303   log->print(" compile_id='%d'", _compile_id);
304   if (_osr_bci != CompileBroker::standard_entry_bci) {
305     log->print(" compile_kind='osr'");  // same as nmethod::compile_kind
306   } // else compile_kind='c2c'
307   if (!method.is_null())  log->method(method());
308   if (_osr_bci != CompileBroker::standard_entry_bci) {
309     log->print(" osr_bci='%d'", _osr_bci);
310   }
311   if (_comp_level != CompilationPolicy::highest_compile_level()) {
312     log->print(" level='%d'", _comp_level);
313   }
314   if (_is_blocking) {
315     log->print(" blocking='1'");
316   }
317   log->stamp();
318 }
319 
320 // ------------------------------------------------------------------
321 // CompileTask::log_task_queued
322 void CompileTask::log_task_queued() {
323   ttyLocker ttyl;
324   ResourceMark rm;
325   NoSafepointVerifier nsv;
326 
327   xtty->begin_elem("task_queued");
328   log_task(xtty);
329   assert(_compile_reason > CompileTask::Reason_None && _compile_reason < CompileTask::Reason_Count, "Valid values");
330   xtty->print(" comment='%s'", reason_name(_compile_reason));
331 
332   if (_hot_method != nullptr && _hot_method != _method) {
333     xtty->method(_hot_method);
334   }
335   if (_hot_count != 0) {
336     xtty->print(" hot_count='%d'", _hot_count);
337   }
338   xtty->end_elem();
339 }
340 
341 
342 // ------------------------------------------------------------------
343 // CompileTask::log_task_start
344 void CompileTask::log_task_start(CompileLog* log)   {
345   log->begin_head("task");
346   log_task(log);
347   log->end_head();
348 }
349 
350 
351 // ------------------------------------------------------------------
352 // CompileTask::log_task_done
353 void CompileTask::log_task_done(CompileLog* log) {
354   Thread* thread = Thread::current();
355   methodHandle method(thread, this->method());
356   ResourceMark rm(thread);
357 
358   if (!_is_success) {
359     assert(_failure_reason != nullptr, "missing");
360     const char* reason = _failure_reason != nullptr ? _failure_reason : "unknown";
361     log->begin_elem("failure reason='");
362     log->text("%s", reason);
363     log->print("'");
364     log->end_elem();
365   }
366 
367   // <task_done ... stamp='1.234'>  </task>
368   log->begin_elem("task_done success='%d' nmsize='%d' count='%d'",
369                   _is_success, _nm_content_size,
370                   method->invocation_count());
371   int bec = method->backedge_count();
372   if (bec != 0)  log->print(" backedge_count='%d'", bec);
373   // Note:  "_is_complete" is about to be set, but is not.
374   if (_num_inlined_bytecodes != 0) {
375     log->print(" inlined_bytes='%d'", _num_inlined_bytecodes);
376   }
377   log->stamp();
378   log->end_elem();
379   log->clear_identities();   // next task will have different CI
380   log->tail("task");
381   log->flush();
382   log->mark_file_end();
383 }
384 
385 // ------------------------------------------------------------------
386 // CompileTask::check_break_at_flags
387 bool CompileTask::check_break_at_flags() {
388   int compile_id = this->_compile_id;
389   bool is_osr = (_osr_bci != CompileBroker::standard_entry_bci);
390 
391   if (CICountOSR && is_osr && (compile_id == CIBreakAtOSR)) {
392     return true;
393   } else {
394     return (compile_id == CIBreakAt);
395   }
396 }
397 
398 // ------------------------------------------------------------------
399 // CompileTask::print_inlining
400 void CompileTask::print_inlining_inner(outputStream* st, ciMethod* method, int inline_level, int bci, InliningResult result, const char* msg) {
401   print_inlining_header(st, method, inline_level, bci);
402   print_inlining_inner_message(st, result, msg);
403   st->cr();
404 }
405 
406 void CompileTask::print_inlining_header(outputStream* st, ciMethod* method, int inline_level, int bci) {
407   //         1234567
408   st->print("        "); // print timestamp
409   //         1234
410   st->print("     "); // print compilation number
411 
412   // method attributes
413   if (method->is_loaded()) {
414     const char sync_char = method->is_synchronized() ? 's' : ' ';
415     const char exception_char = method->has_exception_handlers() ? '!' : ' ';
416     const char monitors_char = method->has_monitor_bytecodes() ? 'm' : ' ';
417 
418     // print method attributes
419     st->print(" %c%c%c  ", sync_char, exception_char, monitors_char);
420   } else {
421     //         %s!bn
422     st->print("      "); // print method attributes
423   }
424 
425   if (TieredCompilation) {
426     st->print("  ");
427   }
428   st->print("     "); // more indent
429   st->print("    ");  // initial inlining indent
430 
431   for (int i = 0; i < inline_level; i++) {
432     st->print("  ");
433   }
434 
435   st->print("@ %d  ", bci); // print bci
436   print_inline_inner_method_info(st, method);
437 }
438 
439 void CompileTask::print_inline_inner_method_info(outputStream* st, ciMethod* method) {
440   method->print_short_name(st);
441   if (method->is_loaded()) {
442     st->print(" (%d bytes)", method->code_size());
443   } else {
444     st->print(" (not loaded)");
445   }
446 }
447 
448 void CompileTask::print_inline_indent(int inline_level, outputStream* st) {
449   //         1234567
450   st->print("        "); // print timestamp
451   //         1234
452   st->print("     "); // print compilation number
453   //         %s!bn
454   st->print("      "); // print method attributes
455   if (TieredCompilation) {
456     st->print("  ");
457   }
458   st->print("     "); // more indent
459   st->print("    ");  // initial inlining indent
460   for (int i = 0; i < inline_level; i++) {
461     st->print("  ");
462   }
463 }
464 
465 void CompileTask::print_inlining_inner_message(outputStream* st, InliningResult result, const char* msg) {
466   if (msg != nullptr) {
467     st->print("   %s%s", result == InliningResult::SUCCESS ? "" : "failed to inline: ", msg);
468   } else if (result == InliningResult::FAILURE) {
469     st->print("   %s", "failed to inline");
470   }
471 }
472 
473 void CompileTask::print_ul(const char* msg){
474   LogTarget(Debug, jit, compilation) lt;
475   if (lt.is_enabled()) {
476     LogStream ls(lt);
477     print(&ls, msg, /* short form */ true, /* cr */ true);
478   }
479 }
480 
481 void CompileTask::print_ul(const nmethod* nm, const char* msg) {
482   LogTarget(Debug, jit, compilation) lt;
483   if (lt.is_enabled()) {
484     LogStream ls(lt);
485     print_impl(&ls, nm->method(), nm->compile_id(),
486                nm->comp_level(), nm->is_osr_method(),
487                nm->is_osr_method() ? nm->osr_entry_bci() : -1,
488                /*is_blocking*/ false,
489                msg, /* short form */ true, /* cr */ true);
490   }
491 }
492 
493 void CompileTask::print_inlining_ul(ciMethod* method, int inline_level, int bci, InliningResult result, const char* msg) {
494   LogTarget(Debug, jit, inlining) lt;
495   if (lt.is_enabled()) {
496     LogStream ls(lt);
497     print_inlining_inner(&ls, method, inline_level, bci, result, msg);
498   }
499 }
500