< prev index next >

src/hotspot/share/runtime/deoptimization.cpp

Print this page

  63 #include "prims/methodHandles.hpp"
  64 #include "prims/vectorSupport.hpp"
  65 #include "runtime/atomic.hpp"
  66 #include "runtime/basicLock.inline.hpp"
  67 #include "runtime/continuation.hpp"
  68 #include "runtime/continuationEntry.inline.hpp"
  69 #include "runtime/deoptimization.hpp"
  70 #include "runtime/escapeBarrier.hpp"
  71 #include "runtime/fieldDescriptor.hpp"
  72 #include "runtime/fieldDescriptor.inline.hpp"
  73 #include "runtime/frame.inline.hpp"
  74 #include "runtime/handles.inline.hpp"
  75 #include "runtime/interfaceSupport.inline.hpp"
  76 #include "runtime/javaThread.hpp"
  77 #include "runtime/jniHandles.inline.hpp"
  78 #include "runtime/keepStackGCProcessed.hpp"
  79 #include "runtime/lightweightSynchronizer.hpp"
  80 #include "runtime/lockStack.inline.hpp"
  81 #include "runtime/objectMonitor.inline.hpp"
  82 #include "runtime/osThread.hpp"

  83 #include "runtime/safepointVerifiers.hpp"
  84 #include "runtime/sharedRuntime.hpp"
  85 #include "runtime/signature.hpp"
  86 #include "runtime/stackFrameStream.inline.hpp"
  87 #include "runtime/stackValue.hpp"
  88 #include "runtime/stackWatermarkSet.hpp"
  89 #include "runtime/stubRoutines.hpp"
  90 #include "runtime/synchronizer.inline.hpp"
  91 #include "runtime/threadSMR.hpp"
  92 #include "runtime/threadWXSetters.inline.hpp"
  93 #include "runtime/vframe.hpp"
  94 #include "runtime/vframeArray.hpp"
  95 #include "runtime/vframe_hp.hpp"
  96 #include "runtime/vmOperations.hpp"

  97 #include "utilities/checkedCast.hpp"
  98 #include "utilities/events.hpp"
  99 #include "utilities/growableArray.hpp"
 100 #include "utilities/macros.hpp"
 101 #include "utilities/preserveException.hpp"
 102 #include "utilities/xmlstream.hpp"
 103 #if INCLUDE_JFR
 104 #include "jfr/jfrEvents.hpp"
 105 #include "jfr/metadata/jfrSerializer.hpp"
 106 #endif
 107 
 108 uint64_t DeoptimizationScope::_committed_deopt_gen = 0;
 109 uint64_t DeoptimizationScope::_active_deopt_gen    = 1;
 110 bool     DeoptimizationScope::_committing_in_progress = false;
 111 
 112 DeoptimizationScope::DeoptimizationScope() : _required_gen(0) {
 113   DEBUG_ONLY(_deopted = false;)
 114 
 115   MutexLocker ml(NMethodState_lock, Mutex::_no_safepoint_check_flag);
 116   // If there is nothing to deopt _required_gen is the same as comitted.

 260   return checked_cast<int>(result);
 261 }
 262 
 263 void Deoptimization::UnrollBlock::print() {
 264   ResourceMark rm;
 265   stringStream st;
 266   st.print_cr("UnrollBlock");
 267   st.print_cr("  size_of_deoptimized_frame = %d", _size_of_deoptimized_frame);
 268   st.print(   "  frame_sizes: ");
 269   for (int index = 0; index < number_of_frames(); index++) {
 270     st.print(INTX_FORMAT " ", frame_sizes()[index]);
 271   }
 272   st.cr();
 273   tty->print_raw(st.freeze());
 274 }
 275 
 276 // In order to make fetch_unroll_info work properly with escape
 277 // analysis, the method was changed from JRT_LEAF to JRT_BLOCK_ENTRY.
 278 // The actual reallocation of previously eliminated objects occurs in realloc_objects,
 279 // which is called from the method fetch_unroll_info_helper below.
 280 JRT_BLOCK_ENTRY(Deoptimization::UnrollBlock*, Deoptimization::fetch_unroll_info(JavaThread* current, int exec_mode))
 281   // fetch_unroll_info() is called at the beginning of the deoptimization
 282   // handler. Note this fact before we start generating temporary frames
 283   // that can confuse an asynchronous stack walker. This counter is
 284   // decremented at the end of unpack_frames().
 285   current->inc_in_deopt_handler();
 286 
 287   if (exec_mode == Unpack_exception) {
 288     // When we get here, a callee has thrown an exception into a deoptimized
 289     // frame. That throw might have deferred stack watermark checking until
 290     // after unwinding. So we deal with such deferred requests here.
 291     StackWatermarkSet::after_unwind(current);
 292   }
 293 
 294   return fetch_unroll_info_helper(current, exec_mode);
 295 JRT_END
 296 
 297 #if COMPILER2_OR_JVMCI
 298 // print information about reallocated objects
 299 static void print_objects(JavaThread* deoptee_thread,
 300                           GrowableArray<ScopeValue*>* objects, bool realloc_failures) {

 832 
 833   assert(f->is_interpreted_frame(), "must be interpreted");
 834 }
 835 
 836 #ifndef PRODUCT
 837 static bool falls_through(Bytecodes::Code bc) {
 838   switch (bc) {
 839     // List may be incomplete.  Here we really only care about bytecodes where compiled code
 840     // can deoptimize.
 841     case Bytecodes::_goto:
 842     case Bytecodes::_goto_w:
 843     case Bytecodes::_athrow:
 844       return false;
 845     default:
 846       return true;
 847   }
 848 }
 849 #endif
 850 
 851 // Return BasicType of value being returned
 852 JRT_LEAF(BasicType, Deoptimization::unpack_frames(JavaThread* thread, int exec_mode))
 853   assert(thread == JavaThread::current(), "pre-condition");
 854 
 855   // We are already active in the special DeoptResourceMark any ResourceObj's we
 856   // allocate will be freed at the end of the routine.
 857 
 858   // JRT_LEAF methods don't normally allocate handles and there is a
 859   // NoHandleMark to enforce that. It is actually safe to use Handles
 860   // in a JRT_LEAF method, and sometimes desirable, but to do so we
 861   // must use ResetNoHandleMark to bypass the NoHandleMark, and
 862   // then use a HandleMark to ensure any Handles we do create are
 863   // cleaned up in this scope.
 864   ResetNoHandleMark rnhm;
 865   HandleMark hm(thread);
 866 
 867   frame stub_frame = thread->last_frame();
 868 
 869   Continuation::notify_deopt(thread, stub_frame.sp());
 870 
 871   // Since the frame to unpack is the top frame of this thread, the vframe_array_head
 872   // must point to the vframeArray for the unpack frame.

1743     if (monitors != nullptr) {
1744       // Unlock in reverse order starting from most nested monitor.
1745       for (int j = (monitors->number_of_monitors() - 1); j >= 0; j--) {
1746         BasicObjectLock* src = monitors->at(j);
1747         if (src->obj() != nullptr) {
1748           ObjectSynchronizer::exit(src->obj(), src->lock(), thread);
1749         }
1750       }
1751       array->element(i)->free_monitors();
1752 #ifdef ASSERT
1753       array->element(i)->set_removed_monitors();
1754 #endif
1755     }
1756   }
1757 }
1758 #endif
1759 
1760 void Deoptimization::deoptimize_single_frame(JavaThread* thread, frame fr, Deoptimization::DeoptReason reason) {
1761   assert(fr.can_be_deoptimized(), "checking frame type");
1762 
1763   gather_statistics(reason, Action_none, Bytecodes::_illegal);






1764 
1765   if (LogCompilation && xtty != nullptr) {
1766     nmethod* nm = fr.cb()->as_nmethod_or_null();
1767     assert(nm != nullptr, "only compiled methods can deopt");
1768 
1769     ttyLocker ttyl;
1770     xtty->begin_head("deoptimized thread='" UINTX_FORMAT "' reason='%s' pc='" INTPTR_FORMAT "'",(uintx)thread->osthread()->thread_id(), trap_reason_name(reason), p2i(fr.pc()));
1771     nm->log_identity(xtty);
1772     xtty->end_head();
1773     for (ScopeDesc* sd = nm->scope_desc_at(fr.pc()); ; sd = sd->sender()) {
1774       xtty->begin_elem("jvms bci='%d'", sd->bci());
1775       xtty->method(sd->method());
1776       xtty->end_elem();
1777       if (sd->is_top())  break;
1778     }
1779     xtty->tail("deoptimized");
1780   }
1781 
1782   Continuation::notify_deopt(thread, fr.sp());
1783 
1784   // Patch the compiled method so that when execution returns to it we will
1785   // deopt the execution state and return to the interpreter.
1786   fr.deoptimize(thread);
1787 }
1788 

1998 static void log_deopt(nmethod* nm, Method* tm, intptr_t pc, frame& fr, int trap_bci,
1999                               const char* reason_name, const char* reason_action) {
2000   LogTarget(Debug, deoptimization) lt;
2001   if (lt.is_enabled()) {
2002     LogStream ls(lt);
2003     bool is_osr = nm->is_osr_method();
2004     ls.print("cid=%4d %s level=%d",
2005              nm->compile_id(), (is_osr ? "osr" : "   "), nm->comp_level());
2006     ls.print(" %s", tm->name_and_sig_as_C_string());
2007     ls.print(" trap_bci=%d ", trap_bci);
2008     if (is_osr) {
2009       ls.print("osr_bci=%d ", nm->osr_entry_bci());
2010     }
2011     ls.print("%s ", reason_name);
2012     ls.print("%s ", reason_action);
2013     ls.print_cr("pc=" INTPTR_FORMAT " relative_pc=" INTPTR_FORMAT,
2014              pc, fr.pc() - nm->code_begin());
2015   }
2016 }
2017 
2018 JRT_ENTRY(void, Deoptimization::uncommon_trap_inner(JavaThread* current, jint trap_request)) {
2019   HandleMark hm(current);
2020 
2021   // uncommon_trap() is called at the beginning of the uncommon trap
2022   // handler. Note this fact before we start generating temporary frames
2023   // that can confuse an asynchronous stack walker. This counter is
2024   // decremented at the end of unpack_frames().
2025 
2026   current->inc_in_deopt_handler();
2027 
2028 #if INCLUDE_JVMCI
2029   // JVMCI might need to get an exception from the stack, which in turn requires the register map to be valid
2030   RegisterMap reg_map(current,
2031                       RegisterMap::UpdateMap::include,
2032                       RegisterMap::ProcessFrames::include,
2033                       RegisterMap::WalkContinuation::skip);
2034 #else
2035   RegisterMap reg_map(current,
2036                       RegisterMap::UpdateMap::skip,
2037                       RegisterMap::ProcessFrames::include,
2038                       RegisterMap::WalkContinuation::skip);

2074 #if INCLUDE_JVMCI
2075     jlong           speculation = current->pending_failed_speculation();
2076     if (nm->is_compiled_by_jvmci()) {
2077       nm->update_speculation(current);
2078     } else {
2079       assert(speculation == 0, "There should not be a speculation for methods compiled by non-JVMCI compilers");
2080     }
2081 
2082     if (trap_bci == SynchronizationEntryBCI) {
2083       trap_bci = 0;
2084       current->set_pending_monitorenter(true);
2085     }
2086 
2087     if (reason == Deoptimization::Reason_transfer_to_interpreter) {
2088       current->set_pending_transfer_to_interpreter(true);
2089     }
2090 #endif
2091 
2092     Bytecodes::Code trap_bc     = trap_method->java_code_at(trap_bci);
2093     // Record this event in the histogram.
2094     gather_statistics(reason, action, trap_bc);
2095 
2096     // Ensure that we can record deopt. history:
2097     bool create_if_missing = ProfileTraps;
2098 
2099     methodHandle profiled_method;
2100 #if INCLUDE_JVMCI
2101     if (nm->is_compiled_by_jvmci()) {
2102       profiled_method = methodHandle(current, nm->method());
2103     } else {
2104       profiled_method = trap_method;
2105     }
2106 #else
2107     profiled_method = trap_method;
2108 #endif
2109 
2110     MethodData* trap_mdo =
2111       get_method_data(current, profiled_method, create_if_missing);
2112 
2113     { // Log Deoptimization event for JFR, UL and event system
2114       Method* tm = trap_method();

2586   bool ignore_maybe_prior_recompile;
2587   assert(!reason_is_speculate(reason), "reason speculate only used by compiler");
2588   // JVMCI uses the total counts to determine if deoptimizations are happening too frequently -> do not adjust total counts
2589   bool update_total_counts = true JVMCI_ONLY( && !UseJVMCICompiler);
2590 
2591   // Lock to read ProfileData, and ensure lock is not broken by a safepoint
2592   MutexLocker ml(trap_mdo->extra_data_lock(), Mutex::_no_safepoint_check_flag);
2593 
2594   query_update_method_data(trap_mdo, trap_bci,
2595                            (DeoptReason)reason,
2596                            update_total_counts,
2597 #if INCLUDE_JVMCI
2598                            false,
2599 #endif
2600                            nullptr,
2601                            ignore_this_trap_count,
2602                            ignore_maybe_prior_trap,
2603                            ignore_maybe_prior_recompile);
2604 }
2605 
2606 Deoptimization::UnrollBlock* Deoptimization::uncommon_trap(JavaThread* current, jint trap_request, jint exec_mode) {
2607   // Enable WXWrite: current function is called from methods compiled by C2 directly
2608   MACOS_AARCH64_ONLY(ThreadWXEnable wx(WXWrite, current));
2609 
2610   // Still in Java no safepoints
2611   {
2612     // This enters VM and may safepoint
2613     uncommon_trap_inner(current, trap_request);
2614   }
2615   HandleMark hm(current);
2616   return fetch_unroll_info_helper(current, exec_mode);
2617 }
2618 
2619 // Local derived constants.
2620 // Further breakdown of DataLayout::trap_state, as promised by DataLayout.
2621 const int DS_REASON_MASK   = ((uint)DataLayout::trap_mask) >> 1;
2622 const int DS_RECOMPILE_BIT = DataLayout::trap_mask - DS_REASON_MASK;
2623 
2624 //---------------------------trap_state_reason---------------------------------
2625 Deoptimization::DeoptReason
2626 Deoptimization::trap_state_reason(int trap_state) {
2627   // This assert provides the link between the width of DataLayout::trap_bits
2628   // and the encoding of "recorded" reasons.  It ensures there are enough
2629   // bits to store all needed reasons in the per-BCI MDO profile.
2630   assert(DS_REASON_MASK >= Reason_RECORDED_LIMIT, "enough bits");
2631   int recompile_bit = (trap_state & DS_RECOMPILE_BIT);
2632   trap_state -= recompile_bit;
2633   if (trap_state == DS_REASON_MASK) {
2634     return Reason_many;
2635   } else {
2636     assert((int)Reason_none == 0, "state=0 => Reason_none");
2637     return (DeoptReason)trap_state;

2786   size_t len;
2787   if (unloaded_class_index < 0) {
2788     len = jio_snprintf(buf, buflen, "reason='%s' action='%s'" JVMCI_ONLY(" debug_id='%d'"),
2789                        reason, action
2790 #if INCLUDE_JVMCI
2791                        ,debug_id
2792 #endif
2793                        );
2794   } else {
2795     len = jio_snprintf(buf, buflen, "reason='%s' action='%s' index='%d'" JVMCI_ONLY(" debug_id='%d'"),
2796                        reason, action, unloaded_class_index
2797 #if INCLUDE_JVMCI
2798                        ,debug_id
2799 #endif
2800                        );
2801   }
2802   return buf;
2803 }
2804 
2805 juint Deoptimization::_deoptimization_hist

2806         [Deoptimization::Reason_LIMIT]
2807     [1 + Deoptimization::Action_LIMIT]
2808         [Deoptimization::BC_CASE_LIMIT]
2809   = {0};
2810 
2811 enum {
2812   LSB_BITS = 8,
2813   LSB_MASK = right_n_bits(LSB_BITS)
2814 };
2815 
2816 void Deoptimization::gather_statistics(DeoptReason reason, DeoptAction action,
2817                                        Bytecodes::Code bc) {
2818   assert(reason >= 0 && reason < Reason_LIMIT, "oob");
2819   assert(action >= 0 && action < Action_LIMIT, "oob");
2820   _deoptimization_hist[Reason_none][0][0] += 1;  // total
2821   _deoptimization_hist[reason][0][0]      += 1;  // per-reason total
2822   juint* cases = _deoptimization_hist[reason][1+action];
2823   juint* bc_counter_addr = nullptr;
2824   juint  bc_counter      = 0;
2825   // Look for an unused counter, or an exact match to this BC.
2826   if (bc != Bytecodes::_illegal) {
2827     for (int bc_case = 0; bc_case < BC_CASE_LIMIT; bc_case++) {
2828       juint* counter_addr = &cases[bc_case];
2829       juint  counter = *counter_addr;
2830       if ((counter == 0 && bc_counter_addr == nullptr)
2831           || (Bytecodes::Code)(counter & LSB_MASK) == bc) {
2832         // this counter is either free or is already devoted to this BC
2833         bc_counter_addr = counter_addr;
2834         bc_counter = counter | bc;
2835       }
2836     }
2837   }
2838   if (bc_counter_addr == nullptr) {
2839     // Overflow, or no given bytecode.
2840     bc_counter_addr = &cases[BC_CASE_LIMIT-1];
2841     bc_counter = (*bc_counter_addr & ~LSB_MASK);  // clear LSB
2842   }
2843   *bc_counter_addr = bc_counter + (1 << LSB_BITS);
2844 }
2845 
















2846 jint Deoptimization::total_deoptimization_count() {
2847   return _deoptimization_hist[Reason_none][0][0];
2848 }
2849 
2850 // Get the deopt count for a specific reason and a specific action. If either
2851 // one of 'reason' or 'action' is null, the method returns the sum of all
2852 // deoptimizations with the specific 'action' or 'reason' respectively.
2853 // If both arguments are null, the method returns the total deopt count.
2854 jint Deoptimization::deoptimization_count(const char *reason_str, const char *action_str) {
2855   if (reason_str == nullptr && action_str == nullptr) {
2856     return total_deoptimization_count();
2857   }
2858   juint counter = 0;
2859   for (int reason = 0; reason < Reason_LIMIT; reason++) {
2860     if (reason_str == nullptr || !strcmp(reason_str, trap_reason_name(reason))) {
2861       for (int action = 0; action < Action_LIMIT; action++) {
2862         if (action_str == nullptr || !strcmp(action_str, trap_action_name(action))) {
2863           juint* cases = _deoptimization_hist[reason][1+action];
2864           for (int bc_case = 0; bc_case < BC_CASE_LIMIT; bc_case++) {
2865             counter += cases[bc_case] >> LSB_BITS;
2866           }
2867         }
2868       }
2869     }
2870   }
2871   return counter;
2872 }
2873 
2874 void Deoptimization::print_statistics() {
2875   juint total = total_deoptimization_count();








2876   juint account = total;
2877   if (total != 0) {
2878     ttyLocker ttyl;
2879     if (xtty != nullptr)  xtty->head("statistics type='deoptimization'");
2880     tty->print_cr("Deoptimization traps recorded:");
2881     #define PRINT_STAT_LINE(name, r) \
2882       tty->print_cr("  %4d (%4.1f%%) %s", (int)(r), ((r) * 100.0) / total, name);
2883     PRINT_STAT_LINE("total", total);
2884     // For each non-zero entry in the histogram, print the reason,
2885     // the action, and (if specifically known) the type of bytecode.
2886     for (int reason = 0; reason < Reason_LIMIT; reason++) {
2887       for (int action = 0; action < Action_LIMIT; action++) {
2888         juint* cases = _deoptimization_hist[reason][1+action];
2889         for (int bc_case = 0; bc_case < BC_CASE_LIMIT; bc_case++) {
2890           juint counter = cases[bc_case];
2891           if (counter != 0) {
2892             char name[1*K];
2893             Bytecodes::Code bc = (Bytecodes::Code)(counter & LSB_MASK);
2894             if (bc_case == BC_CASE_LIMIT && (int)bc == 0)
2895               bc = Bytecodes::_illegal;
2896             os::snprintf_checked(name, sizeof(name), "%s/%s/%s",
2897                     trap_reason_name(reason),
2898                     trap_action_name(action),
2899                     Bytecodes::is_defined(bc)? Bytecodes::name(bc): "other");
2900             juint r = counter >> LSB_BITS;
2901             tty->print_cr("  %40s: " UINT32_FORMAT " (%.1f%%)", name, r, (r * 100.0) / total);


2902             account -= r;
2903           }
2904         }
2905       }
2906     }
2907     if (account != 0) {
2908       PRINT_STAT_LINE("unaccounted", account);
2909     }
2910     #undef PRINT_STAT_LINE
2911     if (xtty != nullptr)  xtty->tail("statistics");
2912   }
2913 }
2914 
























































2915 #else // COMPILER2_OR_JVMCI
2916 
2917 
2918 // Stubs for C1 only system.
2919 bool Deoptimization::trap_state_is_recompiled(int trap_state) {
2920   return false;
2921 }
2922 
2923 const char* Deoptimization::trap_reason_name(int reason) {
2924   return "unknown";
2925 }
2926 
2927 jint Deoptimization::total_deoptimization_count() {
2928   return 0;
2929 }
2930 
2931 jint Deoptimization::deoptimization_count(const char *reason_str, const char *action_str) {
2932   return 0;
2933 }
2934 
2935 void Deoptimization::print_statistics() {
2936   // no output
2937 }
2938 
2939 void
2940 Deoptimization::update_method_data_from_interpreter(MethodData* trap_mdo, int trap_bci, int reason) {
2941   // no update
2942 }
2943 
2944 int Deoptimization::trap_state_has_reason(int trap_state, int reason) {
2945   return 0;
2946 }
2947 
2948 void Deoptimization::gather_statistics(DeoptReason reason, DeoptAction action,
2949                                        Bytecodes::Code bc) {
2950   // no update
2951 }
2952 
2953 const char* Deoptimization::format_trap_state(char* buf, size_t buflen,
2954                                               int trap_state) {
2955   jio_snprintf(buf, buflen, "#%d", trap_state);
2956   return buf;
2957 }
2958 












2959 #endif // COMPILER2_OR_JVMCI

  63 #include "prims/methodHandles.hpp"
  64 #include "prims/vectorSupport.hpp"
  65 #include "runtime/atomic.hpp"
  66 #include "runtime/basicLock.inline.hpp"
  67 #include "runtime/continuation.hpp"
  68 #include "runtime/continuationEntry.inline.hpp"
  69 #include "runtime/deoptimization.hpp"
  70 #include "runtime/escapeBarrier.hpp"
  71 #include "runtime/fieldDescriptor.hpp"
  72 #include "runtime/fieldDescriptor.inline.hpp"
  73 #include "runtime/frame.inline.hpp"
  74 #include "runtime/handles.inline.hpp"
  75 #include "runtime/interfaceSupport.inline.hpp"
  76 #include "runtime/javaThread.hpp"
  77 #include "runtime/jniHandles.inline.hpp"
  78 #include "runtime/keepStackGCProcessed.hpp"
  79 #include "runtime/lightweightSynchronizer.hpp"
  80 #include "runtime/lockStack.inline.hpp"
  81 #include "runtime/objectMonitor.inline.hpp"
  82 #include "runtime/osThread.hpp"
  83 #include "runtime/perfData.inline.hpp"
  84 #include "runtime/safepointVerifiers.hpp"
  85 #include "runtime/sharedRuntime.hpp"
  86 #include "runtime/signature.hpp"
  87 #include "runtime/stackFrameStream.inline.hpp"
  88 #include "runtime/stackValue.hpp"
  89 #include "runtime/stackWatermarkSet.hpp"
  90 #include "runtime/stubRoutines.hpp"
  91 #include "runtime/synchronizer.inline.hpp"
  92 #include "runtime/threadSMR.hpp"
  93 #include "runtime/threadWXSetters.inline.hpp"
  94 #include "runtime/vframe.hpp"
  95 #include "runtime/vframeArray.hpp"
  96 #include "runtime/vframe_hp.hpp"
  97 #include "runtime/vmOperations.hpp"
  98 #include "services/management.hpp"
  99 #include "utilities/checkedCast.hpp"
 100 #include "utilities/events.hpp"
 101 #include "utilities/growableArray.hpp"
 102 #include "utilities/macros.hpp"
 103 #include "utilities/preserveException.hpp"
 104 #include "utilities/xmlstream.hpp"
 105 #if INCLUDE_JFR
 106 #include "jfr/jfrEvents.hpp"
 107 #include "jfr/metadata/jfrSerializer.hpp"
 108 #endif
 109 
 110 uint64_t DeoptimizationScope::_committed_deopt_gen = 0;
 111 uint64_t DeoptimizationScope::_active_deopt_gen    = 1;
 112 bool     DeoptimizationScope::_committing_in_progress = false;
 113 
 114 DeoptimizationScope::DeoptimizationScope() : _required_gen(0) {
 115   DEBUG_ONLY(_deopted = false;)
 116 
 117   MutexLocker ml(NMethodState_lock, Mutex::_no_safepoint_check_flag);
 118   // If there is nothing to deopt _required_gen is the same as comitted.

 262   return checked_cast<int>(result);
 263 }
 264 
 265 void Deoptimization::UnrollBlock::print() {
 266   ResourceMark rm;
 267   stringStream st;
 268   st.print_cr("UnrollBlock");
 269   st.print_cr("  size_of_deoptimized_frame = %d", _size_of_deoptimized_frame);
 270   st.print(   "  frame_sizes: ");
 271   for (int index = 0; index < number_of_frames(); index++) {
 272     st.print(INTX_FORMAT " ", frame_sizes()[index]);
 273   }
 274   st.cr();
 275   tty->print_raw(st.freeze());
 276 }
 277 
 278 // In order to make fetch_unroll_info work properly with escape
 279 // analysis, the method was changed from JRT_LEAF to JRT_BLOCK_ENTRY.
 280 // The actual reallocation of previously eliminated objects occurs in realloc_objects,
 281 // which is called from the method fetch_unroll_info_helper below.
 282 JRT_BLOCK_ENTRY_PROF(Deoptimization::UnrollBlock*, Deoptimization, fetch_unroll_info, Deoptimization::fetch_unroll_info(JavaThread* current, int exec_mode))
 283   // fetch_unroll_info() is called at the beginning of the deoptimization
 284   // handler. Note this fact before we start generating temporary frames
 285   // that can confuse an asynchronous stack walker. This counter is
 286   // decremented at the end of unpack_frames().
 287   current->inc_in_deopt_handler();
 288 
 289   if (exec_mode == Unpack_exception) {
 290     // When we get here, a callee has thrown an exception into a deoptimized
 291     // frame. That throw might have deferred stack watermark checking until
 292     // after unwinding. So we deal with such deferred requests here.
 293     StackWatermarkSet::after_unwind(current);
 294   }
 295 
 296   return fetch_unroll_info_helper(current, exec_mode);
 297 JRT_END
 298 
 299 #if COMPILER2_OR_JVMCI
 300 // print information about reallocated objects
 301 static void print_objects(JavaThread* deoptee_thread,
 302                           GrowableArray<ScopeValue*>* objects, bool realloc_failures) {

 834 
 835   assert(f->is_interpreted_frame(), "must be interpreted");
 836 }
 837 
 838 #ifndef PRODUCT
 839 static bool falls_through(Bytecodes::Code bc) {
 840   switch (bc) {
 841     // List may be incomplete.  Here we really only care about bytecodes where compiled code
 842     // can deoptimize.
 843     case Bytecodes::_goto:
 844     case Bytecodes::_goto_w:
 845     case Bytecodes::_athrow:
 846       return false;
 847     default:
 848       return true;
 849   }
 850 }
 851 #endif
 852 
 853 // Return BasicType of value being returned
 854 JRT_LEAF_PROF_NO_THREAD(BasicType, Deoptimization, unpack_frames, Deoptimization::unpack_frames(JavaThread* thread, int exec_mode))
 855   assert(thread == JavaThread::current(), "pre-condition");
 856 
 857   // We are already active in the special DeoptResourceMark any ResourceObj's we
 858   // allocate will be freed at the end of the routine.
 859 
 860   // JRT_LEAF methods don't normally allocate handles and there is a
 861   // NoHandleMark to enforce that. It is actually safe to use Handles
 862   // in a JRT_LEAF method, and sometimes desirable, but to do so we
 863   // must use ResetNoHandleMark to bypass the NoHandleMark, and
 864   // then use a HandleMark to ensure any Handles we do create are
 865   // cleaned up in this scope.
 866   ResetNoHandleMark rnhm;
 867   HandleMark hm(thread);
 868 
 869   frame stub_frame = thread->last_frame();
 870 
 871   Continuation::notify_deopt(thread, stub_frame.sp());
 872 
 873   // Since the frame to unpack is the top frame of this thread, the vframe_array_head
 874   // must point to the vframeArray for the unpack frame.

1745     if (monitors != nullptr) {
1746       // Unlock in reverse order starting from most nested monitor.
1747       for (int j = (monitors->number_of_monitors() - 1); j >= 0; j--) {
1748         BasicObjectLock* src = monitors->at(j);
1749         if (src->obj() != nullptr) {
1750           ObjectSynchronizer::exit(src->obj(), src->lock(), thread);
1751         }
1752       }
1753       array->element(i)->free_monitors();
1754 #ifdef ASSERT
1755       array->element(i)->set_removed_monitors();
1756 #endif
1757     }
1758   }
1759 }
1760 #endif
1761 
1762 void Deoptimization::deoptimize_single_frame(JavaThread* thread, frame fr, Deoptimization::DeoptReason reason) {
1763   assert(fr.can_be_deoptimized(), "checking frame type");
1764 
1765   nmethod* nm = fr.cb()->as_nmethod_or_null();
1766   assert(nm != nullptr, "only compiled methods can deopt");
1767   DeoptAction action = (nm->is_not_entrant() ? Action_make_not_entrant : Action_none);
1768   ScopeDesc* cur_sd = nm->scope_desc_at(fr.pc());
1769   Bytecodes::Code bc = (cur_sd->bci() == -1 ? Bytecodes::_nop // deopt on method entry
1770                                             : cur_sd->method()->java_code_at(cur_sd->bci()));
1771   gather_statistics(nm, reason, action, bc);
1772 
1773   if (LogCompilation && xtty != nullptr) {



1774     ttyLocker ttyl;
1775     xtty->begin_head("deoptimized thread='" UINTX_FORMAT "' reason='%s' pc='" INTPTR_FORMAT "'",(uintx)thread->osthread()->thread_id(), trap_reason_name(reason), p2i(fr.pc()));
1776     nm->log_identity(xtty);
1777     xtty->end_head();
1778     for (ScopeDesc* sd = nm->scope_desc_at(fr.pc()); ; sd = sd->sender()) {
1779       xtty->begin_elem("jvms bci='%d'", sd->bci());
1780       xtty->method(sd->method());
1781       xtty->end_elem();
1782       if (sd->is_top())  break;
1783     }
1784     xtty->tail("deoptimized");
1785   }
1786 
1787   Continuation::notify_deopt(thread, fr.sp());
1788 
1789   // Patch the compiled method so that when execution returns to it we will
1790   // deopt the execution state and return to the interpreter.
1791   fr.deoptimize(thread);
1792 }
1793 

2003 static void log_deopt(nmethod* nm, Method* tm, intptr_t pc, frame& fr, int trap_bci,
2004                               const char* reason_name, const char* reason_action) {
2005   LogTarget(Debug, deoptimization) lt;
2006   if (lt.is_enabled()) {
2007     LogStream ls(lt);
2008     bool is_osr = nm->is_osr_method();
2009     ls.print("cid=%4d %s level=%d",
2010              nm->compile_id(), (is_osr ? "osr" : "   "), nm->comp_level());
2011     ls.print(" %s", tm->name_and_sig_as_C_string());
2012     ls.print(" trap_bci=%d ", trap_bci);
2013     if (is_osr) {
2014       ls.print("osr_bci=%d ", nm->osr_entry_bci());
2015     }
2016     ls.print("%s ", reason_name);
2017     ls.print("%s ", reason_action);
2018     ls.print_cr("pc=" INTPTR_FORMAT " relative_pc=" INTPTR_FORMAT,
2019              pc, fr.pc() - nm->code_begin());
2020   }
2021 }
2022 
2023 JRT_ENTRY_PROF(void, Deoptimization, uncommon_trap_inner, Deoptimization::uncommon_trap_inner(JavaThread* current, jint trap_request)) {
2024   HandleMark hm(current);
2025 
2026   // uncommon_trap() is called at the beginning of the uncommon trap
2027   // handler. Note this fact before we start generating temporary frames
2028   // that can confuse an asynchronous stack walker. This counter is
2029   // decremented at the end of unpack_frames().
2030 
2031   current->inc_in_deopt_handler();
2032 
2033 #if INCLUDE_JVMCI
2034   // JVMCI might need to get an exception from the stack, which in turn requires the register map to be valid
2035   RegisterMap reg_map(current,
2036                       RegisterMap::UpdateMap::include,
2037                       RegisterMap::ProcessFrames::include,
2038                       RegisterMap::WalkContinuation::skip);
2039 #else
2040   RegisterMap reg_map(current,
2041                       RegisterMap::UpdateMap::skip,
2042                       RegisterMap::ProcessFrames::include,
2043                       RegisterMap::WalkContinuation::skip);

2079 #if INCLUDE_JVMCI
2080     jlong           speculation = current->pending_failed_speculation();
2081     if (nm->is_compiled_by_jvmci()) {
2082       nm->update_speculation(current);
2083     } else {
2084       assert(speculation == 0, "There should not be a speculation for methods compiled by non-JVMCI compilers");
2085     }
2086 
2087     if (trap_bci == SynchronizationEntryBCI) {
2088       trap_bci = 0;
2089       current->set_pending_monitorenter(true);
2090     }
2091 
2092     if (reason == Deoptimization::Reason_transfer_to_interpreter) {
2093       current->set_pending_transfer_to_interpreter(true);
2094     }
2095 #endif
2096 
2097     Bytecodes::Code trap_bc     = trap_method->java_code_at(trap_bci);
2098     // Record this event in the histogram.
2099     gather_statistics(nm, reason, action, trap_bc);
2100 
2101     // Ensure that we can record deopt. history:
2102     bool create_if_missing = ProfileTraps;
2103 
2104     methodHandle profiled_method;
2105 #if INCLUDE_JVMCI
2106     if (nm->is_compiled_by_jvmci()) {
2107       profiled_method = methodHandle(current, nm->method());
2108     } else {
2109       profiled_method = trap_method;
2110     }
2111 #else
2112     profiled_method = trap_method;
2113 #endif
2114 
2115     MethodData* trap_mdo =
2116       get_method_data(current, profiled_method, create_if_missing);
2117 
2118     { // Log Deoptimization event for JFR, UL and event system
2119       Method* tm = trap_method();

2591   bool ignore_maybe_prior_recompile;
2592   assert(!reason_is_speculate(reason), "reason speculate only used by compiler");
2593   // JVMCI uses the total counts to determine if deoptimizations are happening too frequently -> do not adjust total counts
2594   bool update_total_counts = true JVMCI_ONLY( && !UseJVMCICompiler);
2595 
2596   // Lock to read ProfileData, and ensure lock is not broken by a safepoint
2597   MutexLocker ml(trap_mdo->extra_data_lock(), Mutex::_no_safepoint_check_flag);
2598 
2599   query_update_method_data(trap_mdo, trap_bci,
2600                            (DeoptReason)reason,
2601                            update_total_counts,
2602 #if INCLUDE_JVMCI
2603                            false,
2604 #endif
2605                            nullptr,
2606                            ignore_this_trap_count,
2607                            ignore_maybe_prior_trap,
2608                            ignore_maybe_prior_recompile);
2609 }
2610 
2611 PROF_ENTRY(Deoptimization::UnrollBlock*, Deoptimization, uncommon_trap, Deoptimization::uncommon_trap(JavaThread* current, jint trap_request, jint exec_mode))
2612   // Enable WXWrite: current function is called from methods compiled by C2 directly
2613   MACOS_AARCH64_ONLY(ThreadWXEnable wx(WXWrite, current));
2614 
2615   // Still in Java no safepoints
2616   {
2617     // This enters VM and may safepoint
2618     uncommon_trap_inner(current, trap_request);
2619   }
2620   HandleMark hm(current);
2621   return fetch_unroll_info_helper(current, exec_mode);
2622 PROF_END
2623 
2624 // Local derived constants.
2625 // Further breakdown of DataLayout::trap_state, as promised by DataLayout.
2626 const int DS_REASON_MASK   = ((uint)DataLayout::trap_mask) >> 1;
2627 const int DS_RECOMPILE_BIT = DataLayout::trap_mask - DS_REASON_MASK;
2628 
2629 //---------------------------trap_state_reason---------------------------------
2630 Deoptimization::DeoptReason
2631 Deoptimization::trap_state_reason(int trap_state) {
2632   // This assert provides the link between the width of DataLayout::trap_bits
2633   // and the encoding of "recorded" reasons.  It ensures there are enough
2634   // bits to store all needed reasons in the per-BCI MDO profile.
2635   assert(DS_REASON_MASK >= Reason_RECORDED_LIMIT, "enough bits");
2636   int recompile_bit = (trap_state & DS_RECOMPILE_BIT);
2637   trap_state -= recompile_bit;
2638   if (trap_state == DS_REASON_MASK) {
2639     return Reason_many;
2640   } else {
2641     assert((int)Reason_none == 0, "state=0 => Reason_none");
2642     return (DeoptReason)trap_state;

2791   size_t len;
2792   if (unloaded_class_index < 0) {
2793     len = jio_snprintf(buf, buflen, "reason='%s' action='%s'" JVMCI_ONLY(" debug_id='%d'"),
2794                        reason, action
2795 #if INCLUDE_JVMCI
2796                        ,debug_id
2797 #endif
2798                        );
2799   } else {
2800     len = jio_snprintf(buf, buflen, "reason='%s' action='%s' index='%d'" JVMCI_ONLY(" debug_id='%d'"),
2801                        reason, action, unloaded_class_index
2802 #if INCLUDE_JVMCI
2803                        ,debug_id
2804 #endif
2805                        );
2806   }
2807   return buf;
2808 }
2809 
2810 juint Deoptimization::_deoptimization_hist
2811         [1 + 4 + 5] // total + online + archived
2812         [Deoptimization::Reason_LIMIT]
2813     [1 + Deoptimization::Action_LIMIT]
2814         [Deoptimization::BC_CASE_LIMIT]
2815   = {0};
2816 
2817 enum {
2818   LSB_BITS = 8,
2819   LSB_MASK = right_n_bits(LSB_BITS)
2820 };
2821 
2822 static void update(juint* cases, Bytecodes::Code bc) {






2823   juint* bc_counter_addr = nullptr;
2824   juint  bc_counter      = 0;
2825   // Look for an unused counter, or an exact match to this BC.
2826   if (bc != Bytecodes::_illegal) {
2827     for (int bc_case = 0; bc_case < Deoptimization::BC_CASE_LIMIT; bc_case++) {
2828       juint* counter_addr = &cases[bc_case];
2829       juint  counter = *counter_addr;
2830       if ((counter == 0 && bc_counter_addr == nullptr)
2831           || (Bytecodes::Code)(counter & LSB_MASK) == bc) {
2832         // this counter is either free or is already devoted to this BC
2833         bc_counter_addr = counter_addr;
2834         bc_counter = counter | bc;
2835       }
2836     }
2837   }
2838   if (bc_counter_addr == nullptr) {
2839     // Overflow, or no given bytecode.
2840     bc_counter_addr = &cases[Deoptimization::BC_CASE_LIMIT-1];
2841     bc_counter = (*bc_counter_addr & ~LSB_MASK);  // clear LSB
2842   }
2843   *bc_counter_addr = bc_counter + (1 << LSB_BITS);
2844 }
2845 
2846 
2847 void Deoptimization::gather_statistics(nmethod* nm, DeoptReason reason, DeoptAction action,
2848                                        Bytecodes::Code bc) {
2849   assert(reason >= 0 && reason < Reason_LIMIT, "oob");
2850   assert(action >= 0 && action < Action_LIMIT, "oob");
2851   _deoptimization_hist[0][Reason_none][0][0] += 1;  // total
2852   _deoptimization_hist[0][reason][0][0]      += 1;  // per-reason total
2853 
2854   update(_deoptimization_hist[0][reason][1+action], bc);
2855 
2856   uint lvl = nm->comp_level() + (nm->is_scc() ? 4 : 0) + (nm->preloaded() ? 1 : 0);
2857   _deoptimization_hist[lvl][Reason_none][0][0] += 1;  // total
2858   _deoptimization_hist[lvl][reason][0][0]      += 1;  // per-reason total
2859   update(_deoptimization_hist[lvl][reason][1+action], bc);
2860 }
2861 
2862 jint Deoptimization::total_deoptimization_count() {
2863   return _deoptimization_hist[0][Reason_none][0][0];
2864 }
2865 
2866 // Get the deopt count for a specific reason and a specific action. If either
2867 // one of 'reason' or 'action' is null, the method returns the sum of all
2868 // deoptimizations with the specific 'action' or 'reason' respectively.
2869 // If both arguments are null, the method returns the total deopt count.
2870 jint Deoptimization::deoptimization_count(const char *reason_str, const char *action_str) {
2871   if (reason_str == nullptr && action_str == nullptr) {
2872     return total_deoptimization_count();
2873   }
2874   juint counter = 0;
2875   for (int reason = 0; reason < Reason_LIMIT; reason++) {
2876     if (reason_str == nullptr || !strcmp(reason_str, trap_reason_name(reason))) {
2877       for (int action = 0; action < Action_LIMIT; action++) {
2878         if (action_str == nullptr || !strcmp(action_str, trap_action_name(action))) {
2879           juint* cases = _deoptimization_hist[0][reason][1+action];
2880           for (int bc_case = 0; bc_case < BC_CASE_LIMIT; bc_case++) {
2881             counter += cases[bc_case] >> LSB_BITS;
2882           }
2883         }
2884       }
2885     }
2886   }
2887   return counter;
2888 }
2889 
2890 void Deoptimization::print_statistics() {
2891   ttyLocker ttyl;
2892   if (xtty != nullptr)  xtty->head("statistics type='deoptimization'");
2893   tty->print_cr("Deoptimization traps recorded:");
2894   print_statistics_on(tty);
2895   if (xtty != nullptr)  xtty->tail("statistics");
2896 }
2897 
2898 void Deoptimization::print_statistics_on(const char* title, int lvl, outputStream* st) {
2899   juint total = _deoptimization_hist[lvl][Reason_none][0][0];
2900   juint account = total;
2901 #define PRINT_STAT_LINE(name, r) \
2902       st->print_cr("    %d (%4.1f%%) %s", (int)(r), ((r) == total ? 100.0 : (((r) * 100.0) / total)), name);
2903   if (total > 0) {
2904     st->print("  %s: ", title);


2905     PRINT_STAT_LINE("total", total);
2906     // For each non-zero entry in the histogram, print the reason,
2907     // the action, and (if specifically known) the type of bytecode.
2908     for (int reason = 0; reason < Reason_LIMIT; reason++) {
2909       for (int action = 0; action < Action_LIMIT; action++) {
2910         juint* cases = Deoptimization::_deoptimization_hist[lvl][reason][1+action];
2911         for (int bc_case = 0; bc_case < BC_CASE_LIMIT; bc_case++) {
2912           juint counter = cases[bc_case];
2913           if (counter != 0) {

2914             Bytecodes::Code bc = (Bytecodes::Code)(counter & LSB_MASK);
2915             const char* bc_name = "other";
2916             if (bc_case == (BC_CASE_LIMIT-1) && bc == Bytecodes::_nop) {
2917               // overwritten
2918             } else if (Bytecodes::is_defined(bc)) {
2919               bc_name = Bytecodes::name(bc);
2920             }
2921             juint r = counter >> LSB_BITS;
2922             st->print_cr("    %-34s %16s %16s: " UINT32_FORMAT_W(5) " (%4.1f%%)",
2923                          trap_reason_name(reason), trap_action_name(action), bc_name,
2924                          r, (r * 100.0) / total);
2925             account -= r;
2926           }
2927         }
2928       }
2929     }
2930     if (account != 0) {
2931       PRINT_STAT_LINE("unaccounted", account);
2932     }
2933 #undef PRINT_STAT_LINE

2934   }
2935 }
2936 
2937 void Deoptimization::print_statistics_on(outputStream* st) {
2938 //  print_statistics_on("Total", 0, st);
2939   print_statistics_on("Tier1", 1, st);
2940   print_statistics_on("Tier2", 2, st);
2941   print_statistics_on("Tier3", 3, st);
2942   print_statistics_on("Tier4", 4, st);
2943 
2944   print_statistics_on("SC Tier1", 5, st);
2945   print_statistics_on("SC Tier2", 6, st);
2946   print_statistics_on("SC Tier4", 8, st);
2947   print_statistics_on("SC Tier5 (preloaded)", 9, st);
2948 }
2949 
2950 #define DO_COUNTERS(macro) \
2951   macro(Deoptimization, fetch_unroll_info)   \
2952   macro(Deoptimization, unpack_frames) \
2953   macro(Deoptimization, uncommon_trap_inner) \
2954   macro(Deoptimization, uncommon_trap)
2955 
2956 #define INIT_COUNTER(sub, name) \
2957   NEWPERFTICKCOUNTERS(_perf_##sub##_##name##_timer, SUN_RT, #sub "::" #name) \
2958   NEWPERFEVENTCOUNTER(_perf_##sub##_##name##_count, SUN_RT, #sub "::" #name "_count");
2959 
2960 void Deoptimization::init_counters() {
2961   if (ProfileRuntimeCalls && UsePerfData) {
2962     EXCEPTION_MARK;
2963 
2964     DO_COUNTERS(INIT_COUNTER)
2965 
2966     if (HAS_PENDING_EXCEPTION) {
2967       vm_exit_during_initialization("jvm_perf_init failed unexpectedly");
2968     }
2969   }
2970 }
2971 #undef INIT_COUNTER
2972 
2973 #define PRINT_COUNTER(sub, name) { \
2974   jlong count = _perf_##sub##_##name##_count->get_value(); \
2975   if (count > 0) { \
2976     st->print_cr("  %-50s = " JLONG_FORMAT_W(6) "us (elapsed) " JLONG_FORMAT_W(6) "us (thread) (" JLONG_FORMAT_W(5) " events)", #sub "::" #name, \
2977                  _perf_##sub##_##name##_timer->elapsed_counter_value_us(), \
2978                  _perf_##sub##_##name##_timer->thread_counter_value_us(), \
2979                  count); \
2980   }}
2981 
2982 void Deoptimization::print_counters_on(outputStream* st) {
2983   if (ProfileRuntimeCalls && UsePerfData) {
2984     DO_COUNTERS(PRINT_COUNTER)
2985   } else {
2986     st->print_cr("  Deoptimization: no info (%s is disabled)", (UsePerfData ? "ProfileRuntimeCalls" : "UsePerfData"));
2987   }
2988 }
2989 
2990 #undef PRINT_COUNTER
2991 #undef DO_COUNTERS
2992 
2993 #else // COMPILER2_OR_JVMCI
2994 
2995 
2996 // Stubs for C1 only system.
2997 bool Deoptimization::trap_state_is_recompiled(int trap_state) {
2998   return false;
2999 }
3000 
3001 const char* Deoptimization::trap_reason_name(int reason) {
3002   return "unknown";
3003 }
3004 
3005 jint Deoptimization::total_deoptimization_count() {
3006   return 0;
3007 }
3008 
3009 jint Deoptimization::deoptimization_count(const char *reason_str, const char *action_str) {
3010   return 0;
3011 }
3012 
3013 void Deoptimization::print_statistics() {
3014   // no output
3015 }
3016 
3017 void
3018 Deoptimization::update_method_data_from_interpreter(MethodData* trap_mdo, int trap_bci, int reason) {
3019   // no update
3020 }
3021 
3022 int Deoptimization::trap_state_has_reason(int trap_state, int reason) {
3023   return 0;
3024 }
3025 
3026 void Deoptimization::gather_statistics(nmethod* nm, DeoptReason reason, DeoptAction action,
3027                                        Bytecodes::Code bc) {
3028   // no update
3029 }
3030 
3031 const char* Deoptimization::format_trap_state(char* buf, size_t buflen,
3032                                               int trap_state) {
3033   jio_snprintf(buf, buflen, "#%d", trap_state);
3034   return buf;
3035 }
3036 
3037 void Deoptimization::init_counters() {
3038   // nothing to do
3039 }
3040 
3041 void Deoptimization::print_counters_on(outputStream* st) {
3042   // no output
3043 }
3044 
3045 void Deoptimization::print_statistics_on(outputStream* st) {
3046   // no output
3047 }
3048 
3049 #endif // COMPILER2_OR_JVMCI
< prev index next >