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